Skip to content

Commit 8b8837c

Browse files
committed
Do not add home bin path to PATH if it's already there
This is to allow users to control the order via PATH if they so desire. Tested by preparing two different `cargo-foo` scripts in `$HOME/.cargo/bin` and `$HOME/bin`: ``` > env PATH="/usr/bin/:$HOME/bin:$HOME/.cargo/bin" ./target/debug/cargo foo Inside ~/bin/ > env PATH="$HOME/.cargo/bin:/usr/bin/:$HOME/bin" ./target/debug/cargo foo Inside ~/.cargo/bin/ > env PATH="/usr/bin/:$HOME/bin" ./target/debug/cargo foo Inside ~/.cargo/bin/ ``` and trailing slash: ``` > env PATH="$HOME/.cargo/bin/:/usr/bin/:$HOME/bin" ./target/debug/cargo foo Inside ~/.cargo/bin/ > env PATH="/usr/bin/:$HOME/bin:$HOME/.cargo/bin/" ./target/debug/cargo foo Inside ~/bin/ ``` Fix #11020
1 parent 716d401 commit 8b8837c

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

src/bin/cargo/main.rs

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -220,10 +220,30 @@ fn is_executable<P: AsRef<Path>>(path: P) -> bool {
220220
}
221221

222222
fn search_directories(config: &Config) -> Vec<PathBuf> {
223-
let mut dirs = vec![config.home().clone().into_path_unlocked().join("bin")];
224-
if let Some(val) = env::var_os("PATH") {
225-
dirs.extend(env::split_paths(&val));
226-
}
223+
let path_dirs = if let Some(val) = env::var_os("PATH") {
224+
env::split_paths(&val).collect()
225+
} else {
226+
vec![]
227+
};
228+
229+
let home_bin = config.home().clone().into_path_unlocked().join("bin");
230+
231+
// If any of that PATH elements contains `home_bin`, do not
232+
// add it again. This is so that the users can control priority
233+
// of it using PATH, while preserving the historical
234+
// behavior of preferring it over system global directories even
235+
// when not in PATH at all.
236+
// See https://github.com/rust-lang/cargo/issues/11020 for details.
237+
//
238+
// Note: `p == home_bin` will ignore trailing paths, but we don't
239+
// `canonicalize` the paths.
240+
let mut dirs = if path_dirs.iter().any(|p| p == &home_bin) {
241+
vec![]
242+
} else {
243+
vec![home_bin]
244+
};
245+
246+
dirs.extend(path_dirs);
227247
dirs
228248
}
229249

0 commit comments

Comments
 (0)