1use std::io::Read;
4use std::process::{Child, Command, ExitStatus, Stdio};
5use std::time::{Duration, Instant};
6
7use anyhow::{Context, Result, bail};
8
9const KEEP: usize = 1 << 20;
10
11pub struct Output {
12 pub status: ExitStatus,
13 pub stdout: Vec<u8>,
14 pub stderr: Vec<u8>,
15}
16
17impl Output {
18 pub fn success(&self) -> bool {
19 self.status.success()
20 }
21
22 pub fn stdout_text(&self) -> String {
23 String::from_utf8_lossy(&self.stdout).into_owned()
24 }
25
26 pub fn stderr_text(&self) -> String {
27 String::from_utf8_lossy(&self.stderr).into_owned()
28 }
29}
30
31pub fn limit(default: Duration) -> Duration {
33 std::env::var("RUST_ANYTHING_COMMAND_TIMEOUT")
34 .ok()
35 .and_then(|v| v.parse::<f64>().ok())
36 .filter(|s| s.is_finite() && *s > 0.0)
37 .map_or(default, Duration::from_secs_f64)
38}
39
40pub const TESTS: Duration = Duration::from_secs(30 * 60);
41pub const BUILD: Duration = Duration::from_secs(30 * 60);
42pub const QUICK: Duration = Duration::from_secs(60);
43
44pub fn output(cmd: &mut Command, default: Duration) -> Result<Output> {
46 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
47 let mut child = spawn(cmd)?;
48 let out = drain(child.stdout.take());
49 let err = drain(child.stderr.take());
50 let status = wait(&mut child, cmd, limit(default))?;
51 Ok(Output {
52 status,
53 stdout: out.join().unwrap_or_default(),
54 stderr: err.join().unwrap_or_default(),
55 })
56}
57
58pub fn status(cmd: &mut Command, default: Duration) -> Result<ExitStatus> {
60 let mut child = spawn(cmd)?;
61 wait(&mut child, cmd, limit(default))
62}
63
64fn spawn(cmd: &mut Command) -> Result<Child> {
65 cmd.stdin(Stdio::null());
66 #[cfg(unix)]
67 {
68 use std::os::unix::process::CommandExt as _;
69 cmd.process_group(0);
70 }
71 cmd.spawn()
72 .with_context(|| format!("running `{}`", shown(cmd)))
73}
74
75fn drain(stream: Option<impl Read + Send + 'static>) -> std::thread::JoinHandle<Vec<u8>> {
76 std::thread::spawn(move || {
77 let mut kept = Vec::new();
78 let Some(mut stream) = stream else {
79 return kept;
80 };
81 let mut buf = [0u8; 8192];
82 while let Ok(n) = stream.read(&mut buf) {
83 if n == 0 {
84 break;
85 }
86 kept.extend_from_slice(&buf[..n]);
87 if kept.len() > 2 * KEEP {
88 kept.drain(..kept.len() - KEEP);
89 }
90 }
91 if kept.len() > KEEP {
92 kept.drain(..kept.len() - KEEP);
93 }
94 kept
95 })
96}
97
98fn wait(child: &mut Child, cmd: &Command, limit: Duration) -> Result<ExitStatus> {
99 let start = Instant::now();
100 let mut pause = Duration::from_millis(5);
101 loop {
102 if let Some(status) = child.try_wait()? {
103 return Ok(status);
104 }
105 if start.elapsed() > limit {
106 kill(child);
107 bail!(
108 "`{}` was still running after {}s and was stopped (set RUST_ANYTHING_COMMAND_TIMEOUT to allow longer; a test runner in watch mode never ends, so run it once, e.g. `vitest run`)",
109 shown(cmd),
110 limit.as_secs()
111 );
112 }
113 std::thread::sleep(pause);
114 pause = (pause * 2).min(Duration::from_millis(100));
115 }
116}
117
118fn kill(child: &mut Child) {
119 #[cfg(unix)]
120 {
121 let _ = Command::new("/bin/kill")
122 .args(["-KILL", "--", &format!("-{}", child.id())])
123 .stdin(Stdio::null())
124 .stdout(Stdio::null())
125 .stderr(Stdio::null())
126 .status();
127 }
128 let _ = child.kill();
129 let _ = child.wait();
130}
131
132fn shown(cmd: &Command) -> String {
133 std::iter::once(cmd.get_program())
134 .chain(cmd.get_args())
135 .map(|a| a.to_string_lossy().into_owned())
136 .collect::<Vec<_>>()
137 .join(" ")
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143
144 #[cfg(unix)]
145 #[test]
146 fn a_program_past_its_limit_is_stopped() {
147 let start = Instant::now();
148 let err = output(
149 Command::new("sh").args(["-c", "sleep 30"]),
150 Duration::from_millis(300),
151 )
152 .err()
153 .map(|e| e.to_string())
154 .unwrap_or_default();
155 assert!(err.contains("still running"), "{err}");
156 assert!(start.elapsed() < Duration::from_secs(5));
157 }
158
159 #[cfg(unix)]
160 #[test]
161 fn stdin_is_closed() {
162 let out = output(&mut Command::new("cat"), Duration::from_secs(5)).unwrap();
163 assert!(out.success());
164 assert!(out.stdout.is_empty());
165 }
166
167 #[cfg(unix)]
168 #[test]
169 fn output_is_kept_and_capped() {
170 let out = output(
171 Command::new("sh").args(["-c", "yes | head -c 3000000; echo err >&2"]),
172 Duration::from_secs(10),
173 )
174 .unwrap();
175 assert_eq!(out.stdout.len(), KEEP);
176 assert_eq!(out.stderr_text(), "err\n");
177 }
178}