diff --git a/crates/native/src/process.rs b/crates/native/src/process.rs index ce762e21..391bfec4 100644 --- a/crates/native/src/process.rs +++ b/crates/native/src/process.rs @@ -330,10 +330,21 @@ fn detect_discord_scheme_handler() -> bool { false } -/// Finds a program on `PATH`. +/// Finds a program on `PATH`. The path returned is absolute: a relative `PATH` entry (`.`, `bin`) +/// is taken from the working folder, as the shell does, so the result still names the same file +/// after it is stored and used from elsewhere (launch accepts only absolute locations). pub(crate) fn which(name: &str) -> Option { let path = std::env::var_os("PATH")?; - std::env::split_paths(&path).map(|d| d.join(name)).find(|p| p.is_file()) + which_in(&path, std::env::current_dir().ok().as_deref(), name) +} + +/// [`which`] over the given `PATH` value, with relative entries taken from `cwd`. Without a +/// working folder, relative entries are skipped: what they name can't be said. +fn which_in(path: &std::ffi::OsStr, cwd: Option<&Path>, name: &str) -> Option { + std::env::split_paths(path) + .filter_map(|d| if d.is_absolute() { Some(d) } else { cwd.map(|c| c.join(d)) }) + .map(|d| d.join(name)) + .find(|p| p.is_file()) } /// Starts an app binary from its own folder. @@ -570,6 +581,24 @@ mod tests { use super::*; + /// A program found through a relative `PATH` entry comes back as an absolute path, so it is + /// still a launchable location once stored. + #[test] + fn which_makes_a_relative_path_entry_absolute() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("bin")).unwrap(); + std::fs::write(dir.path().join("bin").join("wordcraft"), b"").unwrap(); + let path = std::env::join_paths([Path::new("bin"), Path::new("other")]).unwrap(); + let found = which_in(&path, Some(dir.path()), "wordcraft").unwrap(); + assert!(found.is_absolute() && found.is_file(), "{found:?}"); + assert_eq!(found, dir.path().join("bin").join("wordcraft")); + // An absolute entry is used as it is; without a working folder a relative one is skipped. + let abs = std::env::join_paths([dir.path().join("bin")]).unwrap(); + assert_eq!(which_in(&abs, None, "wordcraft"), Some(dir.path().join("bin").join("wordcraft"))); + assert_eq!(which_in(&path, None, "wordcraft"), None); + assert_eq!(which_in(&path, Some(dir.path()), "missing"), None); + } + struct RunningProbe(Child); impl RunningProbe {