Skip to content

Commit

Permalink
Use which in non-macOS unix
Browse files Browse the repository at this point in the history
  • Loading branch information
hybras committed Feb 19, 2021
1 parent 204f0ca commit ef8ab99
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 17 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
32 changes: 15 additions & 17 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,24 +201,22 @@ mod unix {
process::{Command, ExitStatus, Stdio},
};

use which::which;

pub fn that<T: AsRef<OsStr> + Sized>(path: T) -> Result<ExitStatus> {
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<T: AsRef<OsStr> + Sized>(path: T, app: impl Into<String>) -> Result<ExitStatus> {
Expand Down

0 comments on commit ef8ab99

Please sign in to comment.