Skip to main content

aft/
windows_shell.rs

1//! Shared Windows shell selection for foreground and background bash commands.
2//!
3//! Mirrors OpenCode's resolver:
4//!   1. `$SHELL` env var (typically points at git-bash on Windows dev setups).
5//!   2. `pwsh.exe` (PowerShell 7+).
6//!   3. `powershell.exe` (Windows PowerShell 5.1).
7//!   4. Git-for-Windows `bash.exe` discovered next to `git` on PATH (catches
8//!      users who installed Git for Windows but never set `$SHELL`).
9//!   5. `cmd.exe` (universal floor — always reachable on every Windows SKU).
10//!
11//! POSIX shells (bash, sh, zsh, ksh, dash) are invoked as `<shell> -c <cmd>`
12//! the same way Unix does. PowerShell variants take their `-Command` shape;
13//! cmd.exe takes `/D /C`.
14//!
15//! Compiled on all platforms so the cross-platform retry-decision unit
16//! tests in `commands::bash::try_spawn_with_fallback` (test-only — see the
17//! Windows foreground bash path in `crate::commands::bash`) can run on
18//! macOS/Linux dev machines. The production Windows background spawn path
19//! at `bash_background::registry::detached_shell_command_for` is the live
20//! caller.
21
22#![cfg_attr(not(windows), allow(dead_code))]
23
24use std::path::{Path, PathBuf};
25use std::process::Command;
26use std::sync::OnceLock;
27
28/// POSIX shells that can be invoked as `<shell> -c <command>`. Matches
29/// OpenCode's `POSIX` set in `packages/opencode/src/shell/shell.ts`.
30const POSIX_NAMES: &[&str] = &["bash", "sh", "zsh", "ksh", "dash"];
31
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub(crate) enum WindowsShell {
34    /// PowerShell 7+ (cross-platform). Supports `&&` pipeline operator.
35    Pwsh,
36    /// Windows PowerShell 5.1 (legacy, still default on most Windows desktops
37    /// but **absent on Windows 11 IoT Enterprise LTSC SKUs** — issue #27).
38    /// Does NOT support `&&` in pipelines (PS 7+ only feature).
39    Powershell,
40    /// `cmd.exe` — the universal fallback. Present on every Windows SKU.
41    /// Supports `&&` and `||` natively. Lacks PowerShell's piping/cmdlets but
42    /// handles bash-style chained shell invocations correctly.
43    Cmd,
44    /// User-supplied POSIX shell — typically Git for Windows' bash.exe,
45    /// resolved either from `$SHELL` or auto-detected next to `git` on PATH.
46    /// Invoked as `<binary> -c <command>` exactly like a Unix shell, so
47    /// agents that emit bash-syntax commands (`cmd /c "foo"`, `find . -name`,
48    /// quoting with backslash-escapes, etc.) work the same way they would
49    /// in a real bash session. The string is the absolute path to the binary.
50    Posix(PathBuf),
51}
52
53impl WindowsShell {
54    /// Binary path to spawn. PowerShell/cmd variants resolve via PATH lookup;
55    /// `Posix` carries an already-absolute path resolved at candidate-build
56    /// time so we don't accidentally pick a different bash.exe later.
57    pub(crate) fn binary(&self) -> std::borrow::Cow<'_, str> {
58        match self {
59            WindowsShell::Pwsh => std::borrow::Cow::Borrowed("pwsh.exe"),
60            WindowsShell::Powershell => std::borrow::Cow::Borrowed("powershell.exe"),
61            WindowsShell::Cmd => std::borrow::Cow::Borrowed("cmd.exe"),
62            WindowsShell::Posix(path) => std::borrow::Cow::Owned(path.display().to_string()),
63        }
64    }
65
66    /// Argument vector to pass alongside the user's command string.
67    /// PowerShell variants take `-Command <string>`; cmd takes `/D /C <string>`
68    /// (`/D` disables AutoRun macros that could otherwise inject env-trust
69    /// behavior into our isolated invocation); POSIX shells take `-c <string>`.
70    pub(crate) fn args<'a>(&'a self, command: &'a str) -> Vec<&'a str> {
71        match self {
72            WindowsShell::Pwsh | WindowsShell::Powershell => vec![
73                "-NoLogo",
74                "-NoProfile",
75                "-NonInteractive",
76                "-ExecutionPolicy",
77                "Bypass",
78                "-Command",
79                command,
80            ],
81            WindowsShell::Cmd => vec!["/D", "/C", command],
82            WindowsShell::Posix(_) => vec!["-c", command],
83        }
84    }
85
86    pub(crate) fn command(&self, command: &str) -> Command {
87        let mut cmd = Command::new(self.binary().as_ref());
88        cmd.args(self.args(command));
89        cmd
90    }
91
92    /// Build a `Command` that runs the background wrapper script.
93    ///
94    /// Production background bash now writes cmd wrappers to `.bat` files and
95    /// invokes them without delayed expansion, so paths containing `!` remain
96    /// literal. This helper is retained for tests around legacy inline shapes.
97    ///
98    /// For foreground bash, callers should use [`Self::command`] instead;
99    /// `/V:ON` would change the semantics of user commands containing `!`
100    /// (which would otherwise be passed through literally to the user).
101    // No longer called by production bg-bash (which writes the wrapper
102    // to a temp file and invokes via `-File` / `cmd /C path`), but kept
103    // for tests that exercise the shell-arg shape directly.
104    #[allow(dead_code)]
105    pub(crate) fn bg_command(&self, wrapper: &str) -> Command {
106        let binary = self.binary();
107        let mut cmd = Command::new(binary.as_ref());
108        // PowerShell variants accept the wrapper string directly via
109        // `-Command`; the shell's `-Command` parser is generally happy
110        // with embedded quotes when the script doesn't contain literal
111        // `"` (we use only single quotes in the PS wrapper for that
112        // reason — see `wrapper_script` for `Pwsh|Powershell`).
113        //
114        // For cmd.exe the wrapper contains `cmd_quote`-quoted paths
115        // which CAN survive cmd's /C parser, but only if we add `/S`
116        // to enable simple-quote-stripping mode. Even with /S the
117        // interaction with Rust's std-lib argument quoting is fragile,
118        // so we rely on `args()` for cmd and live with the constraints.
119        //
120        // `/D` skips AutoRun macros; `/S` enables simple quote-stripping.
121        //
122        // POSIX shells (git-bash etc.) take `-c <wrapper>` and execute
123        // the wrapper as a normal shell script — the wrapper's `trap` and
124        // `printf "$?"` mechanics are POSIX-standard, so no special flags.
125        match self {
126            WindowsShell::Pwsh | WindowsShell::Powershell => {
127                cmd.args(self.args(wrapper));
128            }
129            WindowsShell::Cmd => {
130                cmd.args(["/D", "/S", "/C", wrapper]);
131            }
132            WindowsShell::Posix(_) => {
133                cmd.args(["-c", wrapper]);
134            }
135        }
136        cmd
137    }
138
139    /// Wrap a background command so shell termination writes an exit marker.
140    /// The marker is written via temp-file + rename for PowerShell variants and
141    /// via `move /Y` for cmd.exe, matching the Unix background wrapper contract.
142    pub(crate) fn wrapper_script(&self, command: &str, exit_path: &Path) -> String {
143        match self {
144            WindowsShell::Pwsh | WindowsShell::Powershell => {
145                let exit_path = powershell_single_quote(&exit_path.display().to_string());
146                let command = powershell_single_quote(command);
147                // The wrapper itself runs as a PowerShell script (invoked
148                // via `pwsh -File <path>` by `detached_shell_command_for`),
149                // so we execute the user command directly with `Invoke-Expression`
150                // instead of nesting another shell. Earlier versions wrapped
151                // the user command in an inner `& 'pwsh.exe' -Command ...`
152                // which caused PS-on-PS recursion that silently produced
153                // empty output on Windows 11 (likely a console-host issue
154                // with nested non-interactive pwsh sessions).
155                //
156                // CRITICAL: this script must contain NO literal double-quote
157                // characters. Inner `"` would break the outer-shell parse on
158                // some Windows configurations even with `-File`. We use only
159                // single-quoted strings and string concat (`+`) for any
160                // interpolation needs.
161                format!(
162                    concat!(
163                        "$exitPath = {exit_path}; ",
164                        "$tmpPath = $exitPath + '.tmp.' + $PID; ",
165                        "$global:LASTEXITCODE = $null; ",
166                        "Invoke-Expression {command}; ",
167                        "$success = $?; ",
168                        "$nativeCode = $global:LASTEXITCODE; ",
169                        "if ($null -ne $nativeCode) {{ $code = [int]$nativeCode }} ",
170                        "elseif ($success) {{ $code = 0 }} ",
171                        "else {{ $code = 1 }}; ",
172                        "[System.IO.File]::WriteAllText($tmpPath, [string]$code); ",
173                        "Move-Item -LiteralPath $tmpPath -Destination $exitPath -Force; ",
174                        "exit $code"
175                    ),
176                    exit_path = exit_path,
177                    command = command
178                )
179            }
180            WindowsShell::Cmd => {
181                // This body is written to a `.bat` file and invoked as
182                // `cmd /D /C <wrapper.bat>`. Batch files expand `%ERRORLEVEL%`
183                // per line, so we do not need `/V:ON` delayed expansion; paths
184                // containing literal `!` survive unchanged.
185                let tmp_path = format!("{}.tmp", exit_path.display());
186                format!(
187                    concat!(
188                        "@echo off\r\n",
189                        "{command}\r\n",
190                        "set CODE=%ERRORLEVEL%\r\n",
191                        "echo %CODE% > {tmp}\r\n",
192                        "move /Y {tmp} {exit} > nul\r\n",
193                        "exit /B %CODE%\r\n"
194                    ),
195                    command = command,
196                    tmp = cmd_quote(&tmp_path),
197                    exit = cmd_quote(&exit_path.display().to_string())
198                )
199            }
200            WindowsShell::Posix(shell_path) => {
201                // git-bash and friends speak POSIX, so the same temp-file +
202                // mv pattern the Unix bg-bash wrapper uses applies here. The
203                // wrapper writes the user command's $? to a temp file and
204                // atomically renames it into place so partial writes are
205                // never observable. Single-quote the user command to defang
206                // any embedded `;`, `&`, or `$` — POSIX single-quotes don't
207                // interpret anything except `'` itself, which we escape via
208                // the `'\''` close-and-reopen idiom.
209                let exit_str = exit_path.display().to_string();
210                let tmp_path = format!("{}.tmp", exit_str);
211                format!(
212                    "{} -c {} ; printf '%s' \"$?\" > {} && mv {} {}",
213                    posix_single_quote(&shell_path.display().to_string()),
214                    posix_single_quote(command),
215                    posix_single_quote(&tmp_path),
216                    posix_single_quote(&tmp_path),
217                    posix_single_quote(&exit_str),
218                )
219            }
220        }
221    }
222}
223
224/// Resolve which Windows shell to use for `bash` invocations.
225///
226/// Cached after the first resolve to avoid repeated PATH probes — the user's
227/// installed shells don't change mid-session, so a static cache is safe and
228/// keeps bash dispatch fast.
229///
230/// **Note:** PATH probe via `which::which` can disagree with what
231/// `Command::spawn` actually sees at runtime — antivirus / AppLocker rules,
232/// PATH inheritance gaps in the spawning host, or sandbox flags can make
233/// a binary "exist" to `which` but fail to spawn with NotFound. Foreground
234/// bash uses [`shell_candidates`] + runtime retry to defend against this;
235/// callers that take this single-result API are accepting the cached
236/// outcome at face value.
237// No longer called by production bg-bash (the new path uses
238// `shell_candidates()` with retry directly). Kept for potential future
239// use and for parity with the foreground spawn loop.
240#[allow(dead_code)]
241pub(crate) fn resolve_windows_shell() -> WindowsShell {
242    shell_candidates()
243        .first()
244        .cloned()
245        .unwrap_or(WindowsShell::Cmd)
246}
247
248/// All Windows shells that the PATH probe believes are reachable, returned
249/// in priority order. Always non-empty on Windows because cmd.exe is the
250/// floor. Order:
251///
252///   1. `$SHELL` env var (typically points at git-bash on Windows dev setups).
253///   2. `pwsh.exe`.
254///   3. `powershell.exe`.
255///   4. Git-for-Windows `bash.exe` discovered next to `git` on PATH.
256///   5. `cmd.exe`.
257///
258/// Used by the foreground bash spawn site to retry with the next candidate
259/// if the first one fails to spawn at runtime. Cached after the first
260/// resolve.
261pub(crate) fn shell_candidates() -> Vec<WindowsShell> {
262    static CACHED: OnceLock<Vec<WindowsShell>> = OnceLock::new();
263    CACHED
264        .get_or_init(|| {
265            shell_candidates_with(
266                |binary| which::which(binary).ok(),
267                || std::env::var_os("SHELL").map(PathBuf::from),
268            )
269        })
270        .clone()
271}
272
273/// Test seam for [`shell_candidates`]. The two closures let unit tests inject
274/// a fake `which`-like resolver and a fake `$SHELL` env value.
275///
276/// `which_for(binary)` should return `Some(absolute_path)` if the binary is
277/// reachable, `None` otherwise — matching the contract of `which::which`.
278pub(crate) fn shell_candidates_with<W, S>(which_for: W, shell_env: S) -> Vec<WindowsShell>
279where
280    W: Fn(&str) -> Option<PathBuf>,
281    S: FnOnce() -> Option<PathBuf>,
282{
283    let mut candidates: Vec<WindowsShell> = Vec::with_capacity(5);
284
285    // 1. $SHELL env var — typically points at git-bash on Windows dev
286    //    setups (`/c/Program Files/Git/bin/bash.exe` style or a normal
287    //    Windows path). Mirrors OpenCode's preferred() resolution.
288    //    Only honored when the named binary is recognized as POSIX
289    //    (bash/sh/zsh/ksh/dash) — we don't want SHELL=cmd.exe pinning us
290    //    to cmd when the user already gets cmd as the floor candidate.
291    if let Some(shell_path) = shell_env() {
292        if let Some(resolved) = resolve_user_shell(&shell_path, &which_for) {
293            log::info!(
294                "[aft] bash candidate: $SHELL = {} (POSIX, invoked as -c)",
295                resolved.display()
296            );
297            candidates.push(WindowsShell::Posix(resolved));
298        }
299    }
300
301    // 2-3. PowerShell variants.
302    if which_for("pwsh.exe").is_some() {
303        log::info!("[aft] bash candidate: pwsh.exe (PowerShell 7+; supports && pipeline operator)");
304        candidates.push(WindowsShell::Pwsh);
305    }
306    if which_for("powershell.exe").is_some() {
307        log::info!(
308            "[aft] bash candidate: powershell.exe (Windows PowerShell 5.1; && in pipelines unsupported, will surface as parse error)"
309        );
310        candidates.push(WindowsShell::Powershell);
311    }
312
313    // 4. Git for Windows auto-detect — find bash.exe next to git on PATH.
314    //    Catches the common case of "user installed Git for Windows but
315    //    didn't set $SHELL". Skipped when $SHELL already produced a POSIX
316    //    candidate (no point adding the same git-bash twice).
317    let already_posix = candidates
318        .iter()
319        .any(|c| matches!(c, WindowsShell::Posix(_)));
320    if !already_posix {
321        if let Some(git_bash) = locate_git_bash(&which_for) {
322            log::info!(
323                "[aft] bash candidate: git-bash auto-detected at {} (POSIX, invoked as -c)",
324                git_bash.display()
325            );
326            candidates.push(WindowsShell::Posix(git_bash));
327        }
328    }
329
330    // 5. cmd.exe is always added as the floor, regardless of PATH probe
331    //    result. It lives in a Windows search-path location that PATH
332    //    inheritance issues, ASR rules, and sandboxing generally cannot
333    //    remove. Without this floor, foreground bash retry would have
334    //    nowhere to fall back to when other shells fail to spawn at runtime.
335    candidates.push(WindowsShell::Cmd);
336
337    let only_cmd = candidates.len() == 1;
338    if only_cmd {
339        log::warn!(
340            "[aft] No bash, PowerShell, or git-bash is reachable from this \
341             aft process — using cmd.exe only. This can occur even when \
342             PowerShell is installed if PATH inheritance is restricted, \
343             antivirus / AppLocker / Defender ASR rules block PowerShell as a \
344             child process, or you're on a stripped Windows SKU. Bash-style \
345             commands using && and || still work; PowerShell-only cmdlets and \
346             POSIX-only commands will not. Details: \
347             https://github.com/cortexkit/aft/issues/27"
348        );
349    }
350    candidates
351}
352
353/// Resolve a `$SHELL` value into an absolute path to a POSIX shell binary,
354/// or `None` if the value is unusable on Windows. Handles three input
355/// shapes that show up in the wild:
356///
357///   - Full Windows path: `C:\Program Files\Git\bin\bash.exe`
358///   - MSYS/git-bash style: `/c/Program Files/Git/bin/bash.exe` or `/usr/bin/bash`
359///   - Bare name: `bash` or `bash.exe` (resolve via `which`)
360///
361/// Returns `None` if the resolved binary's filename isn't in `POSIX_NAMES`,
362/// so that someone with `SHELL=cmd.exe` doesn't accidentally pin us to a
363/// `Posix(cmd.exe)` invocation that breaks the `-c` contract.
364fn resolve_user_shell<W>(raw: &Path, which_for: &W) -> Option<PathBuf>
365where
366    W: Fn(&str) -> Option<PathBuf>,
367{
368    // Convert MSYS-style /c/foo/bar paths to C:\foo\bar so std::fs::metadata
369    // and Command::new can find them. Pure Windows paths and POSIX paths on
370    // a MSYS root pass through with /-to-\ normalization.
371    let resolved = normalize_shell_path(raw);
372
373    // If the (possibly-normalized) path is absolute and exists on disk,
374    // use it as-is. Otherwise treat it as a bare name and try PATH lookup.
375    let candidate = if resolved.is_absolute() && resolved.exists() {
376        resolved
377    } else {
378        let name = resolved.file_name()?.to_str()?.to_string();
379        which_for(&name)?
380    };
381
382    if !is_posix_shell_name(&candidate) {
383        log::info!(
384            "[aft] $SHELL points at {} which isn't a recognized POSIX shell; \
385             falling back to PowerShell/cmd resolution.",
386            candidate.display()
387        );
388        return None;
389    }
390    Some(candidate)
391}
392
393/// Look for git-bash next to `git` on PATH. Mirrors OpenCode's `gitbash()`:
394/// resolves `git`, then checks `<git_dir>/../../bin/bash.exe`. Returns
395/// `None` if git isn't on PATH, the expected bash.exe doesn't exist, or
396/// the file is empty.
397fn locate_git_bash<W>(which_for: &W) -> Option<PathBuf>
398where
399    W: Fn(&str) -> Option<PathBuf>,
400{
401    let git = which_for("git.exe").or_else(|| which_for("git"))?;
402    // git.exe typically lives at <install>/cmd/git.exe; bash.exe lives at
403    // <install>/bin/bash.exe. The two `parent()` calls walk up from
404    // `cmd/git.exe` to `<install>`, then we descend into `bin/bash.exe`.
405    let candidate = git.parent()?.parent()?.join("bin").join("bash.exe");
406    let metadata = std::fs::metadata(&candidate).ok()?;
407    if metadata.len() == 0 {
408        return None;
409    }
410    Some(candidate)
411}
412
413/// Normalize an MSYS / git-bash POSIX path to a Windows path, leaving
414/// already-Windows paths and bare names alone. This mirrors the relevant
415/// subset of OpenCode's `windowsPath()` for `$SHELL` values.
416fn normalize_shell_path(raw: &Path) -> PathBuf {
417    let s = raw.to_string_lossy();
418
419    // MSYS drive-letter form: /c/Foo/Bar  ->  C:\Foo\Bar
420    if let Some(rest) = s.strip_prefix('/') {
421        if let Some((drive, after)) = rest.split_once('/') {
422            if drive.len() == 1
423                && drive
424                    .chars()
425                    .next()
426                    .is_some_and(|c| c.is_ascii_alphabetic())
427            {
428                let drive_upper = drive.to_uppercase();
429                let win = format!("{}:\\{}", drive_upper, after.replace('/', "\\"));
430                return PathBuf::from(win);
431            }
432        }
433    }
434
435    PathBuf::from(s.as_ref())
436}
437
438/// True when the file name (without extension) is in `POSIX_NAMES`.
439fn is_posix_shell_name(path: &Path) -> bool {
440    let stem = path
441        .file_stem()
442        .and_then(|s| s.to_str())
443        .unwrap_or("")
444        .to_lowercase();
445    POSIX_NAMES.iter().any(|name| *name == stem)
446}
447
448fn powershell_single_quote(value: &str) -> String {
449    format!("'{}'", value.replace('\'', "''"))
450}
451
452/// Single-quote a value for POSIX `sh -c`, escaping inner single quotes via
453/// the standard `'\''` close-and-reopen idiom. Used by the bg-bash wrapper
454/// for [`WindowsShell::Posix`] (git-bash) and matches the Unix wrapper's
455/// quoting contract.
456#[cfg_attr(not(windows), allow(dead_code))]
457fn posix_single_quote(value: &str) -> String {
458    format!("'{}'", value.replace('\'', "'\\''"))
459}
460
461// Used by `wrapper_script` for `WindowsShell::Cmd`; that wrapper is
462// only invoked from `bash_background::registry::detached_shell_command_for`
463// which is `#[cfg(windows)]`. The function compiles on all platforms so
464// `wrapper_script` stays cross-platform-testable.
465#[cfg_attr(not(windows), allow(dead_code))]
466fn cmd_quote(value: &str) -> String {
467    format!("\"{}\"", value.replace('"', "\"\""))
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    /// Helper: build a `which`-like closure that returns Some for the
475    /// listed binaries (mapping each to a synthetic absolute path) and
476    /// None for everything else. The synthetic path layout matches a
477    /// realistic Git for Windows install when `git.exe` is present,
478    /// so [`locate_git_bash`] can synthesize a sibling bash.exe path —
479    /// but the returned path won't exist on disk, so `locate_git_bash`
480    /// will bail at the metadata check, which is what the no-Posix-via-
481    /// auto-detect tests actually want.
482    fn fake_which(binaries: Vec<&'static str>) -> impl Fn(&str) -> Option<PathBuf> {
483        move |query| {
484            if binaries.contains(&query) {
485                match query {
486                    "git.exe" | "git" => Some(PathBuf::from(r"C:\Program Files\Git\cmd\git.exe")),
487                    _ => Some(PathBuf::from(format!(r"C:\fake\{}", query))),
488                }
489            } else {
490                None
491            }
492        }
493    }
494
495    // ---------------------------------------------------------------
496    // Fix for user report: $SHELL must be respected on Windows so
497    // git-bash (and other POSIX shells) can run agent-emitted bash
498    // syntax instead of getting routed to PowerShell where escaping
499    // breaks. Mirrors OpenCode's behavior.
500    // ---------------------------------------------------------------
501
502    #[test]
503    fn user_shell_pointing_at_bash_wins_over_powershell() {
504        // SHELL=C:\Program Files\Git\bin\bash.exe
505        // pwsh.exe also reachable.
506        // Expect: Posix(bash.exe) is the first candidate, pwsh second.
507        let tmp = tempfile::tempdir().expect("tempdir");
508        let bash = tmp.path().join("bash.exe");
509        std::fs::write(&bash, b"shebang").unwrap();
510
511        let candidates = shell_candidates_with(fake_which(vec!["pwsh.exe"]), || Some(bash.clone()));
512
513        assert!(matches!(candidates[0], WindowsShell::Posix(_)));
514        if let WindowsShell::Posix(p) = &candidates[0] {
515            assert_eq!(p, &bash);
516        }
517        assert_eq!(candidates[1], WindowsShell::Pwsh);
518    }
519
520    #[test]
521    fn user_shell_pointing_at_non_posix_binary_is_ignored() {
522        // SHELL=C:\Windows\System32\cmd.exe — not in POSIX_NAMES, so
523        // we should fall back to PowerShell/cmd resolution.
524        let tmp = tempfile::tempdir().expect("tempdir");
525        let cmd = tmp.path().join("cmd.exe");
526        std::fs::write(&cmd, b"").unwrap();
527
528        let candidates = shell_candidates_with(fake_which(vec!["pwsh.exe"]), || Some(cmd));
529
530        // No Posix candidate; pwsh wins.
531        assert!(!candidates
532            .iter()
533            .any(|c| matches!(c, WindowsShell::Posix(_))));
534        assert_eq!(candidates[0], WindowsShell::Pwsh);
535    }
536
537    #[test]
538    fn user_shell_msys_drive_letter_path_is_normalized() {
539        // SHELL=/c/Program Files/Git/bin/bash.exe — git-bash style.
540        // Without normalization this won't exist at all, so the
541        // resolver should at least *try* the normalized form before
542        // falling through.
543        //
544        // We can't easily fake an existing file at C:\... in a unit
545        // test, so we directly assert the normalization output here.
546        let raw = PathBuf::from("/c/Program Files/Git/bin/bash.exe");
547        let normalized = normalize_shell_path(&raw);
548        assert_eq!(
549            normalized,
550            PathBuf::from(r"C:\Program Files\Git\bin\bash.exe")
551        );
552    }
553
554    #[test]
555    fn user_shell_already_windows_path_passes_through() {
556        let raw = PathBuf::from(r"C:\Program Files\Git\bin\bash.exe");
557        let normalized = normalize_shell_path(&raw);
558        assert_eq!(normalized, raw);
559    }
560
561    /// Note: this test runs on every platform but uses platform-native
562    /// path separators because `Path::file_stem()` only recognizes the
563    /// host OS's separator. On macOS/Linux that means a forward-slash
564    /// fake path (`/fake/bash`); on Windows the equivalent backslash
565    /// path. The production code only runs on Windows where backslash
566    /// works correctly, so the test's job is to verify the resolution
567    /// flow, not the path syntax.
568    #[test]
569    fn user_shell_bare_name_resolves_via_which() {
570        // SHELL=bash → not absolute → which("bash") returns the fake
571        // resolver's path → recognized as POSIX.
572        #[cfg(unix)]
573        let expected = PathBuf::from("/fake/bash");
574        #[cfg(windows)]
575        let expected = PathBuf::from(r"C:\fake\bash");
576
577        // Pre-translate the fake_which return so it uses the host's
578        // separator. We can't share fake_which here because that helper
579        // is hard-coded to Windows-style paths.
580        let expected_clone = expected.clone();
581        let which_for = move |query: &str| -> Option<PathBuf> {
582            if query == "bash" {
583                Some(expected_clone.clone())
584            } else {
585                None
586            }
587        };
588
589        let candidates = shell_candidates_with(which_for, || Some(PathBuf::from("bash")));
590        assert!(
591            matches!(&candidates[0], WindowsShell::Posix(p) if p == &expected),
592            "expected Posix({}) as first candidate, got {:?}",
593            expected.display(),
594            candidates
595        );
596    }
597
598    #[test]
599    fn no_user_shell_and_no_git_falls_back_to_pwsh_powershell_cmd() {
600        let candidates =
601            shell_candidates_with(fake_which(vec!["pwsh.exe", "powershell.exe"]), || None);
602        assert_eq!(candidates.len(), 3);
603        assert_eq!(candidates[0], WindowsShell::Pwsh);
604        assert_eq!(candidates[1], WindowsShell::Powershell);
605        assert_eq!(candidates[2], WindowsShell::Cmd);
606    }
607
608    #[test]
609    fn cmd_is_always_the_floor() {
610        // Nothing reachable, no $SHELL — only cmd.exe should be in the list.
611        let candidates = shell_candidates_with(|_| None, || None);
612        assert_eq!(candidates, vec![WindowsShell::Cmd]);
613    }
614
615    // ---------------------------------------------------------------
616    // git-bash auto-detect: when $SHELL is unset but the user installed
617    // Git for Windows, we should still pick up the bundled bash.exe.
618    // ---------------------------------------------------------------
619
620    #[test]
621    fn git_bash_auto_detect_when_shell_unset() {
622        let tmp = tempfile::tempdir().expect("tempdir");
623        // Mirror the Git for Windows layout: <root>/cmd/git.exe and
624        // <root>/bin/bash.exe.
625        std::fs::create_dir_all(tmp.path().join("cmd")).unwrap();
626        std::fs::create_dir_all(tmp.path().join("bin")).unwrap();
627        let git = tmp.path().join("cmd").join("git.exe");
628        std::fs::write(&git, b"git").unwrap();
629        let bash = tmp.path().join("bin").join("bash.exe");
630        std::fs::write(&bash, b"shebang").unwrap();
631
632        let which = |query: &str| -> Option<PathBuf> {
633            match query {
634                "git.exe" | "git" => Some(git.clone()),
635                _ => None,
636            }
637        };
638        let candidates = shell_candidates_with(which, || None);
639
640        // First candidate is the auto-detected git-bash.
641        assert!(matches!(&candidates[0], WindowsShell::Posix(p) if p == &bash));
642        // cmd.exe is still the floor.
643        assert_eq!(*candidates.last().unwrap(), WindowsShell::Cmd);
644    }
645
646    #[test]
647    fn git_bash_skipped_when_user_shell_already_posix() {
648        // $SHELL points at git-bash → no need to auto-detect a second
649        // POSIX candidate. The candidate list should not contain two
650        // Posix entries.
651        let tmp = tempfile::tempdir().expect("tempdir");
652        let bash = tmp.path().join("bash.exe");
653        std::fs::write(&bash, b"shebang").unwrap();
654
655        let candidates = shell_candidates_with(
656            // git is reachable, but git-bash should NOT be added because
657            // we already have a Posix from $SHELL.
658            |query: &str| match query {
659                "git.exe" | "git" => Some(PathBuf::from(r"C:\Program Files\Git\cmd\git.exe")),
660                _ => None,
661            },
662            || Some(bash.clone()),
663        );
664
665        let posix_count = candidates
666            .iter()
667            .filter(|c| matches!(c, WindowsShell::Posix(_)))
668            .count();
669        assert_eq!(
670            posix_count, 1,
671            "exactly one Posix candidate when $SHELL is already set: got {:?}",
672            candidates
673        );
674    }
675
676    // ---------------------------------------------------------------
677    // Spawn-shape tests: Posix(bash) must be invoked as `bash -c <cmd>`
678    // exactly the way Unix bash works.
679    // ---------------------------------------------------------------
680
681    #[test]
682    fn posix_shell_uses_dash_c_invocation() {
683        let bash = PathBuf::from(r"C:\Program Files\Git\bin\bash.exe");
684        let shell = WindowsShell::Posix(bash);
685        let args = shell.args("ls -la /tmp");
686        assert_eq!(args, vec!["-c", "ls -la /tmp"]);
687    }
688
689    #[test]
690    fn posix_shell_binary_returns_full_path() {
691        let bash = PathBuf::from(r"C:\Program Files\Git\bin\bash.exe");
692        let shell = WindowsShell::Posix(bash.clone());
693        assert_eq!(shell.binary().as_ref(), &bash.display().to_string());
694    }
695
696    #[test]
697    fn pwsh_args_unchanged() {
698        // Regression guard: refactor must not have altered PowerShell
699        // arg shape.
700        let shell = WindowsShell::Pwsh;
701        let args = shell.args("Get-ChildItem");
702        assert_eq!(
703            args,
704            vec![
705                "-NoLogo",
706                "-NoProfile",
707                "-NonInteractive",
708                "-ExecutionPolicy",
709                "Bypass",
710                "-Command",
711                "Get-ChildItem"
712            ]
713        );
714    }
715
716    #[test]
717    fn cmd_args_unchanged() {
718        let shell = WindowsShell::Cmd;
719        let args = shell.args("dir");
720        assert_eq!(args, vec!["/D", "/C", "dir"]);
721    }
722
723    // ---------------------------------------------------------------
724    // POSIX wrapper script: bg-bash exit-marker contract for git-bash.
725    // ---------------------------------------------------------------
726
727    #[test]
728    fn posix_wrapper_writes_exit_marker_atomically() {
729        let bash = PathBuf::from(r"C:\Program Files\Git\bin\bash.exe");
730        let shell = WindowsShell::Posix(bash);
731        let script = shell.wrapper_script("echo hi", Path::new(r"C:\Temp\bash.exit"));
732        // The F2 wrapper invokes the resolved shell path directly (not a bare
733        // `sh -c`), so users get bash semantics (`[[ ]]`, arrays, pipefail)
734        // rather than dash. It then captures `$?` via `printf` into a tmp file
735        // and `mv`s atomically into place.
736        assert!(
737            script.contains(r"'C:\Program Files\Git\bin\bash.exe' -c 'echo hi'"),
738            "wrapper must invoke the resolved shell directly: {script}",
739        );
740        assert!(script.contains("printf '%s' \"$?\""), "{script}");
741        assert!(script.contains("mv "), "{script}");
742        assert!(script.contains(r"C:\Temp\bash.exit"), "{script}");
743        assert!(script.contains(r"C:\Temp\bash.exit.tmp"), "{script}");
744    }
745
746    #[test]
747    fn posix_wrapper_escapes_embedded_single_quotes() {
748        // User command contains a single quote — wrapper must use the
749        // standard `'\''` close-and-reopen idiom.
750        let bash = PathBuf::from(r"C:\Program Files\Git\bin\bash.exe");
751        let shell = WindowsShell::Posix(bash);
752        let script = shell.wrapper_script("echo 'hi'", Path::new(r"C:\Temp\bash.exit"));
753        assert!(
754            script.contains(r"'echo '\''hi'\'''"),
755            "embedded single quote must be escaped: got {script}"
756        );
757    }
758
759    // ---------------------------------------------------------------
760    // is_posix_shell_name: case-insensitive, .exe-tolerant lookup.
761    // ---------------------------------------------------------------
762
763    #[test]
764    fn is_posix_shell_name_recognizes_known_shells() {
765        for name in ["bash", "BASH", "bash.exe", "Bash.Exe", "sh", "zsh.exe"] {
766            assert!(
767                is_posix_shell_name(Path::new(name)),
768                "{name} should be POSIX"
769            );
770        }
771    }
772
773    #[test]
774    fn is_posix_shell_name_rejects_non_posix() {
775        for name in ["cmd.exe", "powershell.exe", "pwsh.exe", "fish", "nu.exe"] {
776            assert!(
777                !is_posix_shell_name(Path::new(name)),
778                "{name} must NOT be POSIX"
779            );
780        }
781    }
782}