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

122 lines
3.6 KiB
Rust
Raw Normal View History

use crate::commands::WholeStreamCommand;
use crate::context::CommandRegistry;
use crate::evaluate::evaluate_baseline_expr;
2019-05-16 04:42:44 +02:00
use crate::prelude::*;
use nu_errors::ShellError;
use nu_protocol::{hir::Block, hir::ClassifiedCommand, ReturnSuccess, Signature, SyntaxShape};
2019-07-24 00:22:11 +02:00
pub struct Where;
#[derive(Deserialize)]
pub struct WhereArgs {
block: Block,
}
impl WholeStreamCommand for Where {
2019-07-24 00:22:11 +02:00
fn name(&self) -> &str {
"where"
}
2019-05-28 08:45:18 +02:00
fn signature(&self) -> Signature {
2019-10-28 06:15:35 +01:00
Signature::build("where").required(
"condition",
SyntaxShape::Math,
2019-10-28 06:15:35 +01:00
"the condition that must match",
)
}
fn usage(&self) -> &str {
"Filter table to match the condition."
2019-05-22 09:12:03 +02:00
}
2019-07-24 00:22:11 +02:00
2019-08-02 21:15:07 +02:00
fn run(
&self,
args: CommandArgs,
registry: &CommandRegistry,
2019-08-24 21:36:19 +02:00
) -> Result<OutputStream, ShellError> {
where_command(args, registry)
}
fn examples(&self) -> &[Example] {
&[
Example {
description: "List all files in the current directory with sizes greater than 2kb",
example: "ls | where size > 2kb",
},
Example {
description: "List only the files in the current directory",
example: "ls | where type == File",
},
Example {
description: "List all files with names that contain \"Car\"",
example: "ls | where name =~ \"Car\"",
},
Example {
description: "List all files that were modified in the last two months",
example: "ls | where modified <= 2M",
},
]
}
}
fn where_command(
raw_args: CommandArgs,
registry: &CommandRegistry,
) -> Result<OutputStream, ShellError> {
let registry = registry.clone();
let stream = async_stream! {
let tag = raw_args.call_info.name_tag.clone();
let scope = raw_args.call_info.scope.clone();
let (WhereArgs { block }, mut input) = raw_args.process(&registry).await?;
let condition = {
if block.block.len() != 1 {
yield Err(ShellError::labeled_error(
2019-08-24 21:36:19 +02:00
"Expected a condition",
"expected a condition",
tag,
));
return;
}
match block.block[0].list.get(0) {
Some(item) => match item {
ClassifiedCommand::Expr(expr) => expr.clone(),
_ => {
yield Err(ShellError::labeled_error(
"Expected a condition",
"expected a condition",
tag,
));
return;
}
},
None => {
yield Err(ShellError::labeled_error(
"Expected a condition",
"expected a condition",
tag,
));
return;
}
}
};
let mut input = input;
while let Some(input) = input.next().await {
//FIXME: should we use the scope that's brought in as well?
let condition = evaluate_baseline_expr(&condition, &registry, &scope.clone().set_it(input.clone())).await?;
match condition.as_bool() {
Ok(b) => {
if b {
yield Ok(ReturnSuccess::Value(input));
}
}
Err(e) => yield Err(e),
};
}
};
2019-08-24 21:36:19 +02:00
Ok(stream.to_output_stream())
2019-08-02 21:15:07 +02:00
}