use std::ffi::OsStr;
use std::process::{Command, Stdio};
use std::time::Duration;
const LAUNCHD_DIRS: [&str; 4] = ["/usr/bin", "/bin", "/usr/sbin", "/sbin"];
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
const BEGIN: &str = "__CROFT_PATH_BEGIN__";
const END: &str = "__CROFT_PATH_END__";
fn is_stripped(path: Option<&str>) -> bool {
let Some(path) = path.map(str::trim).filter(|p| !p.is_empty()) else {
return true;
};
path.split(':')
.filter(|e| !e.is_empty())
.filter(|e| !e.contains(".app/"))
.all(|e| LAUNCHD_DIRS.contains(&e.trim_end_matches('/')))
}
fn merge(current: Option<&str>, probed: &str) -> String {
let mut out: Vec<&str> = Vec::new();
for entry in probed
.split(':')
.chain(current.unwrap_or_default().split(':'))
.filter(|e| !e.is_empty())
{
if !out.contains(&entry) {
out.push(entry);
}
}
out.join(":")
}
fn probe(shell: &str) -> Option<String> {
run_probe(probe_cmd(shell), PROBE_TIMEOUT)
}
fn probe_cmd(shell: &str) -> Command {
let mut cmd = Command::new(shell);
let name = std::path::Path::new(shell)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
if name.ends_with("csh") {
std::os::unix::process::CommandExt::arg0(&mut cmd, format!("-{name}"));
cmd.arg("-i");
} else {
cmd.args(["-l", "-i"]);
}
cmd.arg("-c")
.arg(format!(r#"/bin/sh -c 'printf "{BEGIN}%s{END}" "$PATH"'"#));
cmd
}
fn run_probe(mut cmd: Command, timeout: Duration) -> Option<String> {
unsafe {
std::os::unix::process::CommandExt::pre_exec(&mut cmd, || {
libc::setsid();
Ok(())
});
}
let mut child = cmd
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.ok()?;
let mut stdout = child.stdout.take()?;
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let mut buf = Vec::new();
let mut chunk = [0u8; 4096];
loop {
match std::io::Read::read(&mut stdout, &mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => {
buf.extend_from_slice(&chunk[..n]);
if String::from_utf8_lossy(&buf).contains(END) {
break;
}
}
}
}
let _ = tx.send(buf);
});
let out = rx.recv_timeout(timeout).ok();
let _ = child.kill();
std::thread::spawn(move || {
let _ = child.wait();
});
extract(&String::from_utf8_lossy(&out?))
}
fn extract(out: &str) -> Option<String> {
let (_, rest) = out.split_once(BEGIN)?;
let (path, _) = rest.split_once(END)?;
let path = path.trim();
(!path.is_empty()).then(|| path.to_string())
}
fn repaired(current: Option<&str>, probe: impl FnOnce() -> Option<String>) -> Option<String> {
if !is_stripped(current) {
return None;
}
let probed = probe()?;
let merged = merge(current, &probed);
(merged != current.unwrap_or_default()).then_some(merged)
}
fn login_shell() -> String {
std::env::var("SHELL")
.ok()
.filter(|s| !s.trim().is_empty())
.unwrap_or_else(|| String::from("/bin/zsh"))
}
pub fn repair() {
let current = std::env::var("PATH").ok();
let Some(fixed) = repaired(current.as_deref(), || probe(&login_shell())) else {
return;
};
unsafe { std::env::set_var("PATH", OsStr::new(&fixed)) };
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn launchd_path_reads_as_stripped() {
assert!(is_stripped(Some("/usr/bin:/bin:/usr/sbin:/sbin")));
assert!(is_stripped(Some("/bin:/usr/bin:/sbin/:/usr/sbin")));
assert!(is_stripped(Some("")));
assert!(is_stripped(None));
}
#[test]
fn a_dock_launch_through_ghostty_reads_as_stripped() {
assert!(is_stripped(Some(
"/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Ghostty.app/Contents/MacOS"
)));
assert!(is_stripped(Some(
"/Applications/iTerm.app/Contents/Resources/utilities:/usr/bin:/bin"
)));
}
#[test]
fn a_shell_built_path_is_left_alone() {
assert!(!is_stripped(Some(
"/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin"
)));
assert!(!is_stripped(Some("/usr/bin:/bin:/Users/v/.cargo/bin")));
}
#[test]
fn merge_puts_the_login_shell_first_and_keeps_the_system_dirs() {
let merged = merge(
Some("/usr/bin:/bin:/usr/sbin:/sbin"),
"/opt/homebrew/bin:/usr/bin:/bin",
);
assert_eq!(merged, "/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
}
#[test]
fn merge_drops_duplicates() {
let merged = merge(Some("/usr/bin:/usr/bin"), "/usr/bin:/opt/homebrew/bin");
assert_eq!(merged, "/usr/bin:/opt/homebrew/bin");
}
#[test]
fn extract_ignores_rc_file_chatter() {
let out = format!("Welcome to zsh!\nnode v22\n{BEGIN}/opt/homebrew/bin:/usr/bin{END}");
assert_eq!(extract(&out).as_deref(), Some("/opt/homebrew/bin:/usr/bin"));
}
#[test]
fn extract_returns_none_without_both_markers() {
assert!(extract("/opt/homebrew/bin").is_none());
assert!(extract(&format!("{BEGIN}/opt/homebrew/bin")).is_none());
assert!(extract(&format!("{BEGIN}{END}")).is_none());
}
#[test]
fn a_gui_launch_gets_the_shell_path_back() {
let fixed = repaired(Some("/usr/bin:/bin:/usr/sbin:/sbin"), || {
Some(String::from("/opt/homebrew/bin:/usr/bin:/bin"))
});
assert_eq!(
fixed.as_deref(),
Some("/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin")
);
}
#[test]
fn a_terminal_launch_never_probes_or_changes_anything() {
let fixed = repaired(Some("/opt/homebrew/bin:/usr/bin"), || {
panic!("a shell-built PATH must not be probed")
});
assert!(fixed.is_none());
}
#[test]
fn a_failed_probe_keeps_the_inherited_path() {
assert!(repaired(Some("/usr/bin:/bin"), || None).is_none());
}
#[test]
fn a_probe_that_adds_nothing_changes_nothing() {
assert!(
repaired(Some("/usr/bin:/bin:/usr/sbin:/sbin"), || Some(
String::from("/usr/bin:/bin:/usr/sbin:/sbin")
))
.is_none()
);
}
#[test]
fn probing_a_real_shell_returns_a_usable_path() {
let shell = if std::path::Path::new("/bin/zsh").exists() {
"/bin/zsh"
} else {
"/bin/sh"
};
let path = probe(shell).expect("the login shell must report a PATH");
assert!(path.contains("/bin"), "got {path:?}");
}
#[test]
fn a_dock_launch_ends_up_seeing_the_users_own_directories() {
let dir = tempfile::tempdir().unwrap();
let stub = dir.path().join("stub-shell");
std::fs::write(
&stub,
"#!/bin/sh\n\
[ \"$1\" = -l ] || exit 64\n\
[ \"$2\" = -i ] || exit 64\n\
[ \"$3\" = -c ] || exit 64\n\
[ $# -eq 4 ] || exit 64\n\
PATH=\"/stub/tools/bin:$PATH\"; export PATH\n\
exec /bin/sh -c \"$4\"\n",
)
.unwrap();
let mut perm = std::fs::metadata(&stub).unwrap().permissions();
std::os::unix::fs::PermissionsExt::set_mode(&mut perm, 0o755);
std::fs::set_permissions(&stub, perm).unwrap();
let dock = "/usr/bin:/bin:/usr/sbin:/sbin:/Applications/Ghostty.app/Contents/MacOS";
let fixed = repaired(Some(dock), || probe(&stub.display().to_string()))
.expect("a Dock launch must have its PATH repaired");
assert!(
fixed.starts_with("/stub/tools/bin:"),
"the shell's directories must lead, got {fixed:?}"
);
for entry in dock.split(':') {
assert!(fixed.split(':').any(|e| e == entry), "{entry} dropped");
}
}
#[test]
fn a_backgrounded_grandchild_does_not_stall_the_probe() {
let mut cmd = Command::new("/bin/sh");
cmd.args([
"-c",
&format!("printf '{BEGIN}/opt/x:/usr/bin{END}'; sleep 5 &"),
]);
let start = std::time::Instant::now();
let out = run_probe(cmd, Duration::from_millis(1500));
assert_eq!(out.as_deref(), Some("/opt/x:/usr/bin"));
assert!(
start.elapsed() < Duration::from_millis(1200),
"the probe waited {:?} on a grandchild's pipe",
start.elapsed()
);
}
#[test]
fn a_csh_family_login_shell_still_answers() {
if !std::path::Path::new("/bin/tcsh").exists() {
eprintln!("skipping: tcsh not installed");
return;
}
let path = probe("/bin/tcsh").expect("tcsh must report a PATH");
assert!(path.contains("/bin"), "got {path:?}");
}
#[test]
fn a_csh_family_probe_reads_the_login_file() {
if !std::path::Path::new("/bin/tcsh").exists() {
eprintln!("skipping: tcsh not installed");
return;
}
let home = tempfile::tempdir().unwrap();
std::fs::write(
home.path().join(".login"),
"setenv PATH /from/login:$PATH\n",
)
.unwrap();
let mut cmd = probe_cmd("/bin/tcsh");
cmd.env("HOME", home.path());
let path = run_probe(cmd, PROBE_TIMEOUT).expect("tcsh must answer");
assert!(
path.split(':').any(|e| e == "/from/login"),
"~/.login was not sourced; the csh user's PATH is lost: {path:?}"
);
}
#[test]
fn the_probe_cannot_touch_crofts_terminal_session() {
if Command::new("python3").arg("--version").output().is_err() {
eprintln!("SKIPPED: python3 not on PATH");
return;
}
let dir = tempfile::tempdir().unwrap();
let stub = dir.path().join("stub-shell");
std::fs::write(
&stub,
format!(
"#!/bin/sh\n\
exec python3 -c 'import os; \
print(\"{BEGIN}%d{END}\" % os.getsid(0))'\n"
),
)
.unwrap();
let mut perm = std::fs::metadata(&stub).unwrap().permissions();
std::os::unix::fs::PermissionsExt::set_mode(&mut perm, 0o755);
std::fs::set_permissions(&stub, perm).unwrap();
let sid = run_probe(probe_cmd(&stub.display().to_string()), PROBE_TIMEOUT)
.expect("the stub must report its session id");
let own = unsafe { libc::getsid(0) };
assert_ne!(
sid.trim().parse::<i64>().expect("a numeric session id"),
i64::from(own),
"the probe shell shares croft's terminal session"
);
}
#[test]
fn a_hanging_shell_gives_up_instead_of_blocking_startup() {
let mut cmd = Command::new("/bin/sh");
cmd.args(["-c", "sleep 600"]);
let start = std::time::Instant::now();
let out = run_probe(cmd, Duration::from_millis(300));
assert!(out.is_none(), "a wedged shell must not report a PATH");
assert!(
start.elapsed() < Duration::from_secs(5),
"startup waited {:?} on a hung shell",
start.elapsed()
);
}
#[test]
fn a_shell_that_answers_within_the_timeout_is_read() {
let mut cmd = Command::new("/bin/sh");
cmd.args(["-c", &format!("printf '{BEGIN}/opt/x:/usr/bin{END}'")]);
assert_eq!(
run_probe(cmd, PROBE_TIMEOUT).as_deref(),
Some("/opt/x:/usr/bin")
);
}
}