//! Which shell a new terminal runs. use std::ffi::OsString; use std::path::{Path, PathBuf}; /// A program with its arguments. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Shell { /// The program: a path, or a name looked up in `PATH`. pub program: PathBuf, /// Its arguments. pub args: Vec, } impl Shell { /// A shell without arguments. pub fn new(program: impl Into) -> Self { Self { program: program.into(), args: Vec::new(), } } } /// The shell for a new terminal when the user chose none. /// /// - **Windows:** `pwsh.exe` (PowerShell 7) from `PATH`, else /// `powershell.exe` (Windows PowerShell), else `%COMSPEC%`, else /// `cmd.exe`. PowerShell starts with `-NoLogo`. /// - **Unix:** `$SHELL`, else `/bin/sh`. pub fn default_shell() -> Shell { if cfg!(windows) { for name in ["pwsh.exe", "powershell.exe"] { if let Some(path) = find_in_path(name) { return Shell { program: path, args: vec![OsString::from("-NoLogo")], }; } } let comspec = std::env::var_os("COMSPEC") .map(PathBuf::from) .filter(|p| p.is_file()); return Shell::new(comspec.unwrap_or_else(|| PathBuf::from("cmd.exe"))); } let shell = std::env::var_os("SHELL") .filter(|s| !s.is_empty()) .map(PathBuf::from); Shell::new(shell.unwrap_or_else(|| PathBuf::from("/bin/sh"))) } /// Looks a program up in `PATH`. /// /// # Parameters /// - `name`: a file name such as `pwsh.exe`. On Windows a name without an /// extension is also tried with each extension in `PATHEXT`. /// /// # Returns /// The first matching file, or `None`. A name with a directory part is /// returned as is if it is a file. pub fn find_in_path(name: &str) -> Option { let candidate = Path::new(name); if candidate.components().count() > 1 { return candidate.is_file().then(|| candidate.to_path_buf()); } let path = std::env::var_os("PATH")?; let extensions: Vec = if cfg!(windows) && candidate.extension().is_none() { std::env::var("PATHEXT") .unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into()) .split(';') .filter(|e| !e.is_empty()) .map(str::to_string) .collect() } else { Vec::new() }; for dir in std::env::split_paths(&path) { let plain = dir.join(name); if plain.is_file() { return Some(plain); } for ext in &extensions { let with_ext = dir.join(format!("{name}{ext}")); if with_ext.is_file() { return Some(with_ext); } } } None } #[cfg(test)] mod tests { use super::*; #[test] fn default_shell_exists() { let shell = default_shell(); let found = shell.program.is_file() || find_in_path(&shell.program.to_string_lossy()).is_some(); assert!(found, "{shell:?}"); } #[test] fn finds_programs_in_path() { let name = if cfg!(windows) { "cmd" } else { "sh" }; assert!(find_in_path(name).is_some()); assert!(find_in_path("lutra-no-such-program-x").is_none()); } }