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
25pub fn interpreter_exe() -> Result<String> {
31 #[cfg(miri)]
32 {
33 bail!("INTERPRETER is unsupported under Miri isolation")
34 }
35 #[cfg(not(miri))]
36 {
37 let exe = std::env::current_exe().context("determine current executable")?;
38 Ok(exe.display().to_string())
39 }
40}
41
42pub fn batch_shell() -> String {
50 #[cfg(windows)]
51 {
52 "cmd".to_string()
53 }
54
55 #[cfg(not(windows))]
56 {
57 "sh".to_string()
58 }
59}
60
61#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
62pub(crate) fn direct_cmd(argv: &[String]) -> Result<Command> {
63 let (program, rest) = argv
64 .split_first()
65 .ok_or_else(|| anyhow::anyhow!("RUN exec form requires at least one argument"))?;
66 if program.is_empty() {
67 bail!("RUN exec form requires a non-empty executable");
68 }
69 let mut c = Command::new(program);
70 c.args(rest);
71 Ok(c)
72}
73
74#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
75pub(crate) fn shell_cmd(cmd: &str) -> Command {
76 let program = batch_shell();
77 let mut c = Command::new(program);
78 #[allow(clippy::disallowed_macros)]
79 if cfg!(windows) {
80 c.arg("/C").arg(cmd);
81 } else {
82 c.arg("-c").arg(cmd);
83 }
84 c
85}
86
87#[derive(Default)]
88pub struct ShellLauncher;
89
90#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
91impl ShellLauncher {
92 pub fn run(&self, cmd: &mut Command) -> Result<()> {
93 let status = cmd
94 .status()
95 .with_context(|| format!("failed to run {:?}", cmd))?;
96 if !status.success() {
97 bail!("command {:?} failed with status {}", cmd, status);
98 }
99 Ok(())
100 }
101
102 pub fn run_with_output(&self, cmd: &mut Command) -> Result<(ExitStatus, Vec<u8>, Vec<u8>)> {
103 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
104 let output = cmd
105 .output()
106 .with_context(|| format!("failed to run {:?}", cmd))?;
107 Ok((output.status, output.stdout, output.stderr))
108 }
109
110 pub fn spawn(&self, cmd: &mut Command) -> Result<()> {
111 cmd.spawn()
112 .with_context(|| format!("failed to spawn {:?}", cmd))?;
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
128pub fn spawn_interactive_shell(
134 cwd: &GuardedPath,
135 workspace_root: &GuardedPath,
136 banner: &str,
137) -> Result<()> {
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 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 #[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 bail!("shell exited with status {}", status);
171 }
172 Ok(())
173 }
174
175 #[cfg(windows)]
176 {
177 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 cmd.spawn()
199 .context("failed to start interactive shell window")?;
200 Ok(())
201 }
202
203 #[cfg(not(any(unix, windows)))]
204 {
205 let _ = (cwd, workspace_root, banner);
206 bail!("interactive shell unsupported on this platform");
207 }
208}
209
210#[cfg(windows)]
211fn escape_for_cmd(s: &str) -> String {
212 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) -> Result<()> + 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) -> Result<()> + 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) -> Result<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) -> Result<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 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 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}