Skip to content

Commit c44ee9a

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 3532cf7 commit c44ee9a

File tree

5 files changed

+92
-7
lines changed

5 files changed

+92
-7
lines changed

src/cargo/core/workspace.rs

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,12 @@ impl<'cfg> Workspace<'cfg> {
139139
/// before returning it, so `Ok` is only returned for valid workspaces.
140140
pub fn new(manifest_path: &Path, config: &'cfg Config) -> CargoResult<Workspace<'cfg>> {
141141
let mut ws = Workspace::new_default(manifest_path.to_path_buf(), config);
142-
ws.target_dir = config.target_dir()?;
143142
ws.root_manifest = ws.find_root(manifest_path)?;
143+
if let Some(ref root_manifest) = ws.root_manifest {
144+
ws.target_dir = config.target_dir(root_manifest)?;
145+
} else {
146+
ws.target_dir = config.target_dir(manifest_path)?;
147+
}
144148
ws.find_members()?;
145149
ws.validate()?;
146150
Ok(ws)
@@ -174,7 +178,11 @@ impl<'cfg> Workspace<'cfg> {
174178
) -> CargoResult<Workspace<'cfg>> {
175179
let mut ws = Workspace::new_default(current_manifest, config);
176180
ws.root_manifest = Some(root_path.join("Cargo.toml"));
177-
ws.target_dir = config.target_dir()?;
181+
if let Some(ref root_manifest) = ws.root_manifest {
182+
ws.target_dir = config.target_dir(root_manifest)?;
183+
} else {
184+
ws.target_dir = config.target_dir(&ws.current_manifest)?;
185+
}
178186
ws.packages
179187
.packages
180188
.insert(root_path, MaybePackage::Virtual(manifest));
@@ -204,13 +212,13 @@ impl<'cfg> Workspace<'cfg> {
204212
ws.require_optional_deps = require_optional_deps;
205213
let key = ws.current_manifest.parent().unwrap();
206214
let id = package.package_id();
207-
let package = MaybePackage::Package(package);
208-
ws.packages.packages.insert(key.to_path_buf(), package);
209215
ws.target_dir = if let Some(dir) = target_dir {
210216
Some(dir)
211217
} else {
212-
ws.config.target_dir()?
218+
ws.config.target_dir(package.manifest_path())?
213219
};
220+
let package = MaybePackage::Package(package);
221+
ws.packages.packages.insert(key.to_path_buf(), package);
214222
ws.members.push(ws.current_manifest.clone());
215223
ws.member_ids.insert(id);
216224
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
@@ -200,6 +200,7 @@ fn install_one(
200200
)?
201201
};
202202

203+
let manifest_path = pkg.manifest_path().to_path_buf();
203204
let (mut ws, git_package) = if source_id.is_git() {
204205
// Don't use ws.current() in order to keep the package source as a git source so that
205206
// install tracking uses the correct source.
@@ -215,7 +216,7 @@ fn install_one(
215216
let mut td_opt = None;
216217
let mut needs_cleanup = false;
217218
if !source_id.is_path() {
218-
let target_dir = if let Some(dir) = config.target_dir()? {
219+
let target_dir = if let Some(dir) = config.target_dir(manifest_path)? {
219220
dir
220221
} else if let Ok(td) = TempFileBuilder::new().prefix("cargo-install").tempdir() {
221222
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
@@ -427,11 +427,26 @@ impl Config {
427427
/// Returns `None` if the user has not chosen an explicit directory.
428428
///
429429
/// Callers should prefer `Workspace::target_dir` instead.
430-
pub fn target_dir(&self) -> CargoResult<Option<Filesystem>> {
430+
pub fn target_dir(&self, manifest: impl Into<PathBuf>) -> CargoResult<Option<Filesystem>> {
431431
if let Some(dir) = &self.target_dir {
432432
Ok(Some(dir.clone()))
433433
} else if let Some(dir) = env::var_os("CARGO_TARGET_DIR") {
434434
Ok(Some(Filesystem::new(self.cwd.join(dir))))
435+
} else if let Some(dir) = env::var_os("CARGO_TARGET_DIR_PREFIX") {
436+
let prefix = Path::new(&dir);
437+
if !prefix.is_absolute() {
438+
bail!("CARGO_TARGET_DIR_PREFIX must describe an absolute path");
439+
}
440+
let mut manifest = manifest.into();
441+
let result = manifest.pop();
442+
assert!(result);
443+
444+
match manifest.strip_prefix("/") {
445+
Ok(dir) => Ok(Some(Filesystem::new(prefix.join(&dir).join("target")))),
446+
// FIXME: This logic is probably not safe on Windows. Not sure how
447+
// to make a path relative there.
448+
Err(_) => bail!("Current directory must be an absolute path"),
449+
}
435450
} else if let Some(val) = &self.build_config()?.target_dir {
436451
let val = val.resolve_path(self);
437452
Ok(Some(Filesystem::new(val)))

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
@@ -3030,6 +3030,63 @@ fn panic_abort_compiles_with_panic_abort() {
30303030
.run();
30313031
}
30323032

3033+
#[cargo_test]
3034+
fn custom_target_dir_prefix() {
3035+
fn test(cwd: &str) {
3036+
let tmpdir = tempfile::Builder::new()
3037+
.tempdir()
3038+
.unwrap()
3039+
.path()
3040+
.to_path_buf();
3041+
3042+
let p = project()
3043+
.file(
3044+
"Cargo.toml",
3045+
r#"
3046+
[package]
3047+
name = "foo"
3048+
version = "0.0.1"
3049+
authors = []
3050+
"#,
3051+
)
3052+
.file("src/main.rs", "fn main() {}")
3053+
.build();
3054+
3055+
let root = p.root();
3056+
let root_suffix = root.strip_prefix("/").unwrap();
3057+
let exe_name = format!("foo{}", env::consts::EXE_SUFFIX);
3058+
3059+
p.cargo("build")
3060+
.env("CARGO_TARGET_DIR_PREFIX", tmpdir.clone())
3061+
.cwd(p.root().join(cwd))
3062+
.run();
3063+
3064+
assert!(
3065+
tmpdir
3066+
.clone()
3067+
.join(root_suffix)
3068+
.join("target/debug")
3069+
.join(&exe_name)
3070+
.is_file()
3071+
);
3072+
assert!(!&p.root().join("target/debug").join(&exe_name).is_file());
3073+
3074+
p.cargo("build").run();
3075+
assert!(
3076+
tmpdir
3077+
.clone()
3078+
.join(root_suffix)
3079+
.join("target/debug")
3080+
.join(&exe_name)
3081+
.is_file()
3082+
);
3083+
assert!(&p.root().join("target/debug").join(&exe_name).is_file())
3084+
};
3085+
3086+
test(".");
3087+
test("src");
3088+
}
3089+
30333090
#[cargo_test]
30343091
fn compiler_json_error_format() {
30353092
let p = project()

0 commit comments

Comments
 (0)