From 474293bf1cfe1efdf1312de93710f2b741e5260a Mon Sep 17 00:00:00 2001 From: Ian Manske Date: Sun, 19 May 2024 15:35:07 +0000 Subject: [PATCH] Clear environment for child `Command`s (#12901) # Description There is a bug when `hide-env` is used on environment variables that were present at shell startup. Namely, child processes still inherit the hidden environment variable. This PR fixes #12900, fixes #11495, and fixes #7937. # Tests + Formatting Added a test. --- crates/nu-command/src/system/run_external.rs | 4 ++++ tests/shell/environment/env.rs | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/crates/nu-command/src/system/run_external.rs b/crates/nu-command/src/system/run_external.rs index 2941d80de3b..b12b89263c5 100644 --- a/crates/nu-command/src/system/run_external.rs +++ b/crates/nu-command/src/system/run_external.rs @@ -530,6 +530,9 @@ impl ExternalCommand { } /// Spawn a command without shelling out to an external shell + /// + /// Note that this function will not set the cwd or environment variables. + /// It only creates the command and adds arguments. pub fn spawn_simple_command(&self, cwd: &str) -> Result { let (head, _, _) = trim_enclosing_quotes(&self.name.item); let head = nu_path::expand_to_real_path(head) @@ -537,6 +540,7 @@ impl ExternalCommand { .to_string(); let mut process = std::process::Command::new(head); + process.env_clear(); for (arg, arg_keep_raw) in self.args.iter().zip(self.arg_keep_raw.iter()) { trim_expand_and_apply_arg(&mut process, arg, arg_keep_raw, cwd); diff --git a/tests/shell/environment/env.rs b/tests/shell/environment/env.rs index 7061761c705..74736415a37 100644 --- a/tests/shell/environment/env.rs +++ b/tests/shell/environment/env.rs @@ -126,6 +126,15 @@ fn passes_with_env_env_var_to_external_process() { assert_eq!(actual.out, "foo"); } +#[test] +fn hides_environment_from_child() { + let actual = nu!(r#" + $env.TEST = 1; ^$nu.current-exe -c "hide-env TEST; ^$nu.current-exe -c '$env.TEST'" + "#); + assert!(actual.out.is_empty()); + assert!(actual.err.contains("cannot find column")); +} + #[test] fn has_file_pwd() { Playground::setup("has_file_pwd", |dirs, sandbox| {