1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
use super::utils::chain_error_with_input;
use nu_engine::{eval_block, CallExt};
use nu_protocol::ast::Call;
use nu_protocol::engine::{Closure, Command, EngineState, Stack};
use nu_protocol::{
    Category, Example, IntoInterruptiblePipelineData, IntoPipelineData, PipelineData, ShellError,
    Signature, Span, SyntaxShape, Type, Value,
};

#[derive(Clone)]
pub struct Where;

impl Command for Where {
    fn name(&self) -> &str {
        "where"
    }

    fn usage(&self) -> &str {
        "Filter values based on a condition."
    }

    fn signature(&self) -> nu_protocol::Signature {
        Signature::build("where")
            .input_output_types(vec![
                (
                    Type::List(Box::new(Type::Any)),
                    Type::List(Box::new(Type::Any)),
                ),
                (Type::Table(vec![]), Type::Table(vec![])),
            ])
            .optional("cond", SyntaxShape::RowCondition, "condition")
            .named(
                "closure",
                SyntaxShape::Closure(Some(vec![SyntaxShape::Any, SyntaxShape::Int])),
                "use with a closure instead",
                Some('b'),
            )
            .category(Category::Filters)
    }

    fn search_terms(&self) -> Vec<&str> {
        vec!["filter", "find", "search", "condition"]
    }

    fn run(
        &self,
        engine_state: &EngineState,
        stack: &mut Stack,
        call: &Call,
        input: PipelineData,
    ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
        if let Ok(Some(capture_block)) = call.get_flag::<Closure>(engine_state, stack, "block") {
            let metadata = input.metadata();
            let ctrlc = engine_state.ctrlc.clone();
            let engine_state = engine_state.clone();
            let block = engine_state.get_block(capture_block.block_id).clone();
            let mut stack = stack.captures_to_stack(&capture_block.captures);
            let orig_env_vars = stack.env_vars.clone();
            let orig_env_hidden = stack.env_hidden.clone();
            let span = call.head;
            let redirect_stdout = call.redirect_stdout;
            let redirect_stderr = call.redirect_stderr;

            match input {
                PipelineData::Value(Value::Range { .. }, ..)
                | PipelineData::Value(Value::List { .. }, ..)
                | PipelineData::ListStream { .. } => Ok(input
                    // To enumerate over the input (for the index argument),
                    // it must be converted into an iterator using into_iter().
                    .into_iter()
                    .enumerate()
                    .filter_map(move |(idx, x)| {
                        // with_env() is used here to ensure that each iteration uses
                        // a different set of environment variables.
                        // Hence, a 'cd' in the first loop won't affect the next loop.
                        stack.with_env(&orig_env_vars, &orig_env_hidden);

                        if let Some(var) = block.signature.get_positional(0) {
                            if let Some(var_id) = &var.var_id {
                                stack.add_var(*var_id, x.clone());
                            }
                        }
                        // Optional index argument
                        if let Some(var) = block.signature.get_positional(1) {
                            if let Some(var_id) = &var.var_id {
                                stack.add_var(
                                    *var_id,
                                    Value::Int {
                                        val: idx as i64,
                                        span,
                                    },
                                );
                            }
                        }

                        match eval_block(
                            &engine_state,
                            &mut stack,
                            &block,
                            // clone() is used here because x is given to Ok() below.
                            x.clone().into_pipeline_data(),
                            redirect_stdout,
                            redirect_stderr,
                        ) {
                            Ok(v) => {
                                if v.into_value(span).is_true() {
                                    Some(x)
                                } else {
                                    None
                                }
                            }
                            Err(error) => Some(Value::Error {
                                error: chain_error_with_input(error, x.span()),
                            }),
                        }
                    })
                    .into_pipeline_data(ctrlc)),
                PipelineData::ExternalStream { stdout: None, .. } => {
                    Ok(PipelineData::new(call.head))
                }
                PipelineData::ExternalStream {
                    stdout: Some(stream),
                    ..
                } => Ok(stream
                    .into_iter()
                    .enumerate()
                    .filter_map(move |(idx, x)| {
                        // see note above about with_env()
                        stack.with_env(&orig_env_vars, &orig_env_hidden);

                        let x = match x {
                            Ok(x) => x,
                            Err(err) => return Some(Value::Error { error: err }),
                        };

                        if let Some(var) = block.signature.get_positional(0) {
                            if let Some(var_id) = &var.var_id {
                                stack.add_var(*var_id, x.clone());
                            }
                        }
                        // Optional index argument
                        if let Some(var) = block.signature.get_positional(1) {
                            if let Some(var_id) = &var.var_id {
                                stack.add_var(
                                    *var_id,
                                    Value::Int {
                                        val: idx as i64,
                                        span,
                                    },
                                );
                            }
                        }

                        match eval_block(
                            &engine_state,
                            &mut stack,
                            &block,
                            // clone() is used here because x is given to Ok() below.
                            x.clone().into_pipeline_data(),
                            redirect_stdout,
                            redirect_stderr,
                        ) {
                            Ok(v) => {
                                if v.into_value(span).is_true() {
                                    Some(x)
                                } else {
                                    None
                                }
                            }
                            Err(error) => Some(Value::Error {
                                error: chain_error_with_input(error, x.span()),
                            }),
                        }
                    })
                    .into_pipeline_data(ctrlc)),
                // This match allows non-iterables to be accepted,
                // which is currently considered undesirable (Nov 2022).
                PipelineData::Value(x, ..) => {
                    // see note above about with_env()
                    stack.with_env(&orig_env_vars, &orig_env_hidden);

                    if let Some(var) = block.signature.get_positional(0) {
                        if let Some(var_id) = &var.var_id {
                            stack.add_var(*var_id, x.clone());
                        }
                    }
                    Ok(match eval_block(
                        &engine_state,
                        &mut stack,
                        &block,
                        // clone() is used here because x is given to Ok() below.
                        x.clone().into_pipeline_data(),
                        redirect_stdout,
                        redirect_stderr,
                    ) {
                        Ok(v) => {
                            if v.into_value(span).is_true() {
                                Some(x)
                            } else {
                                None
                            }
                        }
                        Err(error) => Some(Value::Error {
                            error: chain_error_with_input(error, x.span()),
                        }),
                    }
                    .into_pipeline_data(ctrlc))
                }
            }
            .map(|x| x.set_metadata(metadata))
        } else {
            let capture_block: Option<Closure> = call.opt(engine_state, stack, 0)?;
            if let Some(block) = capture_block {
                let span = call.head;

                let metadata = input.metadata();
                let mut stack = stack.captures_to_stack(&block.captures);
                let block = engine_state.get_block(block.block_id).clone();

                let orig_env_vars = stack.env_vars.clone();
                let orig_env_hidden = stack.env_hidden.clone();

                let ctrlc = engine_state.ctrlc.clone();
                let engine_state = engine_state.clone();

                let redirect_stdout = call.redirect_stdout;
                let redirect_stderr = call.redirect_stderr;
                Ok(input
                    .into_iter()
                    .enumerate()
                    .filter_map(move |(idx, value)| {
                        stack.with_env(&orig_env_vars, &orig_env_hidden);

                        if let Some(var) = block.signature.get_positional(0) {
                            if let Some(var_id) = &var.var_id {
                                stack.add_var(*var_id, value.clone());
                            }
                        }
                        // Optional index argument
                        if let Some(var) = block.signature.get_positional(1) {
                            if let Some(var_id) = &var.var_id {
                                stack.add_var(
                                    *var_id,
                                    Value::Int {
                                        val: idx as i64,
                                        span,
                                    },
                                );
                            }
                        }
                        let result = eval_block(
                            &engine_state,
                            &mut stack,
                            &block,
                            // clone() is used here because x is given to Ok() below.
                            value.clone().into_pipeline_data(),
                            redirect_stdout,
                            redirect_stderr,
                        );

                        match result {
                            Ok(result) => {
                                let result = result.into_value(span);
                                if result.is_true() {
                                    Some(value)
                                } else {
                                    None
                                }
                            }
                            Err(err) => Some(Value::Error { error: err }),
                        }
                    })
                    .into_pipeline_data(ctrlc))
                .map(|x| x.set_metadata(metadata))
            } else {
                Err(ShellError::MissingParameter(
                    "condition".to_string(),
                    call.head,
                ))
            }
        }
    }

    fn examples(&self) -> Vec<Example> {
        vec![
            Example {
                description: "Filter rows of a table according to a condition",
                example: "[{a: 1} {a: 2}] | where a > 1",
                result: Some(Value::List {
                    vals: vec![Value::Record {
                        cols: vec!["a".to_string()],
                        vals: vec![Value::test_int(2)],
                        span: Span::test_data(),
                    }],
                    span: Span::test_data(),
                }),
            },
            Example {
                description: "Filter items of a list according to a condition",
                example: "[1 2] | where {|x| $x > 1}",
                result: Some(Value::List {
                    vals: vec![Value::test_int(2)],
                    span: Span::test_data(),
                }),
            },
            Example {
                description: "List all files in the current directory with sizes greater than 2kb",
                example: "ls | where size > 2kb",
                result: None,
            },
            Example {
                description: "List only the files in the current directory",
                example: "ls | where type == file",
                result: None,
            },
            Example {
                description: "List all files with names that contain \"Car\"",
                example: "ls | where name =~ \"Car\"",
                result: None,
            },
            Example {
                description: "List all files that were modified in the last two weeks",
                example: "ls | where modified >= (date now) - 2wk",
                result: None,
            },
            // TODO: This should work but does not. (Note that `Let` must be present in the working_set in `example_test.rs`).
            // See https://github.com/nushell/nushell/issues/7034
            // Example {
            //     description: "List all numbers above 3, using an existing closure condition",
            //     example: "let a = {$in > 3}; [1, 2, 5, 6] | where -b $a",
            //     result: Some(Value::List {
            //         vals: vec![
            //             Value::Int {
            //                 val: 5,
            //                 span: Span::test_data(),
            //             },
            //             Value::Int {
            //                 val: 6,
            //                 span: Span::test_data(),
            //             },
            //         ],
            //         span: Span::test_data(),
            //     }),
            // },
        ]
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_examples() {
        use crate::test_examples;

        test_examples(Where {})
    }
}