Skip to main content

oxdock_process/
shell.rs

1use oxdock_diagnostics::DiagnosticResult;
2use oxdock_fs::GuardedPath;
3#[cfg(all(unix, not(miri)))]
4use oxdock_fs::PathResolver;
5use oxdock_fs::env::oxdock::BANNER;
6use std::ffi::OsStr;
7use std::fs::File;
8#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
9use std::process::{Command, ExitStatus, Stdio};
10
11use crate::CommandBuilder;
12use crate::diagnostics as proc_diag;
13
14pub fn shell_program() -> String {
15    #[cfg(windows)]
16    {
17        std::env::var(oxdock_fs::env::os::windows::COMSPEC).unwrap_or_else(|_| "cmd".to_string())
18    }
19
20    #[cfg(not(windows))]
21    {
22        std::env::var(oxdock_fs::env::os::unix::SHELL).unwrap_or_else(|_| "sh".to_string())
23    }
24}
25
26/// Path of the running interpreter binary, for scripts that reinvoke
27/// the engine on another script (`RUN [$exe, "other.oxdock"]`) instead
28/// of bridging an env var. `current_exe` is an unsupported isolation
29/// operation under Miri (hard error, not a recoverable `Err`), so Miri
30/// builds report it as unsupported instead of calling through.
31pub fn interpreter_exe() -> DiagnosticResult<String> {
32    #[cfg(miri)]
33    {
34        Err(proc_diag::run_interpreter_unsupported_miri())
35    }
36    #[cfg(not(miri))]
37    {
38        let exe = std::env::current_exe().map_err(|e| proc_diag::run_current_exe_failed(&e))?;
39        Ok(exe.display().to_string())
40    }
41}
42
43/// Deterministic batch shell for `RUN` step execution: `sh` on Unix,
44/// `cmd` on Windows. Never the operator's `$SHELL`: login shells
45/// re-pollute scrubbed children (observed live: zsh sourcing
46/// `/etc/zshenv` and synthesizing `HOME`/`LOGNAME` from `getpwuid`
47/// regardless of flags) and break script portability (`fish`/`tcsh`
48/// cannot run POSIX step text). Interactive use (`oxdock --shell`)
49/// keeps `shell_program()`.
50pub fn batch_shell() -> String {
51    #[cfg(windows)]
52    {
53        "cmd".to_string()
54    }
55
56    #[cfg(not(windows))]
57    {
58        "sh".to_string()
59    }
60}
61
62#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
63pub(crate) fn direct_cmd(argv: &[String]) -> DiagnosticResult<Command> {
64    let (program, rest) = argv
65        .split_first()
66        .ok_or_else(proc_diag::run_exec_requires_argv)?;
67    if program.is_empty() {
68        return Err(proc_diag::run_exec_requires_program());
69    }
70    let mut c = Command::new(program);
71    c.args(rest);
72    Ok(c)
73}
74
75#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
76pub(crate) fn shell_cmd(cmd: &str) -> Command {
77    let program = batch_shell();
78    let mut c = Command::new(program);
79    #[allow(clippy::disallowed_macros)]
80    if cfg!(windows) {
81        c.arg("/C").arg(cmd);
82    } else {
83        c.arg("-c").arg(cmd);
84    }
85    c
86}
87
88#[derive(Default)]
89pub struct ShellLauncher;
90
91#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
92impl ShellLauncher {
93    pub fn run(&self, cmd: &mut Command) -> DiagnosticResult<()> {
94        let status = cmd.status().map_err(|e| proc_diag::run_failed(&*cmd, &e))?;
95        if !status.success() {
96            return Err(proc_diag::run_command_failed(&*cmd, &status));
97        }
98        Ok(())
99    }
100
101    pub fn run_with_output(
102        &self,
103        cmd: &mut Command,
104    ) -> DiagnosticResult<(ExitStatus, Vec<u8>, Vec<u8>)> {
105        cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
106        let output = cmd.output().map_err(|e| proc_diag::run_failed(&*cmd, &e))?;
107        Ok((output.status, output.stdout, output.stderr))
108    }
109
110    pub fn spawn(&self, cmd: &mut Command) -> DiagnosticResult<()> {
111        cmd.spawn()
112            .map_err(|e| proc_diag::spawn_failed(&*cmd, &e))?;
113        Ok(())
114    }
115
116    pub fn with_stdins<'a>(&self, cmd: &'a mut Command, stdin: Option<File>) -> &'a mut Command {
117        if let Some(file) = stdin {
118            cmd.stdin(file);
119        }
120        cmd
121    }
122
123    pub fn program_arg(&self, program: impl AsRef<OsStr>) -> Command {
124        Command::new(program)
125    }
126}
127
128/// Spawn an interactive shell rooted at `cwd`, printing `banner` before handing
129/// control to the user's shell.
130///
131/// `workspace_root` anchors the guarded path resolver used to reattach the
132/// controlling TTY on Unix.
133pub fn spawn_interactive_shell(
134    cwd: &GuardedPath,
135    workspace_root: &GuardedPath,
136    banner: &str,
137) -> DiagnosticResult<()> {
138    let _ = workspace_root;
139    #[cfg(unix)]
140    {
141        let mut cmd = CommandBuilder::new(shell_program());
142        cmd.current_dir(cwd.as_path());
143
144        // Print a single banner inside the subshell, then exec the user's shell to stay interactive.
145        // The banner travels via env and the shell program via `$1` so neither is interpolated into
146        // the script string (paths with spaces or `%` would break quoting or printf parsing).
147        const SCRIPT: &str = "printf '%s\\n' \"$OXDOCK_BANNER\"; exec \"$1\"";
148        cmd.env(BANNER, banner);
149        cmd.arg("-c").arg(SCRIPT).arg("sh").arg(shell_program());
150
151        // Reattach stdin to the controlling TTY so a piped-in script can still open an interactive shell.
152        #[cfg(not(miri))]
153        {
154            #[allow(clippy::disallowed_types)]
155            let tty_path = oxdock_fs::UnguardedPath::external("/dev/tty");
156            if let Ok(resolver) =
157                PathResolver::new(workspace_root.as_path(), workspace_root.as_path())
158                && let Ok(tty) = resolver.open_file_unguarded(&tty_path)
159            {
160                cmd.stdin_file(tty);
161            }
162        }
163
164        if try_shell_command_hook(&mut cmd)? {
165            return Ok(());
166        }
167
168        let status = cmd.status()?;
169        if !status.success() {
170            return Err(proc_diag::shell_exited_with_status(&status));
171        }
172        Ok(())
173    }
174
175    #[cfg(windows)]
176    {
177        // Launch via `start` so Windows opens a real interactive console window. Normalize the path
178        // and also set the parent process working directory to the temp workspace; this avoids
179        // start's `/D` parsing quirks on paths with spaces or verbatim prefixes.
180        let cwd_path = oxdock_fs::command_path(cwd);
181        let banner_cmd = windows_banner_command(banner, cwd);
182        let mut cmd = CommandBuilder::new("cmd");
183        cmd.env(BANNER, banner);
184        cmd.current_dir(cwd_path.as_ref())
185            .arg("/C")
186            .arg("start")
187            .arg("oxdock shell")
188            .arg("cmd")
189            .arg("/K")
190            .arg(banner_cmd);
191
192        if try_shell_command_hook(&mut cmd)? {
193            return Ok(());
194        }
195
196        // Fire-and-forget so the parent console regains control immediately; the child window is
197        // fully interactive. If the launch fails, surface the error right away.
198        cmd.spawn()
199            .map_err(|e| proc_diag::spawn_interactive_window_failed(&e))?;
200        Ok(())
201    }
202
203    #[cfg(not(any(unix, windows)))]
204    {
205        let _ = (cwd, workspace_root, banner);
206        return Err(proc_diag::run_interactive_unsupported());
207    }
208}
209
210#[cfg(windows)]
211fn escape_for_cmd(s: &str) -> String {
212    // Escape characters that would otherwise be interpreted by cmd when echoed.
213    s.replace('^', "^^")
214        .replace('&', "^&")
215        .replace('|', "^|")
216        .replace('>', "^>")
217        .replace('<', "^<")
218}
219
220#[cfg(windows)]
221fn windows_banner_command(banner: &str, cwd: &GuardedPath) -> String {
222    let mut parts: Vec<String> = banner
223        .lines()
224        .map(|line| format!("echo {}", escape_for_cmd(line)))
225        .collect();
226    let cwd_path = oxdock_fs::command_path(cwd);
227    parts.push(format!(
228        "cd /d {}",
229        escape_for_cmd(&cwd_path.as_ref().display().to_string())
230    ));
231    parts.join(" && ")
232}
233
234#[cfg(test)]
235type ShellCmdHook = dyn FnMut(&crate::CommandSnapshot) -> DiagnosticResult<()> + Send;
236
237#[cfg(test)]
238thread_local! {
239    static SHELL_CMD_HOOK: std::cell::RefCell<Option<Box<ShellCmdHook>>> =
240        std::cell::RefCell::new(None);
241}
242
243#[cfg(test)]
244fn set_shell_command_hook<F>(hook: F)
245where
246    F: FnMut(&crate::CommandSnapshot) -> DiagnosticResult<()> + Send + 'static,
247{
248    SHELL_CMD_HOOK.with(|slot| {
249        *slot.borrow_mut() = Some(Box::new(hook));
250    });
251}
252
253#[cfg(test)]
254fn clear_shell_command_hook() {
255    SHELL_CMD_HOOK.with(|slot| {
256        *slot.borrow_mut() = None;
257    });
258}
259
260#[cfg(test)]
261fn try_shell_command_hook(cmd: &mut CommandBuilder) -> DiagnosticResult<bool> {
262    SHELL_CMD_HOOK.with(|slot| {
263        if let Some(hook) = slot.borrow_mut().as_mut() {
264            let snap = cmd.snapshot();
265            hook(&snap)?;
266            return Ok(true);
267        }
268        Ok(false)
269    })
270}
271
272#[cfg(not(test))]
273fn try_shell_command_hook(cmd: &mut CommandBuilder) -> DiagnosticResult<bool> {
274    let _ = cmd;
275    Ok(false)
276}
277
278#[cfg(test)]
279mod tests {
280    use super::{ShellLauncher, direct_cmd, shell_cmd, shell_program};
281    use crate::TestEnvGuard;
282
283    use std::ffi::OsStr;
284    use std::sync::Mutex;
285
286    // For Windows, fixing COMSPEC override test race condition
287    pub(super) static ENV_LOCK: Mutex<()> = Mutex::new(());
288
289    #[test]
290    fn shell_program_prefers_env_override() {
291        let _lock = ENV_LOCK.lock().expect("env lock");
292        #[cfg(windows)]
293        let _guard = TestEnvGuard::set(oxdock_fs::env::os::windows::COMSPEC, "custom-cmd");
294        #[cfg(not(windows))]
295        let _guard = TestEnvGuard::set(oxdock_fs::env::os::unix::SHELL, "custom-sh");
296        let program = shell_program();
297        #[cfg(windows)]
298        assert_eq!(program, "custom-cmd");
299        #[cfg(not(windows))]
300        assert_eq!(program, "custom-sh");
301    }
302
303    #[cfg_attr(
304        miri,
305        ignore = "spawns shell command; Miri does not support process execution"
306    )]
307    #[test]
308    fn shell_launcher_run_with_output_captures_stdout() {
309        let _lock = ENV_LOCK.lock().expect("env lock");
310        let launcher = ShellLauncher;
311        let mut cmd = shell_cmd("echo hello");
312        let (status, stdout, _stderr) = launcher.run_with_output(&mut cmd).expect("run output");
313        assert!(status.success());
314        let out = String::from_utf8_lossy(&stdout);
315        assert!(out.contains("hello"));
316    }
317
318    #[test]
319    fn shell_launcher_program_arg_tracks_program() {
320        let launcher = ShellLauncher;
321        let cmd = launcher.program_arg("echo");
322        assert_eq!(cmd.get_program(), OsStr::new("echo"));
323    }
324
325    #[test]
326    fn shell_program_falls_back_to_default_without_env() {
327        let _lock = ENV_LOCK.lock().expect("env lock");
328        #[cfg(windows)]
329        {
330            let _guard = TestEnvGuard::remove(oxdock_fs::env::os::windows::COMSPEC);
331            assert_eq!(shell_program(), "cmd");
332        }
333        #[cfg(not(windows))]
334        {
335            let _guard = TestEnvGuard::remove(oxdock_fs::env::os::unix::SHELL);
336            assert_eq!(shell_program(), "sh");
337        }
338    }
339
340    #[test]
341    fn shell_cmd_applies_platform_flag_and_script() {
342        let cmd = shell_cmd("echo hi");
343        let args: Vec<String> = cmd
344            .get_args()
345            .map(|arg| arg.to_string_lossy().into_owned())
346            .collect();
347        #[cfg(windows)]
348        assert_eq!(args, vec!["/C".to_string(), "echo hi".to_string()]);
349        #[cfg(not(windows))]
350        assert_eq!(args, vec!["-c".to_string(), "echo hi".to_string()]);
351    }
352
353    #[test]
354    fn direct_cmd_builds_program_and_args_without_shell() {
355        let argv = vec!["prog".to_string(), "a".to_string(), "b c".to_string()];
356        let cmd = direct_cmd(&argv).expect("direct_cmd");
357        assert_eq!(cmd.get_program(), OsStr::new("prog"));
358        let args: Vec<String> = cmd
359            .get_args()
360            .map(|arg| arg.to_string_lossy().into_owned())
361            .collect();
362        assert_eq!(args, vec!["a".to_string(), "b c".to_string()]);
363    }
364
365    #[test]
366    fn direct_cmd_rejects_empty_argv() {
367        let err = direct_cmd(&[]).expect_err("empty argv must fail");
368        assert!(
369            err.to_string().contains("at least one argument"),
370            "unexpected error: {err:#}"
371        );
372        let err = direct_cmd(&[String::new()]).expect_err("empty program must fail");
373        assert!(
374            err.to_string().contains("non-empty executable"),
375            "unexpected error: {err:#}"
376        );
377    }
378
379    #[cfg_attr(
380        miri,
381        ignore = "spawns shell command; Miri does not support process execution"
382    )]
383    #[test]
384    fn shell_launcher_run_succeeds_on_zero_exit() {
385        let launcher = ShellLauncher;
386        let mut cmd = shell_cmd("exit 0");
387        launcher.run(&mut cmd).expect("zero exit should succeed");
388    }
389
390    #[cfg_attr(
391        miri,
392        ignore = "spawns shell command; Miri does not support process execution"
393    )]
394    #[test]
395    fn shell_launcher_run_reports_nonzero_status() {
396        let launcher = ShellLauncher;
397        let mut cmd = shell_cmd("exit 3");
398        let err = launcher.run(&mut cmd).expect_err("nonzero exit must fail");
399        let msg = err.to_string();
400        assert!(
401            msg.contains("failed with status"),
402            "unexpected error message: {msg}"
403        );
404    }
405
406    #[cfg_attr(
407        miri,
408        ignore = "spawns shell command; Miri does not support process execution"
409    )]
410    #[test]
411    fn shell_launcher_spawn_smoke() {
412        let launcher = ShellLauncher;
413        let mut cmd = shell_cmd("exit 0");
414        launcher.spawn(&mut cmd).expect("spawn should succeed");
415    }
416
417    #[test]
418    fn shell_launcher_with_stdins_none_passthrough_keeps_builder_usable() {
419        let launcher = ShellLauncher;
420        let mut cmd = launcher.program_arg("echo");
421        let same = launcher.with_stdins(&mut cmd, None);
422        assert_eq!(same.get_program(), OsStr::new("echo"));
423    }
424}
425
426#[cfg(test)]
427mod interactive_shell_tests {
428    use super::tests::ENV_LOCK;
429    use super::{clear_shell_command_hook, set_shell_command_hook, spawn_interactive_shell};
430    use crate::CommandSnapshot;
431    use anyhow::Result;
432    use oxdock_fs::GuardedPath;
433    use oxdock_fs::env::oxdock::BANNER;
434    use std::sync::{Arc, Mutex};
435
436    #[cfg(any(unix, windows))]
437    #[test]
438    fn spawn_interactive_shell_builds_command_for_platform() -> Result<()> {
439        // Serializes against sibling tests that mutate SHELL/COMSPEC: the
440        // snapshot below bakes in `shell_program()` at build time and
441        // re-reads it at assert time, so a concurrent mutation fails it.
442        let _lock = ENV_LOCK.lock().expect("env lock");
443        let workspace = GuardedPath::tempdir()?;
444        let workspace_root = workspace.as_guarded_path().clone();
445        let cwd = workspace_root.join("subdir")?;
446        #[cfg(not(miri))]
447        {
448            let resolver =
449                oxdock_fs::PathResolver::new(workspace_root.as_path(), workspace_root.as_path())?;
450            resolver.create_dir_all(&cwd)?;
451        }
452
453        let captured = Arc::new(Mutex::new(None::<CommandSnapshot>));
454        let guard = captured.clone();
455        set_shell_command_hook(move |cmd| {
456            *guard.lock().unwrap() = Some(cmd.clone());
457            Ok(())
458        });
459        spawn_interactive_shell(&cwd, &workspace_root, "test banner")?;
460        clear_shell_command_hook();
461
462        let snap = captured
463            .lock()
464            .unwrap()
465            .clone()
466            .expect("hook should capture snapshot");
467        let cwd_path = snap.cwd.expect("cwd should be set");
468        assert!(
469            cwd_path.ends_with("subdir"),
470            "expected cwd to include subdir, got {}",
471            cwd_path.display()
472        );
473        assert!(
474            snap.envs
475                .iter()
476                .any(|(k, v)| k == BANNER && v == "test banner"),
477            "expected OXDOCK_BANNER env injection, got {:?}",
478            snap.envs
479        );
480
481        #[cfg(unix)]
482        {
483            let program = snap.program.to_string_lossy();
484            assert_eq!(
485                program,
486                super::shell_program(),
487                "expected shell program name"
488            );
489            let args: Vec<_> = snap
490                .args
491                .iter()
492                .map(|s| s.to_string_lossy().to_string())
493                .collect();
494            assert_eq!(
495                args.len(),
496                4,
497                "expected four args (-c script sh shell), got {:?}",
498                args
499            );
500            assert_eq!(args[0], "-c");
501            assert!(
502                args[1].contains("$OXDOCK_BANNER"),
503                "expected env-based banner reference, got {:?}",
504                args[1]
505            );
506            assert!(
507                args[1].contains("exec \"$1\""),
508                "expected positional shell exec, got {:?}",
509                args[1]
510            );
511            assert!(
512                !args[1].contains("test banner"),
513                "banner must not be interpolated into the script, got {:?}",
514                args[1]
515            );
516            assert_eq!(args[2], "sh", "expected $0 placeholder");
517            assert_eq!(args[3], super::shell_program(), "expected shell path as $1");
518        }
519
520        #[cfg(windows)]
521        {
522            use super::windows_banner_command;
523            let program = snap.program.to_string_lossy().to_string();
524            assert_eq!(program, "cmd", "expected cmd.exe launcher");
525            let args: Vec<_> = snap
526                .args
527                .iter()
528                .map(|s| s.to_string_lossy().to_string())
529                .collect();
530            let banner_cmd = windows_banner_command("test banner", &cwd);
531            let expected = vec![
532                "/C".to_string(),
533                "start".to_string(),
534                "oxdock shell".to_string(),
535                "cmd".to_string(),
536                "/K".to_string(),
537                banner_cmd,
538            ];
539            assert_eq!(args, expected, "expected exact windows shell argv");
540        }
541
542        Ok(())
543    }
544
545    #[cfg(windows)]
546    #[test]
547    fn windows_banner_command_emits_all_lines() {
548        let banner = "line1\nline2\nline3";
549        let workspace = GuardedPath::tempdir().expect("tempdir");
550        let cwd = workspace.as_guarded_path().clone();
551        let cmd = super::windows_banner_command(banner, &cwd);
552        assert!(cmd.contains("line1"));
553        assert!(cmd.contains("line2"));
554        assert!(cmd.contains("line3"));
555        assert!(cmd.contains("cd /d "));
556    }
557}