1use schemars::JsonSchema;
2use serde::{Deserialize, Serialize};
3use std::{borrow::Cow, fmt, path::Path, sync::LazyLock};
4
5/// Shell configuration to open the terminal with.
6#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema, Hash)]
7#[serde(rename_all = "snake_case")]
8pub enum Shell {
9 /// Use the system's default terminal configuration in /etc/passwd
10 #[default]
11 System,
12 /// Use a specific program with no arguments.
13 Program(String),
14 /// Use a specific program with arguments.
15 WithArguments {
16 /// The program to run.
17 program: String,
18 /// The arguments to pass to the program.
19 args: Vec<String>,
20 /// An optional string to override the title of the terminal tab
21 title_override: Option<String>,
22 },
23}
24
25impl Shell {
26 pub fn program(&self) -> String {
27 match self {
28 Shell::Program(program) => program.clone(),
29 Shell::WithArguments { program, .. } => program.clone(),
30 Shell::System => get_system_shell(),
31 }
32 }
33
34 pub fn program_and_args(&self) -> (String, &[String]) {
35 match self {
36 Shell::Program(program) => (program.clone(), &[]),
37 Shell::WithArguments { program, args, .. } => (program.clone(), args),
38 Shell::System => (get_system_shell(), &[]),
39 }
40 }
41
42 pub fn shell_kind(&self, is_windows: bool) -> ShellKind {
43 match self {
44 Shell::Program(program) => ShellKind::new(program, is_windows),
45 Shell::WithArguments { program, .. } => ShellKind::new(program, is_windows),
46 Shell::System => ShellKind::system(),
47 }
48 }
49}
50
51#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
52pub enum ShellKind {
53 #[default]
54 Posix,
55 Csh,
56 Tcsh,
57 Rc,
58 Fish,
59 PowerShell,
60 Nushell,
61 Cmd,
62 Xonsh,
63 Elvish,
64}
65
66pub fn get_system_shell() -> String {
67 if cfg!(windows) {
68 get_windows_system_shell()
69 } else {
70 std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
71 }
72}
73
74pub fn get_default_system_shell() -> String {
75 if cfg!(windows) {
76 get_windows_system_shell()
77 } else {
78 "/bin/sh".to_string()
79 }
80}
81
82/// Get the default system shell, preferring git-bash on Windows.
83pub fn get_default_system_shell_preferring_bash() -> String {
84 if cfg!(windows) {
85 get_windows_git_bash().unwrap_or_else(|| get_windows_system_shell())
86 } else {
87 "/bin/sh".to_string()
88 }
89}
90
91pub fn get_windows_git_bash() -> Option<String> {
92 static GIT_BASH: LazyLock<Option<String>> = LazyLock::new(|| {
93 // /path/to/git/cmd/git.exe/../../bin/bash.exe
94 let git = which::which("git").ok()?;
95 let git_bash = git.parent()?.parent()?.join("bin").join("bash.exe");
96 if git_bash.is_file() {
97 log::info!("Found git-bash at {}", git_bash.display());
98 Some(git_bash.to_string_lossy().to_string())
99 } else {
100 None
101 }
102 });
103
104 (*GIT_BASH).clone()
105}
106
107pub fn get_windows_system_shell() -> String {
108 use std::path::PathBuf;
109
110 fn find_pwsh_in_programfiles(find_alternate: bool, find_preview: bool) -> Option<PathBuf> {
111 #[cfg(target_pointer_width = "64")]
112 let env_var = if find_alternate {
113 "ProgramFiles(x86)"
114 } else {
115 "ProgramFiles"
116 };
117
118 #[cfg(target_pointer_width = "32")]
119 let env_var = if find_alternate {
120 "ProgramW6432"
121 } else {
122 "ProgramFiles"
123 };
124
125 let install_base_dir = PathBuf::from(std::env::var_os(env_var)?).join("PowerShell");
126 install_base_dir
127 .read_dir()
128 .ok()?
129 .filter_map(Result::ok)
130 .filter(|entry| matches!(entry.file_type(), Ok(ft) if ft.is_dir()))
131 .filter_map(|entry| {
132 let dir_name = entry.file_name();
133 let dir_name = dir_name.to_string_lossy();
134
135 let version = if find_preview {
136 let dash_index = dir_name.find('-')?;
137 if &dir_name[dash_index + 1..] != "preview" {
138 return None;
139 };
140 dir_name[..dash_index].parse::<u32>().ok()?
141 } else {
142 dir_name.parse::<u32>().ok()?
143 };
144
145 let exe_path = entry.path().join("pwsh.exe");
146 if exe_path.exists() {
147 Some((version, exe_path))
148 } else {
149 None
150 }
151 })
152 .max_by_key(|(version, _)| *version)
153 .map(|(_, path)| path)
154 }
155
156 fn find_pwsh_in_msix(find_preview: bool) -> Option<PathBuf> {
157 let msix_app_dir =
158 PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("Microsoft\\WindowsApps");
159 if !msix_app_dir.exists() {
160 return None;
161 }
162
163 let prefix = if find_preview {
164 "Microsoft.PowerShellPreview_"
165 } else {
166 "Microsoft.PowerShell_"
167 };
168 msix_app_dir
169 .read_dir()
170 .ok()?
171 .filter_map(|entry| {
172 let entry = entry.ok()?;
173 if !matches!(entry.file_type(), Ok(ft) if ft.is_dir()) {
174 return None;
175 }
176
177 if !entry.file_name().to_string_lossy().starts_with(prefix) {
178 return None;
179 }
180
181 let exe_path = entry.path().join("pwsh.exe");
182 exe_path.exists().then_some(exe_path)
183 })
184 .next()
185 }
186
187 fn find_pwsh_in_scoop() -> Option<PathBuf> {
188 let pwsh_exe =
189 PathBuf::from(std::env::var_os("USERPROFILE")?).join("scoop\\shims\\pwsh.exe");
190 pwsh_exe.exists().then_some(pwsh_exe)
191 }
192
193 static SYSTEM_SHELL: LazyLock<String> = LazyLock::new(|| {
194 find_pwsh_in_programfiles(false, false)
195 .or_else(|| find_pwsh_in_programfiles(true, false))
196 .or_else(|| find_pwsh_in_msix(false))
197 .or_else(|| find_pwsh_in_programfiles(false, true))
198 .or_else(|| find_pwsh_in_msix(true))
199 .or_else(|| find_pwsh_in_programfiles(true, true))
200 .or_else(find_pwsh_in_scoop)
201 .map(|p| p.to_string_lossy().into_owned())
202 .unwrap_or("powershell.exe".to_string())
203 });
204
205 (*SYSTEM_SHELL).clone()
206}
207
208impl fmt::Display for ShellKind {
209 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 match self {
211 ShellKind::Posix => write!(f, "sh"),
212 ShellKind::Csh => write!(f, "csh"),
213 ShellKind::Tcsh => write!(f, "tcsh"),
214 ShellKind::Fish => write!(f, "fish"),
215 ShellKind::PowerShell => write!(f, "powershell"),
216 ShellKind::Nushell => write!(f, "nu"),
217 ShellKind::Cmd => write!(f, "cmd"),
218 ShellKind::Rc => write!(f, "rc"),
219 ShellKind::Xonsh => write!(f, "xonsh"),
220 ShellKind::Elvish => write!(f, "elvish"),
221 }
222 }
223}
224
225impl ShellKind {
226 pub fn system() -> Self {
227 Self::new(&get_system_shell(), cfg!(windows))
228 }
229
230 pub fn new(program: impl AsRef<Path>, is_windows: bool) -> Self {
231 let program = program.as_ref();
232 let program = program
233 .file_stem()
234 .unwrap_or_else(|| program.as_os_str())
235 .to_string_lossy();
236
237 match &*program {
238 "powershell" | "pwsh" => ShellKind::PowerShell,
239 "cmd" => ShellKind::Cmd,
240 "nu" => ShellKind::Nushell,
241 "fish" => ShellKind::Fish,
242 "csh" => ShellKind::Csh,
243 "tcsh" => ShellKind::Tcsh,
244 "rc" => ShellKind::Rc,
245 "xonsh" => ShellKind::Xonsh,
246 "elvish" => ShellKind::Elvish,
247 "sh" | "bash" | "zsh" => ShellKind::Posix,
248 _ if is_windows => ShellKind::PowerShell,
249 // Some other shell detected, the user might install and use a
250 // unix-like shell.
251 _ => ShellKind::Posix,
252 }
253 }
254
255 pub fn to_shell_variable(self, input: &str) -> String {
256 match self {
257 Self::PowerShell => Self::to_powershell_variable(input),
258 Self::Cmd => Self::to_cmd_variable(input),
259 Self::Posix => input.to_owned(),
260 Self::Fish => input.to_owned(),
261 Self::Csh => input.to_owned(),
262 Self::Tcsh => input.to_owned(),
263 Self::Rc => input.to_owned(),
264 Self::Nushell => Self::to_nushell_variable(input),
265 Self::Xonsh => input.to_owned(),
266 Self::Elvish => input.to_owned(),
267 }
268 }
269
270 fn to_cmd_variable(input: &str) -> String {
271 if let Some(var_str) = input.strip_prefix("${") {
272 if var_str.find(':').is_none() {
273 // If the input starts with "${", remove the trailing "}"
274 format!("%{}%", &var_str[..var_str.len() - 1])
275 } else {
276 // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
277 // which will result in the task failing to run in such cases.
278 input.into()
279 }
280 } else if let Some(var_str) = input.strip_prefix('$') {
281 // If the input starts with "$", directly append to "$env:"
282 format!("%{}%", var_str)
283 } else {
284 // If no prefix is found, return the input as is
285 input.into()
286 }
287 }
288
289 fn to_powershell_variable(input: &str) -> String {
290 if let Some(var_str) = input.strip_prefix("${") {
291 if var_str.find(':').is_none() {
292 // If the input starts with "${", remove the trailing "}"
293 format!("$env:{}", &var_str[..var_str.len() - 1])
294 } else {
295 // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation,
296 // which will result in the task failing to run in such cases.
297 input.into()
298 }
299 } else if let Some(var_str) = input.strip_prefix('$') {
300 // If the input starts with "$", directly append to "$env:"
301 format!("$env:{}", var_str)
302 } else {
303 // If no prefix is found, return the input as is
304 input.into()
305 }
306 }
307
308 fn to_nushell_variable(input: &str) -> String {
309 let mut result = String::new();
310 let mut source = input;
311 let mut is_start = true;
312
313 loop {
314 match source.chars().next() {
315 None => return result,
316 Some('$') => {
317 source = Self::parse_nushell_var(&source[1..], &mut result, is_start);
318 is_start = false;
319 }
320 Some(_) => {
321 is_start = false;
322 let chunk_end = source.find('$').unwrap_or(source.len());
323 let (chunk, rest) = source.split_at(chunk_end);
324 result.push_str(chunk);
325 source = rest;
326 }
327 }
328 }
329 }
330
331 fn parse_nushell_var<'a>(source: &'a str, text: &mut String, is_start: bool) -> &'a str {
332 if source.starts_with("env.") {
333 text.push('$');
334 return source;
335 }
336
337 match source.chars().next() {
338 Some('{') => {
339 let source = &source[1..];
340 if let Some(end) = source.find('}') {
341 let var_name = &source[..end];
342 if !var_name.is_empty() {
343 if !is_start {
344 text.push_str("(");
345 }
346 text.push_str("$env.");
347 text.push_str(var_name);
348 if !is_start {
349 text.push_str(")");
350 }
351 &source[end + 1..]
352 } else {
353 text.push_str("${}");
354 &source[end + 1..]
355 }
356 } else {
357 text.push_str("${");
358 source
359 }
360 }
361 Some(c) if c.is_alphabetic() || c == '_' => {
362 let end = source
363 .find(|c: char| !c.is_alphanumeric() && c != '_')
364 .unwrap_or(source.len());
365 let var_name = &source[..end];
366 if !is_start {
367 text.push_str("(");
368 }
369 text.push_str("$env.");
370 text.push_str(var_name);
371 if !is_start {
372 text.push_str(")");
373 }
374 &source[end..]
375 }
376 _ => {
377 text.push('$');
378 source
379 }
380 }
381 }
382
383 pub fn args_for_shell(&self, interactive: bool, combined_command: String) -> Vec<String> {
384 match self {
385 ShellKind::PowerShell => vec!["-C".to_owned(), combined_command],
386 ShellKind::Cmd => vec!["/C".to_owned(), combined_command],
387 ShellKind::Posix
388 | ShellKind::Nushell
389 | ShellKind::Fish
390 | ShellKind::Csh
391 | ShellKind::Tcsh
392 | ShellKind::Rc
393 | ShellKind::Xonsh
394 | ShellKind::Elvish => interactive
395 .then(|| "-i".to_owned())
396 .into_iter()
397 .chain(["-c".to_owned(), combined_command])
398 .collect(),
399 }
400 }
401
402 pub const fn command_prefix(&self) -> Option<char> {
403 match self {
404 ShellKind::PowerShell => Some('&'),
405 ShellKind::Nushell => Some('^'),
406 ShellKind::Posix
407 | ShellKind::Csh
408 | ShellKind::Tcsh
409 | ShellKind::Rc
410 | ShellKind::Fish
411 | ShellKind::Cmd
412 | ShellKind::Xonsh
413 | ShellKind::Elvish => None,
414 }
415 }
416
417 pub fn prepend_command_prefix<'a>(&self, command: &'a str) -> Cow<'a, str> {
418 match self.command_prefix() {
419 Some(prefix) if !command.starts_with(prefix) => {
420 Cow::Owned(format!("{prefix}{command}"))
421 }
422 _ => Cow::Borrowed(command),
423 }
424 }
425
426 pub const fn sequential_commands_separator(&self) -> char {
427 match self {
428 ShellKind::Cmd => '&',
429 ShellKind::Posix
430 | ShellKind::Csh
431 | ShellKind::Tcsh
432 | ShellKind::Rc
433 | ShellKind::Fish
434 | ShellKind::PowerShell
435 | ShellKind::Nushell
436 | ShellKind::Xonsh
437 | ShellKind::Elvish => ';',
438 }
439 }
440
441 pub const fn sequential_and_commands_separator(&self) -> &'static str {
442 match self {
443 ShellKind::Cmd
444 | ShellKind::Posix
445 | ShellKind::Csh
446 | ShellKind::Tcsh
447 | ShellKind::Rc
448 | ShellKind::Fish
449 | ShellKind::PowerShell
450 | ShellKind::Xonsh => "&&",
451 ShellKind::Nushell | ShellKind::Elvish => ";",
452 }
453 }
454
455 pub fn try_quote<'a>(&self, arg: &'a str) -> Option<Cow<'a, str>> {
456 shlex::try_quote(arg).ok().map(|arg| match self {
457 // If we are running in PowerShell, we want to take extra care when escaping strings.
458 // In particular, we want to escape strings with a backtick (`) rather than a backslash (\).
459 ShellKind::PowerShell => Cow::Owned(arg.replace("\\\"", "`\"").replace("\\\\", "\\")),
460 ShellKind::Cmd => Cow::Owned(arg.replace("\\\\", "\\")),
461 ShellKind::Posix
462 | ShellKind::Csh
463 | ShellKind::Tcsh
464 | ShellKind::Rc
465 | ShellKind::Fish
466 | ShellKind::Nushell
467 | ShellKind::Xonsh
468 | ShellKind::Elvish => arg,
469 })
470 }
471
472 /// Quotes the given argument if necessary, taking into account the command prefix.
473 ///
474 /// In other words, this will consider quoting arg without its command prefix to not break the command.
475 /// You should use this over `try_quote` when you want to quote a shell command.
476 pub fn try_quote_prefix_aware<'a>(&self, arg: &'a str) -> Option<Cow<'a, str>> {
477 if let Some(char) = self.command_prefix() {
478 if let Some(arg) = arg.strip_prefix(char) {
479 // we have a command that is prefixed
480 for quote in ['\'', '"'] {
481 if let Some(arg) = arg
482 .strip_prefix(quote)
483 .and_then(|arg| arg.strip_suffix(quote))
484 {
485 // and the command itself is wrapped as a literal, that
486 // means the prefix exists to interpret a literal as a
487 // command. So strip the quotes, quote the command, and
488 // re-add the quotes if they are missing after requoting
489 let quoted = self.try_quote(arg)?;
490 return Some(if quoted.starts_with(['\'', '"']) {
491 Cow::Owned(self.prepend_command_prefix("ed).into_owned())
492 } else {
493 Cow::Owned(
494 self.prepend_command_prefix(&format!("{quote}{quoted}{quote}"))
495 .into_owned(),
496 )
497 });
498 }
499 }
500 return self
501 .try_quote(arg)
502 .map(|quoted| Cow::Owned(self.prepend_command_prefix("ed).into_owned()));
503 }
504 }
505 self.try_quote(arg)
506 }
507
508 pub fn split(&self, input: &str) -> Option<Vec<String>> {
509 shlex::split(input)
510 }
511
512 pub const fn activate_keyword(&self) -> &'static str {
513 match self {
514 ShellKind::Cmd => "",
515 ShellKind::Nushell => "overlay use",
516 ShellKind::PowerShell => ".",
517 ShellKind::Fish
518 | ShellKind::Csh
519 | ShellKind::Tcsh
520 | ShellKind::Posix
521 | ShellKind::Rc
522 | ShellKind::Xonsh
523 | ShellKind::Elvish => "source",
524 }
525 }
526
527 pub const fn clear_screen_command(&self) -> &'static str {
528 match self {
529 ShellKind::Cmd => "cls",
530 ShellKind::Posix
531 | ShellKind::Csh
532 | ShellKind::Tcsh
533 | ShellKind::Rc
534 | ShellKind::Fish
535 | ShellKind::PowerShell
536 | ShellKind::Nushell
537 | ShellKind::Xonsh
538 | ShellKind::Elvish => "clear",
539 }
540 }
541
542 #[cfg(windows)]
543 /// We do not want to escape arguments if we are using CMD as our shell.
544 /// If we do we end up with too many quotes/escaped quotes for CMD to handle.
545 pub const fn tty_escape_args(&self) -> bool {
546 match self {
547 ShellKind::Cmd => false,
548 ShellKind::Posix
549 | ShellKind::Csh
550 | ShellKind::Tcsh
551 | ShellKind::Rc
552 | ShellKind::Fish
553 | ShellKind::PowerShell
554 | ShellKind::Nushell
555 | ShellKind::Xonsh
556 | ShellKind::Elvish => true,
557 }
558 }
559}
560
561#[cfg(test)]
562mod tests {
563 use super::*;
564
565 // Examples
566 // WSL
567 // wsl.exe --distribution NixOS --cd /home/user -- /usr/bin/zsh -c "echo hello"
568 // wsl.exe --distribution NixOS --cd /home/user -- /usr/bin/zsh -c "\"echo hello\"" | grep hello"
569 // wsl.exe --distribution NixOS --cd ~ env RUST_LOG=info,remote=debug .zed_wsl_server/zed-remote-server-dev-build proxy --identifier dev-workspace-53
570 // PowerShell from Nushell
571 // nu -c overlay use "C:\Users\kubko\dev\python\39007\tests\.venv\Scripts\activate.nu"; ^"C:\Program Files\PowerShell\7\pwsh.exe" -C "C:\Users\kubko\dev\python\39007\tests\.venv\Scripts\python.exe -m pytest \"test_foo.py::test_foo\""
572 // PowerShell from CMD
573 // cmd /C \" \"C:\\\\Users\\\\kubko\\\\dev\\\\python\\\\39007\\\\tests\\\\.venv\\\\Scripts\\\\activate.bat\"& \"C:\\\\Program Files\\\\PowerShell\\\\7\\\\pwsh.exe\" -C \"C:\\\\Users\\\\kubko\\\\dev\\\\python\\\\39007\\\\tests\\\\.venv\\\\Scripts\\\\python.exe -m pytest \\\"test_foo.py::test_foo\\\"\"\"
574
575 #[test]
576 fn test_try_quote_powershell() {
577 let shell_kind = ShellKind::PowerShell;
578 assert_eq!(
579 shell_kind
580 .try_quote("C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \"test_foo.py::test_foo\"")
581 .unwrap()
582 .into_owned(),
583 "\"C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest `\"test_foo.py::test_foo`\"\"".to_string()
584 );
585 }
586
587 #[test]
588 fn test_try_quote_cmd() {
589 let shell_kind = ShellKind::Cmd;
590 assert_eq!(
591 shell_kind
592 .try_quote("C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \"test_foo.py::test_foo\"")
593 .unwrap()
594 .into_owned(),
595 "\"C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \\\"test_foo.py::test_foo\\\"\"".to_string()
596 );
597 }
598
599 #[test]
600 fn test_try_quote_nu_command() {
601 let shell_kind = ShellKind::Nushell;
602 assert_eq!(
603 shell_kind.try_quote("'uname'").unwrap().into_owned(),
604 "\"'uname'\"".to_string()
605 );
606 assert_eq!(
607 shell_kind
608 .try_quote_prefix_aware("'uname'")
609 .unwrap()
610 .into_owned(),
611 "\"'uname'\"".to_string()
612 );
613 assert_eq!(
614 shell_kind.try_quote("^uname").unwrap().into_owned(),
615 "'^uname'".to_string()
616 );
617 assert_eq!(
618 shell_kind
619 .try_quote_prefix_aware("^uname")
620 .unwrap()
621 .into_owned(),
622 "^uname".to_string()
623 );
624 assert_eq!(
625 shell_kind.try_quote("^'uname'").unwrap().into_owned(),
626 "'^'\"'uname\'\"".to_string()
627 );
628 assert_eq!(
629 shell_kind
630 .try_quote_prefix_aware("^'uname'")
631 .unwrap()
632 .into_owned(),
633 "^'uname'".to_string()
634 );
635 assert_eq!(
636 shell_kind.try_quote("'uname a'").unwrap().into_owned(),
637 "\"'uname a'\"".to_string()
638 );
639 assert_eq!(
640 shell_kind
641 .try_quote_prefix_aware("'uname a'")
642 .unwrap()
643 .into_owned(),
644 "\"'uname a'\"".to_string()
645 );
646 assert_eq!(
647 shell_kind.try_quote("^'uname a'").unwrap().into_owned(),
648 "'^'\"'uname a'\"".to_string()
649 );
650 assert_eq!(
651 shell_kind
652 .try_quote_prefix_aware("^'uname a'")
653 .unwrap()
654 .into_owned(),
655 "^'uname a'".to_string()
656 );
657 assert_eq!(
658 shell_kind.try_quote("uname").unwrap().into_owned(),
659 "uname".to_string()
660 );
661 assert_eq!(
662 shell_kind
663 .try_quote_prefix_aware("uname")
664 .unwrap()
665 .into_owned(),
666 "uname".to_string()
667 );
668 }
669}