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

62 lines
1.5 KiB
Rust
Raw Normal View History

2019-10-15 12:19:06 +02:00
use crate::commands::WholeStreamCommand;
use crate::context::CommandRegistry;
2019-10-15 12:19:06 +02:00
use crate::prelude::*;
use futures::stream::StreamExt;
use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, UntaggedValue, Value};
2019-10-15 12:19:06 +02:00
pub struct Count;
impl WholeStreamCommand for Count {
fn name(&self) -> &str {
"count"
}
fn signature(&self) -> Signature {
Signature::build("count")
}
fn usage(&self) -> &str {
2020-05-12 03:00:55 +02:00
"Show the total number of rows or items."
2019-10-15 12:19:06 +02:00
}
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
count(args, registry)
2019-10-15 12:19:06 +02:00
}
2020-05-12 03:00:55 +02:00
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Count the number of entries in a list",
example: "echo [1 2 3 4 5] | count",
result: Some(vec![UntaggedValue::int(5).into()]),
2020-05-12 03:00:55 +02:00
}]
}
2019-10-15 12:19:06 +02:00
}
pub fn count(args: CommandArgs, _registry: &CommandRegistry) -> Result<OutputStream, ShellError> {
2019-10-15 12:19:06 +02:00
let stream = async_stream! {
let name = args.call_info.name_tag.clone();
let rows: Vec<Value> = args.input.collect().await;
2019-10-15 12:19:06 +02:00
yield ReturnSuccess::value(UntaggedValue::int(rows.len()).into_value(name))
2019-10-15 12:19:06 +02:00
};
Ok(stream.to_output_stream())
}
#[cfg(test)]
mod tests {
use super::Count;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(Count {})
}
}