Skip to main content

lean_ctx/shell/
platform.rs

1/// Sets `LC_CTYPE=C.UTF-8` when no UTF-8 locale is inherited from the parent
2/// process. Without this, commands treat bytes >127 as non-printable (C locale),
3/// mangling Cyrillic, CJK, emoji, etc.
4pub fn apply_utf8_locale(cmd: &mut std::process::Command) {
5    let has_utf8 = std::env::var("LC_ALL")
6        .or_else(|_| std::env::var("LC_CTYPE"))
7        .or_else(|_| std::env::var("LANG"))
8        .is_ok_and(|v| v.to_ascii_lowercase().contains("utf"));
9
10    if !has_utf8 {
11        cmd.env("LC_CTYPE", "C.UTF-8");
12    }
13}
14
15/// Neutralizes inherited startup-file hooks so a non-login/non-interactive
16/// `sh -c` / `bash -c` cannot be hijacked into sourcing a profile or rc file
17/// (#451). lean-ctx runs the system POSIX shell profile-free and deterministic;
18/// a stray inherited `BASH_ENV` (read by bash even for `bash -c`) or `ENV`
19/// pointing at e.g. an `exec nu` snippet would otherwise silently replace the
20/// shell. Cleared to empty so the expansion names no file. No-op in effect for
21/// PowerShell/cmd, which ignore both variables.
22///
23/// Variables through which a tool reads options the command line does not
24/// show, some of which run a command (`TAR_OPTIONS`, a ripgrep config file,
25/// vim's `VIMINIT` and startup-file locations),
26/// are removed as well: the shell gate refuses a command that sets them and
27/// judges the options it sees, so an inherited value must not add others.
28pub fn apply_profile_free_env(cmd: &mut std::process::Command) {
29    cmd.env("BASH_ENV", "").env("ENV", "");
30    for name in HIDDEN_OPTION_ENV {
31        cmd.env_remove(name);
32    }
33}
34
35/// Environment variables a tool reads options from; see
36/// [`apply_profile_free_env`].
37pub const HIDDEN_OPTION_ENV: &[&str] = &[
38    "TAR_OPTIONS",
39    "RIPGREP_CONFIG_PATH",
40    "VIMINIT",
41    "EXINIT",
42    "GVIMINIT",
43    "VIMRUNTIME",
44    "MYVIMRC",
45    "MYGVIMRC",
46    "NVIM_APPNAME",
47    "VIM",
48    "EMACSLOADPATH",
49    "EMACSDIR",
50];
51
52pub fn decode_output(bytes: &[u8]) -> String {
53    match String::from_utf8(bytes.to_vec()) {
54        Ok(s) => s,
55        Err(_) => {
56            #[cfg(windows)]
57            {
58                decode_windows_output(bytes)
59            }
60            #[cfg(not(windows))]
61            {
62                String::from_utf8_lossy(bytes).into_owned()
63            }
64        }
65    }
66}
67/// Resolve carriage-return (`\r`) progress overwrites in captured output.
68///
69/// CLI tools like `git`, `cargo`, and `npm` use `\r` to draw in-place progress
70/// updates. When stdout is captured (not a TTY), these bytes survive as literal
71/// `\r` characters and produce glued-together lines (#1140). This function
72/// emulates terminal behaviour: for each line, only the content after the last
73/// `\r` is kept.
74pub fn resolve_carriage_returns(s: &str) -> String {
75    if !s.contains('\r') {
76        return s.to_string();
77    }
78    let mut out = String::with_capacity(s.len());
79    for (i, line) in s.split('\n').enumerate() {
80        if i > 0 {
81            out.push('\n');
82        }
83        let line = line.strip_suffix('\r').unwrap_or(line);
84        if let Some(pos) = line.rfind('\r') {
85            out.push_str(&line[pos + 1..]);
86        } else {
87            out.push_str(line);
88        }
89    }
90    out
91}
92
93#[cfg(windows)]
94fn decode_windows_output(bytes: &[u8]) -> String {
95    use std::os::windows::ffi::OsStringExt;
96
97    let lossy = String::from_utf8_lossy(bytes);
98    let replacement_count = lossy.chars().filter(|&c| c == '\u{FFFD}').count();
99    if replacement_count == 0 {
100        return lossy.into_owned();
101    }
102
103    // SAFETY: declares Win32 API symbols that exist in kernel32; signatures
104    // match the documented ABI.
105    unsafe extern "system" {
106        fn GetACP() -> u32;
107        fn MultiByteToWideChar(
108            cp: u32,
109            flags: u32,
110            src: *const u8,
111            srclen: i32,
112            dst: *mut u16,
113            dstlen: i32,
114        ) -> i32;
115    }
116
117    // SAFETY: `GetACP` takes no arguments and only returns the active code
118    // page; it cannot fail or cause undefined behaviour.
119    let codepage = unsafe { GetACP() };
120    // SAFETY: called with a null destination and length 0 to measure the
121    // required buffer size; `bytes` is a live slice and every pointer/length
122    // argument is valid.
123    let wide_len = unsafe {
124        MultiByteToWideChar(
125            codepage,
126            0,
127            bytes.as_ptr(),
128            bytes.len() as i32,
129            std::ptr::null_mut(),
130            0,
131        )
132    };
133    if wide_len <= 0 {
134        return lossy.into_owned();
135    }
136    let mut wide: Vec<u16> = vec![0u16; wide_len as usize];
137    // SAFETY: `wide` is sized to the previously measured length and `bytes` is
138    // a live slice; the source and destination pointers/lengths are valid and
139    // do not overlap.
140    unsafe {
141        MultiByteToWideChar(
142            codepage,
143            0,
144            bytes.as_ptr(),
145            bytes.len() as i32,
146            wide.as_mut_ptr(),
147            wide_len,
148        );
149    }
150    std::ffi::OsString::from_wide(&wide)
151        .to_string_lossy()
152        .into_owned()
153}
154
155#[cfg(windows)]
156pub(super) fn set_console_utf8() {
157    // SAFETY: declares a Win32 API symbol that exists in kernel32; the
158    // signature matches the documented ABI.
159    unsafe extern "system" {
160        fn SetConsoleOutputCP(id: u32) -> i32;
161    }
162    // SAFETY: `SetConsoleOutputCP` takes a code-page id (65001 = UTF-8) by
163    // value; it cannot cause undefined behaviour.
164    unsafe {
165        SetConsoleOutputCP(65001);
166    }
167}
168
169/// Detects if the current process runs inside a Docker/container environment.
170pub fn is_container() -> bool {
171    #[cfg(unix)]
172    {
173        if std::path::Path::new("/.dockerenv").exists() {
174            return true;
175        }
176        if let Ok(cgroup) = std::fs::read_to_string("/proc/1/cgroup")
177            && (cgroup.contains("/docker/") || cgroup.contains("/lxc/"))
178        {
179            return true;
180        }
181        if let Ok(mounts) = std::fs::read_to_string("/proc/self/mountinfo")
182            && mounts.contains("/docker/containers/")
183        {
184            return true;
185        }
186        false
187    }
188    #[cfg(not(unix))]
189    {
190        false
191    }
192}
193
194/// Returns true if stdin is NOT a terminal (pipe, /dev/null, etc.)
195pub fn is_non_interactive() -> bool {
196    !crate::core::host_env::stdin_is_terminal()
197}
198
199/// Returns `true` when `shell_path` points to a PowerShell executable.
200pub fn is_powershell(shell_path: &str) -> bool {
201    let name = std::path::Path::new(shell_path)
202        .file_name()
203        .and_then(|n| n.to_str())
204        .unwrap_or("")
205        .to_ascii_lowercase();
206    name.contains("powershell") || name.contains("pwsh")
207}
208
209/// Documented default location of the current-user PowerShell profile
210/// (`$PROFILE.CurrentUserCurrentHost`).
211///
212/// Windows PowerShell 7+ stores it under `Documents\PowerShell\…`, but **PowerShell
213/// (pwsh) on macOS/Linux reads `~/.config/powershell/…` instead** — and stat-ing
214/// anything inside `~/Documents` on macOS pops a TCC privacy prompt ("lean-ctx
215/// would like to access files in your Documents folder", #356). Resolving the
216/// profile per-OS keeps pwsh support everywhere while never touching `~/Documents`
217/// on non-Windows hosts.
218///
219/// This is the *default* path only. On Windows the real `Documents` folder is
220/// frequently redirected (OneDrive folder backup), so callers should prefer
221/// [`resolve_powershell_profile_path`], which asks PowerShell for the live location
222/// and uses this as the fallback.
223pub(crate) fn powershell_profile_path(home: &std::path::Path) -> std::path::PathBuf {
224    const PROFILE_FILE: &str = "Microsoft.PowerShell_profile.ps1";
225    if cfg!(windows) {
226        home.join("Documents").join("PowerShell").join(PROFILE_FILE)
227    } else {
228        home.join(".config").join("powershell").join(PROFILE_FILE)
229    }
230}
231
232/// Resolve the **active** current-user PowerShell profile path.
233///
234/// On Windows the profile lives under the *Documents* known folder, which OneDrive
235/// folder backup (enabled by default on most installs) routinely redirects to e.g.
236/// `…\OneDrive\Documents\PowerShell\…`. A hardcoded `~\Documents` therefore misses
237/// the real `$PROFILE`, so `proxy enable` / shell-hook install silently write to a
238/// file PowerShell never reads and the proxy receives no traffic (#558). We ask
239/// PowerShell itself for `$PROFILE.CurrentUserCurrentHost` — authoritative under any
240/// folder redirection — preferring `pwsh` (7+) then Windows PowerShell, and fall back
241/// to `powershell_profile_path` only when no PowerShell host can be launched (in
242/// which case the profile is moot anyway).
243///
244/// Non-Windows hosts keep the static `~/.config/powershell` path (never `~/Documents`,
245/// #356) and never spawn a process.
246pub fn resolve_powershell_profile_path(home: &std::path::Path) -> std::path::PathBuf {
247    #[cfg(windows)]
248    {
249        if let Some(active) = query_active_powershell_profile() {
250            return active;
251        }
252    }
253    powershell_profile_path(home)
254}
255
256/// Ask PowerShell for `$PROFILE.CurrentUserCurrentHost`, the authoritative profile
257/// path under any `Documents` redirection. Returns `None` when no PowerShell host can
258/// be launched or the output is not a usable absolute path.
259#[cfg(windows)]
260fn query_active_powershell_profile() -> Option<std::path::PathBuf> {
261    // `pwsh` (7+) and `powershell.exe` (5.1) use different profile roots; prefer the
262    // modern host (matching the `Documents\PowerShell` default above), then fall back.
263    // Force UTF-8 output so redirected paths with non-ASCII characters survive the pipe.
264    for exe in ["pwsh", "powershell"] {
265        let output = match std::process::Command::new(exe)
266            .args([
267                "-NoProfile",
268                "-NonInteractive",
269                "-Command",
270                "[Console]::OutputEncoding=[Text.Encoding]::UTF8; $PROFILE.CurrentUserCurrentHost",
271            ])
272            .output()
273        {
274            Ok(out) if out.status.success() => out,
275            _ => continue,
276        };
277        let path = std::path::PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
278        if path.is_absolute() && path.file_name().is_some() {
279            return Some(path);
280        }
281    }
282    None
283}
284
285/// Windows only: argument that passes one command string to the shell binary.
286/// `exe_basename` must already be ASCII-lowercase (e.g. `bash.exe`, `cmd.exe`).
287fn windows_shell_flag_for_exe_basename(exe_basename: &str) -> &'static str {
288    if exe_basename.contains("powershell") || exe_basename.contains("pwsh") {
289        "-Command"
290    } else if exe_basename == "cmd.exe" || exe_basename == "cmd" {
291        "/C"
292    } else {
293        "-c"
294    }
295}
296
297pub fn shell_and_flag() -> (String, String) {
298    let shell = detect_shell();
299    let flag = if cfg!(windows) {
300        let name = std::path::Path::new(&shell)
301            .file_name()
302            .and_then(|n| n.to_str())
303            .unwrap_or("")
304            .to_ascii_lowercase();
305        windows_shell_flag_for_exe_basename(&name).to_string()
306    } else {
307        "-c".to_string()
308    };
309    (shell, flag)
310}
311
312/// Returns a short, human-readable shell name (e.g. "bash", "zsh", "powershell", "cmd").
313pub fn shell_name() -> String {
314    let shell = detect_shell();
315    let basename = std::path::Path::new(&shell)
316        .file_name()
317        .and_then(|n| n.to_str())
318        .unwrap_or("sh")
319        .to_ascii_lowercase();
320    basename
321        .strip_suffix(".exe")
322        .unwrap_or(&basename)
323        .to_string()
324}
325
326/// Wrap a command to disable zsh `nomatch` and `equals` (GH #1439, #1448).
327/// - `nomatch`: zsh aborts when unquoted globs match no files; POSIX passes
328///   the word through unchanged. Agents emit `--include=*.go` etc.
329/// - `equals`: zsh expands `=foo` to the path of the `foo` binary, so
330///   `echo ===` fails with "= not found". Agents use `===` as separators.
331pub fn zsh_safe_command(command: &str, shell: &str) -> String {
332    if cfg!(unix) {
333        let basename = std::path::Path::new(shell)
334            .file_name()
335            .and_then(|n| n.to_str())
336            .unwrap_or("");
337        if basename == "zsh" {
338            return format!("setopt nonomatch noequals; {command}");
339        }
340    }
341    command.to_string()
342}
343
344pub(super) fn detect_shell() -> String {
345    if let Ok(shell) = std::env::var("LEAN_CTX_SHELL") {
346        return shell;
347    }
348
349    if let Ok(shell) = std::env::var("SHELL") {
350        let bin = std::path::Path::new(&shell)
351            .file_name()
352            .and_then(|n| n.to_str())
353            .unwrap_or("sh");
354
355        if bin == "lean-ctx" {
356            return find_real_shell();
357        }
358        // #451: `$SHELL` is the user's *interactive* shell preference, not the
359        // agent's execution shell. Agents emit bash/POSIX command syntax, so an
360        // interactive-only shell like Nushell or Fish silently mis-runs it.
361        // Honor `$SHELL` only when it is POSIX-compatible; otherwise fall back
362        // to a real POSIX shell (deterministic, agent-trained). Set
363        // `LEAN_CTX_SHELL` to force a specific shell regardless of this gate.
364        if shell_acceptable_for_exec(&shell) {
365            return shell;
366        }
367        return find_real_shell();
368    }
369
370    find_real_shell()
371}
372
373/// Whether a `$SHELL` value may be auto-selected as the command-execution shell.
374///
375/// On Unix this rejects non-POSIX interactive shells (Nushell, Fish, Elvish,
376/// xonsh, PowerShell) so lean-ctx never feeds them bash/POSIX syntax (#451). On
377/// Windows the intended shells *are* PowerShell/cmd, so any `$SHELL` is honored
378/// (the POSIX gate would wrongly reject them).
379#[cfg(unix)]
380fn shell_acceptable_for_exec(shell: &str) -> bool {
381    is_posix_compatible_shell(shell)
382}
383
384#[cfg(windows)]
385fn shell_acceptable_for_exec(_shell: &str) -> bool {
386    true
387}
388
389/// `true` if `shell`'s basename is a POSIX-compatible shell that can run
390/// agent-authored bash/POSIX commands. Excludes interactive-only shells
391/// (`nu`, `fish`, `elvish`, `xonsh`) and non-POSIX shells (`pwsh`,
392/// `powershell`, `cmd`) where that syntax fails (#451).
393#[cfg(unix)]
394fn is_posix_compatible_shell(shell: &str) -> bool {
395    let name = std::path::Path::new(shell)
396        .file_name()
397        .and_then(|n| n.to_str())
398        .unwrap_or("")
399        .to_ascii_lowercase();
400    let name = name.strip_suffix(".exe").unwrap_or(&name);
401    matches!(
402        name,
403        "bash" | "zsh" | "sh" | "dash" | "ash" | "ksh" | "ksh93" | "mksh" | "busybox"
404    )
405}
406
407#[cfg(unix)]
408fn find_real_shell() -> String {
409    for shell in &["/bin/zsh", "/bin/bash", "/bin/sh"] {
410        if std::path::Path::new(shell).exists() {
411            return shell.to_string();
412        }
413    }
414    "/bin/sh".to_string()
415}
416
417#[cfg(windows)]
418fn find_real_shell() -> String {
419    if is_running_in_msys_or_gitbash() {
420        for candidate in &["bash.exe", "sh.exe"] {
421            if let Some(path) = crate::core::pathutil::find_on_path(candidate) {
422                return path.to_string_lossy().into_owned();
423            }
424        }
425    }
426    if let Ok(pwsh) = which_powershell() {
427        return pwsh;
428    }
429    if let Ok(comspec) = std::env::var("COMSPEC") {
430        return comspec;
431    }
432    "cmd.exe".to_string()
433}
434
435#[cfg(windows)]
436fn is_running_in_msys_or_gitbash() -> bool {
437    std::env::var("MSYSTEM").is_ok() || std::env::var("MINGW_PREFIX").is_ok()
438}
439
440#[cfg(windows)]
441fn which_powershell() -> Result<String, ()> {
442    for candidate in &["pwsh.exe", "powershell.exe"] {
443        if let Some(path) = crate::core::pathutil::find_on_path(candidate) {
444            return Ok(path.to_string_lossy().into_owned());
445        }
446    }
447    Err(())
448}
449
450/// Join multiple CLI arguments into a single command string, using quoting
451/// conventions appropriate for the detected shell.
452///
453/// On Unix, this always produces POSIX-compatible quoting.
454/// On Windows, the quoting adapts to the actual shell (PowerShell, cmd.exe,
455/// or Git Bash / MSYS).
456pub fn join_command(args: &[String]) -> String {
457    let (_, flag) = shell_and_flag();
458    join_command_for(args, &flag)
459}
460
461pub fn join_command_for(args: &[String], shell_flag: &str) -> String {
462    match shell_flag {
463        "-Command" => join_powershell(args),
464        "/C" => join_cmd(args),
465        _ => join_posix(args),
466    }
467}
468
469fn join_posix(args: &[String]) -> String {
470    args.iter()
471        .map(|a| quote_posix(a))
472        .collect::<Vec<_>>()
473        .join(" ")
474}
475
476fn join_powershell(args: &[String]) -> String {
477    if args.len() == 1 && args[0].contains(' ') {
478        return args[0].clone();
479    }
480    let quoted: Vec<String> = args.iter().map(|a| quote_powershell(a)).collect();
481    format!("& {}", quoted.join(" "))
482}
483
484fn join_cmd(args: &[String]) -> String {
485    args.iter()
486        .map(|a| quote_cmd(a))
487        .collect::<Vec<_>>()
488        .join(" ")
489}
490
491fn quote_posix(s: &str) -> String {
492    if s.is_empty() {
493        return "''".to_string();
494    }
495    if s.bytes()
496        .all(|b| b.is_ascii_alphanumeric() || b"-_./=:@,+%^".contains(&b))
497    {
498        return s.to_string();
499    }
500    format!("'{}'", s.replace('\'', "'\\''"))
501}
502
503fn quote_powershell(s: &str) -> String {
504    if s.is_empty() {
505        return "''".to_string();
506    }
507    // Unlike POSIX, `@` (splatting, `@(…)`) and `,` (array operator) are
508    // syntax in PowerShell, so they are not safe bare (#1848).
509    if s.bytes()
510        .all(|b| b.is_ascii_alphanumeric() || b"-_./=:+%^".contains(&b))
511    {
512        return s.to_string();
513    }
514    format!("'{}'", s.replace('\'', "''"))
515}
516
517fn quote_cmd(s: &str) -> String {
518    if s.is_empty() {
519        return "\"\"".to_string();
520    }
521    if s.bytes()
522        .all(|b| b.is_ascii_alphanumeric() || b"-_./=:@,+%^\\".contains(&b))
523    {
524        return s.to_string();
525    }
526    format!("\"{}\"", s.replace('"', "\\\""))
527}
528
529#[cfg(test)]
530mod join_command_tests {
531    use super::*;
532
533    #[test]
534    fn posix_simple_args() {
535        let args: Vec<String> = vec!["git".into(), "status".into()];
536        assert_eq!(join_command_for(&args, "-c"), "git status");
537    }
538
539    #[test]
540    fn posix_path_with_spaces() {
541        let args: Vec<String> = vec!["/usr/local/my app/bin".into(), "--help".into()];
542        assert_eq!(
543            join_command_for(&args, "-c"),
544            "'/usr/local/my app/bin' --help"
545        );
546    }
547
548    #[test]
549    fn posix_single_quotes_escaped() {
550        let args: Vec<String> = vec!["echo".into(), "it's".into()];
551        assert_eq!(join_command_for(&args, "-c"), "echo 'it'\\''s'");
552    }
553
554    #[test]
555    fn posix_empty_arg() {
556        let args: Vec<String> = vec!["cmd".into(), String::new()];
557        assert_eq!(join_command_for(&args, "-c"), "cmd ''");
558    }
559
560    #[test]
561    fn powershell_simple_args() {
562        let args: Vec<String> = vec!["npm".into(), "install".into()];
563        assert_eq!(join_command_for(&args, "-Command"), "& npm install");
564    }
565
566    #[test]
567    fn powershell_path_with_spaces() {
568        let args: Vec<String> = vec![
569            "C:\\Program Files\\nodejs\\npm.cmd".into(),
570            "install".into(),
571        ];
572        assert_eq!(
573            join_command_for(&args, "-Command"),
574            "& 'C:\\Program Files\\nodejs\\npm.cmd' install"
575        );
576    }
577
578    #[test]
579    fn powershell_single_quotes_escaped() {
580        let args: Vec<String> = vec!["echo".into(), "it's done".into()];
581        assert_eq!(join_command_for(&args, "-Command"), "& echo 'it''s done'");
582    }
583
584    #[test]
585    fn powershell_quotes_splat_and_array_syntax() {
586        let args: Vec<String> = vec!["echo".into(), "@args".into(), "a,b".into()];
587        assert_eq!(join_command_for(&args, "-Command"), "& echo '@args' 'a,b'");
588    }
589
590    #[test]
591    fn cmd_simple_args() {
592        let args: Vec<String> = vec!["npm.cmd".into(), "install".into()];
593        assert_eq!(join_command_for(&args, "/C"), "npm.cmd install");
594    }
595
596    #[test]
597    fn cmd_path_with_spaces() {
598        let args: Vec<String> = vec![
599            "C:\\Program Files\\nodejs\\npm.cmd".into(),
600            "install".into(),
601        ];
602        assert_eq!(
603            join_command_for(&args, "/C"),
604            "\"C:\\Program Files\\nodejs\\npm.cmd\" install"
605        );
606    }
607
608    #[test]
609    fn cmd_double_quotes_escaped() {
610        let args: Vec<String> = vec!["echo".into(), "say \"hello\"".into()];
611        assert_eq!(join_command_for(&args, "/C"), "echo \"say \\\"hello\\\"\"");
612    }
613
614    #[test]
615    fn unknown_flag_uses_posix() {
616        let args: Vec<String> = vec!["ls".into(), "-la".into()];
617        assert_eq!(join_command_for(&args, "--exec"), "ls -la");
618    }
619
620    #[test]
621    fn powershell_single_full_command_not_quoted() {
622        let args: Vec<String> = vec!["git commit -m \"feat: add feature\"".into()];
623        let result = join_command_for(&args, "-Command");
624        assert_eq!(result, "git commit -m \"feat: add feature\"");
625        assert!(
626            !result.starts_with("& '"),
627            "must not wrap full command in & '...'"
628        );
629    }
630
631    #[test]
632    fn powershell_single_no_spaces_still_uses_call_operator() {
633        let args: Vec<String> = vec!["git".into()];
634        assert_eq!(join_command_for(&args, "-Command"), "& git");
635    }
636}
637
638#[cfg(test)]
639mod is_powershell_tests {
640    use super::is_powershell;
641
642    #[test]
643    fn detects_pwsh_exe() {
644        assert!(is_powershell("pwsh.exe"));
645    }
646
647    #[test]
648    fn detects_powershell_exe() {
649        assert!(is_powershell("powershell.exe"));
650    }
651
652    #[test]
653    fn rejects_cmd() {
654        assert!(!is_powershell("cmd.exe"));
655    }
656
657    #[test]
658    fn rejects_bash() {
659        assert!(!is_powershell("/usr/bin/bash"));
660    }
661
662    #[test]
663    fn case_insensitive() {
664        assert!(is_powershell("PWSH.EXE"));
665        assert!(is_powershell("PowerShell.exe"));
666    }
667
668    #[test]
669    fn full_path_with_pwsh() {
670        assert!(is_powershell(
671            "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
672        ));
673        assert!(is_powershell("/usr/local/bin/pwsh"));
674    }
675}
676
677#[cfg(test)]
678mod powershell_profile_tests {
679    use super::{powershell_profile_path, resolve_powershell_profile_path};
680    use std::path::Path;
681
682    #[test]
683    fn always_ends_with_profile_file() {
684        let p = powershell_profile_path(Path::new("/home/u"));
685        assert!(p.ends_with("Microsoft.PowerShell_profile.ps1"));
686    }
687
688    #[cfg(not(windows))]
689    #[test]
690    fn non_windows_uses_config_powershell_never_documents() {
691        // #356: stat-ing anything under ~/Documents pops a macOS TCC prompt, so the
692        // non-Windows profile path must live under ~/.config/powershell instead.
693        let p = powershell_profile_path(Path::new("/Users/jane"));
694        assert_eq!(
695            p,
696            Path::new("/Users/jane/.config/powershell/Microsoft.PowerShell_profile.ps1")
697        );
698        assert!(
699            !p.to_string_lossy().contains("Documents"),
700            "macOS/Linux PowerShell profile must never touch ~/Documents (#356)"
701        );
702    }
703
704    #[cfg(windows)]
705    #[test]
706    fn windows_uses_documents_powershell() {
707        let p = powershell_profile_path(Path::new("C:\\Users\\jane"));
708        assert!(p.ends_with("Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1"));
709    }
710
711    #[cfg(not(windows))]
712    #[test]
713    fn resolver_matches_static_default_on_non_windows() {
714        // Non-Windows never spawns a process: the resolver returns the static config
715        // path verbatim (and must never touch ~/Documents, #356).
716        let home = Path::new("/Users/jane");
717        assert_eq!(
718            resolve_powershell_profile_path(home),
719            powershell_profile_path(home)
720        );
721    }
722
723    #[cfg(windows)]
724    #[test]
725    fn resolver_returns_absolute_profile_on_windows() {
726        // On Windows the resolver asks PowerShell for the live $PROFILE (OneDrive-safe,
727        // #558); whether it queries successfully or falls back, the result is an
728        // absolute path to the profile file.
729        let p = resolve_powershell_profile_path(Path::new("C:\\Users\\jane"));
730        assert!(p.is_absolute(), "resolved profile must be absolute: {p:?}");
731        assert!(p.ends_with("Microsoft.PowerShell_profile.ps1"));
732    }
733}
734
735#[cfg(test)]
736mod windows_shell_flag_tests {
737    use super::windows_shell_flag_for_exe_basename;
738
739    #[test]
740    fn cmd_uses_slash_c() {
741        assert_eq!(windows_shell_flag_for_exe_basename("cmd.exe"), "/C");
742        assert_eq!(windows_shell_flag_for_exe_basename("cmd"), "/C");
743    }
744
745    #[test]
746    fn powershell_uses_command() {
747        assert_eq!(
748            windows_shell_flag_for_exe_basename("powershell.exe"),
749            "-Command"
750        );
751        assert_eq!(windows_shell_flag_for_exe_basename("pwsh.exe"), "-Command");
752    }
753
754    #[test]
755    fn posix_shells_use_dash_c() {
756        assert_eq!(windows_shell_flag_for_exe_basename("bash.exe"), "-c");
757        assert_eq!(windows_shell_flag_for_exe_basename("bash"), "-c");
758        assert_eq!(windows_shell_flag_for_exe_basename("sh.exe"), "-c");
759        assert_eq!(windows_shell_flag_for_exe_basename("zsh.exe"), "-c");
760        assert_eq!(windows_shell_flag_for_exe_basename("fish.exe"), "-c");
761    }
762}
763
764#[cfg(test)]
765mod platform_tests {
766    #[test]
767    fn is_container_returns_bool() {
768        let _ = super::is_container();
769    }
770
771    #[test]
772    fn is_non_interactive_returns_bool() {
773        let _ = super::is_non_interactive();
774    }
775
776    #[test]
777    fn join_command_preserves_structure() {
778        let args = vec![
779            "git".to_string(),
780            "commit".to_string(),
781            "-m".to_string(),
782            "my message".to_string(),
783        ];
784        let joined = super::join_command(&args);
785        assert!(joined.contains("git"));
786        assert!(joined.contains("commit"));
787        assert!(joined.contains("my message") || joined.contains("'my message'"));
788    }
789
790    #[test]
791    fn quote_posix_handles_em_dash() {
792        let result = super::quote_posix("closing — see #407");
793        assert!(
794            result.starts_with('\''),
795            "em-dash args must be single-quoted: {result}"
796        );
797    }
798
799    #[test]
800    fn quote_posix_handles_nested_single_quotes() {
801        let result = super::quote_posix("it's a test");
802        assert!(
803            result.contains("\\'"),
804            "single quotes must be escaped: {result}"
805        );
806    }
807
808    #[test]
809    fn quote_posix_safe_chars_unquoted() {
810        let result = super::quote_posix("simple_word");
811        assert_eq!(result, "simple_word");
812    }
813
814    #[test]
815    fn quote_posix_empty_string() {
816        let result = super::quote_posix("");
817        assert_eq!(result, "''");
818    }
819
820    #[test]
821    fn quote_posix_dollar_expansion_protected() {
822        let result = super::quote_posix("$HOME/test");
823        assert!(
824            result.starts_with('\''),
825            "dollar signs must be single-quoted: {result}"
826        );
827    }
828
829    #[test]
830    fn quote_posix_backtick_protected() {
831        let result = super::quote_posix("echo `date`");
832        assert!(
833            result.starts_with('\''),
834            "backticks must be single-quoted: {result}"
835        );
836    }
837
838    #[test]
839    fn quote_posix_double_quotes_protected() {
840        let result = super::quote_posix(r#"he said "hello""#);
841        assert!(
842            result.starts_with('\''),
843            "double quotes must be single-quoted: {result}"
844        );
845    }
846
847    // #451: a non-interactive `bash -c` sources $BASH_ENV. lean-ctx must run
848    // profile-free, so `apply_profile_free_env` has to neutralize an inherited
849    // BASH_ENV before it can pull in a contaminating startup file.
850    #[cfg(unix)]
851    #[test]
852    fn profile_free_env_blocks_bash_env_contamination() {
853        let Some(bash) = ["/bin/bash", "/usr/bin/bash", "/usr/local/bin/bash"]
854            .into_iter()
855            .find(|p| std::path::Path::new(p).exists())
856        else {
857            return; // no bash on this host → nothing to guard against
858        };
859
860        let startup = std::env::temp_dir().join(format!(
861            "lean_ctx_bashenv_{}_{}.sh",
862            std::process::id(),
863            "guard"
864        ));
865        std::fs::write(&startup, "echo CONTAMINATED\n").expect("write startup file");
866
867        let mut cmd = std::process::Command::new(bash);
868        cmd.arg("-c").arg("echo clean").env("BASH_ENV", &startup);
869        super::apply_profile_free_env(&mut cmd);
870        let out = cmd.output().expect("run bash");
871        let stdout = String::from_utf8_lossy(&out.stdout);
872
873        let _ = std::fs::remove_file(&startup);
874
875        assert!(stdout.contains("clean"), "command output missing: {stdout}");
876        assert!(
877            !stdout.contains("CONTAMINATED"),
878            "apply_profile_free_env must neutralize BASH_ENV, got: {stdout}"
879        );
880    }
881
882    #[cfg(unix)]
883    #[test]
884    fn profile_free_env_removes_hidden_option_variables() {
885        let mut cmd = std::process::Command::new("/bin/sh");
886        cmd.arg("-c")
887            .arg(
888                "echo \"[${TAR_OPTIONS-unset}] [${RIPGREP_CONFIG_PATH-unset}] [${VIMINIT-unset}]\"",
889            )
890            .env("TAR_OPTIONS", "-v")
891            .env("RIPGREP_CONFIG_PATH", "/tmp/rc")
892            .env("VIMINIT", "set nocp");
893        super::apply_profile_free_env(&mut cmd);
894        let out = cmd.output().expect("run sh");
895        assert_eq!(
896            String::from_utf8_lossy(&out.stdout).trim(),
897            "[unset] [unset] [unset]"
898        );
899    }
900}
901
902#[cfg(all(test, unix))]
903mod posix_shell_gate_tests {
904    use super::{detect_shell, is_posix_compatible_shell};
905
906    #[test]
907    fn accepts_posix_shells() {
908        for s in [
909            "/bin/bash",
910            "/bin/zsh",
911            "/bin/sh",
912            "/usr/bin/dash",
913            "/bin/ash",
914            "/usr/bin/ksh",
915            "/usr/bin/mksh",
916            "bash",
917            "zsh",
918        ] {
919            assert!(is_posix_compatible_shell(s), "{s} must be POSIX-compatible");
920        }
921    }
922
923    #[test]
924    fn rejects_interactive_and_nonposix_shells() {
925        // #451: agent bash/POSIX syntax fails in these — never auto-select them.
926        for s in [
927            "/usr/bin/nu",
928            "/opt/homebrew/bin/nu",
929            "/usr/bin/fish",
930            "/usr/local/bin/elvish",
931            "/usr/bin/xonsh",
932            "/usr/bin/pwsh",
933            "powershell.exe",
934            "cmd.exe",
935        ] {
936            assert!(
937                !is_posix_compatible_shell(s),
938                "{s} must be rejected by the POSIX gate"
939            );
940        }
941    }
942
943    #[test]
944    #[cfg_attr(miri, ignore)]
945    fn detect_shell_falls_back_when_shell_is_nushell() {
946        // Serialize env mutation (set_var/remove_var are process-global).
947        let _lock = crate::core::data_dir::test_env_lock();
948        let saved_shell = std::env::var_os("SHELL");
949        let saved_override = std::env::var_os("LEAN_CTX_SHELL");
950
951        crate::test_env::remove_var("LEAN_CTX_SHELL");
952        crate::test_env::set_var("SHELL", "/usr/bin/nu");
953        let resolved = detect_shell();
954        assert!(
955            is_posix_compatible_shell(&resolved),
956            "a non-POSIX $SHELL (nu) must resolve to a POSIX shell, got {resolved}"
957        );
958        assert!(
959            !resolved.ends_with("/nu") && resolved != "/usr/bin/nu",
960            "must not run agent commands in Nushell, got {resolved}"
961        );
962
963        // A POSIX $SHELL is honored verbatim.
964        crate::test_env::set_var("SHELL", "/bin/sh");
965        assert_eq!(detect_shell(), "/bin/sh");
966
967        // LEAN_CTX_SHELL always wins, even when pointing at a non-POSIX shell.
968        crate::test_env::set_var("LEAN_CTX_SHELL", "/usr/bin/nu");
969        assert_eq!(detect_shell(), "/usr/bin/nu");
970
971        match saved_shell {
972            Some(v) => crate::test_env::set_var("SHELL", v),
973            None => crate::test_env::remove_var("SHELL"),
974        }
975        match saved_override {
976            Some(v) => crate::test_env::set_var("LEAN_CTX_SHELL", v),
977            None => crate::test_env::remove_var("LEAN_CTX_SHELL"),
978        }
979    }
980}
981
982#[cfg(test)]
983mod carriage_return_tests {
984    use super::resolve_carriage_returns;
985
986    #[test]
987    fn no_cr_passthrough() {
988        assert_eq!(resolve_carriage_returns("hello\nworld\n"), "hello\nworld\n");
989    }
990
991    #[test]
992    fn progress_overwrite_keeps_last_segment() {
993        assert_eq!(resolve_carriage_returns("first\rsecond"), "second");
994    }
995
996    #[test]
997    fn git_rebase_progress() {
998        let input = "Rebasing (1/1)\rSuccessfully rebased and updated refs/heads/feat.";
999        assert_eq!(
1000            resolve_carriage_returns(input),
1001            "Successfully rebased and updated refs/heads/feat."
1002        );
1003    }
1004
1005    #[test]
1006    fn crlf_line_endings_stripped() {
1007        assert_eq!(
1008            resolve_carriage_returns("line1\r\nline2\r\n"),
1009            "line1\nline2\n"
1010        );
1011    }
1012
1013    #[test]
1014    fn multiple_cr_on_one_line() {
1015        assert_eq!(resolve_carriage_returns("a\rb\rc"), "c");
1016    }
1017
1018    #[test]
1019    fn mixed_lines() {
1020        let input = "clean line\nprogress\rdone\nalso clean\n";
1021        assert_eq!(
1022            resolve_carriage_returns(input),
1023            "clean line\ndone\nalso clean\n"
1024        );
1025    }
1026
1027    #[test]
1028    fn trailing_cr_stripped_as_crlf() {
1029        assert_eq!(resolve_carriage_returns("visible\r"), "visible");
1030    }
1031
1032    #[test]
1033    fn empty_string_passthrough() {
1034        assert_eq!(resolve_carriage_returns(""), "");
1035    }
1036}
1037
1038#[cfg(test)]
1039mod zsh_safe_tests {
1040    use super::zsh_safe_command;
1041
1042    #[test]
1043    #[cfg(unix)]
1044    fn prepends_nonomatch_noequals_for_zsh() {
1045        let cmd = zsh_safe_command("grep --include=*.go pattern", "/bin/zsh");
1046        assert_eq!(
1047            cmd,
1048            "setopt nonomatch noequals; grep --include=*.go pattern"
1049        );
1050    }
1051
1052    #[test]
1053    #[cfg(unix)]
1054    fn prepends_nonomatch_noequals_for_usr_bin_zsh() {
1055        let cmd = zsh_safe_command("echo *.rs", "/usr/bin/zsh");
1056        assert_eq!(cmd, "setopt nonomatch noequals; echo *.rs");
1057    }
1058
1059    #[test]
1060    #[cfg(unix)]
1061    fn equals_separator_safe_under_zsh() {
1062        let cmd = zsh_safe_command("echo ===", "/bin/zsh");
1063        assert!(cmd.starts_with("setopt nonomatch noequals;"));
1064        assert!(cmd.contains("echo ==="));
1065    }
1066
1067    #[test]
1068    fn passthrough_for_bash() {
1069        let cmd = zsh_safe_command("grep --include=*.go pattern", "/bin/bash");
1070        assert_eq!(cmd, "grep --include=*.go pattern");
1071    }
1072
1073    #[test]
1074    fn passthrough_for_sh() {
1075        let cmd = zsh_safe_command("find -name *.ts", "/bin/sh");
1076        assert_eq!(cmd, "find -name *.ts");
1077    }
1078}