From 3133b426312a4e75a9c650a39994113e0621d5bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Ci=C4=99=C5=BCarkiewicz?= Date: Thu, 25 Aug 2022 12:15:34 -0700 Subject: [PATCH] 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/ ``` Fix #11020 --- src/bin/cargo/main.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/bin/cargo/main.rs b/src/bin/cargo/main.rs index d0a18293f6ef..b7ef26987fce 100644 --- a/src/bin/cargo/main.rs +++ b/src/bin/cargo/main.rs @@ -177,10 +177,30 @@ fn is_executable>(path: P) -> bool { } fn search_directories(config: &Config) -> Vec { - let mut dirs = vec![config.home().clone().into_path_unlocked().join("bin")]; - if let Some(val) = env::var_os("PATH") { - dirs.extend(env::split_paths(&val)); - } + let path_dirs = if let Some(val) = env::var_os("PATH") { + env::split_paths(&val).collect() + } else { + vec![] + }; + + let home_bin = config.home().clone().into_path_unlocked().join("bin"); + + // If any of that PATH elements contains `home_bin`, do not + // add it again. This is so that the users can control priority + // of it using PATH, while preserving the historical + // behavior of preferring it over system global directories even + // when not in PATH at all. + // See https://github.com/rust-lang/cargo/issues/11020 for details. + // + // Note: `p == home_bin` will ignore trailing paths, but we don't + // `canonicalize` the paths. + let mut dirs = if path_dirs.iter().any(|p| p == &home_bin) { + vec![] + } else { + vec![home_bin] + }; + + dirs.extend(path_dirs); dirs }