nu_cmd_lang/core_commands/
export_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};
8
9#[derive(Clone)]
10pub struct ExportUse;
11
12impl Command for ExportUse {
13    fn name(&self) -> &str {
14        "export use"
15    }
16
17    fn description(&self) -> &str {
18        "Use definitions from a module and export them from this module."
19    }
20
21    fn signature(&self) -> nu_protocol::Signature {
22        Signature::build("export use")
23            .input_output_types(vec![(Type::Nothing, Type::Nothing)])
24            .required("module", SyntaxShape::String, "Module or module file.")
25            .rest(
26                "members",
27                SyntaxShape::Any,
28                "Which members of the module to import.",
29            )
30            .category(Category::Core)
31    }
32
33    fn extra_description(&self) -> &str {
34        r#"This command is a parser keyword. For details, check:
35  https://www.nushell.sh/book/thinking_in_nu.html"#
36    }
37
38    fn command_type(&self) -> CommandType {
39        CommandType::Keyword
40    }
41
42    fn run(
43        &self,
44        engine_state: &EngineState,
45        caller_stack: &mut Stack,
46        call: &Call,
47        input: PipelineData,
48    ) -> Result<PipelineData, ShellError> {
49        if call.get_parser_info(caller_stack, "noop").is_some() {
50            return Ok(PipelineData::empty());
51        }
52        let Some(Expression {
53            expr: Expr::ImportPattern(import_pattern),
54            ..
55        }) = call.get_parser_info(caller_stack, "import_pattern")
56        else {
57            return Err(ShellError::GenericError {
58                error: "Unexpected import".into(),
59                msg: "import pattern not supported".into(),
60                span: Some(call.head),
61                help: None,
62                inner: vec![],
63            });
64        };
65
66        // Necessary so that we can modify the stack.
67        let import_pattern = import_pattern.clone();
68
69        if let Some(module_id) = import_pattern.head.id {
70            // Add constants
71            for var_id in &import_pattern.constants {
72                let var = engine_state.get_var(*var_id);
73
74                if let Some(constval) = &var.const_val {
75                    caller_stack.add_var(*var_id, constval.clone());
76                } else {
77                    return Err(ShellError::NushellFailedSpanned {
78                        msg: "Missing Constant".to_string(),
79                        label: "constant not added by the parser".to_string(),
80                        span: var.declaration_span,
81                    });
82                }
83            }
84
85            // Evaluate the export-env block if there is one
86            let module = engine_state.get_module(module_id);
87
88            if let Some(block_id) = module.env_block {
89                let block = engine_state.get_block(block_id);
90
91                // See if the module is a file
92                let module_arg_str = String::from_utf8_lossy(
93                    engine_state.get_span_contents(import_pattern.head.span),
94                );
95
96                let maybe_file_path_or_dir = find_in_dirs_env(
97                    &module_arg_str,
98                    engine_state,
99                    caller_stack,
100                    get_dirs_var_from_call(caller_stack, call),
101                )?;
102                // module_arg_str maybe a directory, in this case
103                // find_in_dirs_env returns a directory.
104                let maybe_parent = maybe_file_path_or_dir.as_ref().and_then(|path| {
105                    if path.is_dir() {
106                        Some(path.to_path_buf())
107                    } else {
108                        path.parent().map(|p| p.to_path_buf())
109                    }
110                });
111
112                let mut callee_stack = caller_stack
113                    .gather_captures(engine_state, &block.captures)
114                    .reset_pipes();
115
116                // If so, set the currently evaluated directory (file-relative PWD)
117                if let Some(parent) = maybe_parent {
118                    let file_pwd = Value::string(parent.to_string_lossy(), call.head);
119                    callee_stack.add_env_var("FILE_PWD".to_string(), file_pwd);
120                }
121
122                if let Some(path) = maybe_file_path_or_dir {
123                    let module_file_path = if path.is_dir() {
124                        // the existence of `mod.nu` is verified in parsing time
125                        // so it's safe to use it here.
126                        Value::string(path.join("mod.nu").to_string_lossy(), call.head)
127                    } else {
128                        Value::string(path.to_string_lossy(), call.head)
129                    };
130                    callee_stack.add_env_var("CURRENT_FILE".to_string(), module_file_path);
131                }
132
133                let eval_block = get_eval_block(engine_state);
134
135                // Run the block (discard the result)
136                let _ = eval_block(engine_state, &mut callee_stack, block, input)?;
137
138                // Merge the block's environment to the current stack
139                redirect_env(engine_state, caller_stack, &callee_stack);
140            }
141        } else {
142            return Err(ShellError::GenericError {
143                error: format!(
144                    "Could not import from '{}'",
145                    String::from_utf8_lossy(&import_pattern.head.name)
146                ),
147                msg: "module does not exist".to_string(),
148                span: Some(import_pattern.head.span),
149                help: None,
150                inner: vec![],
151            });
152        }
153
154        Ok(PipelineData::empty())
155    }
156
157    fn examples(&self) -> Vec<Example<'_>> {
158        vec![Example {
159            description: "Re-export a command from another module",
160            example: r#"module spam { export def foo [] { "foo" } }
161    module eggs { export use spam foo }
162    use eggs foo
163    foo
164            "#,
165            result: Some(Value::test_string("foo")),
166        }]
167    }
168
169    fn search_terms(&self) -> Vec<&str> {
170        vec!["reexport", "import", "module"]
171    }
172}