rec/replay/executor.rs
1//! Command execution for replay.
2//!
3//! Executes recorded commands through the shell via `sh -c` with
4//! inherited stdio for real-time output.
5
6use std::process::{Command, Stdio};
7
8/// Execute a command string through the shell.
9///
10/// Uses the `SHELL` environment variable (fallback `/bin/sh`) to run
11/// the command via `sh -c`. Stdin, stdout, and stderr are inherited so
12/// the user sees output in real-time and can interact with prompts.
13///
14/// If `cwd` is provided and the directory exists, the command runs in
15/// that directory. If the directory doesn't exist, a warning is printed
16/// to stderr and the current directory is used instead.
17///
18/// # Errors
19///
20/// Returns an error if the shell process cannot be spawned or waited on.
21pub fn execute_command(
22 command_text: &str,
23 cwd: Option<&std::path::Path>,
24) -> std::io::Result<std::process::ExitStatus> {
25 let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
26
27 let mut cmd = Command::new(&shell);
28 cmd.arg("-c").arg(command_text);
29
30 if let Some(dir) = cwd {
31 if dir.exists() {
32 cmd.current_dir(dir);
33 } else {
34 eprintln!(
35 "\x1b[33m Warning: directory '{}' does not exist, using current directory\x1b[0m",
36 dir.display()
37 );
38 }
39 }
40
41 cmd.stdin(Stdio::inherit())
42 .stdout(Stdio::inherit())
43 .stderr(Stdio::inherit());
44
45 cmd.status()
46}