1use std::io::{self, IsTerminal};
2
3pub(crate) fn apply_utf8_locale(cmd: &mut std::process::Command) {
7 let has_utf8 = std::env::var("LC_ALL")
8 .or_else(|_| std::env::var("LC_CTYPE"))
9 .or_else(|_| std::env::var("LANG"))
10 .is_ok_and(|v| v.to_ascii_lowercase().contains("utf"));
11
12 if !has_utf8 {
13 cmd.env("LC_CTYPE", "C.UTF-8");
14 }
15}
16
17pub(crate) fn apply_profile_free_env(cmd: &mut std::process::Command) {
25 cmd.env("BASH_ENV", "").env("ENV", "");
26}
27
28pub fn decode_output(bytes: &[u8]) -> String {
29 match String::from_utf8(bytes.to_vec()) {
30 Ok(s) => s,
31 Err(_) => {
32 #[cfg(windows)]
33 {
34 decode_windows_output(bytes)
35 }
36 #[cfg(not(windows))]
37 {
38 String::from_utf8_lossy(bytes).into_owned()
39 }
40 }
41 }
42}
43pub fn resolve_carriage_returns(s: &str) -> String {
51 if !s.contains('\r') {
52 return s.to_string();
53 }
54 let mut out = String::with_capacity(s.len());
55 for (i, line) in s.split('\n').enumerate() {
56 if i > 0 {
57 out.push('\n');
58 }
59 let line = line.strip_suffix('\r').unwrap_or(line);
60 if let Some(pos) = line.rfind('\r') {
61 out.push_str(&line[pos + 1..]);
62 } else {
63 out.push_str(line);
64 }
65 }
66 out
67}
68
69#[cfg(windows)]
70fn decode_windows_output(bytes: &[u8]) -> String {
71 use std::os::windows::ffi::OsStringExt;
72
73 let lossy = String::from_utf8_lossy(bytes);
74 let replacement_count = lossy.chars().filter(|&c| c == '\u{FFFD}').count();
75 if replacement_count == 0 {
76 return lossy.into_owned();
77 }
78
79 unsafe extern "system" {
82 fn GetACP() -> u32;
83 fn MultiByteToWideChar(
84 cp: u32,
85 flags: u32,
86 src: *const u8,
87 srclen: i32,
88 dst: *mut u16,
89 dstlen: i32,
90 ) -> i32;
91 }
92
93 let codepage = unsafe { GetACP() };
96 let wide_len = unsafe {
100 MultiByteToWideChar(
101 codepage,
102 0,
103 bytes.as_ptr(),
104 bytes.len() as i32,
105 std::ptr::null_mut(),
106 0,
107 )
108 };
109 if wide_len <= 0 {
110 return lossy.into_owned();
111 }
112 let mut wide: Vec<u16> = vec![0u16; wide_len as usize];
113 unsafe {
117 MultiByteToWideChar(
118 codepage,
119 0,
120 bytes.as_ptr(),
121 bytes.len() as i32,
122 wide.as_mut_ptr(),
123 wide_len,
124 );
125 }
126 std::ffi::OsString::from_wide(&wide)
127 .to_string_lossy()
128 .into_owned()
129}
130
131#[cfg(windows)]
132pub(super) fn set_console_utf8() {
133 unsafe extern "system" {
136 fn SetConsoleOutputCP(id: u32) -> i32;
137 }
138 unsafe {
141 SetConsoleOutputCP(65001);
142 }
143}
144
145pub fn is_container() -> bool {
147 #[cfg(unix)]
148 {
149 if std::path::Path::new("/.dockerenv").exists() {
150 return true;
151 }
152 if let Ok(cgroup) = std::fs::read_to_string("/proc/1/cgroup")
153 && (cgroup.contains("/docker/") || cgroup.contains("/lxc/"))
154 {
155 return true;
156 }
157 if let Ok(mounts) = std::fs::read_to_string("/proc/self/mountinfo")
158 && mounts.contains("/docker/containers/")
159 {
160 return true;
161 }
162 false
163 }
164 #[cfg(not(unix))]
165 {
166 false
167 }
168}
169
170pub fn is_non_interactive() -> bool {
172 !io::stdin().is_terminal()
173}
174
175pub(crate) fn is_powershell(shell_path: &str) -> bool {
177 let name = std::path::Path::new(shell_path)
178 .file_name()
179 .and_then(|n| n.to_str())
180 .unwrap_or("")
181 .to_ascii_lowercase();
182 name.contains("powershell") || name.contains("pwsh")
183}
184
185pub(crate) fn powershell_profile_path(home: &std::path::Path) -> std::path::PathBuf {
200 const PROFILE_FILE: &str = "Microsoft.PowerShell_profile.ps1";
201 if cfg!(windows) {
202 home.join("Documents").join("PowerShell").join(PROFILE_FILE)
203 } else {
204 home.join(".config").join("powershell").join(PROFILE_FILE)
205 }
206}
207
208pub(crate) fn resolve_powershell_profile_path(home: &std::path::Path) -> std::path::PathBuf {
223 #[cfg(windows)]
224 {
225 if let Some(active) = query_active_powershell_profile() {
226 return active;
227 }
228 }
229 powershell_profile_path(home)
230}
231
232#[cfg(windows)]
236fn query_active_powershell_profile() -> Option<std::path::PathBuf> {
237 for exe in ["pwsh", "powershell"] {
241 let output = match std::process::Command::new(exe)
242 .args([
243 "-NoProfile",
244 "-NonInteractive",
245 "-Command",
246 "[Console]::OutputEncoding=[Text.Encoding]::UTF8; $PROFILE.CurrentUserCurrentHost",
247 ])
248 .output()
249 {
250 Ok(out) if out.status.success() => out,
251 _ => continue,
252 };
253 let path = std::path::PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
254 if path.is_absolute() && path.file_name().is_some() {
255 return Some(path);
256 }
257 }
258 None
259}
260
261fn windows_shell_flag_for_exe_basename(exe_basename: &str) -> &'static str {
264 if exe_basename.contains("powershell") || exe_basename.contains("pwsh") {
265 "-Command"
266 } else if exe_basename == "cmd.exe" || exe_basename == "cmd" {
267 "/C"
268 } else {
269 "-c"
270 }
271}
272
273pub fn shell_and_flag() -> (String, String) {
274 let shell = detect_shell();
275 let flag = if cfg!(windows) {
276 let name = std::path::Path::new(&shell)
277 .file_name()
278 .and_then(|n| n.to_str())
279 .unwrap_or("")
280 .to_ascii_lowercase();
281 windows_shell_flag_for_exe_basename(&name).to_string()
282 } else {
283 "-c".to_string()
284 };
285 (shell, flag)
286}
287
288pub fn shell_name() -> String {
290 let shell = detect_shell();
291 let basename = std::path::Path::new(&shell)
292 .file_name()
293 .and_then(|n| n.to_str())
294 .unwrap_or("sh")
295 .to_ascii_lowercase();
296 basename
297 .strip_suffix(".exe")
298 .unwrap_or(&basename)
299 .to_string()
300}
301
302pub(crate) fn zsh_safe_command(command: &str, shell: &str) -> String {
308 if cfg!(unix) {
309 let basename = std::path::Path::new(shell)
310 .file_name()
311 .and_then(|n| n.to_str())
312 .unwrap_or("");
313 if basename == "zsh" {
314 return format!("setopt nonomatch noequals; {command}");
315 }
316 }
317 command.to_string()
318}
319
320pub(super) fn detect_shell() -> String {
321 if let Ok(shell) = std::env::var("LEAN_CTX_SHELL") {
322 return shell;
323 }
324
325 if let Ok(shell) = std::env::var("SHELL") {
326 let bin = std::path::Path::new(&shell)
327 .file_name()
328 .and_then(|n| n.to_str())
329 .unwrap_or("sh");
330
331 if bin == "lean-ctx" {
332 return find_real_shell();
333 }
334 if shell_acceptable_for_exec(&shell) {
341 return shell;
342 }
343 return find_real_shell();
344 }
345
346 find_real_shell()
347}
348
349#[cfg(unix)]
356fn shell_acceptable_for_exec(shell: &str) -> bool {
357 is_posix_compatible_shell(shell)
358}
359
360#[cfg(windows)]
361fn shell_acceptable_for_exec(_shell: &str) -> bool {
362 true
363}
364
365#[cfg(unix)]
370fn is_posix_compatible_shell(shell: &str) -> bool {
371 let name = std::path::Path::new(shell)
372 .file_name()
373 .and_then(|n| n.to_str())
374 .unwrap_or("")
375 .to_ascii_lowercase();
376 let name = name.strip_suffix(".exe").unwrap_or(&name);
377 matches!(
378 name,
379 "bash" | "zsh" | "sh" | "dash" | "ash" | "ksh" | "ksh93" | "mksh" | "busybox"
380 )
381}
382
383#[cfg(unix)]
384fn find_real_shell() -> String {
385 for shell in &["/bin/zsh", "/bin/bash", "/bin/sh"] {
386 if std::path::Path::new(shell).exists() {
387 return shell.to_string();
388 }
389 }
390 "/bin/sh".to_string()
391}
392
393#[cfg(windows)]
394fn find_real_shell() -> String {
395 if is_running_in_msys_or_gitbash() {
396 for candidate in &["bash.exe", "sh.exe"] {
397 if let Ok(output) = std::process::Command::new("where").arg(candidate).output() {
398 if output.status.success() {
399 if let Ok(path) = String::from_utf8(output.stdout) {
400 if let Some(first_line) = path.lines().next() {
401 let trimmed = first_line.trim();
402 if !trimmed.is_empty() {
403 return trimmed.to_string();
404 }
405 }
406 }
407 }
408 }
409 }
410 }
411 if let Ok(pwsh) = which_powershell() {
412 return pwsh;
413 }
414 if let Ok(comspec) = std::env::var("COMSPEC") {
415 return comspec;
416 }
417 "cmd.exe".to_string()
418}
419
420#[cfg(windows)]
421fn is_running_in_msys_or_gitbash() -> bool {
422 std::env::var("MSYSTEM").is_ok() || std::env::var("MINGW_PREFIX").is_ok()
423}
424
425#[cfg(windows)]
426fn which_powershell() -> Result<String, ()> {
427 for candidate in &["pwsh.exe", "powershell.exe"] {
428 if let Ok(output) = std::process::Command::new("where").arg(candidate).output() {
429 if output.status.success() {
430 if let Ok(path) = String::from_utf8(output.stdout) {
431 if let Some(first_line) = path.lines().next() {
432 let trimmed = first_line.trim();
433 if !trimmed.is_empty() {
434 return Ok(trimmed.to_string());
435 }
436 }
437 }
438 }
439 }
440 }
441 Err(())
442}
443
444pub fn join_command(args: &[String]) -> String {
451 let (_, flag) = shell_and_flag();
452 join_command_for(args, &flag)
453}
454
455pub fn join_command_for(args: &[String], shell_flag: &str) -> String {
456 match shell_flag {
457 "-Command" => join_powershell(args),
458 "/C" => join_cmd(args),
459 _ => join_posix(args),
460 }
461}
462
463fn join_posix(args: &[String]) -> String {
464 args.iter()
465 .map(|a| quote_posix(a))
466 .collect::<Vec<_>>()
467 .join(" ")
468}
469
470fn join_powershell(args: &[String]) -> String {
471 if args.len() == 1 && args[0].contains(' ') {
472 return args[0].clone();
473 }
474 let quoted: Vec<String> = args.iter().map(|a| quote_powershell(a)).collect();
475 format!("& {}", quoted.join(" "))
476}
477
478fn join_cmd(args: &[String]) -> String {
479 args.iter()
480 .map(|a| quote_cmd(a))
481 .collect::<Vec<_>>()
482 .join(" ")
483}
484
485fn quote_posix(s: &str) -> String {
486 if s.is_empty() {
487 return "''".to_string();
488 }
489 if s.bytes()
490 .all(|b| b.is_ascii_alphanumeric() || b"-_./=:@,+%^".contains(&b))
491 {
492 return s.to_string();
493 }
494 format!("'{}'", s.replace('\'', "'\\''"))
495}
496
497fn quote_powershell(s: &str) -> String {
498 if s.is_empty() {
499 return "''".to_string();
500 }
501 if s.bytes()
502 .all(|b| b.is_ascii_alphanumeric() || b"-_./=:@,+%^".contains(&b))
503 {
504 return s.to_string();
505 }
506 format!("'{}'", s.replace('\'', "''"))
507}
508
509fn quote_cmd(s: &str) -> String {
510 if s.is_empty() {
511 return "\"\"".to_string();
512 }
513 if s.bytes()
514 .all(|b| b.is_ascii_alphanumeric() || b"-_./=:@,+%^\\".contains(&b))
515 {
516 return s.to_string();
517 }
518 format!("\"{}\"", s.replace('"', "\\\""))
519}
520
521#[cfg(test)]
522mod join_command_tests {
523 use super::*;
524
525 #[test]
526 fn posix_simple_args() {
527 let args: Vec<String> = vec!["git".into(), "status".into()];
528 assert_eq!(join_command_for(&args, "-c"), "git status");
529 }
530
531 #[test]
532 fn posix_path_with_spaces() {
533 let args: Vec<String> = vec!["/usr/local/my app/bin".into(), "--help".into()];
534 assert_eq!(
535 join_command_for(&args, "-c"),
536 "'/usr/local/my app/bin' --help"
537 );
538 }
539
540 #[test]
541 fn posix_single_quotes_escaped() {
542 let args: Vec<String> = vec!["echo".into(), "it's".into()];
543 assert_eq!(join_command_for(&args, "-c"), "echo 'it'\\''s'");
544 }
545
546 #[test]
547 fn posix_empty_arg() {
548 let args: Vec<String> = vec!["cmd".into(), String::new()];
549 assert_eq!(join_command_for(&args, "-c"), "cmd ''");
550 }
551
552 #[test]
553 fn powershell_simple_args() {
554 let args: Vec<String> = vec!["npm".into(), "install".into()];
555 assert_eq!(join_command_for(&args, "-Command"), "& npm install");
556 }
557
558 #[test]
559 fn powershell_path_with_spaces() {
560 let args: Vec<String> = vec![
561 "C:\\Program Files\\nodejs\\npm.cmd".into(),
562 "install".into(),
563 ];
564 assert_eq!(
565 join_command_for(&args, "-Command"),
566 "& 'C:\\Program Files\\nodejs\\npm.cmd' install"
567 );
568 }
569
570 #[test]
571 fn powershell_single_quotes_escaped() {
572 let args: Vec<String> = vec!["echo".into(), "it's done".into()];
573 assert_eq!(join_command_for(&args, "-Command"), "& echo 'it''s done'");
574 }
575
576 #[test]
577 fn cmd_simple_args() {
578 let args: Vec<String> = vec!["npm.cmd".into(), "install".into()];
579 assert_eq!(join_command_for(&args, "/C"), "npm.cmd install");
580 }
581
582 #[test]
583 fn cmd_path_with_spaces() {
584 let args: Vec<String> = vec![
585 "C:\\Program Files\\nodejs\\npm.cmd".into(),
586 "install".into(),
587 ];
588 assert_eq!(
589 join_command_for(&args, "/C"),
590 "\"C:\\Program Files\\nodejs\\npm.cmd\" install"
591 );
592 }
593
594 #[test]
595 fn cmd_double_quotes_escaped() {
596 let args: Vec<String> = vec!["echo".into(), "say \"hello\"".into()];
597 assert_eq!(join_command_for(&args, "/C"), "echo \"say \\\"hello\\\"\"");
598 }
599
600 #[test]
601 fn unknown_flag_uses_posix() {
602 let args: Vec<String> = vec!["ls".into(), "-la".into()];
603 assert_eq!(join_command_for(&args, "--exec"), "ls -la");
604 }
605
606 #[test]
607 fn powershell_single_full_command_not_quoted() {
608 let args: Vec<String> = vec!["git commit -m \"feat: add feature\"".into()];
609 let result = join_command_for(&args, "-Command");
610 assert_eq!(result, "git commit -m \"feat: add feature\"");
611 assert!(
612 !result.starts_with("& '"),
613 "must not wrap full command in & '...'"
614 );
615 }
616
617 #[test]
618 fn powershell_single_no_spaces_still_uses_call_operator() {
619 let args: Vec<String> = vec!["git".into()];
620 assert_eq!(join_command_for(&args, "-Command"), "& git");
621 }
622}
623
624#[cfg(test)]
625mod is_powershell_tests {
626 use super::is_powershell;
627
628 #[test]
629 fn detects_pwsh_exe() {
630 assert!(is_powershell("pwsh.exe"));
631 }
632
633 #[test]
634 fn detects_powershell_exe() {
635 assert!(is_powershell("powershell.exe"));
636 }
637
638 #[test]
639 fn rejects_cmd() {
640 assert!(!is_powershell("cmd.exe"));
641 }
642
643 #[test]
644 fn rejects_bash() {
645 assert!(!is_powershell("/usr/bin/bash"));
646 }
647
648 #[test]
649 fn case_insensitive() {
650 assert!(is_powershell("PWSH.EXE"));
651 assert!(is_powershell("PowerShell.exe"));
652 }
653
654 #[test]
655 fn full_path_with_pwsh() {
656 assert!(is_powershell(
657 "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
658 ));
659 assert!(is_powershell("/usr/local/bin/pwsh"));
660 }
661}
662
663#[cfg(test)]
664mod powershell_profile_tests {
665 use super::{powershell_profile_path, resolve_powershell_profile_path};
666 use std::path::Path;
667
668 #[test]
669 fn always_ends_with_profile_file() {
670 let p = powershell_profile_path(Path::new("/home/u"));
671 assert!(p.ends_with("Microsoft.PowerShell_profile.ps1"));
672 }
673
674 #[cfg(not(windows))]
675 #[test]
676 fn non_windows_uses_config_powershell_never_documents() {
677 let p = powershell_profile_path(Path::new("/Users/jane"));
680 assert_eq!(
681 p,
682 Path::new("/Users/jane/.config/powershell/Microsoft.PowerShell_profile.ps1")
683 );
684 assert!(
685 !p.to_string_lossy().contains("Documents"),
686 "macOS/Linux PowerShell profile must never touch ~/Documents (#356)"
687 );
688 }
689
690 #[cfg(windows)]
691 #[test]
692 fn windows_uses_documents_powershell() {
693 let p = powershell_profile_path(Path::new("C:\\Users\\jane"));
694 assert!(p.ends_with("Documents\\PowerShell\\Microsoft.PowerShell_profile.ps1"));
695 }
696
697 #[cfg(not(windows))]
698 #[test]
699 fn resolver_matches_static_default_on_non_windows() {
700 let home = Path::new("/Users/jane");
703 assert_eq!(
704 resolve_powershell_profile_path(home),
705 powershell_profile_path(home)
706 );
707 }
708
709 #[cfg(windows)]
710 #[test]
711 fn resolver_returns_absolute_profile_on_windows() {
712 let p = resolve_powershell_profile_path(Path::new("C:\\Users\\jane"));
716 assert!(p.is_absolute(), "resolved profile must be absolute: {p:?}");
717 assert!(p.ends_with("Microsoft.PowerShell_profile.ps1"));
718 }
719}
720
721#[cfg(test)]
722mod windows_shell_flag_tests {
723 use super::windows_shell_flag_for_exe_basename;
724
725 #[test]
726 fn cmd_uses_slash_c() {
727 assert_eq!(windows_shell_flag_for_exe_basename("cmd.exe"), "/C");
728 assert_eq!(windows_shell_flag_for_exe_basename("cmd"), "/C");
729 }
730
731 #[test]
732 fn powershell_uses_command() {
733 assert_eq!(
734 windows_shell_flag_for_exe_basename("powershell.exe"),
735 "-Command"
736 );
737 assert_eq!(windows_shell_flag_for_exe_basename("pwsh.exe"), "-Command");
738 }
739
740 #[test]
741 fn posix_shells_use_dash_c() {
742 assert_eq!(windows_shell_flag_for_exe_basename("bash.exe"), "-c");
743 assert_eq!(windows_shell_flag_for_exe_basename("bash"), "-c");
744 assert_eq!(windows_shell_flag_for_exe_basename("sh.exe"), "-c");
745 assert_eq!(windows_shell_flag_for_exe_basename("zsh.exe"), "-c");
746 assert_eq!(windows_shell_flag_for_exe_basename("fish.exe"), "-c");
747 }
748}
749
750#[cfg(test)]
751mod platform_tests {
752 #[test]
753 fn is_container_returns_bool() {
754 let _ = super::is_container();
755 }
756
757 #[test]
758 fn is_non_interactive_returns_bool() {
759 let _ = super::is_non_interactive();
760 }
761
762 #[test]
763 fn join_command_preserves_structure() {
764 let args = vec![
765 "git".to_string(),
766 "commit".to_string(),
767 "-m".to_string(),
768 "my message".to_string(),
769 ];
770 let joined = super::join_command(&args);
771 assert!(joined.contains("git"));
772 assert!(joined.contains("commit"));
773 assert!(joined.contains("my message") || joined.contains("'my message'"));
774 }
775
776 #[test]
777 fn quote_posix_handles_em_dash() {
778 let result = super::quote_posix("closing — see #407");
779 assert!(
780 result.starts_with('\''),
781 "em-dash args must be single-quoted: {result}"
782 );
783 }
784
785 #[test]
786 fn quote_posix_handles_nested_single_quotes() {
787 let result = super::quote_posix("it's a test");
788 assert!(
789 result.contains("\\'"),
790 "single quotes must be escaped: {result}"
791 );
792 }
793
794 #[test]
795 fn quote_posix_safe_chars_unquoted() {
796 let result = super::quote_posix("simple_word");
797 assert_eq!(result, "simple_word");
798 }
799
800 #[test]
801 fn quote_posix_empty_string() {
802 let result = super::quote_posix("");
803 assert_eq!(result, "''");
804 }
805
806 #[test]
807 fn quote_posix_dollar_expansion_protected() {
808 let result = super::quote_posix("$HOME/test");
809 assert!(
810 result.starts_with('\''),
811 "dollar signs must be single-quoted: {result}"
812 );
813 }
814
815 #[test]
816 fn quote_posix_backtick_protected() {
817 let result = super::quote_posix("echo `date`");
818 assert!(
819 result.starts_with('\''),
820 "backticks must be single-quoted: {result}"
821 );
822 }
823
824 #[test]
825 fn quote_posix_double_quotes_protected() {
826 let result = super::quote_posix(r#"he said "hello""#);
827 assert!(
828 result.starts_with('\''),
829 "double quotes must be single-quoted: {result}"
830 );
831 }
832
833 #[cfg(unix)]
837 #[test]
838 fn profile_free_env_blocks_bash_env_contamination() {
839 let Some(bash) = ["/bin/bash", "/usr/bin/bash", "/usr/local/bin/bash"]
840 .into_iter()
841 .find(|p| std::path::Path::new(p).exists())
842 else {
843 return; };
845
846 let startup = std::env::temp_dir().join(format!(
847 "lean_ctx_bashenv_{}_{}.sh",
848 std::process::id(),
849 "guard"
850 ));
851 std::fs::write(&startup, "echo CONTAMINATED\n").expect("write startup file");
852
853 let mut cmd = std::process::Command::new(bash);
854 cmd.arg("-c").arg("echo clean").env("BASH_ENV", &startup);
855 super::apply_profile_free_env(&mut cmd);
856 let out = cmd.output().expect("run bash");
857 let stdout = String::from_utf8_lossy(&out.stdout);
858
859 let _ = std::fs::remove_file(&startup);
860
861 assert!(stdout.contains("clean"), "command output missing: {stdout}");
862 assert!(
863 !stdout.contains("CONTAMINATED"),
864 "apply_profile_free_env must neutralize BASH_ENV, got: {stdout}"
865 );
866 }
867}
868
869#[cfg(all(test, unix))]
870mod posix_shell_gate_tests {
871 use super::{detect_shell, is_posix_compatible_shell};
872
873 #[test]
874 fn accepts_posix_shells() {
875 for s in [
876 "/bin/bash",
877 "/bin/zsh",
878 "/bin/sh",
879 "/usr/bin/dash",
880 "/bin/ash",
881 "/usr/bin/ksh",
882 "/usr/bin/mksh",
883 "bash",
884 "zsh",
885 ] {
886 assert!(is_posix_compatible_shell(s), "{s} must be POSIX-compatible");
887 }
888 }
889
890 #[test]
891 fn rejects_interactive_and_nonposix_shells() {
892 for s in [
894 "/usr/bin/nu",
895 "/opt/homebrew/bin/nu",
896 "/usr/bin/fish",
897 "/usr/local/bin/elvish",
898 "/usr/bin/xonsh",
899 "/usr/bin/pwsh",
900 "powershell.exe",
901 "cmd.exe",
902 ] {
903 assert!(
904 !is_posix_compatible_shell(s),
905 "{s} must be rejected by the POSIX gate"
906 );
907 }
908 }
909
910 #[test]
911 #[cfg_attr(miri, ignore)]
912 fn detect_shell_falls_back_when_shell_is_nushell() {
913 let _lock = crate::core::data_dir::test_env_lock();
915 let saved_shell = std::env::var_os("SHELL");
916 let saved_override = std::env::var_os("LEAN_CTX_SHELL");
917
918 crate::test_env::remove_var("LEAN_CTX_SHELL");
919 crate::test_env::set_var("SHELL", "/usr/bin/nu");
920 let resolved = detect_shell();
921 assert!(
922 is_posix_compatible_shell(&resolved),
923 "a non-POSIX $SHELL (nu) must resolve to a POSIX shell, got {resolved}"
924 );
925 assert!(
926 !resolved.ends_with("/nu") && resolved != "/usr/bin/nu",
927 "must not run agent commands in Nushell, got {resolved}"
928 );
929
930 crate::test_env::set_var("SHELL", "/bin/sh");
932 assert_eq!(detect_shell(), "/bin/sh");
933
934 crate::test_env::set_var("LEAN_CTX_SHELL", "/usr/bin/nu");
936 assert_eq!(detect_shell(), "/usr/bin/nu");
937
938 match saved_shell {
939 Some(v) => crate::test_env::set_var("SHELL", v),
940 None => crate::test_env::remove_var("SHELL"),
941 }
942 match saved_override {
943 Some(v) => crate::test_env::set_var("LEAN_CTX_SHELL", v),
944 None => crate::test_env::remove_var("LEAN_CTX_SHELL"),
945 }
946 }
947}
948
949#[cfg(test)]
950mod carriage_return_tests {
951 use super::resolve_carriage_returns;
952
953 #[test]
954 fn no_cr_passthrough() {
955 assert_eq!(resolve_carriage_returns("hello\nworld\n"), "hello\nworld\n");
956 }
957
958 #[test]
959 fn progress_overwrite_keeps_last_segment() {
960 assert_eq!(resolve_carriage_returns("first\rsecond"), "second");
961 }
962
963 #[test]
964 fn git_rebase_progress() {
965 let input = "Rebasing (1/1)\rSuccessfully rebased and updated refs/heads/feat.";
966 assert_eq!(
967 resolve_carriage_returns(input),
968 "Successfully rebased and updated refs/heads/feat."
969 );
970 }
971
972 #[test]
973 fn crlf_line_endings_stripped() {
974 assert_eq!(
975 resolve_carriage_returns("line1\r\nline2\r\n"),
976 "line1\nline2\n"
977 );
978 }
979
980 #[test]
981 fn multiple_cr_on_one_line() {
982 assert_eq!(resolve_carriage_returns("a\rb\rc"), "c");
983 }
984
985 #[test]
986 fn mixed_lines() {
987 let input = "clean line\nprogress\rdone\nalso clean\n";
988 assert_eq!(
989 resolve_carriage_returns(input),
990 "clean line\ndone\nalso clean\n"
991 );
992 }
993
994 #[test]
995 fn trailing_cr_stripped_as_crlf() {
996 assert_eq!(resolve_carriage_returns("visible\r"), "visible");
997 }
998
999 #[test]
1000 fn empty_string_passthrough() {
1001 assert_eq!(resolve_carriage_returns(""), "");
1002 }
1003}
1004
1005#[cfg(test)]
1006mod zsh_safe_tests {
1007 use super::zsh_safe_command;
1008
1009 #[test]
1010 #[cfg(unix)]
1011 fn prepends_nonomatch_noequals_for_zsh() {
1012 let cmd = zsh_safe_command("grep --include=*.go pattern", "/bin/zsh");
1013 assert_eq!(
1014 cmd,
1015 "setopt nonomatch noequals; grep --include=*.go pattern"
1016 );
1017 }
1018
1019 #[test]
1020 #[cfg(unix)]
1021 fn prepends_nonomatch_noequals_for_usr_bin_zsh() {
1022 let cmd = zsh_safe_command("echo *.rs", "/usr/bin/zsh");
1023 assert_eq!(cmd, "setopt nonomatch noequals; echo *.rs");
1024 }
1025
1026 #[test]
1027 #[cfg(unix)]
1028 fn equals_separator_safe_under_zsh() {
1029 let cmd = zsh_safe_command("echo ===", "/bin/zsh");
1030 assert!(cmd.starts_with("setopt nonomatch noequals;"));
1031 assert!(cmd.contains("echo ==="));
1032 }
1033
1034 #[test]
1035 fn passthrough_for_bash() {
1036 let cmd = zsh_safe_command("grep --include=*.go pattern", "/bin/bash");
1037 assert_eq!(cmd, "grep --include=*.go pattern");
1038 }
1039
1040 #[test]
1041 fn passthrough_for_sh() {
1042 let cmd = zsh_safe_command("find -name *.ts", "/bin/sh");
1043 assert_eq!(cmd, "find -name *.ts");
1044 }
1045}