nu_command/filters/
each.rs

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            Example {
94                example: r#"$env.name? | each { $"hello ($in)" } | default "bye""#,
95                description: "Update value if not null, otherwise do nothing",
96                result: None,
97            },
98        ]
99    }
100
101    fn run(
102        &self,
103        engine_state: &EngineState,
104        stack: &mut Stack,
105        call: &Call,
106        input: PipelineData,
107    ) -> Result<PipelineData, ShellError> {
108        let head = call.head;
109        let closure: Closure = call.req(engine_state, stack, 0)?;
110        let keep_empty = call.has_flag(engine_state, stack, "keep-empty")?;
111
112        let metadata = input.metadata();
113        match input {
114            PipelineData::Empty => Ok(PipelineData::empty()),
115            PipelineData::Value(Value::Nothing { .. }, ..) => Ok(input),
116            PipelineData::Value(Value::Range { .. }, ..)
117            | PipelineData::Value(Value::List { .. }, ..)
118            | PipelineData::ListStream(..) => {
119                let mut closure = ClosureEval::new(engine_state, stack, closure);
120                Ok(input
121                    .into_iter()
122                    .map_while(move |value| {
123                        let span = value.span();
124                        let is_error = value.is_error();
125                        match closure.run_with_value(value) {
126                            Ok(PipelineData::ListStream(s, ..)) => {
127                                let mut vals = vec![];
128                                for v in s {
129                                    if let Value::Error { .. } = v {
130                                        return Some(v);
131                                    } else {
132                                        vals.push(v)
133                                    }
134                                }
135                                Some(Value::list(vals, span))
136                            }
137                            Ok(data) => Some(data.into_value(head).unwrap_or_else(|err| {
138                                Value::error(chain_error_with_input(err, is_error, span), span)
139                            })),
140                            Err(error) => {
141                                let error = chain_error_with_input(error, is_error, span);
142                                Some(Value::error(error, span))
143                            }
144                        }
145                    })
146                    .into_pipeline_data(head, engine_state.signals().clone()))
147            }
148            PipelineData::ByteStream(stream, ..) => {
149                if let Some(chunks) = stream.chunks() {
150                    let mut closure = ClosureEval::new(engine_state, stack, closure);
151                    Ok(chunks
152                        .map_while(move |value| {
153                            let value = match value {
154                                Ok(value) => value,
155                                Err(err) => return Some(Value::error(err, head)),
156                            };
157
158                            let span = value.span();
159                            let is_error = value.is_error();
160                            match closure
161                                .run_with_value(value)
162                                .and_then(|data| data.into_value(head))
163                            {
164                                Ok(value) => Some(value),
165                                Err(error) => {
166                                    let error = chain_error_with_input(error, is_error, span);
167                                    Some(Value::error(error, span))
168                                }
169                            }
170                        })
171                        .into_pipeline_data(head, engine_state.signals().clone()))
172                } else {
173                    Ok(PipelineData::empty())
174                }
175            }
176            // This match allows non-iterables to be accepted,
177            // which is currently considered undesirable (Nov 2022).
178            PipelineData::Value(value, ..) => {
179                ClosureEvalOnce::new(engine_state, stack, closure).run_with_value(value)
180            }
181        }
182        .and_then(|x| {
183            x.filter(
184                move |x| if !keep_empty { !x.is_nothing() } else { true },
185                engine_state.signals(),
186            )
187        })
188        .map(|data| data.set_metadata(metadata))
189    }
190}
191
192#[cfg(test)]
193mod test {
194    use super::*;
195
196    #[test]
197    fn test_examples() {
198        use crate::test_examples;
199
200        test_examples(Each {})
201    }
202}