Skip to content

Commit 50fa9ea

Browse files
committed
Add support for CARGO_TARGET_DIR_PREFIX
This change adds support for a new environment variable, CARGO_TARGET_DIR_PREFIX, to cargo. This variable, when set, is treated as a prefix to the target directory. Note that support for the functionality behind this variable is not trivial to implement with the current design. In particular, we wanted to stick as close to the existing CARGO_TARGET_DIR logic. However, the Config in which it is implemented really does not know anything about the directory of the particular crate we concerned with. As a quick work around to this problem, we just pass in the path to the Cargo.toml from the "upper layer". That works, but ultimately it would be better to make the other layer handle the CARGO_TARGET_DIR_PREFIX logic. This change addresses rust-lang#5544. TODO: Definitely not finished. This patch needs more tests and may need additional config.toml support (?). TODO: There is also the potential for a permission related problems. E.g., when user root compiles something below /tmp/ and then user nobody tries to do the same the resulting directory ${CARGO_TARGET_DIR_PREFIX}/tmp/ may be owned by root, causing the build for nobody to fail with a permission denied error.
1 parent 6e9a833 commit 50fa9ea

File tree

5 files changed

+93
-7
lines changed

5 files changed

+93
-7
lines changed

src/cargo/core/workspace.rs

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,6 @@ impl<'cfg> Workspace<'cfg> {
185185
/// before returning it, so `Ok` is only returned for valid workspaces.
186186
pub fn new(manifest_path: &Path, config: &'cfg Config) -> CargoResult<Workspace<'cfg>> {
187187
let mut ws = Workspace::new_default(manifest_path.to_path_buf(), config);
188-
ws.target_dir = config.target_dir()?;
189188

190189
if manifest_path.is_relative() {
191190
bail!(
@@ -196,6 +195,12 @@ impl<'cfg> Workspace<'cfg> {
196195
ws.root_manifest = ws.find_root(manifest_path)?;
197196
}
198197

198+
if let Some(ref root_manifest) = ws.root_manifest {
199+
ws.target_dir = config.target_dir(root_manifest)?;
200+
} else {
201+
ws.target_dir = config.target_dir(manifest_path)?;
202+
}
203+
199204
ws.custom_metadata = ws
200205
.load_workspace_config()?
201206
.and_then(|cfg| cfg.custom_metadata);
@@ -235,7 +240,11 @@ impl<'cfg> Workspace<'cfg> {
235240
) -> CargoResult<Workspace<'cfg>> {
236241
let mut ws = Workspace::new_default(current_manifest, config);
237242
ws.root_manifest = Some(root_path.join("Cargo.toml"));
238-
ws.target_dir = config.target_dir()?;
243+
if let Some(ref root_manifest) = ws.root_manifest {
244+
ws.target_dir = config.target_dir(root_manifest)?;
245+
} else {
246+
ws.target_dir = config.target_dir(&ws.current_manifest)?;
247+
}
239248
ws.packages
240249
.packages
241250
.insert(root_path, MaybePackage::Virtual(manifest));
@@ -266,13 +275,13 @@ impl<'cfg> Workspace<'cfg> {
266275
ws.require_optional_deps = require_optional_deps;
267276
let key = ws.current_manifest.parent().unwrap();
268277
let id = package.package_id();
269-
let package = MaybePackage::Package(package);
270-
ws.packages.packages.insert(key.to_path_buf(), package);
271278
ws.target_dir = if let Some(dir) = target_dir {
272279
Some(dir)
273280
} else {
274-
ws.config.target_dir()?
281+
ws.config.target_dir(package.manifest_path())?
275282
};
283+
let package = MaybePackage::Package(package);
284+
ws.packages.packages.insert(key.to_path_buf(), package);
276285
ws.members.push(ws.current_manifest.clone());
277286
ws.member_ids.insert(id);
278287
ws.default_members.push(ws.current_manifest.clone());

src/cargo/ops/cargo_install.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,8 @@ impl<'cfg, 'a> InstallablePackage<'cfg, 'a> {
289289
let mut td_opt = None;
290290
let mut needs_cleanup = false;
291291
if !self.source_id.is_path() {
292-
let target_dir = if let Some(dir) = self.config.target_dir()? {
292+
let manifest_path = self.pkg.manifest_path().to_path_buf();
293+
let target_dir = if let Some(dir) = self.config.target_dir(manifest_path)? {
293294
dir
294295
} else if let Ok(td) = TempFileBuilder::new().prefix("cargo-install").tempdir() {
295296
let p = td.path().to_owned();

src/cargo/util/config/mod.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -551,7 +551,7 @@ impl Config {
551551
/// Returns `None` if the user has not chosen an explicit directory.
552552
///
553553
/// Callers should prefer `Workspace::target_dir` instead.
554-
pub fn target_dir(&self) -> CargoResult<Option<Filesystem>> {
554+
pub fn target_dir(&self, manifest: impl Into<PathBuf>) -> CargoResult<Option<Filesystem>> {
555555
if let Some(dir) = &self.target_dir {
556556
Ok(Some(dir.clone()))
557557
} else if let Some(dir) = self.get_env_os("CARGO_TARGET_DIR") {
@@ -564,6 +564,21 @@ impl Config {
564564
}
565565

566566
Ok(Some(Filesystem::new(self.cwd.join(dir))))
567+
} else if let Some(dir) = env::var_os("CARGO_TARGET_DIR_PREFIX") {
568+
let prefix = Path::new(&dir);
569+
if !prefix.is_absolute() {
570+
bail!("CARGO_TARGET_DIR_PREFIX must describe an absolute path");
571+
}
572+
let mut manifest = manifest.into();
573+
let result = manifest.pop();
574+
assert!(result);
575+
576+
match manifest.strip_prefix("/") {
577+
Ok(dir) => Ok(Some(Filesystem::new(prefix.join(&dir).join("target")))),
578+
// FIXME: This logic is probably not safe on Windows. Not sure how
579+
// to make a path relative there.
580+
Err(_) => bail!("Current directory must be an absolute path"),
581+
}
567582
} else if let Some(val) = &self.build_config()?.target_dir {
568583
let path = val.resolve_path(self);
569584

src/doc/src/reference/environment-variables.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ system:
2020
location of this directory. Once a crate is cached it is not removed by the
2121
clean command.
2222
For more details refer to the [guide](../guide/cargo-home.md).
23+
* `CARGO_TARGET_DIR_PREFIX` — Prefix to the location where to place all
24+
generated artifacts. The current working directory will be appended to this
25+
prefix to form the final path for generated artifacts. Note that
26+
`CARGO_TARGET_DIR`, if set, takes precedence over this variable.
2327
* `CARGO_TARGET_DIR` --- Location of where to place all generated artifacts,
2428
relative to the current working directory. See [`build.target-dir`] to set
2529
via config.

tests/testsuite/build.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3837,6 +3837,63 @@ fn panic_abort_compiles_with_panic_abort() {
38373837
.run();
38383838
}
38393839

3840+
#[cargo_test]
3841+
fn custom_target_dir_prefix() {
3842+
fn test(cwd: &str) {
3843+
let tmpdir = tempfile::Builder::new()
3844+
.tempdir()
3845+
.unwrap()
3846+
.path()
3847+
.to_path_buf();
3848+
3849+
let p = project()
3850+
.file(
3851+
"Cargo.toml",
3852+
r#"
3853+
[package]
3854+
name = "foo"
3855+
version = "0.0.1"
3856+
authors = []
3857+
"#,
3858+
)
3859+
.file("src/main.rs", "fn main() {}")
3860+
.build();
3861+
3862+
let root = p.root();
3863+
let root_suffix = root.strip_prefix("/").unwrap();
3864+
let exe_name = format!("foo{}", env::consts::EXE_SUFFIX);
3865+
3866+
p.cargo("build")
3867+
.env("CARGO_TARGET_DIR_PREFIX", tmpdir.clone())
3868+
.cwd(p.root().join(cwd))
3869+
.run();
3870+
3871+
assert!(
3872+
tmpdir
3873+
.clone()
3874+
.join(root_suffix)
3875+
.join("target/debug")
3876+
.join(&exe_name)
3877+
.is_file()
3878+
);
3879+
assert!(!&p.root().join("target/debug").join(&exe_name).is_file());
3880+
3881+
p.cargo("build").run();
3882+
assert!(
3883+
tmpdir
3884+
.clone()
3885+
.join(root_suffix)
3886+
.join("target/debug")
3887+
.join(&exe_name)
3888+
.is_file()
3889+
);
3890+
assert!(&p.root().join("target/debug").join(&exe_name).is_file())
3891+
};
3892+
3893+
test(".");
3894+
test("src");
3895+
}
3896+
38403897
#[cargo_test]
38413898
fn compiler_json_error_format() {
38423899
let p = project()

0 commit comments

Comments
 (0)