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

95 lines
2.4 KiB
Rust
Raw Normal View History

use crate::command_registry::CommandRegistry;
2019-11-24 00:57:12 +01:00
use crate::commands::WholeStreamCommand;
use crate::prelude::*;
use futures::future;
2019-11-24 00:57:12 +01:00
use futures::stream::StreamExt;
use nu_errors::ShellError;
use nu_protocol::{ReturnSuccess, Signature, SyntaxShape, UntaggedValue, Value};
use nu_source::Tagged;
2019-11-24 00:57:12 +01:00
pub struct Compact;
#[derive(Deserialize)]
pub struct CompactArgs {
rest: Vec<Tagged<String>>,
}
2020-05-29 10:22:52 +02:00
#[async_trait]
2019-11-24 00:57:12 +01:00
impl WholeStreamCommand for Compact {
fn name(&self) -> &str {
"compact"
}
fn signature(&self) -> Signature {
Signature::build("compact").rest(SyntaxShape::Any, "the columns to compact from the table")
}
fn usage(&self) -> &str {
"Creates a table with non-empty rows"
}
2020-05-29 10:22:52 +02:00
async fn run(
2019-11-24 00:57:12 +01:00
&self,
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
compact(args, registry).await
2019-11-24 00:57:12 +01:00
}
2020-05-12 03:00:55 +02:00
fn examples(&self) -> Vec<Example> {
vec![Example {
description: "Filter out all directory entries having no 'target'",
example: "ls -la | compact target",
result: None,
}]
2020-05-12 03:00:55 +02:00
}
2019-11-24 00:57:12 +01:00
}
pub async fn compact(
args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let (CompactArgs { rest: columns }, input) = args.process(&registry).await?;
Ok(input
.filter_map(move |item| {
future::ready(if columns.is_empty() {
if !item.is_empty() {
Some(ReturnSuccess::value(item))
} else {
None
}
} else {
match item {
Value {
value: UntaggedValue::Row(ref r),
..
} => {
if columns
.iter()
.all(|field| r.get_data(field).borrow().is_some())
{
Some(ReturnSuccess::value(item))
} else {
None
}
}
_ => None,
}
})
})
.to_output_stream())
2019-11-24 00:57:12 +01:00
}
#[cfg(test)]
mod tests {
use super::Compact;
#[test]
fn examples_work_as_expected() {
use crate::examples::test as test_examples;
test_examples(Compact {})
}
}