Skip to main content

nu_command/env/
export_env.rs

1use nu_engine::{command_prelude::*, get_eval_block, redirect_env};
2use nu_protocol::engine::CommandType;
3
4#[derive(Clone)]
5pub struct ExportEnv;
6
7impl Command for ExportEnv {
8    fn name(&self) -> &str {
9        "export-env"
10    }
11
12    fn signature(&self) -> Signature {
13        Signature::build("export-env")
14            .input_output_types(vec![(Type::Nothing, Type::Nothing)])
15            .required(
16                "block",
17                SyntaxShape::Block,
18                "The block to run to set the environment.",
19            )
20            .category(Category::Env)
21    }
22
23    fn description(&self) -> &str {
24        "Run a block and preserve its environment in a current scope."
25    }
26
27    fn extra_description(&self) -> &str {
28        "This command is a parser keyword. For details, check:
29  https://www.nushell.sh/book/thinking_in_nu.html"
30    }
31
32    fn command_type(&self) -> CommandType {
33        CommandType::Keyword
34    }
35
36    // Needed so IR retains the block Expression for `as_block()`.
37    fn requires_ast_for_arguments(&self) -> bool {
38        true
39    }
40
41    fn run(
42        &self,
43        engine_state: &EngineState,
44        caller_stack: &mut Stack,
45        call: &Call,
46        input: PipelineData,
47    ) -> Result<PipelineData, ShellError> {
48        let block_id = call
49            .positional_nth(caller_stack, 0)
50            .expect("checked through parser")
51            .as_block()
52            .expect("internal error: missing block");
53
54        let block = engine_state.get_block(block_id);
55        let mut callee_stack = caller_stack
56            .gather_captures(engine_state, &block.captures)
57            .reset_pipes();
58
59        let eval_block = get_eval_block(engine_state);
60
61        // Run the block (discard the result)
62        let _ = eval_block(engine_state, &mut callee_stack, block, input)?;
63
64        // Merge the block's environment to the current stack
65        redirect_env(engine_state, caller_stack, &callee_stack);
66
67        Ok(PipelineData::empty())
68    }
69
70    fn examples(&self) -> Vec<Example<'_>> {
71        vec![
72            Example {
73                description: "Set an environment variable.",
74                example: "export-env { $env.SPAM = 'eggs' }",
75                result: Some(Value::nothing(Span::test_data())),
76            },
77            Example {
78                description: "Set an environment variable and examine its value.",
79                example: "export-env { $env.SPAM = 'eggs' }; $env.SPAM",
80                result: Some(Value::test_string("eggs")),
81            },
82        ]
83    }
84}
85
86#[cfg(test)]
87mod test {
88    use super::*;
89
90    #[test]
91    fn test_examples() -> nu_test_support::Result {
92        nu_test_support::test().examples(ExportEnv)
93    }
94}