nu_command/filters/
filter.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::{DeprecationEntry, DeprecationType, ReportMode};
3
4#[derive(Clone)]
5pub struct Filter;
6
7impl Command for Filter {
8    fn name(&self) -> &str {
9        "filter"
10    }
11
12    fn description(&self) -> &str {
13        "Filter values based on a predicate closure."
14    }
15
16    fn extra_description(&self) -> &str {
17        r#"This command works similar to 'where' but can only use a closure as a predicate.
18The "row condition" syntax is not supported."#
19    }
20
21    fn signature(&self) -> nu_protocol::Signature {
22        Signature::build("filter")
23            .input_output_types(vec![
24                (
25                    Type::List(Box::new(Type::Any)),
26                    Type::List(Box::new(Type::Any)),
27                ),
28                (Type::Range, Type::List(Box::new(Type::Any))),
29            ])
30            .required(
31                "closure",
32                SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
33                "Predicate closure.",
34            )
35            .category(Category::Filters)
36    }
37
38    fn search_terms(&self) -> Vec<&str> {
39        vec!["where", "find", "search", "condition"]
40    }
41
42    fn run(
43        &self,
44        engine_state: &EngineState,
45        stack: &mut Stack,
46        call: &Call,
47        input: PipelineData,
48    ) -> Result<PipelineData, ShellError> {
49        use super::where_::Where;
50        <Where as Command>::run(&Where, engine_state, stack, call, input)
51    }
52
53    fn deprecation_info(&self) -> Vec<nu_protocol::DeprecationEntry> {
54        vec![
55            DeprecationEntry {
56                ty: DeprecationType::Command,
57                report_mode: ReportMode::FirstUse,
58                since: Some("0.105.0".into()),
59                expected_removal: None,
60                help: Some("`where` command can be used instead, as it can now read the predicate closure from a variable".into()),
61            }
62        ]
63    }
64
65    fn examples(&self) -> Vec<Example<'_>> {
66        vec![
67            Example {
68                description: "Filter items of a list according to a condition",
69                example: "[1 2] | filter {|x| $x > 1}",
70                result: Some(Value::test_list(vec![Value::test_int(2)])),
71            },
72            Example {
73                description: "Filter rows of a table according to a condition",
74                example: "[{a: 1} {a: 2}] | filter {|x| $x.a > 1}",
75                result: Some(Value::test_list(vec![Value::test_record(record! {
76                    "a" => Value::test_int(2),
77                })])),
78            },
79            Example {
80                description: "Filter rows of a table according to a stored condition",
81                example: "let cond = {|x| $x.a > 1}; [{a: 1} {a: 2}] | filter $cond",
82                result: Some(Value::test_list(vec![Value::test_record(record! {
83                    "a" => Value::test_int(2),
84                })])),
85            },
86            Example {
87                description: "Filter items of a range according to a condition",
88                example: "9..13 | filter {|el| $el mod 2 != 0}",
89                result: Some(Value::test_list(vec![
90                    Value::test_int(9),
91                    Value::test_int(11),
92                    Value::test_int(13),
93                ])),
94            },
95            Example {
96                description: "List all numbers above 3, using an existing closure condition",
97                example: "let a = {$in > 3}; [1, 2, 5, 6] | filter $a",
98                result: None, // TODO: This should work
99                              // result: Some(Value::test_list(
100                              //     vec![
101                              //         Value::Int {
102                              //             val: 5,
103                              //             Span::test_data(),
104                              //         },
105                              //         Value::Int {
106                              //             val: 6,
107                              //             span: Span::test_data(),
108                              //         },
109                              //     ],
110                              // }),
111            },
112        ]
113    }
114}
115
116#[cfg(test)]
117mod test {
118    use super::*;
119
120    #[test]
121    fn test_examples() {
122        use crate::test_examples;
123
124        test_examples(Filter {})
125    }
126}