nushell/src/plugins/edit.rs
Andrés N. Robalino ca0c6eaf58 This commit introduces a basic help feature. We can go to it
with the `help` command to explore and list all commands available.

Enter will also try to see if the location to be entered is an existing
Nu command, if it is it will let you inspect the command under `help`.

This provides baseline needed so we can iterate on it.
2019-08-31 19:06:11 -05:00

85 lines
2.5 KiB
Rust

use nu::{
serve_plugin, CallInfo, Plugin, Primitive, ReturnSuccess, ReturnValue, ShellError, Signature,
SyntaxType, Tagged, Value,
};
struct Edit {
field: Option<String>,
value: Option<Value>,
}
impl Edit {
fn new() -> Edit {
Edit {
field: None,
value: None,
}
}
fn edit(&self, value: Tagged<Value>) -> Result<Tagged<Value>, ShellError> {
let value_tag = value.tag();
match (value.item, self.value.clone()) {
(obj @ Value::Object(_), Some(v)) => match &self.field {
Some(f) => match obj.replace_data_at_path(value_tag, &f, v) {
Some(v) => return Ok(v),
None => {
return Err(ShellError::string(
"edit could not find place to insert field",
))
}
},
None => Err(ShellError::string(
"edit needs a field when adding a value to an object",
)),
},
x => Err(ShellError::string(format!(
"Unrecognized type in stream: {:?}",
x
))),
}
}
}
impl Plugin for Edit {
fn config(&mut self) -> Result<Signature, ShellError> {
Ok(Signature::build("edit")
.desc("Edit an existing field to have a new value.")
.required("Field", SyntaxType::String)
.required("Value", SyntaxType::String)
.filter())
}
fn begin_filter(&mut self, call_info: CallInfo) -> Result<Vec<ReturnValue>, ShellError> {
if let Some(args) = call_info.args.positional {
match &args[0] {
Tagged {
item: Value::Primitive(Primitive::String(s)),
..
} => {
self.field = Some(s.clone());
}
_ => {
return Err(ShellError::string(format!(
"Unrecognized type in params: {:?}",
args[0]
)))
}
}
match &args[1] {
Tagged { item: v, .. } => {
self.value = Some(v.clone());
}
}
}
Ok(vec![])
}
fn filter(&mut self, input: Tagged<Value>) -> Result<Vec<ReturnValue>, ShellError> {
Ok(vec![ReturnSuccess::value(self.edit(input)?)])
}
}
fn main() {
serve_plugin(&mut Edit::new());
}