use std::collections::HashMap;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
#[derive(Debug, Clone)]
pub struct ProcessConfig {
pub argv: Vec<String>,
pub cwd: Option<PathBuf>,
pub env: HashMap<String, String>,
pub inherit_env: bool,
}
impl ProcessConfig {
pub fn new(argv: Vec<String>) -> Self {
Self {
argv,
cwd: None,
env: HashMap::new(),
inherit_env: true,
}
}
#[must_use]
pub fn with_cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
self.cwd = Some(cwd.into());
self
}
#[must_use]
pub fn with_env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.env.insert(key.into(), value.into());
self
}
#[must_use]
pub fn with_inherit_env(mut self, inherit: bool) -> Self {
self.inherit_env = inherit;
self
}
}
#[derive(Debug, Clone)]
pub struct ProcessOutput {
pub stdout: Vec<u8>,
pub stderr: Vec<u8>,
pub combined: Vec<u8>,
pub combined_str: String,
pub exit_code: Option<i32>,
pub timed_out: bool,
}
#[derive(Debug, Clone)]
pub struct ProcessWaitResult {
pub output: ProcessOutput,
pub timed_out: bool,
}
#[derive(Debug)]
pub enum ProcessError {
EmptyArgv,
SpawnFailed(String),
Io(String),
NotStarted,
InvalidTimeout(String),
}
impl std::fmt::Display for ProcessError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::EmptyArgv => write!(f, "argv must not be empty"),
Self::SpawnFailed(msg) => write!(f, "failed to spawn process: {msg}"),
Self::Io(msg) => write!(f, "process I/O error: {msg}"),
Self::NotStarted => write!(f, "process session has not been started"),
Self::InvalidTimeout(msg) => write!(f, "invalid timeout: {msg}"),
}
}
}
impl std::error::Error for ProcessError {}
pub struct ProcessSession {
config: ProcessConfig,
child: Option<Child>,
stdin: Option<ChildStdin>,
combined: Arc<Mutex<Vec<u8>>>,
stdout_buf: Arc<Mutex<Vec<u8>>>,
stderr_buf: Arc<Mutex<Vec<u8>>>,
stdout_handle: Option<JoinHandle<()>>,
stderr_handle: Option<JoinHandle<()>>,
exit_code: Option<i32>,
timed_out: bool,
}
impl std::fmt::Debug for ProcessSession {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProcessSession")
.field("argv", &self.config.argv)
.field("cwd", &self.config.cwd)
.field("exit_code", &self.exit_code)
.field("timed_out", &self.timed_out)
.finish()
}
}
impl ProcessSession {
pub fn new(config: ProcessConfig) -> Self {
Self {
config,
child: None,
stdin: None,
combined: Arc::new(Mutex::new(Vec::new())),
stdout_buf: Arc::new(Mutex::new(Vec::new())),
stderr_buf: Arc::new(Mutex::new(Vec::new())),
stdout_handle: None,
stderr_handle: None,
exit_code: None,
timed_out: false,
}
}
pub fn from_parts(
argv: Vec<String>,
cwd: Option<PathBuf>,
env: HashMap<String, String>,
) -> Self {
Self::new(ProcessConfig {
argv,
cwd,
env,
inherit_env: true,
})
}
pub fn spawn(&mut self) -> Result<(), ProcessError> {
if self.config.argv.is_empty() {
return Err(ProcessError::EmptyArgv);
}
if self.child.is_some() {
return Ok(());
}
let mut cmd = Command::new(&self.config.argv[0]);
if self.config.argv.len() > 1 {
cmd.args(&self.config.argv[1..]);
}
if let Some(cwd) = &self.config.cwd {
cmd.current_dir(cwd);
}
if self.config.inherit_env {
for (k, v) in &self.config.env {
cmd.env(k, v);
}
if std::env::var("TERM").unwrap_or_default().is_empty()
&& !self.config.env.contains_key("TERM")
{
cmd.env("TERM", "xterm-256color");
}
} else {
cmd.env_clear();
let mut env = self.config.env.clone();
env.entry("TERM".to_string())
.or_insert_with(|| "xterm-256color".to_string());
for (k, v) in &env {
cmd.env(k, v);
}
}
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd
.spawn()
.map_err(|e| ProcessError::SpawnFailed(e.to_string()))?;
let stdin = child.stdin.take();
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let combined_stdout = Arc::clone(&self.combined);
let stdout_buf = Arc::clone(&self.stdout_buf);
let stdout_handle = stdout.map(|mut out| {
thread::spawn(move || {
let mut buf = [0u8; 4096];
loop {
match out.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
if let Ok(mut c) = stdout_buf.lock() {
c.extend_from_slice(&buf[..n]);
}
if let Ok(mut c) = combined_stdout.lock() {
c.extend_from_slice(&buf[..n]);
}
}
Err(_) => break,
}
}
})
});
let combined_stderr = Arc::clone(&self.combined);
let stderr_buf = Arc::clone(&self.stderr_buf);
let stderr_handle = stderr.map(|mut err| {
thread::spawn(move || {
let mut buf = [0u8; 4096];
loop {
match err.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
if let Ok(mut c) = stderr_buf.lock() {
c.extend_from_slice(&buf[..n]);
}
if let Ok(mut c) = combined_stderr.lock() {
c.extend_from_slice(&buf[..n]);
}
}
Err(_) => break,
}
}
})
});
self.child = Some(child);
self.stdin = stdin;
self.stdout_handle = stdout_handle;
self.stderr_handle = stderr_handle;
Ok(())
}
pub fn write(&mut self, data: &[u8]) -> Result<(), ProcessError> {
let stdin = self.stdin.as_mut().ok_or(ProcessError::NotStarted)?;
stdin
.write_all(data)
.map_err(|e| ProcessError::Io(e.to_string()))?;
stdin.flush().map_err(|e| ProcessError::Io(e.to_string()))?;
Ok(())
}
pub fn write_line(&mut self, text: &str) -> Result<(), ProcessError> {
let mut buf = text.as_bytes().to_vec();
buf.push(b'\n');
self.write(&buf)
}
pub fn send_text(&mut self, text: &str) -> Result<(), ProcessError> {
self.write(text.as_bytes())
}
pub fn send_line(&mut self, text: &str) -> Result<(), ProcessError> {
self.write_line(text)
}
pub fn send_eof(&mut self) -> Result<(), ProcessError> {
self.stdin.take();
Ok(())
}
pub fn is_alive(&mut self) -> bool {
if let Some(child) = self.child.as_mut() {
match child.try_wait() {
Ok(None) => true,
Ok(Some(status)) => {
if self.exit_code.is_none() {
self.exit_code = status.code().or_else(|| {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
status.signal().map(|s| 128 + s)
}
#[cfg(not(unix))]
{
None
}
});
}
false
}
Err(_) => false,
}
} else {
false
}
}
pub fn raw_output(&self) -> Vec<u8> {
self.combined.lock().map(|c| c.clone()).unwrap_or_default()
}
pub fn raw_output_str(&self) -> String {
String::from_utf8_lossy(&self.raw_output()).to_string()
}
pub fn stdout(&self) -> Vec<u8> {
self.stdout_buf
.lock()
.map(|c| c.clone())
.unwrap_or_default()
}
pub fn stderr(&self) -> Vec<u8> {
self.stderr_buf
.lock()
.map(|c| c.clone())
.unwrap_or_default()
}
pub fn exit_code(&self) -> Option<i32> {
self.exit_code
}
pub fn timed_out(&self) -> bool {
self.timed_out
}
pub fn wait_with_timeout(
&mut self,
timeout: Duration,
) -> Result<ProcessWaitResult, ProcessError> {
if self.child.is_none() {
return Err(ProcessError::NotStarted);
}
let deadline = Instant::now() + timeout;
loop {
if !self.is_alive() {
self.reap_if_needed();
self.join_reader_threads();
let output = self.snapshot_output(false);
return Ok(ProcessWaitResult {
output,
timed_out: false,
});
}
if Instant::now() >= deadline {
self.timed_out = true;
let _ = self.kill_tree();
let grace = Duration::from_millis(200);
let grace_deadline = Instant::now() + grace;
while self.is_alive() && Instant::now() < grace_deadline {
thread::sleep(Duration::from_millis(10));
}
if self.is_alive() {
let _ = self.kill_tree();
}
self.reap_if_needed();
self.join_reader_threads();
let output = self.snapshot_output(true);
return Ok(ProcessWaitResult {
output,
timed_out: true,
});
}
thread::sleep(Duration::from_millis(10));
}
}
pub fn wait(&mut self) -> Result<ProcessOutput, ProcessError> {
self.wait_with_timeout(Duration::from_secs(3600))
.map(|r| r.output)
}
pub fn check_exit_code(&self, expected: Option<i32>) -> bool {
match expected {
None => true,
Some(code) => self.exit_code == Some(code),
}
}
pub fn kill_tree(&mut self) -> Result<(), ProcessError> {
if let Some(child) = self.child.as_mut() {
let _ = child.kill();
self.stdin.take();
}
Ok(())
}
pub fn close(&mut self) {
if self.is_alive() {
let _ = self.kill_tree();
thread::sleep(Duration::from_millis(50));
self.reap_if_needed();
} else {
self.reap_if_needed();
}
self.join_reader_threads();
self.stdin.take();
}
fn snapshot_output(&self, timed_out: bool) -> ProcessOutput {
let stdout = self.stdout();
let stderr = self.stderr();
let combined = self.raw_output();
let combined_str = String::from_utf8_lossy(&combined).to_string();
ProcessOutput {
stdout,
stderr,
combined,
combined_str,
exit_code: self.exit_code,
timed_out,
}
}
fn reap_if_needed(&mut self) {
if let Some(child) = self.child.as_mut() {
match child.try_wait() {
Ok(Some(status)) => {
if self.exit_code.is_none() {
self.exit_code = status.code().or_else(|| {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
status.signal().map(|s| 128 + s)
}
#[cfg(not(unix))]
{
None
}
});
}
}
Ok(None) => {
let _ = child.try_wait();
}
Err(_) => {}
}
if self.exit_code.is_none() {
if let Ok(Some(status)) = child.try_wait() {
self.exit_code = status.code();
}
}
}
}
fn join_reader_threads(&mut self) {
if let Some(h) = self.stdout_handle.take() {
let _ = h.join();
}
if let Some(h) = self.stderr_handle.take() {
let _ = h.join();
}
}
pub fn cwd(&self) -> Option<&Path> {
self.config.cwd.as_deref()
}
pub fn argv(&self) -> &[String] {
&self.config.argv
}
}
impl Drop for ProcessSession {
fn drop(&mut self) {
self.close();
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
fn argv_echo(msg: &str) -> Vec<String> {
vec!["sh".to_string(), "-c".to_string(), format!("echo {msg}")]
}
#[test]
fn spawns_and_captures_output() {
let config = ProcessConfig::new(vec![
"sh".to_string(),
"-c".to_string(),
"echo hello".to_string(),
]);
let mut sess = ProcessSession::new(config);
sess.spawn().expect("spawn");
let result = sess
.wait_with_timeout(Duration::from_secs(2))
.expect("wait");
assert!(!result.timed_out);
assert!(result.output.combined_str.contains("hello"));
assert_eq!(result.output.exit_code, Some(0));
}
#[test]
fn env_override_is_visible() {
let mut env = HashMap::new();
env.insert("TERMTEST_FOO".to_string(), "bar123".to_string());
let mut sess = ProcessSession::from_parts(
vec![
"sh".to_string(),
"-c".to_string(),
"echo $TERMTEST_FOO".to_string(),
],
None,
env,
);
sess.spawn().expect("spawn");
let result = sess
.wait_with_timeout(Duration::from_secs(2))
.expect("wait");
assert!(result.output.combined_str.contains("bar123"));
}
#[test]
fn cwd_is_respected() {
let dir = std::env::temp_dir();
let mut sess = ProcessSession::new(
ProcessConfig::new(vec!["sh".to_string(), "-c".to_string(), "pwd".to_string()])
.with_cwd(dir.clone()),
);
sess.spawn().expect("spawn");
let result = sess
.wait_with_timeout(Duration::from_secs(2))
.expect("wait");
let out = result.output.combined_str.trim().to_string();
assert!(!out.is_empty());
}
#[test]
fn timeout_kills_and_returns_partial_output() {
let mut sess = ProcessSession::new(ProcessConfig::new(vec![
"sh".to_string(),
"-c".to_string(),
"echo start; sleep 5; echo end".to_string(),
]));
sess.spawn().expect("spawn");
let result = sess
.wait_with_timeout(Duration::from_millis(300))
.expect("wait");
assert!(result.timed_out);
assert!(
result.output.combined_str.contains("start"),
"partial output missing start: {:?}",
result.output.combined_str
);
assert!(!sess.is_alive());
}
#[test]
fn stdin_write_and_eof() {
let mut sess = ProcessSession::new(ProcessConfig::new(vec![
"sh".to_string(),
"-c".to_string(),
"cat".to_string(),
]));
sess.spawn().expect("spawn");
sess.send_text("hello stdin").expect("write");
sess.send_eof().expect("eof");
let result = sess
.wait_with_timeout(Duration::from_secs(2))
.expect("wait");
assert!(result.output.combined_str.contains("hello stdin"));
}
#[test]
fn expected_exit_code_check() {
let mut sess = ProcessSession::new(ProcessConfig::new(vec![
"sh".to_string(),
"-c".to_string(),
"exit 42".to_string(),
]));
sess.spawn().expect("spawn");
let result = sess
.wait_with_timeout(Duration::from_secs(2))
.expect("wait");
assert_eq!(result.output.exit_code, Some(42));
assert!(sess.check_exit_code(Some(42)));
assert!(!sess.check_exit_code(Some(0)));
}
#[test]
fn empty_argv_is_error() {
let mut sess = ProcessSession::new(ProcessConfig::new(vec![]));
let err = sess.spawn().unwrap_err();
assert!(matches!(err, ProcessError::EmptyArgv));
}
#[test]
fn no_leaked_child_after_drop() {
{
let mut sess = ProcessSession::new(ProcessConfig::new(vec![
"sh".to_string(),
"-c".to_string(),
"sleep 10".to_string(),
]));
sess.spawn().expect("spawn");
assert!(sess.is_alive());
}
let mut sess2 = ProcessSession::new(ProcessConfig::new(argv_echo("after_drop")));
sess2.spawn().expect("spawn2");
let r = sess2
.wait_with_timeout(Duration::from_secs(1))
.expect("wait2");
assert!(r.output.combined_str.contains("after_drop"));
}
#[test]
fn hermetic_env_does_not_inherit_parent() {
let mut env = HashMap::new();
env.insert("TERMTEST_HERMETIC".to_string(), "hermetic_val".to_string());
let mut sess = ProcessSession::new(
ProcessConfig::new(vec![
"sh".to_string(),
"-c".to_string(),
"echo $TERMTEST_HERMETIC".to_string(),
])
.with_inherit_env(false),
);
sess.config.env = env;
sess.spawn().expect("spawn");
let result = sess
.wait_with_timeout(Duration::from_secs(2))
.expect("wait");
assert!(result.output.combined_str.contains("hermetic_val"));
}
}