nushell/crates/nu-cli/src/commands/edit.rs

83 lines
2.2 KiB
Rust
Raw Normal View History

use crate::commands::WholeStreamCommand;
2019-12-05 21:15:41 +01:00
use crate::context::CommandRegistry;
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{ColumnPath, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
2019-12-09 19:52:01 +01:00
use nu_value_ext::ValueExt;
2019-12-05 21:15:41 +01:00
pub struct Edit;
#[derive(Deserialize)]
pub struct EditArgs {
field: ColumnPath,
replacement: Value,
}
impl WholeStreamCommand for Edit {
2019-12-05 21:15:41 +01:00
fn name(&self) -> &str {
"edit"
}
fn signature(&self) -> Signature {
Signature::build("edit")
.required(
"field",
2019-12-05 21:15:41 +01:00
SyntaxShape::ColumnPath,
"the name of the column to edit",
)
.required(
"replacement value",
SyntaxShape::Any,
2019-12-05 21:15:41 +01:00
"the new value to give the cell(s)",
)
}
fn usage(&self) -> &str {
"Edit an existing column to have a new value."
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
2019-12-05 21:15:41 +01:00
) -> Result<OutputStream, ShellError> {
args.process(registry, edit)?.run()
}
}
fn edit(
EditArgs { field, replacement }: EditArgs,
RunnableContext { input, .. }: RunnableContext,
) -> Result<OutputStream, ShellError> {
let mut input = input;
2019-12-05 21:15:41 +01:00
let stream = async_stream! {
match input.next().await {
Some(obj @ Value {
2019-12-05 21:15:41 +01:00
value: UntaggedValue::Row(_),
..
}) => match obj.replace_data_at_column_path(&field, replacement.clone()) {
Some(v) => yield Ok(ReturnSuccess::Value(v)),
2019-12-05 21:15:41 +01:00
None => {
yield Err(ShellError::labeled_error(
2019-12-05 21:15:41 +01:00
"edit could not find place to insert column",
"column name",
obj.tag,
2019-12-05 21:15:41 +01:00
))
}
},
Some(Value { tag, ..}) => {
yield Err(ShellError::labeled_error(
2019-12-05 21:15:41 +01:00
"Unrecognized type in stream",
"original value",
tag,
2019-12-05 21:15:41 +01:00
))
}
_ => {}
}
};
2019-12-05 21:15:41 +01:00
Ok(stream.to_output_stream())
2019-12-05 21:15:41 +01:00
}