diff --git a/crates/zet-pty/src/lib.rs b/crates/zet-pty/src/lib.rs index bafe19b..619eab5 100644 --- a/crates/zet-pty/src/lib.rs +++ b/crates/zet-pty/src/lib.rs @@ -45,7 +45,36 @@ pub struct Session { } impl Session { + /// Spawn a shell in the process's current directory. + /// + /// `portable_pty` does not inherit the caller's working directory by + /// default; leaving it unset starts the shell in `$HOME`. Resolve the + /// directory explicitly so ZET behaves like an ordinary terminal. If the + /// inherited directory is invalid (for example, deleted after launch), + /// fall back to the platform default instead of failing to start. pub fn spawn(program: &str, args: &[&str], cols: u16, rows: u16) -> std::io::Result { + Self::spawn_with_cwd( + program, + args, + cols, + rows, + std::env::current_dir().ok().as_deref(), + ) + } + + /// Spawn a shell with an explicit working directory. + /// + /// A missing or inaccessible directory falls back to `portable_pty`'s + /// default startup directory (`$HOME`). Passing `None` also uses that + /// default. This keeps callers from having to special-case deleted + /// launch directories while preserving explicit, testable cwd handling. + pub fn spawn_with_cwd( + program: &str, + args: &[&str], + cols: u16, + rows: u16, + cwd: Option<&std::path::Path>, + ) -> std::io::Result { let pty_system = native_pty_system(); let pair = pty_system .openpty(PtySize { @@ -57,6 +86,11 @@ impl Session { .map_err(std::io::Error::other)?; let mut cmd = CommandBuilder::new(program); cmd.args(args); + if let Some(cwd) = cwd { + if cwd.is_dir() { + cmd.cwd(cwd); + } + } let child = pair .slave .spawn_command(cmd) diff --git a/crates/zet-pty/tests/session.rs b/crates/zet-pty/tests/session.rs index 26748e4..3819e40 100644 --- a/crates/zet-pty/tests/session.rs +++ b/crates/zet-pty/tests/session.rs @@ -119,3 +119,131 @@ fn shutdown_reaps_the_child() { "process {pid} lingers" ); } + +fn unique_temp_dir(prefix: &str) -> std::path::PathBuf { + for attempt in 0..1000 { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let path = std::env::temp_dir().join(format!( + "zet-cwd-{prefix}-{}-{nanos}-{attempt}", + std::process::id() + )); + match std::fs::create_dir(&path) { + Ok(()) => return path, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => panic!("could not create isolated test directory {path:?}: {e}"), + } + } + panic!("could not allocate a unique temporary directory"); +} + +#[test] +fn spawn_with_cwd_starts_shell_in_requested_directory() { + let dir = unique_temp_dir("project"); + std::fs::write( + dir.join("Cargo.toml"), + "[package]\nname = \"x\"\nversion = \"0.1.0\"\n", + ) + .unwrap(); + + let mut s = Session::spawn_with_cwd("sh", &["-c", "pwd"], 80, 24, Some(&dir)).unwrap(); + let mut out = Vec::new(); + let code = s.wait_with_output(&mut out).unwrap(); + assert_eq!(code, 0); + + let text = String::from_utf8_lossy(&out); + let actual = text + .lines() + .map(str::trim) + .find(|line| !line.is_empty()) + .unwrap_or_default(); + let actual = std::fs::canonicalize(actual).unwrap_or_else(|_| std::path::PathBuf::from(actual)); + let expected = std::fs::canonicalize(&dir).unwrap(); + assert_eq!(actual, expected, "pwd was {text:?}"); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn spawn_with_cwd_falls_back_when_directory_is_invalid() { + let missing = std::env::temp_dir().join(format!( + "zet-cwd-missing-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + assert!( + !missing.exists(), + "test fixture unexpectedly exists: {missing:?}" + ); + + let mut s = Session::spawn_with_cwd("sh", &["-c", "pwd"], 80, 24, Some(&missing)).unwrap(); + let mut out = Vec::new(); + let code = s.wait_with_output(&mut out).unwrap(); + assert_eq!(code, 0); + + let text = String::from_utf8_lossy(&out); + let actual = text + .lines() + .map(str::trim) + .find(|line| !line.is_empty()) + .unwrap_or_default(); + assert!( + !actual.is_empty(), + "shell did not report a working directory" + ); + assert!( + !actual.contains("zet-cwd-missing"), + "invalid directory leaked into shell: {text:?}" + ); +} + +#[test] +fn spawn_inherits_process_current_directory() { + if std::env::var_os("ZET_PTY_INHERIT_CWD_CHILD").is_some() { + let mut s = Session::spawn("sh", &["-c", "pwd"], 80, 24).unwrap(); + let mut out = Vec::new(); + let code = s.wait_with_output(&mut out).unwrap(); + assert_eq!(code, 0); + let text = String::from_utf8_lossy(&out); + let actual = text + .lines() + .map(str::trim) + .find(|line| !line.is_empty()) + .unwrap_or_default(); + println!("ZET_CWD_RESULT={actual}"); + return; + } + + let dir = unique_temp_dir("inherit"); + let expected = std::fs::canonicalize(&dir).unwrap(); + let exe = std::env::current_exe().unwrap(); + let output = std::process::Command::new(&exe) + .arg("spawn_inherits_process_current_directory") + .arg("--exact") + .arg("--nocapture") + .env("ZET_PTY_INHERIT_CWD_CHILD", "1") + .current_dir(&dir) + .output() + .unwrap(); + assert!( + output.status.success(), + "child test failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let stdout = String::from_utf8_lossy(&output.stdout); + let result = stdout + .lines() + .find_map(|line| line.strip_prefix("ZET_CWD_RESULT=")) + .unwrap_or_default() + .trim(); + let actual = std::fs::canonicalize(result).unwrap_or_else(|_| std::path::PathBuf::from(result)); + assert_eq!(actual, expected, "child pwd was {stdout:?}"); + + let _ = std::fs::remove_dir_all(&dir); +}