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#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
25#[expect(clippy::doc_markdown)]
26pub enum Shell {
27 Bash,
29 Fish,
31 Powershell,
33 Cmd,
35 Zsh,
37 Nushell,
39 Csh,
41 Ksh,
43}
44
45impl Shell {
46 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 if std::env::var_os(EnvVars::PROMPT).is_some() {
76 Some(Self::Cmd)
77 } else {
78 Some(Self::Powershell)
80 }
81 } else {
82 Self::from_parent_process()
84 }
85 }
86
87 fn from_parent_process() -> Option<Self> {
96 #[cfg(unix)]
97 {
98 let ppid = nix::unistd::getppid();
100 debug!("Detected parent process ID: {ppid}");
101
102 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 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 fn from_shell_path(path: impl AsRef<Path>) -> Option<Self> {
143 parse_shell_from_path(path.as_ref())
144 }
145
146 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 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 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 vec![home_dir.join(".profile"), home_dir.join(".kshrc")]
182 }
183 Self::Zsh => {
184 let zsh_dot_dir = std::env::var(EnvVars::ZDOTDIR)
190 .ok()
191 .filter(|dir| !dir.is_empty())
192 .map(PathBuf::from);
193
194 if let Some(zsh_dot_dir) = zsh_dot_dir.as_ref() {
196 let zshenv = zsh_dot_dir.join(".zshenv");
198 if zshenv.is_file() {
199 return vec![zshenv];
200 }
201 }
202 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 vec![zsh_dot_dir.join(".zshenv")]
211 } else {
212 vec![home_dir.join(".zshenv")]
214 }
215 }
216 Self::Fish => {
217 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 vec![home_dir.join(".cshrc"), home_dir.join(".login")]
234 }
235 Self::Nushell => vec![],
237 Self::Powershell => vec![],
239 Self::Cmd => vec![],
241 }
242 }
243
244 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 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 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
311fn 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
325fn 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
342fn 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 '"' | '`' | '\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 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}