use std::io;
use std::io::Read;
use std::process::Command;
use std::process::Output;
use std::process::Stdio;
use std::thread;
use std::time::Duration;
pub fn timestamp() -> String {
chrono::Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
}
pub fn sleep_secs(secs: f64) {
thread::sleep(Duration::from_secs_f64(secs));
}
pub fn run_with_timeout(cmd: Command, timeout: Duration) -> io::Result<Output> {
let (output, timed_out) = run_capturing_timeout(cmd, timeout)?;
if timed_out {
return Err(io::Error::new(
io::ErrorKind::TimedOut,
"process exceeded timeout",
));
}
Ok(output)
}
pub fn run_capturing_timeout(mut cmd: Command, timeout: Duration) -> io::Result<(Output, bool)> {
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = cmd.spawn()?;
let mut stdout_pipe = child.stdout.take();
let mut stderr_pipe = child.stderr.take();
let drain_stdout = thread::spawn(move || {
let mut buf = Vec::new();
if let Some(pipe) = stdout_pipe.as_mut() {
let _ = pipe.read_to_end(&mut buf);
}
buf
});
let drain_stderr = thread::spawn(move || {
let mut buf = Vec::new();
if let Some(pipe) = stderr_pipe.as_mut() {
let _ = pipe.read_to_end(&mut buf);
}
buf
});
let step = Duration::from_millis(50);
let mut waited = Duration::ZERO;
let timed_out = loop {
if child.try_wait()?.is_some() {
break false;
}
if waited >= timeout {
child.kill()?;
break true;
}
thread::sleep(step);
waited += step;
};
let status = child.wait()?;
let output = Output {
status,
stdout: drain_stdout.join().unwrap_or_default(),
stderr: drain_stderr.join().unwrap_or_default(),
};
Ok((output, timed_out))
}
pub fn combined_output(output: &Output) -> String {
let mut parts: Vec<String> = Vec::new();
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
if !stdout.trim().is_empty() {
parts.push(stdout);
}
if !stderr.trim().is_empty() {
parts.push(stderr);
}
parts.join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn timestamp_has_expected_shape() {
let ts = timestamp();
assert_eq!(ts.len(), 19);
assert_eq!(&ts[4..5], "-");
assert_eq!(&ts[10..11], " ");
}
#[test]
fn quick_command_succeeds() {
let mut cmd = Command::new("true");
let out = run_with_timeout(cmd, Duration::from_secs(5)).unwrap();
assert!(out.status.success());
cmd = Command::new("echo");
cmd.arg("hi");
let out = run_with_timeout(cmd, Duration::from_secs(5)).unwrap();
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hi");
}
#[test]
fn output_larger_than_a_pipe_buffer_does_not_look_like_a_hang() {
let mut cmd = Command::new("sh");
cmd.arg("-c").arg("yes hello | head -c 1000000");
let out = run_with_timeout(cmd, Duration::from_secs(5)).expect("should not time out");
assert_eq!(out.stdout.len(), 1_000_000);
}
#[test]
fn a_timed_out_run_still_yields_what_it_printed() {
let mut cmd = Command::new("sh");
cmd.arg("-c").arg("echo partial; sleep 10");
let (output, timed_out) =
run_capturing_timeout(cmd, Duration::from_millis(300)).expect("spawned");
assert!(timed_out);
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "partial");
}
#[test]
fn slow_command_times_out() {
let mut cmd = Command::new("sleep");
cmd.arg("10");
let err = run_with_timeout(cmd, Duration::from_millis(200)).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::TimedOut);
}
}