diff --git a/src/cargo/util/config/mod.rs b/src/cargo/util/config/mod.rs index a0dc0963c17..a71d84cedfe 100644 --- a/src/cargo/util/config/mod.rs +++ b/src/cargo/util/config/mod.rs @@ -473,10 +473,24 @@ impl Config { if let Some(dir) = &self.target_dir { Ok(Some(dir.clone())) } else if let Some(dir) = env::var_os("CARGO_TARGET_DIR") { + // Check if the CARGO_TARGET_DIR environment variable is set to an empty string. + if dir.to_string_lossy() == "" { + anyhow::bail!("the target directory is set to an empty string in the `CARGO_TARGET_DIR` environment variable") + } + Ok(Some(Filesystem::new(self.cwd.join(dir)))) } else if let Some(val) = &self.build_config()?.target_dir { - let val = val.resolve_path(self); - Ok(Some(Filesystem::new(val))) + let path = val.resolve_path(self); + + // Check if the target directory is set to an empty string in the config.toml file. + if val.raw_value() == "" { + anyhow::bail!(format!( + "the target directory is set to an empty string in {}", + val.value().definition + ),) + } + + Ok(Some(Filesystem::new(path))) } else { Ok(None) } diff --git a/src/cargo/util/config/path.rs b/src/cargo/util/config/path.rs index f859b556306..6180d0f3f13 100644 --- a/src/cargo/util/config/path.rs +++ b/src/cargo/util/config/path.rs @@ -10,6 +10,11 @@ use std::path::PathBuf; pub struct ConfigRelativePath(Value); impl ConfigRelativePath { + /// Returns the underlying value. + pub fn value(&self) -> &Value { + &self.0 + } + /// Returns the raw underlying configuration value for this key. pub fn raw_value(&self) -> &str { &self.0.val diff --git a/tests/testsuite/config.rs b/tests/testsuite/config.rs index 1b45b65b307..c53fc1e07fc 100644 --- a/tests/testsuite/config.rs +++ b/tests/testsuite/config.rs @@ -1460,3 +1460,31 @@ strip = 'debuginfo' let strip = p.strip.unwrap(); assert_eq!(strip, toml::StringOrBool::String("debuginfo".to_string())); } + +#[cargo_test] +fn cargo_target_empty_cfg() { + write_config( + "\ +[build] +target-dir = '' +", + ); + + let config = new_config(); + + assert_error( + config.target_dir().unwrap_err(), + "the target directory is set to an empty string in [..]/.cargo/config", + ); +} + +#[cargo_test] +fn cargo_target_empty_env() { + let project = project().build(); + + project.cargo("build") + .env("CARGO_TARGET_DIR", "") + .with_stderr("error: the target directory is set to an empty string in the `CARGO_TARGET_DIR` environment variable") + .with_status(101) + .run() +}