Skip to content

Commit 85ebc79

Browse files
author
William Page
committed
Add '--directory,-C' flag for changing current dir before build
This implements the suggestion in #10098 to make cargo change cwd before completing config processing and starting the build. It is also an alternative to --manifest-path that resolves the issue described in #2930.
1 parent e6827ee commit 85ebc79

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/bin/cargo/cli.rs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use anyhow::anyhow;
1+
use anyhow::{anyhow, Context as _};
22
use cargo::core::{features, CliUnstable};
33
use cargo::{self, drop_print, drop_println, CliResult, Config};
44
use clap::{
@@ -55,6 +55,13 @@ pub fn main(config: &mut Config) -> CliResult {
5555
}
5656
};
5757

58+
if let Some(new_cwd) = args.get_one::<std::path::PathBuf>("directory") {
59+
// Change the configured directory to work in, before any config files are read
60+
config
61+
.set_cwd(new_cwd.as_path())
62+
.with_context(|| "could not change to requested directory")?;
63+
}
64+
5865
// Global args need to be extracted before expanding aliases because the
5966
// clap code for extracting a subcommand discards global options
6067
// (appearing before the subcommand).
@@ -473,6 +480,14 @@ See 'cargo help <command>' for more information on a specific command.\n",
473480
.value_name("WHEN")
474481
.global(true),
475482
)
483+
.arg(
484+
opt("directory", "Change to DIRECTORY before doing anything")
485+
.short('C')
486+
.value_name("DIRECTORY")
487+
.value_hint(clap::ValueHint::DirPath)
488+
.value_parser(clap::builder::ValueParser::path_buf())
489+
.global(true),
490+
)
476491
.arg(flag("frozen", "Require Cargo.lock and cache are up to date").global(true))
477492
.arg(flag("locked", "Require Cargo.lock is up to date").global(true))
478493
.arg(flag("offline", "Run without accessing the network").global(true))

src/cargo/util/config/mod.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,23 @@ impl Config {
483483
Ok(())
484484
}
485485

486+
/// Updates the application's notion of current working directory, both in
487+
/// the process environment as well as the configuration data
488+
pub fn set_cwd(&mut self, new_cwd: &Path) -> CargoResult<()> {
489+
// Update the process-level notion of cwd
490+
std::env::set_current_dir(&new_cwd)?;
491+
// Update struct members derived from the process-wide cwd
492+
// processing occurs
493+
self.cwd = new_cwd.to_path_buf();
494+
self.home_path = Filesystem::new(homedir(new_cwd).ok_or_else(|| {
495+
anyhow!(
496+
"Cargo couldn't find your home directory. \
497+
This probably means that $HOME was not set."
498+
)
499+
})?);
500+
Ok(())
501+
}
502+
486503
/// The current working directory.
487504
pub fn cwd(&self) -> &Path {
488505
&self.cwd

0 commit comments

Comments
 (0)