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

84 lines
2.0 KiB
Rust
Raw Normal View History

2019-11-04 02:55:34 +01:00
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use crate::utils::data_processing::reduce;
use nu_errors::ShellError;
use nu_protocol::{Primitive, ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::Tagged;
2019-11-12 08:07:43 +01:00
use num_traits::cast::ToPrimitive;
2019-11-04 02:55:34 +01:00
pub struct ReduceBy;
#[derive(Deserialize)]
pub struct ReduceByArgs {
2019-11-12 08:07:43 +01:00
reduce_with: Option<Tagged<String>>,
2019-11-04 02:55:34 +01:00
}
2020-05-29 10:22:52 +02:00
#[async_trait]
2019-11-04 02:55:34 +01:00
impl WholeStreamCommand for ReduceBy {
fn name(&self) -> &str {
"reduce-by"
}
fn signature(&self) -> Signature {
2019-11-12 08:07:43 +01:00
Signature::build("reduce-by").named(
"reduce_with",
SyntaxShape::String,
"the command to reduce by with",
Some('w'),
2019-11-04 02:55:34 +01:00
)
}
fn usage(&self) -> &str {
2019-11-12 08:07:43 +01:00
"Creates a new table with the data from the tables rows reduced by the command given."
2019-11-04 02:55:34 +01:00
}
2020-05-29 10:22:52 +02:00
async fn run(
2019-11-04 02:55:34 +01:00
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
reduce_by(args, registry).await
2019-11-04 02:55:34 +01:00
}
}
pub async fn reduce_by(
args: CommandArgs,
registry: &CommandRegistry,
2019-11-04 02:55:34 +01:00
) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let name = args.call_info.name_tag.clone();
let (ReduceByArgs { reduce_with }, mut input) = args.process(&registry).await?;
let values: Vec<Value> = input.collect().await;
2019-11-04 02:55:34 +01:00
if values.is_empty() {
return Err(ShellError::labeled_error(
"Expected table from pipeline",
"requires a table input",
name,
));
}
2019-11-12 08:07:43 +01:00
let reduce_with = if let Some(reducer) = reduce_with {
Some(reducer.item().clone())
} else {
None
2019-11-04 02:55:34 +01:00
};
match reduce(&values[0], reduce_with, name) {
Ok(reduced) => Ok(OutputStream::one(ReturnSuccess::value(reduced))),
Err(err) => Err(err),
}
2019-11-04 02:55:34 +01:00
}
#[cfg(test)]
mod tests {
use super::ReduceBy;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(ReduceBy {})
}
}