nushell/src/commands/where_.rs

49 lines
1.3 KiB
Rust
Raw Normal View History

2019-05-16 04:42:44 +02:00
use crate::errors::ShellError;
2019-05-28 08:45:18 +02:00
use crate::parser::registry::PositionalType;
use crate::parser::CommandConfig;
2019-05-16 04:42:44 +02:00
use crate::prelude::*;
2019-05-28 08:45:18 +02:00
pub struct Where;
impl Command for Where {
fn run(&self, args: CommandArgs) -> Result<OutputStream, ShellError> {
r#where(args)
}
fn name(&self) -> &str {
"where"
}
fn config(&self) -> CommandConfig {
CommandConfig {
name: self.name().to_string(),
mandatory_positional: vec![PositionalType::Block("condition".to_string())],
optional_positional: vec![],
rest_positional: false,
named: indexmap::IndexMap::new(),
}
}
}
pub fn r#where(args: CommandArgs) -> Result<OutputStream, ShellError> {
if args.positional.is_empty() {
2019-05-22 09:12:03 +02:00
return Err(ShellError::string("select requires a field"));
}
2019-05-16 04:42:44 +02:00
let block = args.positional[0].as_block()?;
let input = args.input;
2019-05-16 04:42:44 +02:00
2019-05-28 08:45:18 +02:00
let objects = input.filter_map(move |item| {
let result = block.invoke(&item);
let return_value = match result {
Err(err) => Some(ReturnValue::Value(Value::Error(Box::new(err)))),
Ok(v) if v.is_true() => Some(ReturnValue::Value(item.copy())),
_ => None,
};
futures::future::ready(return_value)
});
2019-05-16 04:42:44 +02:00
2019-05-26 08:54:41 +02:00
Ok(objects.boxed())
2019-05-16 04:42:44 +02:00
}