Skip to main content

nu_cmd_lang/core_commands/
hide_env.rs

1use nu_engine::command_prelude::*;
2use nu_protocol::did_you_mean;
3
4#[derive(Clone)]
5pub struct HideEnv;
6
7impl Command for HideEnv {
8    fn name(&self) -> &str {
9        "hide-env"
10    }
11
12    fn signature(&self) -> nu_protocol::Signature {
13        Signature::build("hide-env")
14            .input_output_types(vec![(Type::Nothing, Type::Nothing)])
15            .rest(
16                "name",
17                SyntaxShape::String,
18                "Environment variable names to hide.",
19            )
20            .switch(
21                "ignore-errors",
22                "Do not throw an error if an environment variable was not found.",
23                Some('i'),
24            )
25            .category(Category::Core)
26    }
27
28    fn description(&self) -> &str {
29        "Hide environment variables in the current scope."
30    }
31
32    fn search_terms(&self) -> Vec<&str> {
33        vec!["unset", "drop"]
34    }
35
36    fn run(
37        &self,
38        engine_state: &EngineState,
39        stack: &mut Stack,
40        call: &Call,
41        _input: PipelineData,
42    ) -> Result<PipelineData, ShellError> {
43        let env_var_names: Vec<Spanned<String>> = call.rest(engine_state, stack, 0)?;
44        let ignore_errors = call.has_flag(engine_state, stack, "ignore-errors")?;
45
46        for name in env_var_names {
47            if !stack.hide_env_var(engine_state, &name.item) && !ignore_errors {
48                let all_names = stack.get_env_var_names(engine_state);
49
50                // Do not produce a suggestion for exact-name misses (for example when an outer
51                // scope still has the same variable name). Those cases should remain a plain
52                // not-found error for this scope.
53                let closest_match = if all_names.contains(&name.item) {
54                    None
55                } else {
56                    did_you_mean(&all_names, &name.item)
57                };
58
59                if let Some(closest_match) = closest_match {
60                    return Err(ShellError::DidYouMeanCustom {
61                        msg: format!("Environment variable '{}' not found", name.item),
62                        suggestion: closest_match,
63                        span: name.span,
64                    });
65                }
66
67                return Err(ShellError::EnvVarNotFoundAtRuntime {
68                    envvar_name: name.item,
69                    span: name.span,
70                });
71            }
72        }
73
74        Ok(PipelineData::empty())
75    }
76
77    fn examples(&self) -> Vec<Example<'_>> {
78        vec![Example {
79            description: "Hide an environment variable.",
80            example: "$env.HZ_ENV_ABC = 1; hide-env HZ_ENV_ABC; 'HZ_ENV_ABC' in $env",
81            result: Some(Value::test_bool(false)),
82        }]
83    }
84}