nu_cmd_lang/core_commands/
let_.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::engine::CommandType;
3
4#[derive(Clone)]
5pub struct Let;
6
7impl Command for Let {
8    fn name(&self) -> &str {
9        "let"
10    }
11
12    fn description(&self) -> &str {
13        "Create a variable and give it a value."
14    }
15
16    fn signature(&self) -> nu_protocol::Signature {
17        Signature::build("let")
18            .input_output_types(vec![(Type::Any, Type::Nothing)])
19            .allow_variants_without_examples(true)
20            .required("var_name", SyntaxShape::VarWithOptType, "Variable name.")
21            .required(
22                "initial_value",
23                SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::MathExpression)),
24                "Equals sign followed by value.",
25            )
26            .category(Category::Core)
27    }
28
29    fn extra_description(&self) -> &str {
30        r#"This command is a parser keyword. For details, check:
31  https://www.nushell.sh/book/thinking_in_nu.html"#
32    }
33
34    fn command_type(&self) -> CommandType {
35        CommandType::Keyword
36    }
37
38    fn search_terms(&self) -> Vec<&str> {
39        vec!["set", "const"]
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        // This is compiled specially by the IR compiler. The code here is never used when
50        // running in IR mode.
51        eprintln!(
52            "Tried to execute 'run' for the 'let' command: this code path should never be reached in IR mode"
53        );
54        unreachable!()
55    }
56
57    fn examples(&self) -> Vec<Example<'_>> {
58        vec![
59            Example {
60                description: "Set a variable to a value",
61                example: "let x = 10",
62                result: None,
63            },
64            Example {
65                description: "Set a variable to the result of an expression",
66                example: "let x = 10 + 100",
67                result: None,
68            },
69            Example {
70                description: "Set a variable based on the condition",
71                example: "let x = if false { -1 } else { 1 }",
72                result: None,
73            },
74        ]
75    }
76}
77
78#[cfg(test)]
79mod test {
80    use nu_protocol::engine::CommandType;
81
82    use super::*;
83
84    #[test]
85    fn test_examples() {
86        use crate::test_examples;
87
88        test_examples(Let {})
89    }
90
91    #[test]
92    fn test_command_type() {
93        assert!(matches!(Let.command_type(), CommandType::Keyword));
94    }
95}