Skip to main content

pitchfork_cli/
shell.rs

1//! Shell abstraction for cross-platform command execution
2//!
3//! This module provides a platform-agnostic way to execute shell commands,
4//! supporting different shells on Unix and Windows platforms.
5
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8
9/// Supported shell types for command execution
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
11#[serde(rename_all = "lowercase")]
12#[allow(clippy::enum_variant_names)] // PowerShell is the correct name for this shell
13pub enum Shell {
14    /// POSIX-compatible shell (default on Unix)
15    #[default]
16    Sh,
17    /// Bash shell
18    Bash,
19    /// Zsh shell
20    Zsh,
21    /// Fish shell
22    Fish,
23    /// Windows Command Prompt
24    Cmd,
25    /// PowerShell (cross-platform)
26    #[serde(alias = "pwsh")]
27    PowerShell,
28}
29
30impl Shell {
31    /// Returns the default shell for the current platform
32    #[cfg(unix)]
33    pub fn default_for_platform() -> Self {
34        Shell::Sh
35    }
36
37    /// Returns the default shell for the current platform
38    #[cfg(windows)]
39    pub fn default_for_platform() -> Self {
40        Shell::Cmd
41    }
42
43    /// Returns the shell program name/path
44    pub fn program(&self) -> &'static str {
45        match self {
46            Shell::Sh => "sh",
47            Shell::Bash => "bash",
48            Shell::Zsh => "zsh",
49            Shell::Fish => "fish",
50            Shell::Cmd => "cmd",
51            Shell::PowerShell => {
52                // pwsh is the cross-platform PowerShell, powershell is Windows-only
53                #[cfg(windows)]
54                {
55                    "powershell"
56                }
57                #[cfg(not(windows))]
58                {
59                    "pwsh"
60                }
61            }
62        }
63    }
64
65    /// Returns the arguments needed to execute a command string
66    pub fn exec_args(&self, command: &str) -> Vec<String> {
67        match self {
68            Shell::Sh | Shell::Bash | Shell::Zsh => {
69                vec!["-c".to_string(), command.to_string()]
70            }
71            Shell::Fish => {
72                vec!["-c".to_string(), command.to_string()]
73            }
74            Shell::Cmd => {
75                vec!["/C".to_string(), command.to_string()]
76            }
77            Shell::PowerShell => {
78                vec!["-Command".to_string(), command.to_string()]
79            }
80        }
81    }
82
83    /// Creates a tokio Command configured to run the given command string
84    pub fn command(&self, cmd: &str) -> tokio::process::Command {
85        let mut command = tokio::process::Command::new(self.program());
86        command.shell_script(self.program(), &self.exec_options(), cmd);
87        command
88    }
89
90    /// Creates a std Command configured to run the given command string
91    #[allow(dead_code)] // Available for future use (e.g., spawn commands)
92    pub fn std_command(&self, cmd: &str) -> std::process::Command {
93        let mut command = std::process::Command::new(self.program());
94        command.shell_script(self.program(), &self.exec_options(), cmd);
95        command
96    }
97
98    /// The options that come before the command string: `exec_args` without it.
99    fn exec_options(&self) -> Vec<String> {
100        let mut args = self.exec_args("");
101        args.pop();
102        args
103    }
104}
105
106/// Prevents a spawned command from creating a console window on Windows.
107///
108/// The supervisor is created with `DETACHED_PROCESS | CREATE_NO_WINDOW`, so it
109/// has no console of its own. On Windows the loader gives every
110/// console-subsystem child of a console-less parent a brand new *visible*
111/// console. Redirecting the child's stdio to pipes or NUL does not suppress
112/// that, because the allocation is decided from the PE subsystem and the
113/// creation flags rather than from the handles, so anything spawned from
114/// inside the supervisor has to opt out explicitly.
115///
116/// Opting out does not leave the child without a console: `CREATE_NO_WINDOW`
117/// gives it one of its own that simply has no window, so console APIs keep
118/// working. Measured on Windows 11 — a child spawned with the flag reports
119/// `GetConsoleCP() = 932` and `GetConsoleProcessList() = 1`, both of which fail
120/// for a process with no console. What changes is only that the console is not
121/// drawn, and that `GetConsoleWindow` returns null for it.
122///
123/// Implemented for both `std::process::Command` and `tokio::process::Command`,
124/// and returns `&mut Self` so it drops into the existing fluent chains. The
125/// non-Windows impls are no-ops, which keeps the call sites free of `cfg`.
126///
127/// The flag is only applied when this process has no console, because that is
128/// the only case where a child would get one of its own. See
129/// `child_would_get_its_own_console`.
130///
131/// Note: `creation_flags` *replaces* a command's creation flags rather than
132/// OR-ing into them. Call this once per command, and after any other
133/// `creation_flags` call, or those flags are silently dropped.
134pub(crate) trait HideConsoleWindow {
135    fn hide_console_window(&mut self) -> &mut Self;
136}
137
138/// Whether a console-subsystem child of this process would be given a console
139/// of its own rather than inheriting one.
140///
141/// A child inherits the parent's console whenever the parent has one, and no
142/// new window appears, so `CREATE_NO_WINDOW` is unnecessary there. It would
143/// also be a behaviour change: the child would be put on a separate console
144/// instead of the shared one, so a console control event sent to the parent's
145/// console would no longer reach it. Detached processes such as the background
146/// supervisor have no console, and only there does a child get a new — and
147/// visible — one.
148///
149/// `GetConsoleWindow` reports the absence of a console *window*, which is not
150/// quite the same as the absence of a console: it also returns null for a
151/// console that has no window, such as a ConPTY session or a process started
152/// with `CREATE_NO_WINDOW` itself. Those cases are counted as "no console"
153/// here, and that costs nothing — the child is then given a console of its own
154/// instead of sharing a console nobody can see, which is what every one of
155/// these spawns did unconditionally before this check existed. What the check
156/// is for is the case it does detect precisely: a supervisor running in the
157/// foreground on a real console, whose children should keep sharing it.
158#[cfg(windows)]
159fn child_would_get_its_own_console() -> bool {
160    let console = unsafe { windows_sys::Win32::System::Console::GetConsoleWindow() };
161    console.is_null()
162}
163
164#[cfg(windows)]
165impl HideConsoleWindow for std::process::Command {
166    fn hide_console_window(&mut self) -> &mut Self {
167        use std::os::windows::process::CommandExt;
168        if child_would_get_its_own_console() {
169            self.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW)
170        } else {
171            self
172        }
173    }
174}
175
176#[cfg(windows)]
177impl HideConsoleWindow for tokio::process::Command {
178    fn hide_console_window(&mut self) -> &mut Self {
179        // tokio exposes `creation_flags` as an inherent method on Windows;
180        // `CommandExt` is not implemented for this type.
181        if child_would_get_its_own_console() {
182            self.creation_flags(windows_sys::Win32::System::Threading::CREATE_NO_WINDOW)
183        } else {
184            self
185        }
186    }
187}
188
189#[cfg(not(windows))]
190impl HideConsoleWindow for std::process::Command {
191    fn hide_console_window(&mut self) -> &mut Self {
192        self
193    }
194}
195
196#[cfg(not(windows))]
197impl HideConsoleWindow for tokio::process::Command {
198    fn hide_console_window(&mut self) -> &mut Self {
199        self
200    }
201}
202
203/// Hands a script to a shell: the shell's own options, then the script.
204///
205/// On Windows, when the shell is cmd.exe, the script is passed as
206/// `/S /C "<script>"` on the raw command line instead of as an argument.
207/// `Command::arg` quotes an argument for the Microsoft C runtime, turning each
208/// `"` into `\"`, and cmd does not undo that: `node "my server.js"` would reach
209/// it as `node \"my server.js\"`. With `/S`, cmd strips the outer pair of
210/// quotes and runs the rest exactly as written.
211///
212/// When the shell is PowerShell, a script that starts with a quoted string is
213/// run with the call operator, as `& <script>`. See `powershell_script`.
214///
215/// Implemented for both `std::process::Command` and `tokio::process::Command`.
216pub(crate) trait ShellScript {
217    /// `program` is the shell the command was created for, and `options` the
218    /// arguments that come before the script, such as `-c` or `/C`.
219    fn shell_script(&mut self, program: &str, options: &[String], script: &str) -> &mut Self;
220}
221
222/// The script as PowerShell should be given it.
223///
224/// PowerShell reads a statement that starts with a quoted string as an
225/// expression rather than a command, so `"C:\Program Files\app\app.exe" --port 80`
226/// fails to parse ("Unexpected token"), and a quoted path on its own just
227/// prints itself. A quoted program path has to be run with the call operator,
228/// `& "C:\Program Files\app\app.exe" --port 80`, which is what this adds when
229/// the shell is `powershell` or `pwsh` with `-Command` (or `-c`) last.
230///
231/// The script is returned unchanged for any other shell, and for a script that
232/// does not start with a quote.
233pub(crate) fn powershell_script<'a>(
234    program: &str,
235    options: &[String],
236    script: &'a str,
237) -> std::borrow::Cow<'a, str> {
238    let stem = program_stem(program);
239    let is_powershell =
240        stem.eq_ignore_ascii_case("powershell") || stem.eq_ignore_ascii_case("pwsh");
241    let runs_command = options.last().is_some_and(|flag| {
242        flag.eq_ignore_ascii_case("-command") || flag.eq_ignore_ascii_case("-c")
243    });
244    if is_powershell && runs_command && script.trim_start().starts_with(['"', '\'']) {
245        format!("& {script}").into()
246    } else {
247        script.into()
248    }
249}
250
251/// Carry a shell script through mise without letting it re-quote cmd's script.
252/// Deferred cmd templates must keep cmd as mise's program so its `quote`
253/// filter uses cmd syntax. They require mise's native cmd forwarding support.
254pub(crate) fn mise_shell_words(
255    mut words: Vec<String>,
256    script: String,
257    deferred: bool,
258) -> Vec<String> {
259    let (program, options) = words.split_first().expect("resolved shell has a program");
260    #[cfg(not(windows))]
261    let _ = deferred;
262    #[cfg(windows)]
263    if !deferred && cmd_raw_script(program, options, &script).is_some() {
264        let mut bridged = vec![
265            crate::env::PITCHFORK_BIN.to_string_lossy().into_owned(),
266            "shell-exec".to_string(),
267            "--".to_string(),
268        ];
269        bridged.extend(words);
270        bridged.push(script);
271        return bridged;
272    }
273    let script = powershell_script(program, options, &script).into_owned();
274    words.push(script);
275    words
276}
277
278/// The file name of `program` without its extension: `cmd` for
279/// `C:\Windows\System32\cmd.exe`.
280///
281/// Split by hand rather than with `Path`, which does not treat `\` as a
282/// separator outside Windows and so could not be tested there.
283fn program_stem(program: &str) -> &str {
284    let name = program.rsplit(['/', '\\']).next().unwrap_or(program);
285    name.rsplit_once('.').map_or(name, |(stem, _)| stem)
286}
287
288/// For cmd.exe run with `/C` as its last option, the options to pass before
289/// the script, and the raw text that carries the script.
290///
291/// `None` for any other shell, which takes the script as a normal argument.
292/// Platform-independent so that it can be tested everywhere; only Windows
293/// acts on it.
294#[cfg(any(windows, test))]
295fn cmd_raw_script<'a>(
296    program: &str,
297    options: &'a [String],
298    script: &str,
299) -> Option<(&'a [String], String)> {
300    let is_cmd = program_stem(program).eq_ignore_ascii_case("cmd");
301    let (flag, leading) = options.split_last()?;
302    if !is_cmd || !flag.eq_ignore_ascii_case("/c") {
303        return None;
304    }
305    // `/S` has to come before `/C`: everything after `/C` is the command.
306    let strip = if leading.iter().any(|o| o.eq_ignore_ascii_case("/s")) {
307        ""
308    } else {
309        "/S "
310    };
311    Some((leading, format!("{strip}{flag} \"{script}\"")))
312}
313
314#[cfg(windows)]
315impl ShellScript for std::process::Command {
316    fn shell_script(&mut self, program: &str, options: &[String], script: &str) -> &mut Self {
317        use std::os::windows::process::CommandExt;
318        match cmd_raw_script(program, options, script) {
319            Some((leading, raw)) => self.args(leading).raw_arg(raw),
320            None => self
321                .args(options)
322                .arg(&*powershell_script(program, options, script)),
323        }
324    }
325}
326
327#[cfg(windows)]
328impl ShellScript for tokio::process::Command {
329    fn shell_script(&mut self, program: &str, options: &[String], script: &str) -> &mut Self {
330        // tokio exposes `raw_arg` as an inherent method on Windows.
331        match cmd_raw_script(program, options, script) {
332            Some((leading, raw)) => self.args(leading).raw_arg(raw),
333            None => self
334                .args(options)
335                .arg(&*powershell_script(program, options, script)),
336        }
337    }
338}
339
340#[cfg(not(windows))]
341impl ShellScript for std::process::Command {
342    fn shell_script(&mut self, program: &str, options: &[String], script: &str) -> &mut Self {
343        self.args(options)
344            .arg(&*powershell_script(program, options, script))
345    }
346}
347
348#[cfg(not(windows))]
349impl ShellScript for tokio::process::Command {
350    fn shell_script(&mut self, program: &str, options: &[String], script: &str) -> &mut Self {
351        self.args(options)
352            .arg(&*powershell_script(program, options, script))
353    }
354}
355
356impl std::fmt::Display for Shell {
357    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358        match self {
359            Shell::Sh => write!(f, "sh"),
360            Shell::Bash => write!(f, "bash"),
361            Shell::Zsh => write!(f, "zsh"),
362            Shell::Fish => write!(f, "fish"),
363            Shell::Cmd => write!(f, "cmd"),
364            Shell::PowerShell => write!(f, "powershell"),
365        }
366    }
367}
368
369impl std::str::FromStr for Shell {
370    type Err = String;
371
372    fn from_str(s: &str) -> Result<Self, Self::Err> {
373        match s.to_lowercase().as_str() {
374            "sh" => Ok(Shell::Sh),
375            "bash" => Ok(Shell::Bash),
376            "zsh" => Ok(Shell::Zsh),
377            "fish" => Ok(Shell::Fish),
378            "cmd" => Ok(Shell::Cmd),
379            "powershell" | "pwsh" => Ok(Shell::PowerShell),
380            _ => Err(format!("unknown shell: {s}")),
381        }
382    }
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    #[test]
390    fn test_shell_program() {
391        assert_eq!(Shell::Sh.program(), "sh");
392        assert_eq!(Shell::Bash.program(), "bash");
393        assert_eq!(Shell::Zsh.program(), "zsh");
394        assert_eq!(Shell::Fish.program(), "fish");
395        assert_eq!(Shell::Cmd.program(), "cmd");
396    }
397
398    #[test]
399    fn test_shell_exec_args() {
400        assert_eq!(Shell::Sh.exec_args("echo hello"), vec!["-c", "echo hello"]);
401        assert_eq!(
402            Shell::Bash.exec_args("echo hello"),
403            vec!["-c", "echo hello"]
404        );
405        assert_eq!(Shell::Cmd.exec_args("echo hello"), vec!["/C", "echo hello"]);
406        assert_eq!(
407            Shell::PowerShell.exec_args("echo hello"),
408            vec!["-Command", "echo hello"]
409        );
410    }
411
412    #[test]
413    fn test_shell_from_str() {
414        assert_eq!("sh".parse::<Shell>().unwrap(), Shell::Sh);
415        assert_eq!("bash".parse::<Shell>().unwrap(), Shell::Bash);
416        assert_eq!("BASH".parse::<Shell>().unwrap(), Shell::Bash);
417        assert_eq!("powershell".parse::<Shell>().unwrap(), Shell::PowerShell);
418        assert_eq!("pwsh".parse::<Shell>().unwrap(), Shell::PowerShell);
419        assert!("unknown".parse::<Shell>().is_err());
420    }
421
422    #[test]
423    fn test_shell_display() {
424        assert_eq!(Shell::Sh.to_string(), "sh");
425        assert_eq!(Shell::Bash.to_string(), "bash");
426        assert_eq!(Shell::Cmd.to_string(), "cmd");
427    }
428
429    #[test]
430    fn test_default_shell() {
431        // Default should be Sh (or Cmd on Windows)
432        let default = Shell::default_for_platform();
433        #[cfg(unix)]
434        assert_eq!(default, Shell::Sh);
435        #[cfg(windows)]
436        assert_eq!(default, Shell::Cmd);
437    }
438
439    /// Checks that `hide_console_window` is available for both command types,
440    /// chains inside a builder expression, and leaves spawning intact.
441    ///
442    /// This does not assert that no console window appears: the reliable
443    /// oracles for that are version-dependent Windows behaviour, so the
444    /// absence of a window is verified manually instead.
445    #[test]
446    fn test_hide_console_window() {
447        let program = if cfg!(windows) { "cmd" } else { "echo" };
448        let args: Vec<&str> = if cfg!(windows) {
449            vec!["/C", "echo hi"]
450        } else {
451            vec!["hi"]
452        };
453
454        let output = std::process::Command::new(program)
455            .args(&args)
456            .hide_console_window()
457            .output()
458            .expect("spawning the child should succeed");
459        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "hi");
460
461        // Building a tokio command needs no runtime, so this pins the second
462        // impl without making the test async.
463        let mut async_command = tokio::process::Command::new(program);
464        async_command.args(&args).hide_console_window();
465    }
466
467    fn strings(words: &[&str]) -> Vec<String> {
468        words.iter().map(|w| w.to_string()).collect()
469    }
470
471    #[test]
472    fn mise_deferred_scripts_keep_their_shell_and_script() {
473        let script = "{{ vars.program | quote }} {{ vars.argument | quote }}";
474        for shell in [
475            strings(&["cmd", "/C"]),
476            strings(&[r"C:\Windows\System32\CMD.EXE", "/d", "/s", "/c"]),
477            strings(&["sh", "-c"]),
478        ] {
479            let mut expected = shell.clone();
480            expected.push(script.to_string());
481            assert_eq!(mise_shell_words(shell, script.to_string(), true), expected);
482        }
483        assert_eq!(
484            mise_shell_words(
485                strings(&["pwsh", "-NoProfile", "-Command"]),
486                "'C:\\Program Files\\app.exe' {{ vars.argument | quote }}".to_string(),
487                true,
488            ),
489            strings(&[
490                "pwsh",
491                "-NoProfile",
492                "-Command",
493                "& 'C:\\Program Files\\app.exe' {{ vars.argument | quote }}",
494            ])
495        );
496    }
497
498    #[cfg(windows)]
499    #[test]
500    fn mise_ordinary_cmd_scripts_keep_the_compatibility_bridge() {
501        let script = r#""C:\Program Files\app.exe" "a b""#;
502        for shell in [strings(&["cmd", "/C"]), strings(&["CMD.EXE", "/d", "/c"])] {
503            let bridged = mise_shell_words(shell.clone(), script.to_string(), false);
504            assert_eq!(bridged[0], crate::env::PITCHFORK_BIN.to_string_lossy());
505            assert_eq!(&bridged[1..3], &["shell-exec", "--"]);
506            assert_eq!(&bridged[3..bridged.len() - 1], shell);
507            assert_eq!(bridged.last().unwrap(), script);
508        }
509    }
510
511    #[test]
512    fn test_cmd_raw_script_wraps_the_script_for_cmd() {
513        let options = strings(&["/C"]);
514        let (leading, raw) = cmd_raw_script("cmd", &options, r#"echo "a b""#).unwrap();
515        assert!(leading.is_empty());
516        assert_eq!(raw, r#"/S /C "echo "a b"""#);
517
518        // Any spelling of cmd.exe, and any case of the flags.
519        let options = strings(&["/d", "/s", "/c"]);
520        let (leading, raw) =
521            cmd_raw_script(r"C:\Windows\System32\CMD.EXE", &options, "echo hi").unwrap();
522        assert_eq!(leading, &options[..2]);
523        assert_eq!(raw, r#"/c "echo hi""#);
524    }
525
526    #[test]
527    fn test_cmd_raw_script_leaves_other_shells_alone() {
528        assert_eq!(cmd_raw_script("sh", &strings(&["-c"]), "echo hi"), None);
529        assert_eq!(
530            cmd_raw_script("pwsh", &strings(&["-Command"]), "echo hi"),
531            None
532        );
533        // cmd without /C last is not running a script this way.
534        assert_eq!(cmd_raw_script("cmd", &strings(&["/K"]), "echo hi"), None);
535        assert_eq!(cmd_raw_script("cmd", &[], "echo hi"), None);
536    }
537
538    /// The case the raw command line exists for: quotes in the script reach
539    /// cmd.exe as written, including a quoted program path with spaces.
540    #[cfg(windows)]
541    #[test]
542    fn test_cmd_runs_a_script_with_quotes() {
543        let dir = tempfile::tempdir().unwrap();
544        let script_dir = dir.path().join("with space");
545        std::fs::create_dir_all(&script_dir).unwrap();
546        let script = script_dir.join("say.cmd");
547        std::fs::write(&script, "@echo [%~1]\r\n").unwrap();
548
549        let run = format!(r#""{}" "a b""#, script.display());
550        let output = std::process::Command::new("cmd")
551            .shell_script("cmd", &strings(&["/C"]), &run)
552            .output()
553            .unwrap();
554        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "[a b]");
555
556        let output = Shell::Cmd.std_command(r#"echo "a b""#).output().unwrap();
557        assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), r#""a b""#);
558    }
559
560    #[test]
561    fn test_powershell_script_calls_a_quoted_program() {
562        let command = strings(&["-Command"]);
563        assert_eq!(
564            powershell_script("powershell", &command, r#""C:\a b\app.exe" --port 80"#),
565            r#"& "C:\a b\app.exe" --port 80"#
566        );
567        assert_eq!(
568            powershell_script(
569                r"C:\Program Files\PowerShell\7\pwsh.exe",
570                &strings(&["-NoProfile", "-c"]),
571                "'app' x"
572            ),
573            "& 'app' x"
574        );
575        // Not quoted, not PowerShell, or not run as a command: unchanged.
576        assert_eq!(
577            powershell_script("pwsh", &command, "app --port 80"),
578            "app --port 80"
579        );
580        assert_eq!(powershell_script("pwsh", &command, "& 'app'"), "& 'app'");
581        assert_eq!(
582            powershell_script("pwsh", &command, r#"echo "a b""#),
583            r#"echo "a b""#
584        );
585        assert_eq!(
586            powershell_script("cmd", &strings(&["/C"]), r#""app""#),
587            r#""app""#
588        );
589        assert_eq!(powershell_script("sh", &strings(&["-c"]), "'app'"), "'app'");
590        assert_eq!(
591            powershell_script("pwsh", &strings(&["-File"]), "'app'"),
592            "'app'"
593        );
594    }
595
596    /// PowerShell runs a script that starts with a quoted program path,
597    /// which it would otherwise fail to parse.
598    #[cfg(windows)]
599    #[test]
600    fn test_powershell_runs_a_script_starting_with_a_quoted_path() {
601        let dir = tempfile::tempdir().unwrap();
602        let script_dir = dir.path().join("with space");
603        std::fs::create_dir_all(&script_dir).unwrap();
604        let script = script_dir.join("say.cmd");
605        std::fs::write(&script, "@echo [%~1]\r\n").unwrap();
606
607        for run in [
608            format!(r#""{}" "a b""#, script.display()),
609            format!("'{}' 'a b'", script.display()),
610        ] {
611            let output = Shell::PowerShell.std_command(&run).output().unwrap();
612            assert!(output.status.success(), "{run}: {output:?}");
613            assert_eq!(
614                String::from_utf8_lossy(&output.stdout).trim(),
615                "[a b]",
616                "{run}"
617            );
618        }
619    }
620}