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 .and_then(seconds)
37 .unwrap_or(default)
38}
39
40pub fn seconds(v: f64) -> Option<Duration> {
43 if !v.is_finite() || v <= 0.0 {
44 return None;
45 }
46 Duration::try_from_secs_f64(v).ok()
47}
48
49pub const TESTS: Duration = Duration::from_secs(30 * 60);
50pub const BUILD: Duration = Duration::from_secs(30 * 60);
51pub const QUICK: Duration = Duration::from_secs(60);
52
53pub fn output(cmd: &mut Command, default: Duration) -> Result<Output> {
55 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
56 let mut child = spawn(cmd)?;
57 let out = drain(child.stdout.take());
58 let err = drain(child.stderr.take());
59 let status = wait(&mut child, cmd, limit(default))?;
60 Ok(Output {
61 status,
62 stdout: out.join().unwrap_or_default(),
63 stderr: err.join().unwrap_or_default(),
64 })
65}
66
67pub fn status(cmd: &mut Command, default: Duration) -> Result<ExitStatus> {
69 let mut child = spawn(cmd)?;
70 wait(&mut child, cmd, limit(default))
71}
72
73pub fn status_with_input(cmd: &mut Command, input: &[u8], default: Duration) -> Result<ExitStatus> {
76 let mut child = spawn_with(cmd, Stdio::piped())?;
77 let mut stdin = child.stdin.take().context("no stdin")?;
78 let input = input.to_vec();
79 let writer = std::thread::spawn(move || {
80 use std::io::Write as _;
81 let _ = stdin.write_all(&input);
82 });
83 let status = wait(&mut child, cmd, limit(default));
84 let _ = writer.join();
85 status
86}
87
88fn spawn(cmd: &mut Command) -> Result<Child> {
89 spawn_with(cmd, Stdio::null())
90}
91
92fn spawn_with(cmd: &mut Command, stdin: Stdio) -> Result<Child> {
93 cmd.stdin(stdin);
94 #[cfg(unix)]
95 {
96 use std::os::unix::process::CommandExt as _;
97 cmd.process_group(0);
98 }
99 cmd.spawn()
100 .with_context(|| format!("running `{}`", shown(cmd)))
101}
102
103fn drain(stream: Option<impl Read + Send + 'static>) -> std::thread::JoinHandle<Vec<u8>> {
104 std::thread::spawn(move || {
105 let mut kept = Vec::new();
106 let Some(mut stream) = stream else {
107 return kept;
108 };
109 let mut buf = [0u8; 8192];
110 while let Ok(n) = stream.read(&mut buf) {
111 if n == 0 {
112 break;
113 }
114 kept.extend_from_slice(&buf[..n]);
115 if kept.len() > 2 * KEEP {
116 kept.drain(..kept.len() - KEEP);
117 }
118 }
119 if kept.len() > KEEP {
120 kept.drain(..kept.len() - KEEP);
121 }
122 kept
123 })
124}
125
126fn wait(child: &mut Child, cmd: &Command, limit: Duration) -> Result<ExitStatus> {
127 let start = Instant::now();
128 let mut pause = Duration::from_millis(5);
129 loop {
130 if let Some(status) = child.try_wait()? {
131 return Ok(status);
132 }
133 if start.elapsed() > limit {
134 kill(child);
135 bail!(
136 "`{}` 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`)",
137 shown(cmd),
138 limit.as_secs()
139 );
140 }
141 std::thread::sleep(pause);
142 pause = (pause * 2).min(Duration::from_millis(100));
143 }
144}
145
146fn kill(child: &mut Child) {
147 #[cfg(unix)]
148 {
149 let _ = Command::new("/bin/kill")
150 .args(["-KILL", "--", &format!("-{}", child.id())])
151 .stdin(Stdio::null())
152 .stdout(Stdio::null())
153 .stderr(Stdio::null())
154 .status();
155 }
156 let _ = child.kill();
157 let _ = child.wait();
158}
159
160fn shown(cmd: &Command) -> String {
161 std::iter::once(cmd.get_program())
162 .chain(cmd.get_args())
163 .map(|a| a.to_string_lossy().into_owned())
164 .collect::<Vec<_>>()
165 .join(" ")
166}
167
168#[cfg(test)]
169mod tests {
170 use super::*;
171
172 #[test]
173 fn a_timeout_value_that_cannot_be_a_duration_falls_back_instead_of_panicking() {
174 assert_eq!(seconds(1e20), None);
176 assert_eq!(seconds(f64::INFINITY), None);
177 assert_eq!(seconds(f64::NAN), None);
178 assert_eq!(seconds(-1.0), None);
179 assert_eq!(seconds(0.0), None);
180 assert_eq!(seconds(2.5), Some(Duration::from_secs_f64(2.5)));
181 }
182
183 #[cfg(unix)]
184 #[test]
185 fn a_program_past_its_limit_is_stopped() {
186 let start = Instant::now();
187 let err = output(
188 Command::new("sh").args(["-c", "sleep 30"]),
189 Duration::from_millis(300),
190 )
191 .err()
192 .map(|e| e.to_string())
193 .unwrap_or_default();
194 assert!(err.contains("still running"), "{err}");
195 assert!(start.elapsed() < Duration::from_secs(5));
196 }
197
198 #[cfg(unix)]
199 #[test]
200 fn stdin_is_closed() {
201 let out = output(&mut Command::new("cat"), Duration::from_secs(5)).unwrap();
202 assert!(out.success());
203 assert!(out.stdout.is_empty());
204 }
205
206 #[cfg(unix)]
207 #[test]
208 fn output_is_kept_and_capped() {
209 let out = output(
210 Command::new("sh").args(["-c", "yes | head -c 3000000; echo err >&2"]),
211 Duration::from_secs(10),
212 )
213 .unwrap();
214 assert_eq!(out.stdout.len(), KEEP);
215 assert_eq!(out.stderr_text(), "err\n");
216 }
217}