2022-01-08 01:40:40 +01:00
|
|
|
use nu_engine::{eval_block, CallExt};
|
|
|
|
|
|
|
|
use nu_protocol::ast::Call;
|
2022-01-12 05:06:56 +01:00
|
|
|
use nu_protocol::engine::{CaptureBlock, Command, EngineState, Stack};
|
2022-01-08 01:40:40 +01:00
|
|
|
use nu_protocol::{
|
|
|
|
Example, IntoPipelineData, PipelineData, ShellError, Signature, Span, SyntaxShape, Value,
|
|
|
|
};
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct Reduce;
|
|
|
|
|
|
|
|
impl Command for Reduce {
|
|
|
|
fn name(&self) -> &str {
|
|
|
|
"reduce"
|
|
|
|
}
|
|
|
|
|
|
|
|
fn signature(&self) -> Signature {
|
|
|
|
Signature::build("reduce")
|
|
|
|
.named(
|
|
|
|
"fold",
|
|
|
|
SyntaxShape::Any,
|
|
|
|
"reduce with initial value",
|
|
|
|
Some('f'),
|
|
|
|
)
|
|
|
|
.required(
|
|
|
|
"block",
|
2022-02-17 12:40:24 +01:00
|
|
|
SyntaxShape::Block(Some(vec![SyntaxShape::Any, SyntaxShape::Any])),
|
2022-01-08 01:40:40 +01:00
|
|
|
"reducing function",
|
|
|
|
)
|
|
|
|
.switch("numbered", "iterate with an index", Some('n'))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn usage(&self) -> &str {
|
|
|
|
"Aggregate a list table to a single value using an accumulator block."
|
|
|
|
}
|
|
|
|
|
|
|
|
fn examples(&self) -> Vec<Example> {
|
|
|
|
vec![
|
|
|
|
Example {
|
2022-02-17 12:40:24 +01:00
|
|
|
example: "[ 1 2 3 4 ] | reduce {|it, acc| $it + $acc }",
|
2022-01-08 01:40:40 +01:00
|
|
|
description: "Sum values of a list (same as 'math sum')",
|
|
|
|
result: Some(Value::Int {
|
|
|
|
val: 10,
|
|
|
|
span: Span::test_data(),
|
|
|
|
}),
|
|
|
|
},
|
|
|
|
Example {
|
2022-02-17 12:40:24 +01:00
|
|
|
example: "[ 1 2 3 4 ] | reduce -f 10 {|it, acc| $acc + $it }",
|
2022-01-08 01:40:40 +01:00
|
|
|
description: "Sum values with a starting value (fold)",
|
|
|
|
result: Some(Value::Int {
|
|
|
|
val: 20,
|
|
|
|
span: Span::test_data(),
|
|
|
|
}),
|
|
|
|
},
|
|
|
|
Example {
|
2022-02-17 12:40:24 +01:00
|
|
|
example: r#"[ i o t ] | reduce -f "Arthur, King of the Britons" {|it, acc| $acc | str find-replace -a $it "X" }"#,
|
2022-01-08 01:40:40 +01:00
|
|
|
description: "Replace selected characters in a string with 'X'",
|
|
|
|
result: Some(Value::String {
|
|
|
|
val: "ArXhur, KXng Xf Xhe BrXXXns".to_string(),
|
|
|
|
span: Span::test_data(),
|
|
|
|
}),
|
|
|
|
},
|
|
|
|
Example {
|
2022-02-17 12:40:24 +01:00
|
|
|
example: r#"[ one longest three bar ] | reduce -n { |it, acc|
|
|
|
|
if ($it.item | str length) > ($acc | str length) {
|
2022-01-08 01:40:40 +01:00
|
|
|
$it.item
|
|
|
|
} else {
|
2022-02-17 12:40:24 +01:00
|
|
|
$acc
|
2022-01-08 01:40:40 +01:00
|
|
|
}
|
|
|
|
}"#,
|
|
|
|
description: "Find the longest string and its index",
|
|
|
|
result: Some(Value::Record {
|
|
|
|
cols: vec!["index".to_string(), "item".to_string()],
|
|
|
|
vals: vec![
|
|
|
|
Value::Int {
|
|
|
|
val: 3,
|
|
|
|
span: Span::test_data(),
|
|
|
|
},
|
|
|
|
Value::String {
|
|
|
|
val: "longest".to_string(),
|
|
|
|
span: Span::test_data(),
|
|
|
|
},
|
|
|
|
],
|
|
|
|
span: Span::test_data(),
|
|
|
|
}),
|
|
|
|
},
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
|
|
|
fn run(
|
|
|
|
&self,
|
|
|
|
engine_state: &EngineState,
|
|
|
|
stack: &mut Stack,
|
|
|
|
call: &Call,
|
|
|
|
input: PipelineData,
|
|
|
|
) -> Result<PipelineData, ShellError> {
|
|
|
|
// TODO: How to make this interruptible?
|
|
|
|
// TODO: Change the vars to $acc and $it instead of $it.acc and $it.item
|
|
|
|
// (requires parser change)
|
|
|
|
|
|
|
|
let span = call.head;
|
|
|
|
|
|
|
|
let fold: Option<Value> = call.get_flag(engine_state, stack, "fold")?;
|
|
|
|
let numbered = call.has_flag("numbered");
|
2022-01-12 05:06:56 +01:00
|
|
|
let capture_block: CaptureBlock = call.req(engine_state, stack, 0)?;
|
|
|
|
let mut stack = stack.captures_to_stack(&capture_block.captures);
|
|
|
|
let block = engine_state.get_block(capture_block.block_id);
|
2022-01-08 01:40:40 +01:00
|
|
|
|
|
|
|
let orig_env_vars = stack.env_vars.clone();
|
|
|
|
let orig_env_hidden = stack.env_hidden.clone();
|
|
|
|
|
|
|
|
let mut input_iter = input.into_iter();
|
|
|
|
|
|
|
|
let (off, start_val) = if let Some(val) = fold {
|
|
|
|
(0, val)
|
|
|
|
} else if let Some(val) = input_iter.next() {
|
|
|
|
(1, val)
|
|
|
|
} else {
|
|
|
|
return Err(ShellError::SpannedLabeledError(
|
|
|
|
"Expected input".to_string(),
|
|
|
|
"needs input".to_string(),
|
|
|
|
span,
|
|
|
|
));
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok(input_iter
|
|
|
|
.enumerate()
|
|
|
|
.fold(start_val, move |acc, (idx, x)| {
|
|
|
|
stack.with_env(&orig_env_vars, &orig_env_hidden);
|
|
|
|
|
|
|
|
// if the acc coming from previous iter is indexed, drop the index
|
|
|
|
let acc = if let Value::Record { cols, vals, .. } = &acc {
|
|
|
|
if cols.len() == 2 && vals.len() == 2 {
|
|
|
|
if cols[0].eq("index") && cols[1].eq("item") {
|
|
|
|
vals[1].clone()
|
|
|
|
} else {
|
|
|
|
acc
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
acc
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
acc
|
|
|
|
};
|
|
|
|
|
|
|
|
if let Some(var) = block.signature.get_positional(0) {
|
|
|
|
if let Some(var_id) = &var.var_id {
|
|
|
|
let it = if numbered {
|
|
|
|
Value::Record {
|
2022-02-17 12:40:24 +01:00
|
|
|
cols: vec!["index".to_string(), "item".to_string()],
|
2022-01-08 01:40:40 +01:00
|
|
|
vals: vec![
|
|
|
|
Value::Int {
|
|
|
|
val: idx as i64 + off,
|
|
|
|
span,
|
|
|
|
},
|
|
|
|
x,
|
|
|
|
],
|
|
|
|
span,
|
|
|
|
}
|
|
|
|
} else {
|
2022-02-17 12:40:24 +01:00
|
|
|
x
|
2022-01-08 01:40:40 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
stack.add_var(*var_id, it);
|
|
|
|
}
|
|
|
|
}
|
2022-02-17 12:40:24 +01:00
|
|
|
if let Some(var) = block.signature.get_positional(1) {
|
|
|
|
if let Some(var_id) = &var.var_id {
|
|
|
|
stack.add_var(*var_id, acc);
|
|
|
|
}
|
|
|
|
}
|
2022-01-08 01:40:40 +01:00
|
|
|
|
|
|
|
let v = match eval_block(engine_state, &mut stack, block, PipelineData::new(span)) {
|
|
|
|
Ok(v) => v.into_value(span),
|
|
|
|
Err(error) => Value::Error { error },
|
|
|
|
};
|
|
|
|
|
|
|
|
if numbered {
|
|
|
|
// make sure the output is indexed
|
|
|
|
Value::Record {
|
|
|
|
cols: vec!["index".to_string(), "item".to_string()],
|
|
|
|
vals: vec![
|
|
|
|
Value::Int {
|
|
|
|
val: idx as i64 + off,
|
|
|
|
span,
|
|
|
|
},
|
|
|
|
v,
|
|
|
|
],
|
|
|
|
span,
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
v
|
|
|
|
}
|
|
|
|
})
|
2022-02-15 13:59:51 +01:00
|
|
|
.with_span(span)
|
2022-01-08 01:40:40 +01:00
|
|
|
.into_pipeline_data())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_examples() {
|
|
|
|
use crate::test_examples;
|
|
|
|
|
|
|
|
test_examples(Reduce {})
|
|
|
|
}
|
|
|
|
}
|