diff --git a/Cargo.toml b/Cargo.toml index 8dfa70e..88003d0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,3 +18,6 @@ name = "open" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["shellapi"] } + +[target.'cfg(all(unix, not(macos)))'.dependencies] +which = "4" \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 3c6a11b..ac11a02 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -201,24 +201,22 @@ mod unix { process::{Command, ExitStatus, Stdio}, }; + use which::which; + pub fn that + Sized>(path: T) -> Result { - let path_ref = path.as_ref(); - let mut last_err = Error::from_raw_os_error(0); - for program in &["xdg-open", "gnome-open", "kde-open", "wslview"] { - match Command::new(program) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .arg(path_ref) - .spawn() - { - Ok(mut child) => return child.wait(), - Err(err) => { - last_err = err; - continue; - } - } - } - Err(last_err) + ["xdg-open", "gnome-open", "kde-open", "wslview"] // Open handlers + .iter() + .find(|it| which(it).is_ok()) // find the first handler that exists + .ok_or(Error::from_raw_os_error(0)) // If not found, return err + .and_then(|program| { + // If found run the handler + Command::new(program) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .arg(path.as_ref()) + .spawn()? + .wait() + }) } pub fn with + Sized>(path: T, app: impl Into) -> Result {