use std::collections::VecDeque;
use std::io::Read;
use std::process::{Command, Stdio};
use std::sync::mpsc;
#[derive(Debug, Clone)]
pub struct CmdResult {
pub code: Option<i32>,
pub stdout: String,
pub stderr: String,
pub spawned: bool,
}
impl CmdResult {
pub fn success(&self) -> bool {
self.code == Some(0)
}
}
pub fn run(program: &str, args: &[&str]) -> CmdResult {
tracing::debug!(program, ?args, "exec");
match Command::new(program).args(args).output() {
Ok(out) => {
let res = CmdResult {
code: out.status.code(),
stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
spawned: true,
};
tracing::debug!(program, code = ?res.code, "exec done");
res
}
Err(e) => {
tracing::warn!(program, error = %e, "exec spawn failed");
CmdResult {
code: None,
stdout: String::new(),
stderr: e.to_string(),
spawned: false,
}
}
}
}
pub fn run_cmd(mut cmd: Command) -> CmdResult {
let program = cmd.get_program().to_string_lossy().into_owned();
tracing::debug!(program, args = ?cmd.get_args().collect::<Vec<_>>(), "exec");
match cmd.output() {
Ok(out) => CmdResult {
code: out.status.code(),
stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
spawned: true,
},
Err(e) => {
tracing::warn!(program, error = %e, "exec spawn failed");
CmdResult {
code: None,
stdout: String::new(),
stderr: e.to_string(),
spawned: false,
}
}
}
}
pub fn run_with_stdin(program: &str, args: &[&str], input: &[u8]) -> CmdResult {
use std::io::Write;
tracing::debug!(program, ?args, "exec (stdin input withheld)");
let spawned = Command::new(program)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn();
let mut child = match spawned {
Ok(c) => c,
Err(e) => {
tracing::warn!(program, error = %e, "exec spawn failed");
return CmdResult {
code: None,
stdout: String::new(),
stderr: e.to_string(),
spawned: false,
};
}
};
if let Some(mut stdin) = child.stdin.take() {
let _ = stdin.write_all(input);
}
match child.wait_with_output() {
Ok(out) => {
let res = CmdResult {
code: out.status.code(),
stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
spawned: true,
};
tracing::debug!(program, code = ?res.code, "exec done");
res
}
Err(e) => CmdResult {
code: None,
stdout: String::new(),
stderr: e.to_string(),
spawned: true,
},
}
}
pub fn run_ok(program: &str, args: &[&str]) -> bool {
run(program, args).success()
}
pub fn run_checked(program: &str, args: &[&str]) -> anyhow::Result<CmdResult> {
let res = run(program, args);
if res.success() {
Ok(res)
} else if !res.spawned {
anyhow::bail!("`{program}` could not be spawned: {}", res.stderr.trim());
} else {
anyhow::bail!("`{program}` exited {:?}: {}", res.code, res.stderr.trim());
}
}
#[derive(Debug, Clone, Copy)]
enum StreamKind {
Out,
Err,
}
const STREAM_TAIL_CAP: usize = 120;
const MAX_LINE_CHARS: usize = 500;
fn pump<R: Read>(mut reader: R, kind: StreamKind, tx: mpsc::Sender<(StreamKind, String)>) {
let mut buf = [0u8; 4096];
let mut line: Vec<u8> = Vec::with_capacity(256);
let emit = |line: &mut Vec<u8>| -> bool {
if line.is_empty() {
return true;
}
let s: String = String::from_utf8_lossy(line)
.chars()
.take(MAX_LINE_CHARS)
.collect();
line.clear();
tx.send((kind, s)).is_ok()
};
loop {
match reader.read(&mut buf) {
Ok(0) => break,
Ok(n) => {
for &b in &buf[..n] {
if b == b'\n' || b == b'\r' {
if !emit(&mut line) {
return;
}
} else {
line.push(b);
}
}
}
Err(_) => break,
}
}
let _ = emit(&mut line);
}
pub fn run_streamed<F: FnMut(&str)>(program: &str, args: &[&str], on_line: F) -> CmdResult {
let mut cmd = Command::new(program);
cmd.args(args);
run_streamed_cmd(cmd, on_line)
}
pub fn run_streamed_cmd<F: FnMut(&str)>(mut cmd: Command, mut on_line: F) -> CmdResult {
let program = cmd.get_program().to_string_lossy().into_owned();
tracing::debug!(program, args = ?cmd.get_args().collect::<Vec<_>>(), "exec-streamed");
let mut child = match cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
Ok(c) => c,
Err(e) => {
tracing::warn!(program, error = %e, "exec spawn failed");
return CmdResult {
code: None,
stdout: String::new(),
stderr: e.to_string(),
spawned: false,
};
}
};
let stdout = child.stdout.take().expect("piped stdout present");
let stderr = child.stderr.take().expect("piped stderr present");
let (tx, rx) = mpsc::channel::<(StreamKind, String)>();
let tx_err = tx.clone();
let h_out = std::thread::spawn(move || pump(stdout, StreamKind::Out, tx));
let h_err = std::thread::spawn(move || pump(stderr, StreamKind::Err, tx_err));
let mut out_tail: VecDeque<String> = VecDeque::with_capacity(STREAM_TAIL_CAP);
let mut err_tail: VecDeque<String> = VecDeque::with_capacity(STREAM_TAIL_CAP);
for (kind, line) in rx {
on_line(&line);
let tail = match kind {
StreamKind::Out => &mut out_tail,
StreamKind::Err => &mut err_tail,
};
if tail.len() == STREAM_TAIL_CAP {
tail.pop_front();
}
tail.push_back(line);
}
let _ = h_out.join();
let _ = h_err.join();
let code = child.wait().ok().and_then(|s| s.code());
tracing::debug!(program, code = ?code, "exec-streamed done");
CmdResult {
code,
stdout: Vec::from(out_tail).join("\n"),
stderr: Vec::from(err_tail).join("\n"),
spawned: true,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_captures_stdout_of_true_echo() {
let r = run("echo", &["hello"]);
assert!(r.success());
assert_eq!(r.stdout.trim(), "hello");
}
#[test]
fn run_reports_spawn_failure_without_panicking() {
let r = run("definitely-not-a-real-binary-xyz", &["--nope"]);
assert!(!r.spawned);
assert_eq!(r.code, None);
assert!(!r.success());
}
#[test]
fn run_checked_errors_on_nonzero() {
let err = run_checked("false", &[]).unwrap_err();
assert!(err.to_string().contains("exited"));
}
#[test]
fn run_streamed_delivers_each_line_and_keeps_the_tail() {
let mut lines = Vec::new();
let r = run_streamed("sh", &["-c", "printf 'a\\nb\\nc\\n'"], |l| {
lines.push(l.to_string())
});
assert!(r.success());
assert_eq!(lines, vec!["a", "b", "c"]);
assert_eq!(r.stdout, "a\nb\nc");
}
#[test]
fn run_streamed_splits_carriage_returns() {
let mut lines = Vec::new();
let r = run_streamed("sh", &["-c", "printf 'x\\ry\\rz'"], |l| {
lines.push(l.to_string())
});
assert!(r.success());
assert_eq!(lines, vec!["x", "y", "z"]);
}
#[test]
fn run_streamed_captures_stderr_tail_for_errors() {
let mut count = 0usize;
let r = run_streamed("sh", &["-c", "echo boom 1>&2; exit 3"], |_| count += 1);
assert!(!r.success());
assert_eq!(r.code, Some(3));
assert!(r.stderr.contains("boom"));
assert_eq!(count, 1);
}
#[test]
fn run_streamed_reports_spawn_failure() {
let r = run_streamed("definitely-not-a-real-binary-xyz", &[], |_| {});
assert!(!r.spawned);
assert_eq!(r.code, None);
}
#[test]
fn command_runners_honor_the_working_directory() {
let dir = std::env::temp_dir();
let want = dir.canonicalize().unwrap();
let mut cmd = Command::new("sh");
cmd.args(["-c", "pwd -P"]).current_dir(&dir);
let r = run_cmd(cmd);
assert!(r.success());
assert_eq!(std::path::Path::new(r.stdout.trim()), want);
let mut cmd = Command::new("sh");
cmd.args(["-c", "pwd -P"]).current_dir(&dir);
let mut lines = Vec::new();
let r = run_streamed_cmd(cmd, |l| lines.push(l.to_string()));
assert!(r.success());
assert_eq!(lines.len(), 1);
assert_eq!(std::path::Path::new(&lines[0]), want);
}
}