nushell/crates/nu-command/src/commands/default.rs
Michael Angerman d06f457b2a
nu-cli refactor moving commands into their own crate nu-command (#2910)
* move commands, futures.rs, script.rs, utils

* move over maybe_print_errors

* add nu_command crate references to nu_cli

* in commands.rs open up to pub mod from pub(crate)

* nu-cli, nu-command, and nu tests are now passing

* cargo fmt

* clean up nu-cli/src/prelude.rs

* code cleanup

* for some reason lex.rs was not formatted, may be causing my error

* remove mod completion from lib.rs which was not being used along with quickcheck macros

* add in allow unused imports

* comment out one failing external test; comment out one failing internal test

* revert commenting out failing tests; something else might be going on; someone with a windows machine should check and see what is going on with these failing windows tests

* Update Cargo.toml

Extend the optional features to nu-command

Co-authored-by: Jonathan Turner <jonathandturner@users.noreply.github.com>
2021-01-12 17:59:53 +13:00

85 lines
2.2 KiB
Rust

use crate::prelude::*;
use nu_engine::WholeStreamCommand;
use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::Tagged;
use nu_value_ext::ValueExt;
#[derive(Deserialize)]
struct DefaultArgs {
column: Tagged<String>,
value: Value,
}
pub struct Default;
#[async_trait]
impl WholeStreamCommand for Default {
fn name(&self) -> &str {
"default"
}
fn signature(&self) -> Signature {
Signature::build("default")
.required("column name", SyntaxShape::String, "the name of the column")
.required(
"column value",
SyntaxShape::Any,
"the value of the column to default",
)
}
fn usage(&self) -> &str {
"Sets a default row's column if missing."
}
async fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
default(args).await
}
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Give a default 'target' to all file entries",
example: "ls -la | default target 'nothing'",
result: None,
}]
}
}
async fn default(args: CommandArgs) -> Result<OutputStream, ShellError> {
let (DefaultArgs { column, value }, input) = args.process().await?;
Ok(input
.map(move |item| {
let should_add = matches!(
item,
Value {
value: UntaggedValue::Row(ref r),
..
} if r.get_data(&column.item).borrow().is_none()
);
if should_add {
match item.insert_data_at_path(&column.item, value.clone()) {
Some(new_value) => ReturnSuccess::value(new_value),
None => ReturnSuccess::value(item),
}
} else {
ReturnSuccess::value(item)
}
})
.to_output_stream())
}
#[cfg(test)]
mod tests {
use super::Default;
use super::ShellError;
#[test]
fn examples_work_as_expected() -> Result<(), ShellError> {
use crate::examples::test as test_examples;
Ok(test_examples(Default {})?)
}
}