Skip to main content

oxdock_process/
shell.rs

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