1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use crate::{shell_error::ShellError, shells::*};
use std::path::Path;
use std::str::FromStr;
use std::{env, fmt};
use tracing::{debug, instrument};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ShellType {
    Bash,
    Elvish,
    Fish,
    Ion,
    Nu,
    Pwsh,
    Sh,
    Xonsh,
    Zsh,
}

impl ShellType {
    /// Return a list of all shell types.
    pub fn variants() -> Vec<Self> {
        vec![
            Self::Bash,
            Self::Elvish,
            Self::Fish,
            Self::Ion,
            Self::Nu,
            Self::Pwsh,
            Self::Sh,
            Self::Xonsh,
            Self::Zsh,
        ]
    }

    /// Return a list of shell types for the current operating system.
    pub fn os_variants() -> Vec<Self> {
        #[cfg(windows)]
        {
            vec![
                Self::Bash,
                Self::Elvish,
                Self::Fish,
                Self::Nu,
                Self::Xonsh,
                Self::Pwsh,
            ]
        }

        #[cfg(unix)]
        Self::variants()
    }

    /// Detect the current shell by inspecting the `$SHELL` environment variable,
    /// and the parent process hierarchy.
    pub fn detect() -> Option<Self> {
        Self::try_detect().ok()
    }

    /// Detect the current shell by inspecting the `$SHELL` environment variable,
    /// and the parent process hierarchy. If no shell could be find, return a fallback.
    pub fn detect_with_fallback() -> Self {
        Self::detect().unwrap_or_else(|| {
            let fallback = if env::consts::OS == "windows" {
                ShellType::Pwsh
            } else {
                ShellType::Sh
            };

            debug!("Falling back to {} shell", fallback);

            fallback
        })
    }

    /// Detect the current shell by inspecting the `$SHELL` environment variable,
    /// and the parent process hierarchy, and return an error if not detected.
    #[instrument]
    pub fn try_detect() -> Result<Self, ShellError> {
        debug!("Attempting to detect the current shell");

        if let Ok(env_value) = env::var("SHELL") {
            if !env_value.is_empty() {
                debug!(
                    env = &env_value,
                    "Detecting from SHELL environment variable"
                );

                if let Some(shell) = parse_shell_from_path(&env_value) {
                    debug!("Detected {} shell", shell);

                    return Ok(shell);
                }
            }
        }

        debug!("Detecting from operating system");

        if let Some(shell) = detect_from_os() {
            debug!("Detected {} shell", shell);

            return Ok(shell);
        }

        debug!("Could not detect a shell!");

        Err(ShellError::CouldNotDetectShell)
    }

    /// Build a [`Shell`] instance from the current type.
    pub fn build(&self) -> BoxedShell {
        match self {
            Self::Bash => Box::new(Bash::new()),
            Self::Elvish => Box::new(Elvish::new()),
            Self::Fish => Box::new(Fish::new()),
            Self::Ion => Box::new(Ion::new()),
            Self::Nu => Box::new(Nu::new()),
            Self::Pwsh => Box::new(Pwsh::new()),
            Self::Sh => Box::new(Sh::new()),
            Self::Xonsh => Box::new(Xonsh::new()),
            Self::Zsh => Box::new(Zsh::new()),
        }
    }
}

impl fmt::Display for ShellType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Bash => "bash",
                Self::Elvish => "elvish",
                Self::Fish => "fish",
                Self::Ion => "ion",
                Self::Nu => "nu",
                Self::Pwsh => "pwsh",
                Self::Sh => "sh",
                Self::Xonsh => "xonsh",
                Self::Zsh => "zsh",
            }
        )
    }
}

impl FromStr for ShellType {
    type Err = ShellError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "bash" => Ok(ShellType::Bash),
            "elv" | "elvish" => Ok(ShellType::Elvish),
            "fish" => Ok(ShellType::Fish),
            "ion" => Ok(ShellType::Ion),
            "nu" | "nushell" => Ok(ShellType::Nu),
            "pwsh" | "powershell" | "powershell_ise" => Ok(ShellType::Pwsh),
            "sh" => Ok(ShellType::Sh),
            "xonsh" | "xon.sh" => Ok(ShellType::Xonsh),
            "zsh" => Ok(ShellType::Zsh),
            _ => Err(ShellError::UnknownShell {
                name: value.to_owned(),
            }),
        }
    }
}

impl TryFrom<&str> for ShellType {
    type Error = ShellError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::from_str(value)
    }
}

impl TryFrom<String> for ShellType {
    type Error = ShellError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::from_str(&value)
    }
}

pub fn parse_shell_from_path<P: AsRef<Path>>(path: P) -> Option<ShellType> {
    // Remove trailing extensions (like `.exe`)
    let name = path.as_ref().file_stem()?.to_str()?;

    // Remove login shell leading `-`
    ShellType::from_str(name.strip_prefix('-').unwrap_or(name)).ok()
}

fn detect_from_os() -> Option<ShellType> {
    #[cfg(windows)]
    {
        windows::detect()
    }

    #[cfg(unix)]
    {
        unix::detect()
    }
}

#[cfg(unix)]
mod unix {
    use super::*;
    use std::io::BufRead;
    use std::process::{self, Command};
    use tracing::trace;

    pub struct ProcessStatus {
        ppid: Option<u32>,
        comm: String,
    }

    // PPID COMM
    //  635 -zsh
    pub fn detect_from_process_status(current_pid: u32) -> Option<ProcessStatus> {
        let output = Command::new("ps")
            .args(["-o", "ppid,comm"])
            .arg(current_pid.to_string())
            .output()
            .ok()?;

        let mut lines = output.stdout.lines();
        let line = lines.nth(1)?.ok()?;
        let mut parts = line.split_whitespace();

        match (parts.next(), parts.next()) {
            (Some(ppid), Some(comm)) => {
                let status = ProcessStatus {
                    ppid: ppid.parse().ok(),
                    comm: comm.to_owned(),
                };

                trace!(
                    pid = current_pid,
                    next_pid = &status.ppid,
                    comm = &status.comm,
                    "Running ps command to find shell"
                );

                Some(status)
            }
            _ => None,
        }
    }

    pub fn detect() -> Option<ShellType> {
        let mut pid = Some(process::id());
        let mut depth = 0;

        while let Some(current_pid) = pid {
            if depth > 10 {
                return None;
            }

            let Some(status) = detect_from_process_status(current_pid) else {
                break;
            };

            if let Some(shell) = parse_shell_from_path(status.comm) {
                return Some(shell);
            }

            pid = status.ppid;
            depth += 1;
        }

        None
    }
}

#[cfg(windows)]
mod windows {
    use super::*;
    use sysinfo::{get_current_pid, System};
    use tracing::trace;

    pub fn detect() -> Option<ShellType> {
        let mut system = System::new();
        let mut pid = get_current_pid().ok();
        let mut depth = 0;

        while let Some(current_pid) = pid {
            if depth > 10 {
                return None;
            }

            system.refresh_process(current_pid);

            if let Some(process) = system.process(current_pid) {
                pid = process.parent();

                if let Some(exe_path) = process.exe() {
                    trace!(
                        pid = current_pid.as_u32(),
                        next_pid = pid.map(|p| p.as_u32()),
                        exe = ?exe_path,
                        "Inspecting process to find shell"
                    );

                    if let Some(shell) = parse_shell_from_path(exe_path) {
                        return Some(shell);
                    }
                }
            } else {
                break;
            }

            depth += 1;
        }

        None
    }
}