nu_command/filters/
all.rs

1use super::utils;
2use nu_engine::command_prelude::*;
3
4#[derive(Clone)]
5pub struct All;
6
7impl Command for All {
8    fn name(&self) -> &str {
9        "all"
10    }
11
12    fn signature(&self) -> Signature {
13        Signature::build(self.name())
14            .input_output_types(vec![(Type::List(Box::new(Type::Any)), Type::Bool)])
15            .required(
16                "predicate",
17                SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
18                "A closure that must evaluate to a boolean.",
19            )
20            .category(Category::Filters)
21    }
22
23    fn description(&self) -> &str {
24        "Test if every element of the input fulfills a predicate expression."
25    }
26
27    fn search_terms(&self) -> Vec<&str> {
28        vec!["every", "and"]
29    }
30
31    fn examples(&self) -> Vec<Example> {
32        vec![
33            Example {
34                description: "Check if a list contains only true values",
35                example: "[false true true false] | all {}",
36                result: Some(Value::test_bool(false)),
37            },
38            Example {
39                description: "Check if each row's status is the string 'UP'",
40                example: "[[status]; [UP] [UP]] | all {|el| $el.status == UP }",
41                result: Some(Value::test_bool(true)),
42            },
43            Example {
44                description: "Check that each item is a string",
45                example: "[foo bar 2 baz] | all {|| ($in | describe) == 'string' }",
46                result: Some(Value::test_bool(false)),
47            },
48            Example {
49                description: "Check that all values are equal to twice their index",
50                example: "[0 2 4 6] | enumerate | all {|i| $i.item == $i.index * 2 }",
51                result: Some(Value::test_bool(true)),
52            },
53            Example {
54                description: "Check that all of the values are even, using a stored closure",
55                example: "let cond = {|el| ($el mod 2) == 0 }; [2 4 6 8] | all $cond",
56                result: Some(Value::test_bool(true)),
57            },
58        ]
59    }
60
61    fn run(
62        &self,
63        engine_state: &EngineState,
64        stack: &mut Stack,
65        call: &Call,
66        input: PipelineData,
67    ) -> Result<PipelineData, ShellError> {
68        utils::boolean_fold(engine_state, stack, call, input, false)
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn test_examples() {
78        use crate::test_examples;
79
80        test_examples(All)
81    }
82}