Skip to content

Commit acf88ad

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 387270b commit acf88ad

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
@@ -186,7 +186,6 @@ impl<'cfg> Workspace<'cfg> {
186186
/// before returning it, so `Ok` is only returned for valid workspaces.
187187
pub fn new(manifest_path: &Path, config: &'cfg Config) -> CargoResult<Workspace<'cfg>> {
188188
let mut ws = Workspace::new_default(manifest_path.to_path_buf(), config);
189-
ws.target_dir = config.target_dir()?;
190189

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

199+
if let Some(ref root_manifest) = ws.root_manifest {
200+
ws.target_dir = config.target_dir(root_manifest)?;
201+
} else {
202+
ws.target_dir = config.target_dir(manifest_path)?;
203+
}
204+
200205
ws.custom_metadata = ws
201206
.load_workspace_config()?
202207
.and_then(|cfg| cfg.custom_metadata);
@@ -236,7 +241,11 @@ impl<'cfg> Workspace<'cfg> {
236241
) -> CargoResult<Workspace<'cfg>> {
237242
let mut ws = Workspace::new_default(current_manifest, config);
238243
ws.root_manifest = Some(root_path.join("Cargo.toml"));
239-
ws.target_dir = config.target_dir()?;
244+
if let Some(ref root_manifest) = ws.root_manifest {
245+
ws.target_dir = config.target_dir(root_manifest)?;
246+
} else {
247+
ws.target_dir = config.target_dir(&ws.current_manifest)?;
248+
}
240249
ws.packages
241250
.packages
242251
.insert(root_path, MaybePackage::Virtual(manifest));
@@ -267,13 +276,13 @@ impl<'cfg> Workspace<'cfg> {
267276
ws.require_optional_deps = require_optional_deps;
268277
let key = ws.current_manifest.parent().unwrap();
269278
let id = package.package_id();
270-
let package = MaybePackage::Package(package);
271-
ws.packages.packages.insert(key.to_path_buf(), package);
272279
ws.target_dir = if let Some(dir) = target_dir {
273280
Some(dir)
274281
} else {
275-
ws.config.target_dir()?
282+
ws.config.target_dir(package.manifest_path())?
276283
};
284+
let package = MaybePackage::Package(package);
285+
ws.packages.packages.insert(key.to_path_buf(), package);
277286
ws.members.push(ws.current_manifest.clone());
278287
ws.member_ids.insert(id);
279288
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
@@ -281,7 +281,8 @@ impl<'cfg, 'a> InstallablePackage<'cfg, 'a> {
281281
let mut td_opt = None;
282282
let mut needs_cleanup = false;
283283
if !self.source_id.is_path() {
284-
let target_dir = if let Some(dir) = self.config.target_dir()? {
284+
let manifest_path = self.pkg.manifest_path().to_path_buf();
285+
let target_dir = if let Some(dir) = self.config.target_dir(manifest_path)? {
285286
dir
286287
} else if let Ok(td) = TempFileBuilder::new().prefix("cargo-install").tempdir() {
287288
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
@@ -493,7 +493,7 @@ impl Config {
493493
/// Returns `None` if the user has not chosen an explicit directory.
494494
///
495495
/// Callers should prefer `Workspace::target_dir` instead.
496-
pub fn target_dir(&self) -> CargoResult<Option<Filesystem>> {
496+
pub fn target_dir(&self, manifest: impl Into<PathBuf>) -> CargoResult<Option<Filesystem>> {
497497
if let Some(dir) = &self.target_dir {
498498
Ok(Some(dir.clone()))
499499
} else if let Some(dir) = self.env.get("CARGO_TARGET_DIR") {
@@ -506,6 +506,21 @@ impl Config {
506506
}
507507

508508
Ok(Some(Filesystem::new(self.cwd.join(dir))))
509+
} else if let Some(dir) = env::var_os("CARGO_TARGET_DIR_PREFIX") {
510+
let prefix = Path::new(&dir);
511+
if !prefix.is_absolute() {
512+
bail!("CARGO_TARGET_DIR_PREFIX must describe an absolute path");
513+
}
514+
let mut manifest = manifest.into();
515+
let result = manifest.pop();
516+
assert!(result);
517+
518+
match manifest.strip_prefix("/") {
519+
Ok(dir) => Ok(Some(Filesystem::new(prefix.join(&dir).join("target")))),
520+
// FIXME: This logic is probably not safe on Windows. Not sure how
521+
// to make a path relative there.
522+
Err(_) => bail!("Current directory must be an absolute path"),
523+
}
509524
} else if let Some(val) = &self.build_config()?.target_dir {
510525
let path = val.resolve_path(self);
511526

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

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

tests/testsuite/build.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3737,6 +3737,63 @@ fn panic_abort_compiles_with_panic_abort() {
37373737
.run();
37383738
}
37393739

3740+
#[cargo_test]
3741+
fn custom_target_dir_prefix() {
3742+
fn test(cwd: &str) {
3743+
let tmpdir = tempfile::Builder::new()
3744+
.tempdir()
3745+
.unwrap()
3746+
.path()
3747+
.to_path_buf();
3748+
3749+
let p = project()
3750+
.file(
3751+
"Cargo.toml",
3752+
r#"
3753+
[package]
3754+
name = "foo"
3755+
version = "0.0.1"
3756+
authors = []
3757+
"#,
3758+
)
3759+
.file("src/main.rs", "fn main() {}")
3760+
.build();
3761+
3762+
let root = p.root();
3763+
let root_suffix = root.strip_prefix("/").unwrap();
3764+
let exe_name = format!("foo{}", env::consts::EXE_SUFFIX);
3765+
3766+
p.cargo("build")
3767+
.env("CARGO_TARGET_DIR_PREFIX", tmpdir.clone())
3768+
.cwd(p.root().join(cwd))
3769+
.run();
3770+
3771+
assert!(
3772+
tmpdir
3773+
.clone()
3774+
.join(root_suffix)
3775+
.join("target/debug")
3776+
.join(&exe_name)
3777+
.is_file()
3778+
);
3779+
assert!(!&p.root().join("target/debug").join(&exe_name).is_file());
3780+
3781+
p.cargo("build").run();
3782+
assert!(
3783+
tmpdir
3784+
.clone()
3785+
.join(root_suffix)
3786+
.join("target/debug")
3787+
.join(&exe_name)
3788+
.is_file()
3789+
);
3790+
assert!(&p.root().join("target/debug").join(&exe_name).is_file())
3791+
};
3792+
3793+
test(".");
3794+
test("src");
3795+
}
3796+
37403797
#[cargo_test]
37413798
fn compiler_json_error_format() {
37423799
let p = project()

0 commit comments

Comments
 (0)