127 lines
5.5 KiB
Rust
127 lines
5.5 KiB
Rust
use std::path::PathBuf;
|
|
|
|
pub(crate) fn find_executable(name: &str) -> Option<PathBuf> {
|
|
find_executable_in_path(name, &std::env::var_os("PATH").unwrap_or_default())
|
|
}
|
|
|
|
fn find_executable_in_path(name: &str, search_path: &std::ffi::OsStr) -> Option<PathBuf> {
|
|
std::env::split_paths(search_path)
|
|
.map(|dir| dir.join(name)).find(|path| {
|
|
let Ok(metadata) = path.metadata() else { return false };
|
|
if !metadata.is_file() { return false; }
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
metadata.permissions().mode() & 0o111 != 0
|
|
}
|
|
#[cfg(not(unix))]
|
|
{ true }
|
|
})
|
|
}
|
|
|
|
#[cfg(all(unix, not(target_os = "macos")))]
|
|
pub(crate) fn open_external_terminal(folder: &std::path::Path) -> std::io::Result<()> {
|
|
spawn_external_terminal(folder, |command| command.spawn().map(|_| ()))
|
|
}
|
|
|
|
#[cfg(all(unix, not(target_os = "macos")))]
|
|
fn spawn_external_terminal(
|
|
folder: &std::path::Path,
|
|
mut spawn: impl FnMut(&mut std::process::Command) -> std::io::Result<()>,
|
|
) -> std::io::Result<()> {
|
|
// x-terminal-emulator is a Debian alternative, not a cross-desktop standard.
|
|
// Explicit directory flags also work with terminals using an existing server.
|
|
let candidates = [
|
|
("x-terminal-emulator", None),
|
|
("gnome-terminal", Some("--working-directory")),
|
|
("konsole", Some("--workdir")),
|
|
("xfce4-terminal", Some("--working-directory")),
|
|
("mate-terminal", Some("--working-directory")),
|
|
("lxterminal", Some("--working-directory")),
|
|
("xterm", None),
|
|
];
|
|
for (program, directory_flag) in candidates {
|
|
let mut command = std::process::Command::new(program);
|
|
command.current_dir(folder);
|
|
if let Some(flag) = directory_flag { command.arg(flag).arg(folder); }
|
|
match spawn(&mut command) {
|
|
Ok(()) => return Ok(()),
|
|
Err(reason) if reason.kind() == std::io::ErrorKind::NotFound => continue,
|
|
Err(reason) => return Err(std::io::Error::new(reason.kind(), format!("Could not start {program}: {reason}"))),
|
|
}
|
|
}
|
|
Err(std::io::Error::new(std::io::ErrorKind::NotFound,
|
|
"No supported external terminal was found. Install a supported terminal emulator or use RuneStone's Terminal plugin."))
|
|
}
|
|
|
|
// Every test here checks Unix behavior.
|
|
#[cfg(all(test, unix))]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[cfg(unix)]
|
|
#[test]
|
|
fn shell_lookup_skips_non_executable_files_and_directories() {
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let unique = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
|
|
let root = std::env::temp_dir().join(format!("rs-shell-path-{}-{unique}", std::process::id()));
|
|
let first = root.join("first");
|
|
let second = root.join("second");
|
|
std::fs::create_dir_all(&first).unwrap();
|
|
std::fs::create_dir_all(&second).unwrap();
|
|
let blocked = first.join("bash");
|
|
let executable = second.join("bash");
|
|
for path in [&blocked, &executable] { std::fs::write(path, "#!/bin/sh\n").unwrap(); }
|
|
std::fs::set_permissions(&blocked, std::fs::Permissions::from_mode(0o644)).unwrap();
|
|
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap();
|
|
let paths = std::env::join_paths([&first, &second]).unwrap();
|
|
assert_eq!(find_executable_in_path("bash", &paths), Some(executable.clone()));
|
|
std::fs::remove_file(&blocked).unwrap();
|
|
std::fs::create_dir(&blocked).unwrap();
|
|
assert_eq!(find_executable_in_path("bash", &paths), Some(executable.clone()));
|
|
std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o644)).unwrap();
|
|
assert!(find_executable_in_path("bash", &paths).is_none());
|
|
std::fs::remove_dir_all(root).unwrap();
|
|
}
|
|
|
|
#[cfg(all(unix, not(target_os = "macos")))]
|
|
#[test]
|
|
fn external_terminal_falls_back_and_preserves_working_directory() {
|
|
let folder = std::path::Path::new("/tmp/workspace with spaces");
|
|
let mut attempted = Vec::new();
|
|
spawn_external_terminal(folder, |command| {
|
|
let program = command.get_program().to_string_lossy().into_owned();
|
|
attempted.push(program.clone());
|
|
assert_eq!(command.get_current_dir(), Some(folder));
|
|
if program == "gnome-terminal" {
|
|
assert_eq!(command.get_args().collect::<Vec<_>>(), vec![std::ffi::OsStr::new("--working-directory"), folder.as_os_str()]);
|
|
Ok(())
|
|
} else {
|
|
Err(std::io::Error::from(std::io::ErrorKind::NotFound))
|
|
}
|
|
}).unwrap();
|
|
assert_eq!(attempted, ["x-terminal-emulator", "gnome-terminal"]);
|
|
}
|
|
|
|
#[cfg(all(unix, not(target_os = "macos")))]
|
|
#[test]
|
|
fn external_terminal_does_not_hide_launch_errors() {
|
|
let mut attempts = 0;
|
|
let error = spawn_external_terminal(std::path::Path::new("/tmp"), |_| {
|
|
attempts += 1;
|
|
Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
|
|
}).unwrap_err();
|
|
assert_eq!(attempts, 1);
|
|
assert!(error.to_string().contains("Could not start x-terminal-emulator"));
|
|
}
|
|
|
|
#[cfg(all(unix, not(target_os = "macos")))]
|
|
#[test]
|
|
fn external_terminal_reports_missing_emulators() {
|
|
let error = spawn_external_terminal(std::path::Path::new("/tmp"), |_| {
|
|
Err(std::io::Error::from(std::io::ErrorKind::NotFound))
|
|
}).unwrap_err();
|
|
assert!(error.to_string().contains("No supported external terminal"));
|
|
}
|
|
}
|