Skip to main content

uv_shell/
lib.rs

1mod configuration;
2mod runnable;
3mod shlex;
4#[cfg(windows)]
5mod windows;
6
7pub use configuration::{ConfigurationUpdate, update_configuration_file};
8pub use runnable::WindowsRunnable;
9pub use shlex::{escape_posix_for_single_quotes, shlex_posix, shlex_windows};
10#[cfg(windows)]
11pub use windows::prepend_path;
12
13use std::borrow::Cow;
14use std::env::home_dir;
15use std::path::{Path, PathBuf};
16
17use uv_fs::Simplified;
18use uv_static::EnvVars;
19
20#[cfg(unix)]
21use tracing::debug;
22
23/// Shells for which virtualenv activation scripts are available.
24#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
25#[expect(clippy::doc_markdown)]
26pub enum Shell {
27    /// Bourne Again SHell (bash)
28    Bash,
29    /// Friendly Interactive SHell (fish)
30    Fish,
31    /// PowerShell
32    Powershell,
33    /// Cmd (Command Prompt)
34    Cmd,
35    /// Z SHell (zsh)
36    Zsh,
37    /// Nushell
38    Nushell,
39    /// C SHell (csh)
40    Csh,
41    /// Korn SHell (ksh)
42    Ksh,
43}
44
45impl Shell {
46    /// Determine the user's current shell from the environment.
47    ///
48    /// First checks shell-specific environment variables (`NU_VERSION`, `FISH_VERSION`,
49    /// `BASH_VERSION`, `ZSH_VERSION`, `KSH_VERSION`, `PSModulePath`) which are set by the
50    /// respective shells. This takes priority over `SHELL` because on Unix, `SHELL` refers
51    /// to the user's login shell, not the currently running shell.
52    ///
53    /// Falls back to parsing the `SHELL` environment variable if no shell-specific variables
54    /// are found. On Windows, defaults to PowerShell (or Command Prompt if `PROMPT` is set).
55    ///
56    /// Returns `None` if the shell cannot be determined.
57    pub fn from_env() -> Option<Self> {
58        if std::env::var_os(EnvVars::NU_VERSION).is_some() {
59            Some(Self::Nushell)
60        } else if std::env::var_os(EnvVars::FISH_VERSION).is_some() {
61            Some(Self::Fish)
62        } else if std::env::var_os(EnvVars::BASH_VERSION).is_some() {
63            Some(Self::Bash)
64        } else if std::env::var_os(EnvVars::ZSH_VERSION).is_some() {
65            Some(Self::Zsh)
66        } else if std::env::var_os(EnvVars::KSH_VERSION).is_some() {
67            Some(Self::Ksh)
68        } else if std::env::var_os(EnvVars::PS_MODULE_PATH).is_some() {
69            Some(Self::Powershell)
70        } else if let Some(env_shell) = std::env::var_os(EnvVars::SHELL) {
71            Self::from_shell_path(env_shell)
72        } else if cfg!(windows) {
73            // Command Prompt relies on PROMPT for its appearance whereas PowerShell does not.
74            // See: https://stackoverflow.com/a/66415037.
75            if std::env::var_os(EnvVars::PROMPT).is_some() {
76                Some(Self::Cmd)
77            } else {
78                // Fallback to PowerShell if the PROMPT environment variable is not set.
79                Some(Self::Powershell)
80            }
81        } else {
82            // Fallback to detecting the shell from the parent process
83            Self::from_parent_process()
84        }
85    }
86
87    /// Attempt to determine the shell from the parent process.
88    ///
89    /// This is a fallback method for when environment variables don't provide
90    /// enough information about the current shell. It looks at the parent process
91    /// to try to identify which shell is running.
92    ///
93    /// This method currently only works on Unix-like systems. On other platforms,
94    /// it returns `None`.
95    fn from_parent_process() -> Option<Self> {
96        #[cfg(unix)]
97        {
98            // Get the parent process ID
99            let ppid = nix::unistd::getppid();
100            debug!("Detected parent process ID: {ppid}");
101
102            // Try to read the parent process executable path
103            let proc_exe_path = format!("/proc/{ppid}/exe");
104            if let Ok(exe_path) = fs_err::read_link(&proc_exe_path) {
105                debug!("Parent process executable: {}", exe_path.display());
106                if let Some(shell) = Self::from_shell_path(&exe_path) {
107                    return Some(shell);
108                }
109            }
110
111            // If reading exe fails, try reading the comm file
112            let proc_comm_path = format!("/proc/{ppid}/comm");
113            if let Ok(comm) = fs_err::read_to_string(&proc_comm_path) {
114                let comm = comm.trim();
115                debug!("Parent process comm: {comm}");
116                if let Some(shell) = parse_shell_from_path(Path::new(comm)) {
117                    return Some(shell);
118                }
119            }
120
121            debug!("Could not determine shell from parent process");
122            None
123        }
124
125        #[cfg(not(unix))]
126        {
127            None
128        }
129    }
130
131    /// Parse a shell from a path to the executable for the shell.
132    ///
133    /// # Examples
134    ///
135    /// ```ignore
136    /// use crate::shells::Shell;
137    ///
138    /// assert_eq!(Shell::from_shell_path("/bin/bash"), Some(Shell::Bash));
139    /// assert_eq!(Shell::from_shell_path("/usr/bin/zsh"), Some(Shell::Zsh));
140    /// assert_eq!(Shell::from_shell_path("/opt/my_custom_shell"), None);
141    /// ```
142    fn from_shell_path(path: impl AsRef<Path>) -> Option<Self> {
143        parse_shell_from_path(path.as_ref())
144    }
145
146    /// Returns `true` if the shell supports a `PATH` update command.
147    pub fn supports_update(self) -> bool {
148        match self {
149            Self::Powershell | Self::Cmd => true,
150            shell => !shell.configuration_files().is_empty(),
151        }
152    }
153
154    /// Return the configuration files that should be modified to append to a shell's `PATH`.
155    ///
156    /// Some of the logic here is based on rustup's rc file detection.
157    ///
158    /// See: <https://github.com/rust-lang/rustup/blob/fede22fea7b160868cece632bd213e6d72f8912f/src/cli/self_update/shell.rs#L197>
159    pub fn configuration_files(self) -> Vec<PathBuf> {
160        let Some(home_dir) = home_dir() else {
161            return vec![];
162        };
163        match self {
164            Self::Bash => {
165                // On Bash, we need to update both `.bashrc` and `.bash_profile`. The former is
166                // sourced for non-login shells, and the latter is sourced for login shells.
167                //
168                // In lieu of `.bash_profile`, shells will also respect `.bash_login` and
169                // `.profile`, if they exist. So we respect those too.
170                vec![
171                    [".bash_profile", ".bash_login", ".profile"]
172                        .iter()
173                        .map(|rc| home_dir.join(rc))
174                        .find(|rc| rc.is_file())
175                        .unwrap_or_else(|| home_dir.join(".bash_profile")),
176                    home_dir.join(".bashrc"),
177                ]
178            }
179            Self::Ksh => {
180                // On Ksh it's standard POSIX `.profile` for login shells, and `.kshrc` for non-login.
181                vec![home_dir.join(".profile"), home_dir.join(".kshrc")]
182            }
183            Self::Zsh => {
184                // On Zsh, we only need to update `.zshenv`. This file is sourced for both login and
185                // non-login shells. However, we match rustup's logic for determining _which_
186                // `.zshenv` to use.
187                //
188                // See: https://github.com/rust-lang/rustup/blob/fede22fea7b160868cece632bd213e6d72f8912f/src/cli/self_update/shell.rs#L197
189                let zsh_dot_dir = std::env::var(EnvVars::ZDOTDIR)
190                    .ok()
191                    .filter(|dir| !dir.is_empty())
192                    .map(PathBuf::from);
193
194                // Attempt to update an existing `.zshenv` file.
195                if let Some(zsh_dot_dir) = zsh_dot_dir.as_ref() {
196                    // If `ZDOTDIR` is set, and `ZDOTDIR/.zshenv` exists, then we update that file.
197                    let zshenv = zsh_dot_dir.join(".zshenv");
198                    if zshenv.is_file() {
199                        return vec![zshenv];
200                    }
201                }
202                // Whether `ZDOTDIR` is set or not, if `~/.zshenv` exists then we update that file.
203                let zshenv = home_dir.join(".zshenv");
204                if zshenv.is_file() {
205                    return vec![zshenv];
206                }
207
208                if let Some(zsh_dot_dir) = zsh_dot_dir.as_ref() {
209                    // If `ZDOTDIR` is set, then we create `ZDOTDIR/.zshenv`.
210                    vec![zsh_dot_dir.join(".zshenv")]
211                } else {
212                    // If `ZDOTDIR` is _not_ set, then we create `~/.zshenv`.
213                    vec![home_dir.join(".zshenv")]
214                }
215            }
216            Self::Fish => {
217                // On Fish, we only need to update `config.fish`. This file is sourced for both
218                // login and non-login shells. However, we must respect Fish's logic, which reads
219                // from `$XDG_CONFIG_HOME/fish/config.fish` if set, and `~/.config/fish/config.fish`
220                // otherwise.
221                if let Some(xdg_home_dir) = std::env::var(EnvVars::XDG_CONFIG_HOME)
222                    .ok()
223                    .filter(|dir| !dir.is_empty())
224                    .map(PathBuf::from)
225                {
226                    vec![xdg_home_dir.join("fish/config.fish")]
227                } else {
228                    vec![home_dir.join(".config/fish/config.fish")]
229                }
230            }
231            Self::Csh => {
232                // On Csh, we need to update both `.cshrc` and `.login`, like Bash.
233                vec![home_dir.join(".cshrc"), home_dir.join(".login")]
234            }
235            // TODO(charlie): Add support for Nushell.
236            Self::Nushell => vec![],
237            // See: [`crate::windows::prepend_path`].
238            Self::Powershell => vec![],
239            // See: [`crate::windows::prepend_path`].
240            Self::Cmd => vec![],
241        }
242    }
243
244    /// Returns `true` if the given path is on the `PATH` in this shell.
245    pub fn contains_path(path: &Path) -> bool {
246        let home_dir = home_dir();
247        std::env::var_os(EnvVars::PATH)
248            .as_ref()
249            .iter()
250            .flat_map(std::env::split_paths)
251            .map(|path| {
252                // If the first component is `~`, expand to the home directory.
253                if let Some(home_dir) = home_dir.as_ref() {
254                    if path
255                        .components()
256                        .next()
257                        .map(std::path::Component::as_os_str)
258                        == Some("~".as_ref())
259                    {
260                        return home_dir.join(path.components().skip(1).collect::<PathBuf>());
261                    }
262                }
263                path
264            })
265            .any(|p| same_file::is_same_file(path, p).unwrap_or(false))
266    }
267
268    /// Returns the command necessary to prepend a directory to the `PATH` in this shell.
269    pub fn prepend_path(self, path: &Path) -> Option<String> {
270        match self {
271            Self::Nushell => None,
272            Self::Bash | Self::Zsh | Self::Ksh => Some(format!(
273                "export PATH=\"{}:$PATH\"",
274                backslash_escape(&path.simplified_display().to_string()),
275            )),
276            Self::Fish => Some(format!(
277                "fish_add_path \"{}\"",
278                backslash_escape(&path.simplified_display().to_string()),
279            )),
280            Self::Csh => Some(format!(
281                "setenv PATH \"{}:$PATH\"",
282                backslash_escape(&path.simplified_display().to_string()),
283            )),
284            Self::Powershell => Some(format!(
285                "$env:PATH = \"{};$env:PATH\"",
286                backtick_escape(&path.simplified_display().to_string()),
287            )),
288            Self::Cmd => Some(format!(
289                "set PATH=\"{};%PATH%\"",
290                backslash_escape(&path.simplified_display().to_string()),
291            )),
292        }
293    }
294}
295
296impl std::fmt::Display for Shell {
297    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
298        match self {
299            Self::Bash => write!(f, "Bash"),
300            Self::Fish => write!(f, "Fish"),
301            Self::Powershell => write!(f, "PowerShell"),
302            Self::Cmd => write!(f, "Command Prompt"),
303            Self::Zsh => write!(f, "Zsh"),
304            Self::Nushell => write!(f, "Nushell"),
305            Self::Csh => write!(f, "Csh"),
306            Self::Ksh => write!(f, "Ksh"),
307        }
308    }
309}
310
311/// Parse the shell from the name of the shell executable.
312fn parse_shell_from_path(path: &Path) -> Option<Shell> {
313    let name = path.file_stem()?.to_str()?;
314    match name {
315        "bash" => Some(Shell::Bash),
316        "zsh" => Some(Shell::Zsh),
317        "fish" => Some(Shell::Fish),
318        "csh" => Some(Shell::Csh),
319        "ksh" => Some(Shell::Ksh),
320        "powershell" | "powershell_ise" | "pwsh" => Some(Shell::Powershell),
321        _ => None,
322    }
323}
324
325/// Escape a string for use in a shell command by inserting backslashes.
326fn backslash_escape(s: &str) -> Cow<'_, str> {
327    if !s.chars().any(|c| matches!(c, '\\' | '"')) {
328        return Cow::Borrowed(s);
329    }
330
331    let mut escaped = String::with_capacity(s.len());
332    for c in s.chars() {
333        match c {
334            '\\' | '"' => escaped.push('\\'),
335            _ => {}
336        }
337        escaped.push(c);
338    }
339    Cow::Owned(escaped)
340}
341
342/// Escape a string for use in a `PowerShell` command by inserting backticks.
343fn backtick_escape(s: &str) -> Cow<'_, str> {
344    if !s
345        .chars()
346        .any(|c| matches!(c, '"' | '`' | '\u{201C}' | '\u{201D}' | '\u{201E}' | '$'))
347    {
348        return Cow::Borrowed(s);
349    }
350
351    let mut escaped = String::with_capacity(s.len());
352    for c in s.chars() {
353        match c {
354            // Need to also escape unicode double quotes that PowerShell treats
355            // as the ASCII double quote.
356            '"' | '`' | '\u{201C}' | '\u{201D}' | '\u{201E}' | '$' => escaped.push('`'),
357            _ => {}
358        }
359        escaped.push(c);
360    }
361    Cow::Owned(escaped)
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367    use fs_err::File;
368    use temp_env::with_vars;
369    use tempfile::tempdir;
370
371    // First option used by std::env::home_dir.
372    const HOME_DIR_ENV_VAR: &str = if cfg!(windows) {
373        EnvVars::USERPROFILE
374    } else {
375        EnvVars::HOME
376    };
377
378    #[test]
379    fn configuration_files_zsh_no_existing_zshenv() {
380        let tmp_home_dir = tempdir().unwrap();
381        let tmp_zdotdir = tempdir().unwrap();
382
383        with_vars(
384            [
385                (EnvVars::ZDOTDIR, None),
386                (HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
387            ],
388            || {
389                assert_eq!(
390                    Shell::Zsh.configuration_files(),
391                    vec![tmp_home_dir.path().join(".zshenv")]
392                );
393            },
394        );
395
396        with_vars(
397            [
398                (EnvVars::ZDOTDIR, tmp_zdotdir.path().to_str()),
399                (HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
400            ],
401            || {
402                assert_eq!(
403                    Shell::Zsh.configuration_files(),
404                    vec![tmp_zdotdir.path().join(".zshenv")]
405                );
406            },
407        );
408    }
409
410    #[test]
411    fn configuration_files_zsh_existing_home_zshenv() {
412        let tmp_home_dir = tempdir().unwrap();
413        File::create(tmp_home_dir.path().join(".zshenv")).unwrap();
414
415        let tmp_zdotdir = tempdir().unwrap();
416
417        with_vars(
418            [
419                (EnvVars::ZDOTDIR, None),
420                (HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
421            ],
422            || {
423                assert_eq!(
424                    Shell::Zsh.configuration_files(),
425                    vec![tmp_home_dir.path().join(".zshenv")]
426                );
427            },
428        );
429
430        with_vars(
431            [
432                (EnvVars::ZDOTDIR, tmp_zdotdir.path().to_str()),
433                (HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
434            ],
435            || {
436                assert_eq!(
437                    Shell::Zsh.configuration_files(),
438                    vec![tmp_home_dir.path().join(".zshenv")]
439                );
440            },
441        );
442    }
443
444    #[test]
445    fn configuration_files_zsh_existing_zdotdir_zshenv() {
446        let tmp_home_dir = tempdir().unwrap();
447
448        let tmp_zdotdir = tempdir().unwrap();
449        File::create(tmp_zdotdir.path().join(".zshenv")).unwrap();
450
451        with_vars(
452            [
453                (EnvVars::ZDOTDIR, tmp_zdotdir.path().to_str()),
454                (HOME_DIR_ENV_VAR, tmp_home_dir.path().to_str()),
455            ],
456            || {
457                assert_eq!(
458                    Shell::Zsh.configuration_files(),
459                    vec![tmp_zdotdir.path().join(".zshenv")]
460                );
461            },
462        );
463    }
464}