Skip to content

Commit 9c5b9c7

Browse files
committed
Add env_clear_cargo_vars method
Signed-off-by: Jorge Prendes <jorge.prendes@gmail.com>
1 parent 079520c commit 9c5b9c7

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

src/command.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use std::process::Command as StdCommand;
88
use std::{env, iter};
99

1010
use anyhow::{Context, Result};
11+
use os_str_bytes::OsStrBytesExt;
1112

1213
use crate::CargoCommandExt;
1314
use crate::cargo_cmd::{CargoBinary, CargoCmd as _, find_cargo, merge_env};
@@ -55,6 +56,7 @@ pub struct Command {
5556
args: Vec<OsString>,
5657
/// Environment variable mappings to set for the child process
5758
inherit_envs: bool,
59+
inherit_cargo_envs: bool,
5860
envs: BTreeMap<OsString, Option<OsString>>,
5961
// Working directory for the child process
6062
current_dir: Option<PathBuf>,
@@ -122,6 +124,7 @@ impl Command {
122124
args: Vec::new(),
123125
envs: BTreeMap::new(),
124126
inherit_envs: true,
127+
inherit_cargo_envs: true,
125128
current_dir: None,
126129
})
127130
}
@@ -285,6 +288,39 @@ impl Command {
285288
self
286289
}
287290

291+
/// Clears all `CARGO_` environment variables that will be set for the child process.
292+
///
293+
/// This method will remove all environment variables starting with `CARGO_`
294+
/// from the child process, including those that would normally be inherited
295+
/// from the parent process. Other environment variables will remain unaffected.
296+
/// Environment variables can be added back individually using [`env`].
297+
///
298+
/// This is particularly useful when using cargo-hyperlight from a build script
299+
/// or other cargo-invoked context where `CARGO_` variables may change the behavior
300+
/// of the cargo command being executed.
301+
///
302+
/// # Examples
303+
///
304+
/// Basic usage:
305+
///
306+
/// ```no_run
307+
/// use cargo_hyperlight::cargo;
308+
///
309+
/// cargo()
310+
/// .unwrap()
311+
/// .env_clear_cargo_vars()
312+
/// .env("CARGO_TARGET_DIR", "/path/to/target")
313+
/// .arg("build")
314+
/// .exec();
315+
/// ```
316+
///
317+
/// [`env`]: Command::env
318+
pub fn env_clear_cargo_vars(&mut self) -> &mut Self {
319+
self.inherit_cargo_envs = false;
320+
self.envs.retain(|k, _| !k.starts_with("CARGO_"));
321+
self
322+
}
323+
288324
/// Removes an explicitly set environment variable and prevents inheriting
289325
/// it from a parent process.
290326
///
@@ -477,6 +513,11 @@ impl Command {
477513
if !self.inherit_envs {
478514
command.env_clear();
479515
}
516+
if !self.inherit_cargo_envs {
517+
for (k, _) in std::env::vars_os().filter(|(k, _)| k.starts_with("CARGO_")) {
518+
command.env_remove(k);
519+
}
520+
}
480521
if let Some(rustup_toolchain) = &self.cargo.rustup_toolchain {
481522
command.env("RUSTUP_TOOLCHAIN", rustup_toolchain);
482523
}

0 commit comments

Comments
 (0)