Skip to content

Commit b8d3fe3

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 1c6ec66 commit b8d3fe3

File tree

5 files changed

+91
-7
lines changed

5 files changed

+91
-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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ fn install_one(
204204
let mut needs_cleanup = false;
205205
let overidden_target_dir = if source_id.is_path() {
206206
None
207-
} else if let Some(dir) = config.target_dir()? {
207+
} else if let Some(dir) = config.target_dir(pkg.manifest_path())? {
208208
Some(dir)
209209
} else if let Ok(td) = TempFileBuilder::new().prefix("cargo-install").tempdir() {
210210
let p = td.path().to_owned();

src/cargo/util/config.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,11 +322,26 @@ impl Config {
322322
&self.cwd
323323
}
324324

325-
pub fn target_dir(&self) -> CargoResult<Option<Filesystem>> {
325+
pub fn target_dir(&self, manifest: impl Into<PathBuf>) -> CargoResult<Option<Filesystem>> {
326326
if let Some(ref dir) = self.target_dir {
327327
Ok(Some(dir.clone()))
328328
} else if let Some(dir) = env::var_os("CARGO_TARGET_DIR") {
329329
Ok(Some(Filesystem::new(self.cwd.join(dir))))
330+
} else if let Some(dir) = env::var_os("CARGO_TARGET_DIR_PREFIX") {
331+
let prefix = Path::new(&dir);
332+
if !prefix.is_absolute() {
333+
failure::bail!("CARGO_TARGET_DIR_PREFIX must describe an absolute path");
334+
}
335+
let mut manifest = manifest.into();
336+
let result = manifest.pop();
337+
assert!(result);
338+
339+
match manifest.strip_prefix("/") {
340+
Ok(dir) => Ok(Some(Filesystem::new(prefix.join(&dir).join("target")))),
341+
// FIXME: This logic is probably not safe on Windows. Not sure how
342+
// to make a path relative there.
343+
Err(_) => failure::bail!("Current directory must be an absolute path"),
344+
}
330345
} else if let Some(val) = self.get_path("build.target-dir")? {
331346
let val = self.cwd.join(val.val);
332347
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
@@ -14,6 +14,10 @@ system:
1414
this variable overrides the location of this directory. Once a crate is cached
1515
it is not removed by the clean command.
1616
For more details refer to the [guide](../guide/cargo-home.md).
17+
* `CARGO_TARGET_DIR_PREFIX` — Prefix to the location where to place all
18+
generated artifacts. The current working directory will be appended to this
19+
prefix to form the final path for generated artifacts. Note that
20+
`CARGO_TARGET_DIR`, if set, takes precedence over this variable.
1721
* `CARGO_TARGET_DIR` — Location of where to place all generated artifacts,
1822
relative to the current working directory.
1923
* `RUSTC` — Instead of running `rustc`, Cargo will execute this specified

tests/testsuite/build.rs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3018,6 +3018,63 @@ fn explicit_color_config_is_propagated_to_rustc() {
30183018
.run();
30193019
}
30203020

3021+
#[cargo_test]
3022+
fn custom_target_dir_prefix() {
3023+
fn test(cwd: &str) {
3024+
let tmpdir = tempfile::Builder::new()
3025+
.tempdir()
3026+
.unwrap()
3027+
.path()
3028+
.to_path_buf();
3029+
3030+
let p = project()
3031+
.file(
3032+
"Cargo.toml",
3033+
r#"
3034+
[package]
3035+
name = "foo"
3036+
version = "0.0.1"
3037+
authors = []
3038+
"#,
3039+
)
3040+
.file("src/main.rs", "fn main() {}")
3041+
.build();
3042+
3043+
let root = p.root();
3044+
let root_suffix = root.strip_prefix("/").unwrap();
3045+
let exe_name = format!("foo{}", env::consts::EXE_SUFFIX);
3046+
3047+
p.cargo("build")
3048+
.env("CARGO_TARGET_DIR_PREFIX", tmpdir.clone())
3049+
.cwd(p.root().join(cwd))
3050+
.run();
3051+
3052+
assert!(
3053+
tmpdir
3054+
.clone()
3055+
.join(root_suffix)
3056+
.join("target/debug")
3057+
.join(&exe_name)
3058+
.is_file()
3059+
);
3060+
assert!(!&p.root().join("target/debug").join(&exe_name).is_file());
3061+
3062+
p.cargo("build").run();
3063+
assert!(
3064+
tmpdir
3065+
.clone()
3066+
.join(root_suffix)
3067+
.join("target/debug")
3068+
.join(&exe_name)
3069+
.is_file()
3070+
);
3071+
assert!(&p.root().join("target/debug").join(&exe_name).is_file())
3072+
};
3073+
3074+
test(".");
3075+
test("src");
3076+
}
3077+
30213078
#[cargo_test]
30223079
fn compiler_json_error_format() {
30233080
let p = project()

0 commit comments

Comments
 (0)