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

89 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 Insert;
#[derive(Deserialize)]
pub struct InsertArgs {
column: ColumnPath,
value: Value,
}
impl WholeStreamCommand for Insert {
2019-12-05 21:15:41 +01:00
fn name(&self) -> &str {
"insert"
}
fn signature(&self) -> Signature {
Signature::build("insert")
.required(
"column",
SyntaxShape::ColumnPath,
"the column name to insert",
)
.required(
"value",
SyntaxShape::String,
"the value to give the cell(s)",
)
}
fn usage(&self) -> &str {
"Insert a new column with a given value."
2019-12-05 21:15:41 +01:00
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
2019-12-05 21:15:41 +01:00
) -> Result<OutputStream, ShellError> {
insert(args, registry)
}
}
2019-12-05 21:15:41 +01:00
fn insert(args: CommandArgs, registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
let (InsertArgs { column, value }, mut input) = args.process(&registry).await?;
2020-05-17 14:30:52 +02:00
while let Some(row) = input.next().await {
match row {
Value {
value: UntaggedValue::Row(_),
..
} => match row.insert_data_at_column_path(&column, value.clone()) {
Ok(v) => yield Ok(ReturnSuccess::Value(v)),
Err(err) => yield Err(err),
},
2019-12-05 21:15:41 +01:00
2020-05-17 14:30:52 +02:00
Value { tag, ..} => {
yield Err(ShellError::labeled_error(
"Unrecognized type in stream",
"original value",
tag,
));
}
2020-05-17 14:30:52 +02:00
}
2019-12-05 21:15:41 +01:00
};
};
Ok(stream.to_output_stream())
2019-12-05 21:15:41 +01:00
}
#[cfg(test)]
mod tests {
use super::Insert;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(Insert {})
}
}