Skip to main content

nu_cmd_lang/core_commands/
use_.rs

1use nu_engine::{
2    command_prelude::*, find_in_dirs_env, get_dirs_var_from_call, get_eval_block, redirect_env,
3};
4use nu_protocol::{
5    ast::{Expr, Expression},
6    engine::CommandType,
7    shell_error::generic::GenericError,
8};
9
10#[derive(Clone)]
11pub struct Use;
12
13impl Command for Use {
14    fn name(&self) -> &str {
15        "use"
16    }
17
18    fn description(&self) -> &str {
19        "Use definitions from a module, making them available in your shell."
20    }
21
22    fn signature(&self) -> nu_protocol::Signature {
23        Signature::build("use")
24            .input_output_types(vec![(Type::Nothing, Type::Nothing)])
25            .allow_variants_without_examples(true)
26            .param(Parameter::Required(
27                PositionalArg::new(
28                    "module",
29                    SyntaxShape::OneOf(vec![SyntaxShape::String, SyntaxShape::Nothing]),
30                )
31                .desc("Module or module file (`null` for no-op).")
32                .completion(Completion::Builtin(BuiltinCompletion::NuFile {
33                    std_virtual_path: true,
34                })),
35            ))
36            .param(Parameter::Rest(
37                PositionalArg::new("members", SyntaxShape::Any)
38                    .desc("Which members of the module to import.")
39                    .completion(Completion::Builtin(BuiltinCompletion::ModuleExports)),
40            ))
41            .category(Category::Core)
42    }
43
44    fn search_terms(&self) -> Vec<&str> {
45        vec!["module", "import", "include", "scope"]
46    }
47
48    fn extra_description(&self) -> &str {
49        "See `help std` for the standard library module.
50See `help modules` to list all available modules.
51
52This command is a parser keyword. For details, check:
53  https://www.nushell.sh/book/thinking_in_nu.html"
54    }
55
56    fn command_type(&self) -> CommandType {
57        CommandType::Keyword
58    }
59
60    fn run(
61        &self,
62        engine_state: &EngineState,
63        caller_stack: &mut Stack,
64        call: &Call,
65        input: PipelineData,
66    ) -> Result<PipelineData, ShellError> {
67        if call.get_parser_info(caller_stack, "noop").is_some() {
68            return Ok(PipelineData::empty());
69        }
70        let Some(Expression {
71            expr: Expr::ImportPattern(import_pattern),
72            ..
73        }) = call.get_parser_info(caller_stack, "import_pattern")
74        else {
75            return Err(ShellError::Generic(GenericError::new(
76                "Unexpected import",
77                "import pattern not supported",
78                call.head,
79            )));
80        };
81
82        // Necessary so that we can modify the stack.
83        let import_pattern = import_pattern.clone();
84
85        if let Some(module_id) = import_pattern.head.id {
86            // Add constants
87            for var_id in &import_pattern.constants {
88                let var = engine_state.get_var(*var_id);
89
90                if let Some(constval) = &var.const_val {
91                    caller_stack.add_var(*var_id, constval.clone());
92                } else {
93                    return Err(ShellError::NushellFailedSpanned {
94                        msg: "Missing Constant".to_string(),
95                        label: "constant not added by the parser".to_string(),
96                        span: var.declaration_span,
97                    });
98                }
99            }
100
101            // Evaluate the export-env block if there is one
102            let module = engine_state.get_module(module_id);
103
104            if let Some(block_id) = module.env_block {
105                let block = engine_state.get_block(block_id);
106
107                // See if the module is a file
108                let module_arg_str = String::from_utf8_lossy(
109                    engine_state.get_span_contents(import_pattern.head.span),
110                );
111
112                let maybe_file_path_or_dir = find_in_dirs_env(
113                    &module_arg_str,
114                    engine_state,
115                    caller_stack,
116                    get_dirs_var_from_call(caller_stack, call),
117                )?;
118                // module_arg_str maybe a directory, in this case
119                // find_in_dirs_env returns a directory.
120                let maybe_parent = maybe_file_path_or_dir.as_ref().and_then(|path| {
121                    if path.is_dir() {
122                        Some(path.to_path_buf())
123                    } else {
124                        path.parent().map(|p| p.to_path_buf())
125                    }
126                });
127
128                let mut callee_stack = caller_stack
129                    .gather_captures(engine_state, &block.captures)
130                    .reset_pipes();
131
132                // If so, set the currently evaluated directory (file-relative PWD)
133                if let Some(parent) = maybe_parent {
134                    let file_pwd = Value::string(parent.to_string_lossy(), call.head);
135                    callee_stack.add_env_var("FILE_PWD".to_string(), file_pwd);
136                }
137
138                if let Some(path) = maybe_file_path_or_dir {
139                    let module_file_path = if path.is_dir() {
140                        // the existence of `mod.nu` is verified in parsing time
141                        // so it's safe to use it here.
142                        Value::string(path.join("mod.nu").to_string_lossy(), call.head)
143                    } else {
144                        Value::string(path.to_string_lossy(), call.head)
145                    };
146                    callee_stack.add_env_var("CURRENT_FILE".to_string(), module_file_path);
147                }
148
149                let eval_block = get_eval_block(engine_state);
150
151                // Run the block (discard the result)
152                let _ = eval_block(engine_state, &mut callee_stack, block, input)?;
153
154                // Merge the block's environment to the current stack
155                redirect_env(engine_state, caller_stack, &callee_stack);
156            }
157        } else {
158            return Err(ShellError::Generic(GenericError::new(
159                format!(
160                    "Could not import from '{}'",
161                    String::from_utf8_lossy(&import_pattern.head.name)
162                ),
163                "module does not exist",
164                import_pattern.head.span,
165            )));
166        }
167
168        Ok(PipelineData::empty())
169    }
170
171    fn examples(&self) -> Vec<Example<'_>> {
172        vec![
173            Example {
174                description: "Define a custom command in a module and call it.",
175                example: r#"module spam { export def foo [] { "foo" } }; use spam foo; foo"#,
176                result: Some(Value::test_string("foo")),
177            },
178            Example {
179                description: "Define a custom command that participates in the environment in a module and call it.",
180                example: r#"module foo { export def --env bar [] { $env.FOO_BAR = "BAZ" } }; use foo bar; bar; $env.FOO_BAR"#,
181                result: Some(Value::test_string("BAZ")),
182            },
183            Example {
184                description: "Use a plain module name to import its definitions qualified by the module name.",
185                example: r#"module spam { export def foo [] { "foo" }; export def bar [] { "bar" } }; use spam; (spam foo) + (spam bar)"#,
186                result: Some(Value::test_string("foobar")),
187            },
188            Example {
189                description: "Specify * to use all definitions in a module.",
190                example: r#"module spam { export def foo [] { "foo" }; export def bar [] { "bar" } }; use spam *; (foo) + (bar)"#,
191                result: Some(Value::test_string("foobar")),
192            },
193            Example {
194                description: "To use commands with spaces, like subcommands, surround them with quotes.",
195                example: r#"module spam { export def 'foo bar' [] { "baz" } }; use spam 'foo bar'; foo bar"#,
196                result: Some(Value::test_string("baz")),
197            },
198            Example {
199                description: "To use multiple definitions from a module, wrap them in a list.",
200                example: r#"module spam { export def foo [] { "foo" }; export def 'foo bar' [] { "baz" } }; use spam ['foo', 'foo bar']; (foo) + (foo bar)"#,
201                result: Some(Value::test_string("foobaz")),
202            },
203        ]
204    }
205}
206
207#[cfg(test)]
208mod test {
209    #[test]
210    fn test_examples() -> nu_test_support::Result {
211        use super::Use;
212        nu_test_support::test().examples(Use)
213    }
214}