use std::io;
use std::path::Path;
use std::process::Command;
pub fn open_url(url: &str) -> io::Result<()> {
if cfg!(target_os = "macos") {
Command::new("open").arg(url).spawn()?;
} else if cfg!(windows) {
Command::new("cmd")
.args(["/C", "start", ""])
.arg(url)
.spawn()?;
} else if cfg!(unix) {
Command::new("xdg-open").arg(url).spawn()?;
} else {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"open URL not supported on this platform",
));
}
Ok(())
}
pub fn editor_for_open(editor_path: Option<&str>) -> Option<String> {
editor_path
.map(ToString::to_string)
.or_else(|| std::env::var("EDITOR").ok())
}
pub fn open_in_editor(editor: &str, path: &Path) -> std::io::Result<bool> {
let status = Command::new(editor).arg(path).status()?;
Ok(status.code().is_some())
}
#[cfg(target_os = "macos")]
pub fn open_in_gui(path: &Path) -> std::io::Result<std::process::Child> {
Command::new("open").arg(path).spawn()
}
#[cfg(all(unix, not(target_os = "macos")))]
pub fn open_in_gui(path: &Path) -> std::io::Result<std::process::Child> {
Command::new("xdg-open").arg(path).spawn()
}
#[cfg(windows)]
pub fn open_in_gui(path: &Path) -> std::io::Result<std::process::Child> {
Command::new("explorer").arg(path).spawn()
}
#[cfg(not(any(unix, windows)))]
pub fn open_in_gui(_path: &Path) -> std::io::Result<std::process::Child> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"Open (GUI) not supported on this platform",
))
}
pub fn reveal_in_file_manager(path: &Path) -> std::io::Result<std::process::Child> {
if cfg!(target_os = "macos") {
Command::new("open").arg("-R").arg(path).spawn()
} else if cfg!(windows) {
let abs = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
let p = abs.to_string_lossy();
Command::new("explorer").arg(format!("/select,{p}")).spawn()
} else if cfg!(all(unix, not(target_os = "macos"))) {
let dir = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(path);
Command::new("xdg-open").arg(dir).spawn()
} else {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"Reveal in file manager not supported on this platform",
))
}
}