get_shell/
lib.rs

1use std::str::FromStr;
2use sysinfo::{get_current_pid, ProcessExt, System, SystemExt};
3use thiserror::Error;
4
5#[derive(Error, Debug)]
6#[non_exhaustive]
7pub enum Error {
8    #[error("The platform is not supported")]
9    UnsupportedPlatform,
10    #[error("Current process does not have a parent")]
11    NoParent,
12    #[error("Unknown shell")]
13    Unknown,
14    #[error("Unavailable with some su implementations")]
15    InSu,
16}
17
18#[must_use]
19pub fn get_shell_name() -> Result<String, Error> {
20    let sys = System::new_all();
21    let process = sys
22        .get_process(get_current_pid().map_err(|_| Error::UnsupportedPlatform)?)
23        .expect("Process with current pid does not exist");
24    let parent = sys
25        .get_process(process.parent().ok_or(Error::NoParent)?)
26        .expect("Process with parent pid does not exist");
27    let shell = parent.name().trim().to_lowercase();
28    let shell = shell.strip_suffix(".exe").unwrap_or(&shell); // windows bad
29    let shell = shell.strip_prefix("-").unwrap_or(&shell); // login shells
30    Ok(shell.to_owned())
31}
32#[must_use]
33pub fn get_shell() -> Result<Shell, Error> {
34    Shell::get()
35}
36
37#[derive(Debug)]
38pub enum Shell {
39    Bash,
40    Elvish,
41    Fish,
42    Ion,
43    Nushell,
44    Powershell,
45    Xonsh,
46    Zsh,
47}
48
49impl Shell {
50    #[must_use]
51    pub fn get() -> Result<Self, Error> {
52        match get_shell_name()?.as_str() {
53            "su" => Err(Error::InSu),
54            shell if shell.starts_with("python") => Ok(Self::Xonsh),
55            shell => Self::from_str(shell),
56        }
57    }
58}
59
60impl FromStr for Shell {
61    type Err = Error;
62
63    fn from_str(s: &str) -> Result<Self, Self::Err> {
64        match s {
65            "bash" => Ok(Shell::Bash),
66            "elvish" => Ok(Shell::Elvish),
67            "fish" => Ok(Shell::Fish),
68            "ion" => Ok(Shell::Ion),
69            "nu" | "nushell" => Ok(Shell::Nushell),
70            "pwsh" | "powershell" => Ok(Shell::Powershell),
71            "xonsh" | "xon.sh" => Ok(Shell::Xonsh),
72            "zsh" => Ok(Shell::Zsh),
73            _ => Err(Error::Unknown),
74        }
75    }
76}