1use super::utils::chain_error_with_input;
2use nu_engine::{ClosureEval, ClosureEvalOnce, command_prelude::*};
3use nu_protocol::engine::Closure;
4
5#[derive(Clone)]
6pub struct Each;
7
8impl Command for Each {
9 fn name(&self) -> &str {
10 "each"
11 }
12
13 fn description(&self) -> &str {
14 "Run a closure on each row of the input list, creating a new list with the results."
15 }
16
17 fn extra_description(&self) -> &str {
18 r#"Since tables are lists of records, passing a table into 'each' will
19iterate over each record, not necessarily each cell within it.
20
21Avoid passing single records to this command. Since a record is a
22one-row structure, 'each' will only run once, behaving similar to 'do'.
23To iterate over a record's values, use 'items' or try converting it to a table
24with 'transpose' first."#
25 }
26
27 fn search_terms(&self) -> Vec<&str> {
28 vec!["for", "loop", "iterate", "map"]
29 }
30
31 fn signature(&self) -> nu_protocol::Signature {
32 Signature::build("each")
33 .input_output_types(vec![
34 (
35 Type::List(Box::new(Type::Any)),
36 Type::List(Box::new(Type::Any)),
37 ),
38 (Type::table(), Type::List(Box::new(Type::Any))),
39 (Type::Any, Type::Any),
40 ])
41 .required(
42 "closure",
43 SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
44 "The closure to run.",
45 )
46 .switch("keep-empty", "keep empty result cells", Some('k'))
47 .allow_variants_without_examples(true)
48 .category(Category::Filters)
49 }
50
51 fn examples(&self) -> Vec<Example> {
52 vec![
53 Example {
54 example: "[1 2 3] | each {|e| 2 * $e }",
55 description: "Multiplies elements in the list",
56 result: Some(Value::test_list(vec![
57 Value::test_int(2),
58 Value::test_int(4),
59 Value::test_int(6),
60 ])),
61 },
62 Example {
63 example: "{major:2, minor:1, patch:4} | values | each {|| into string }",
64 description: "Produce a list of values in the record, converted to string",
65 result: Some(Value::test_list(vec![
66 Value::test_string("2"),
67 Value::test_string("1"),
68 Value::test_string("4"),
69 ])),
70 },
71 Example {
72 example: r#"[1 2 3 2] | each {|e| if $e == 2 { "two" } }"#,
73 description: "'null' items will be dropped from the result list. It has the same effect as 'filter_map' in other languages.",
74 result: Some(Value::test_list(vec![
75 Value::test_string("two"),
76 Value::test_string("two"),
77 ])),
78 },
79 Example {
80 example: r#"[1 2 3] | enumerate | each {|e| if $e.item == 2 { $"found 2 at ($e.index)!"} }"#,
81 description: "Iterate over each element, producing a list showing indexes of any 2s",
82 result: Some(Value::test_list(vec![Value::test_string("found 2 at 1!")])),
83 },
84 Example {
85 example: r#"[1 2 3] | each --keep-empty {|e| if $e == 2 { "found 2!"} }"#,
86 description: "Iterate over each element, keeping null results",
87 result: Some(Value::test_list(vec![
88 Value::nothing(Span::test_data()),
89 Value::test_string("found 2!"),
90 Value::nothing(Span::test_data()),
91 ])),
92 },
93 ]
94 }
95
96 fn run(
97 &self,
98 engine_state: &EngineState,
99 stack: &mut Stack,
100 call: &Call,
101 input: PipelineData,
102 ) -> Result<PipelineData, ShellError> {
103 let head = call.head;
104 let closure: Closure = call.req(engine_state, stack, 0)?;
105 let keep_empty = call.has_flag(engine_state, stack, "keep-empty")?;
106
107 let metadata = input.metadata();
108 match input {
109 PipelineData::Empty => Ok(PipelineData::Empty),
110 PipelineData::Value(Value::Range { .. }, ..)
111 | PipelineData::Value(Value::List { .. }, ..)
112 | PipelineData::ListStream(..) => {
113 let mut closure = ClosureEval::new(engine_state, stack, closure);
114 Ok(input
115 .into_iter()
116 .map_while(move |value| {
117 let span = value.span();
118 let is_error = value.is_error();
119 match closure.run_with_value(value) {
120 Ok(PipelineData::ListStream(s, ..)) => {
121 let mut vals = vec![];
122 for v in s {
123 if let Value::Error { .. } = v {
124 return Some(v);
125 } else {
126 vals.push(v)
127 }
128 }
129 Some(Value::list(vals, span))
130 }
131 Ok(data) => Some(data.into_value(head).unwrap_or_else(|err| {
132 Value::error(chain_error_with_input(err, is_error, span), span)
133 })),
134 Err(error) => {
135 let error = chain_error_with_input(error, is_error, span);
136 Some(Value::error(error, span))
137 }
138 }
139 })
140 .into_pipeline_data(head, engine_state.signals().clone()))
141 }
142 PipelineData::ByteStream(stream, ..) => {
143 if let Some(chunks) = stream.chunks() {
144 let mut closure = ClosureEval::new(engine_state, stack, closure);
145 Ok(chunks
146 .map_while(move |value| {
147 let value = match value {
148 Ok(value) => value,
149 Err(err) => return Some(Value::error(err, head)),
150 };
151
152 let span = value.span();
153 let is_error = value.is_error();
154 match closure
155 .run_with_value(value)
156 .and_then(|data| data.into_value(head))
157 {
158 Ok(value) => Some(value),
159 Err(error) => {
160 let error = chain_error_with_input(error, is_error, span);
161 Some(Value::error(error, span))
162 }
163 }
164 })
165 .into_pipeline_data(head, engine_state.signals().clone()))
166 } else {
167 Ok(PipelineData::Empty)
168 }
169 }
170 PipelineData::Value(value, ..) => {
173 ClosureEvalOnce::new(engine_state, stack, closure).run_with_value(value)
174 }
175 }
176 .and_then(|x| {
177 x.filter(
178 move |x| if !keep_empty { !x.is_nothing() } else { true },
179 engine_state.signals(),
180 )
181 })
182 .map(|data| data.set_metadata(metadata))
183 }
184}
185
186#[cfg(test)]
187mod test {
188 use super::*;
189
190 #[test]
191 fn test_examples() {
192 use crate::test_examples;
193
194 test_examples(Each {})
195 }
196}