nushell/crates/nu-command/src/each.rs

80 lines
2.7 KiB
Rust
Raw Normal View History

2021-09-03 09:35:29 +02:00
use nu_engine::eval_block;
2021-09-03 05:45:34 +02:00
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EvaluationContext};
2021-09-03 09:35:29 +02:00
use nu_protocol::{IntoValueStream, Signature, SyntaxShape, Value};
2021-09-03 05:45:34 +02:00
pub struct Each;
impl Command for Each {
fn name(&self) -> &str {
"each"
}
fn usage(&self) -> &str {
"Run a block on each element of input"
}
fn signature(&self) -> nu_protocol::Signature {
2021-09-06 01:16:27 +02:00
Signature::build("each").required("block", SyntaxShape::Block, "the block to run")
2021-09-03 05:45:34 +02:00
}
fn run(
&self,
context: &EvaluationContext,
call: &Call,
input: Value,
) -> Result<nu_protocol::Value, nu_protocol::ShellError> {
2021-09-06 01:16:27 +02:00
let block_id = call.positional[0]
2021-09-03 05:45:34 +02:00
.as_block()
.expect("internal error: expected block");
let context = context.clone();
match input {
Value::List { val, .. } => Ok(Value::List {
val: val
2021-09-04 08:52:28 +02:00
.into_iter()
.map(move |x| {
let engine_state = context.engine_state.borrow();
2021-09-06 01:16:27 +02:00
let block = engine_state.get_block(block_id);
2021-09-04 08:52:28 +02:00
let state = context.enter_scope();
2021-09-06 01:16:27 +02:00
if let Some(var) = block.signature.required_positional.first() {
if let Some(var_id) = &var.var_id {
state.add_var(*var_id, x);
}
}
2021-09-04 08:52:28 +02:00
2021-09-06 01:16:27 +02:00
match eval_block(&state, block, Value::nothing()) {
Ok(v) => v,
Err(err) => Value::Error { err },
}
2021-09-04 08:52:28 +02:00
})
.collect(),
span: call.head,
}),
Value::ValueStream { stream, .. } => Ok(Value::ValueStream {
stream: stream
2021-09-03 05:45:34 +02:00
.map(move |x| {
let engine_state = context.engine_state.borrow();
2021-09-06 01:16:27 +02:00
let block = engine_state.get_block(block_id);
2021-09-03 05:45:34 +02:00
let state = context.enter_scope();
2021-09-06 01:16:27 +02:00
if let Some(var) = block.signature.required_positional.first() {
if let Some(var_id) = &var.var_id {
state.add_var(*var_id, x);
}
}
2021-09-03 05:45:34 +02:00
2021-09-06 01:16:27 +02:00
match eval_block(&state, block, Value::nothing()) {
Ok(v) => v,
Err(err) => Value::Error { err },
}
2021-09-03 05:45:34 +02:00
})
.into_value_stream(),
span: call.head,
}),
_ => Ok(Value::nothing()),
}
}
}