use std::io;
use std::process::{Command, Output, Stdio};
use std::time::{Duration, Instant};
pub const TIMEOUT: Duration = Duration::from_secs(5);
const POLL: Duration = Duration::from_millis(5);
pub fn output(command: &mut Command, timeout: Duration) -> io::Result<Output> {
let mut child = command.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;
let mut stdout = child.stdout.take().map(reader);
let mut stderr = child.stderr.take().map(reader);
let started = Instant::now();
let status = loop {
match child.try_wait()? {
Some(status) => break status,
None if started.elapsed() >= timeout => {
let _ = child.kill();
let _ = child.wait();
return Err(io::Error::new(
io::ErrorKind::TimedOut,
format!("{:?} did not answer within {:?}", command.get_program(), timeout),
));
}
None => std::thread::sleep(POLL),
}
};
Ok(Output {
status,
stdout: stdout.take().map(collect).unwrap_or_default(),
stderr: stderr.take().map(collect).unwrap_or_default(),
})
}
fn reader<R: io::Read + Send + 'static>(mut source: R) -> std::thread::JoinHandle<Vec<u8>> {
std::thread::spawn(move || {
let mut buffer = Vec::new();
let _ = source.read_to_end(&mut buffer);
buffer
})
}
fn collect(handle: std::thread::JoinHandle<Vec<u8>>) -> Vec<u8> {
handle.join().unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_ordinary_command_still_returns_its_output() {
let out = output(Command::new("echo").arg("hello"), TIMEOUT).unwrap();
assert!(out.status.success());
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hello");
}
#[test]
fn a_failing_command_is_reported_by_its_status_not_an_error() {
let out = output(&mut Command::new("false"), TIMEOUT).unwrap();
assert!(!out.status.success(), "a non-zero exit is data, not an error");
}
#[test]
fn a_command_that_never_returns_gives_up() {
let started = Instant::now();
let result = output(Command::new("sleep").arg("60"), Duration::from_millis(200));
let error = result.expect_err("sleep 60 must not be waited on");
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
assert!(started.elapsed() < Duration::from_secs(5), "waited {:?}", started.elapsed());
}
#[test]
fn output_larger_than_a_pipe_buffer_does_not_deadlock() {
let out = output(
Command::new("sh").arg("-c").arg("yes hyprforge | head -c 400000"),
Duration::from_secs(10),
)
.expect("a chatty command is not a hung one");
assert_eq!(out.stdout.len(), 400_000);
}
#[test]
fn a_program_that_does_not_exist_is_an_error_like_before() {
let error = output(&mut Command::new("hyprforge-no-such-program"), TIMEOUT).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::NotFound);
}
}