diff --git a/library/std/src/process/tests.rs b/library/std/src/process/tests.rs index 0d5321c2eea..b50dea2e737 100644 --- a/library/std/src/process/tests.rs +++ b/library/std/src/process/tests.rs @@ -560,6 +560,29 @@ fn debug_print() { "FOO": None, }}, }}, +{PIDFD}}}"# + ) + ); + + let mut command_with_cleared_env = Command::new("boring-name"); + command_with_cleared_env.env_clear().env("BAR", "val").env_remove("FOO"); + assert_eq!(format!("{command_with_cleared_env:?}"), r#"env -i BAR="val" "boring-name""#); + assert_eq!( + format!("{command_with_cleared_env:#?}"), + format!( + r#"Command {{ + program: "boring-name", + args: [ + "boring-name", + ], + env: CommandEnv {{ + clear: true, + vars: {{ + "BAR": Some( + "val", + ), + }}, + }}, {PIDFD}}}"# ) ); diff --git a/library/std/src/sys/unix/process/process_common.rs b/library/std/src/sys/unix/process/process_common.rs index 3a02a6c20d9..23d9f3b78ee 100644 --- a/library/std/src/sys/unix/process/process_common.rs +++ b/library/std/src/sys/unix/process/process_common.rs @@ -558,20 +558,25 @@ impl fmt::Debug for Command { if let Some(ref cwd) = self.cwd { write!(f, "cd {cwd:?} && ")?; } - // Removed env vars need a separate command. - // We use a single `unset` command for all of them. - let mut any_removed = false; - for (key, value_opt) in self.get_envs() { - if value_opt.is_none() { - if !any_removed { - write!(f, "unset ")?; - any_removed = true; + if self.env.does_clear() { + write!(f, "env -i ")?; + // Altered env vars will be printed next, that should exactly work as expected. + } else { + // Removed env vars need a separate command. + // We use a single `unset` command for all of them. + let mut any_removed = false; + for (key, value_opt) in self.get_envs() { + if value_opt.is_none() { + if !any_removed { + write!(f, "unset ")?; + any_removed = true; + } + write!(f, "{} ", key.to_string_lossy())?; } - write!(f, "{} ", key.to_string_lossy())?; } - } - if any_removed { - write!(f, "&& ")?; + if any_removed { + write!(f, "&& ")?; + } } // Altered env vars can just be added in front of the program. for (key, value_opt) in self.get_envs() { diff --git a/library/std/src/sys_common/process.rs b/library/std/src/sys_common/process.rs index 18883048dae..4d295cf0f09 100644 --- a/library/std/src/sys_common/process.rs +++ b/library/std/src/sys_common/process.rs @@ -80,6 +80,10 @@ impl CommandEnv { self.vars.clear(); } + pub fn does_clear(&self) -> bool { + self.clear + } + pub fn have_changed_path(&self) -> bool { self.saw_path || self.clear }