1use std::ffi::OsStr;
4use std::io::Read;
5use std::path::Path;
6use std::process::{Child, Command, ExitStatus, Stdio};
7use std::time::{Duration, Instant};
8
9use anyhow::{Context, Result, bail};
10
11const KEEP: usize = 1 << 20;
12
13pub struct Output {
14 pub status: ExitStatus,
15 pub stdout: Vec<u8>,
16 pub stderr: Vec<u8>,
17}
18
19impl Output {
20 pub fn success(&self) -> bool {
21 self.status.success()
22 }
23
24 pub fn stdout_text(&self) -> String {
25 String::from_utf8_lossy(&self.stdout).into_owned()
26 }
27
28 pub fn stderr_text(&self) -> String {
29 String::from_utf8_lossy(&self.stderr).into_owned()
30 }
31}
32
33pub fn limit(default: Duration) -> Duration {
35 std::env::var("RUST_ANYTHING_COMMAND_TIMEOUT")
36 .ok()
37 .and_then(|v| v.parse::<f64>().ok())
38 .and_then(seconds)
39 .unwrap_or(default)
40}
41
42pub fn seconds(v: f64) -> Option<Duration> {
45 if !v.is_finite() || v <= 0.0 {
46 return None;
47 }
48 Duration::try_from_secs_f64(v).ok()
49}
50
51pub const TESTS: Duration = Duration::from_secs(30 * 60);
52pub const BUILD: Duration = Duration::from_secs(30 * 60);
53pub const QUICK: Duration = Duration::from_secs(60);
54
55pub fn output(cmd: &mut Command, default: Duration) -> Result<Output> {
57 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
58 let mut child = spawn(cmd)?;
59 let out = drain(child.stdout.take());
60 let err = drain(child.stderr.take());
61 let status = wait(&mut child, cmd, limit(default))?;
62 Ok(Output {
63 status,
64 stdout: out.join().unwrap_or_default(),
65 stderr: err.join().unwrap_or_default(),
66 })
67}
68
69pub fn status(cmd: &mut Command, default: Duration) -> Result<ExitStatus> {
71 let mut child = spawn(cmd)?;
72 wait(&mut child, cmd, limit(default))
73}
74
75pub fn status_with_input(cmd: &mut Command, input: &[u8], default: Duration) -> Result<ExitStatus> {
78 let mut child = spawn_with(cmd, Stdio::piped())?;
79 let mut stdin = child.stdin.take().context("no stdin")?;
80 let input = input.to_vec();
81 let writer = std::thread::spawn(move || {
82 use std::io::Write as _;
83 let _ = stdin.write_all(&input);
84 });
85 let status = wait(&mut child, cmd, limit(default));
86 let _ = writer.join();
87 status
88}
89
90fn spawn(cmd: &mut Command) -> Result<Child> {
91 spawn_with(cmd, Stdio::null())
92}
93
94#[derive(Debug)]
98pub(crate) struct SpawnError {
99 pub(crate) program: String,
100 pub(crate) missing: bool,
101 message: String,
102 source: std::io::Error,
103}
104
105impl std::fmt::Display for SpawnError {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 f.write_str(&self.message)
108 }
109}
110
111impl std::error::Error for SpawnError {
112 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
113 (!self.missing).then_some(&self.source)
114 }
115}
116
117fn effective_env(cmd: &Command, key: &str) -> Option<std::ffi::OsString> {
118 let mut overridden = None;
119 for (k, v) in cmd.get_envs() {
120 let matched = if cfg!(windows) {
121 k.to_string_lossy().eq_ignore_ascii_case(key)
122 } else {
123 k == OsStr::new(key)
124 };
125 if matched {
126 overridden = Some(v);
127 }
128 }
129 match overridden {
130 Some(Some(val)) => Some(val.to_os_string()),
131 Some(None) => None,
132 None => std::env::var_os(key),
133 }
134}
135
136#[cfg(windows)]
139fn file_exists_as_executable(path: &Path) -> bool {
140 if path.is_file() {
141 return true;
142 }
143 if path.extension().is_none() {
144 let mut with_exe = path.as_os_str().to_os_string();
145 with_exe.push(".exe");
146 return Path::new(&with_exe).is_file();
147 }
148 false
149}
150
151#[cfg(not(windows))]
153fn file_exists_as_executable(path: &Path) -> bool {
154 path.is_file()
155}
156
157fn program_exists(cmd: &Command) -> bool {
161 let program = cmd.get_program();
162 let prog_str = program.to_string_lossy();
163 let base = cmd
164 .get_current_dir()
165 .map(Path::to_path_buf)
166 .or_else(|| std::env::current_dir().ok());
167 if prog_str.contains('/') || prog_str.contains('\\') {
168 let path = Path::new(program);
169 return if path.is_absolute() {
170 file_exists_as_executable(path)
171 } else {
172 base.is_some_and(|dir| file_exists_as_executable(&dir.join(path)))
173 };
174 }
175 let Some(paths) = effective_env(cmd, "PATH") else {
176 return false;
177 };
178 let path_base = if cfg!(windows) {
181 std::env::current_dir().ok()
182 } else {
183 base
184 };
185 std::env::split_paths(&paths).any(|dir| {
186 let resolved = if dir.is_absolute() {
187 dir
188 } else if let Some(cwd) = &path_base {
189 cwd.join(dir)
190 } else {
191 dir
192 };
193 file_exists_as_executable(&resolved.join(program))
194 })
195}
196
197pub(crate) fn spawn_error(cmd: &Command, what: &str, err: std::io::Error) -> anyhow::Error {
201 let program = cmd.get_program().to_string_lossy().into_owned();
202 if err.kind() == std::io::ErrorKind::NotFound && cmd.get_current_dir().is_none_or(Path::is_dir)
203 {
204 if !program_exists(cmd) {
205 let message = if program.contains('/') || program.contains('\\') {
206 format!("`{program}` not found; run `rust-anything doctor`")
207 } else {
208 match crate::doctor::missing_command(&program) {
209 Some(install) if install.contains('\n') => format!(
210 "`{program}` not found on PATH; run `rust-anything doctor` or install it:\n{install}"
211 ),
212 Some(install) => format!(
213 "`{program}` not found on PATH; install it with `{install}`, or run `rust-anything doctor`"
214 ),
215 None => format!("`{program}` not found on PATH; run `rust-anything doctor`"),
216 }
217 };
218 return anyhow::Error::new(SpawnError {
219 program,
220 missing: true,
221 message,
222 source: err,
223 });
224 }
225 return anyhow::Error::new(SpawnError {
226 program,
227 missing: false,
228 message: format!(
229 "running {what} (executable exists, but its interpreter or loader may be missing)"
230 ),
231 source: err,
232 });
233 }
234 anyhow::Error::new(SpawnError {
235 program,
236 missing: false,
237 message: format!("running {what}"),
238 source: err,
239 })
240}
241
242fn spawn_with(cmd: &mut Command, stdin: Stdio) -> Result<Child> {
243 cmd.stdin(stdin);
244 #[cfg(unix)]
245 {
246 use std::os::unix::process::CommandExt as _;
247 cmd.process_group(0);
248 }
249 cmd.spawn()
250 .map_err(|e| spawn_error(cmd, &format!("`{}`", shown(cmd)), e))
251}
252
253fn drain(stream: Option<impl Read + Send + 'static>) -> std::thread::JoinHandle<Vec<u8>> {
254 std::thread::spawn(move || {
255 let mut kept = Vec::new();
256 let Some(mut stream) = stream else {
257 return kept;
258 };
259 let mut buf = [0u8; 8192];
260 while let Ok(n) = stream.read(&mut buf) {
261 if n == 0 {
262 break;
263 }
264 kept.extend_from_slice(&buf[..n]);
265 if kept.len() > 2 * KEEP {
266 kept.drain(..kept.len() - KEEP);
267 }
268 }
269 if kept.len() > KEEP {
270 kept.drain(..kept.len() - KEEP);
271 }
272 kept
273 })
274}
275
276fn wait(child: &mut Child, cmd: &Command, limit: Duration) -> Result<ExitStatus> {
277 let start = Instant::now();
278 let mut pause = Duration::from_millis(5);
279 loop {
280 if let Some(status) = child.try_wait()? {
281 return Ok(status);
282 }
283 if start.elapsed() > limit {
284 kill(child);
285 bail!(
286 "`{}` 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`)",
287 shown(cmd),
288 limit.as_secs()
289 );
290 }
291 std::thread::sleep(pause);
292 pause = (pause * 2).min(Duration::from_millis(100));
293 }
294}
295
296fn kill(child: &mut Child) {
297 #[cfg(unix)]
298 {
299 let _ = Command::new("/bin/kill")
300 .args(["-KILL", "--", &format!("-{}", child.id())])
301 .stdin(Stdio::null())
302 .stdout(Stdio::null())
303 .stderr(Stdio::null())
304 .status();
305 }
306 let _ = child.kill();
307 let _ = child.wait();
308}
309
310fn shown(cmd: &Command) -> String {
311 std::iter::once(cmd.get_program())
312 .chain(cmd.get_args())
313 .map(|a| a.to_string_lossy().into_owned())
314 .collect::<Vec<_>>()
315 .join(" ")
316}
317
318#[cfg(test)]
319mod tests {
320 use super::*;
321
322 #[test]
323 fn a_timeout_value_that_cannot_be_a_duration_falls_back_instead_of_panicking() {
324 assert_eq!(seconds(1e20), None);
326 assert_eq!(seconds(f64::INFINITY), None);
327 assert_eq!(seconds(f64::NAN), None);
328 assert_eq!(seconds(-1.0), None);
329 assert_eq!(seconds(0.0), None);
330 assert_eq!(seconds(2.5), Some(Duration::from_secs_f64(2.5)));
331 }
332
333 #[cfg(unix)]
334 #[test]
335 fn a_program_past_its_limit_is_stopped() {
336 let start = Instant::now();
337 let err = output(
338 Command::new("sh").args(["-c", "sleep 30"]),
339 Duration::from_millis(300),
340 )
341 .err()
342 .map(|e| e.to_string())
343 .unwrap_or_default();
344 assert!(err.contains("still running"), "{err}");
345 assert!(start.elapsed() < Duration::from_secs(5));
346 }
347
348 #[cfg(unix)]
349 #[test]
350 fn stdin_is_closed() {
351 let out = output(&mut Command::new("cat"), Duration::from_secs(5)).unwrap();
352 assert!(out.success());
353 assert!(out.stdout.is_empty());
354 }
355
356 #[cfg(unix)]
357 #[test]
358 fn output_is_kept_and_capped() {
359 let out = output(
360 Command::new("sh").args(["-c", "yes | head -c 3000000; echo err >&2"]),
361 Duration::from_secs(10),
362 )
363 .unwrap();
364 assert_eq!(out.stdout.len(), KEEP);
365 assert_eq!(out.stderr_text(), "err\n");
366 }
367
368 #[test]
369 fn missing_program_names_it_and_points_to_doctor() {
370 let program = "rust-anything-nonexistent-program-498";
371 let err = output(&mut Command::new(program), Duration::from_secs(5))
372 .err()
373 .expect("nonexistent program must fail");
374 let msg = format!("{err:#}");
375 assert!(
376 msg.contains(&format!("`{program}` not found on PATH")),
377 "{msg}"
378 );
379 assert!(msg.contains("rust-anything doctor"), "{msg}");
380 assert!(!msg.contains("os error"), "{msg}");
381 }
382
383 #[test]
384 fn missing_cargo_includes_doctor_install_command() {
385 let mut cmd = Command::new("cargo");
386 cmd.env_remove("PATH");
387 let err = spawn_error(
388 &cmd,
389 "cargo build",
390 std::io::Error::new(std::io::ErrorKind::NotFound, "not found"),
391 );
392 let spawn = err.downcast_ref::<SpawnError>().unwrap();
393 assert!(spawn.missing);
394 assert_eq!(spawn.program, "cargo");
395 let msg = format!("{err:#}");
396 let install = crate::doctor::missing_command("cargo").unwrap();
397 assert!(msg.contains("`cargo` not found on PATH"), "{msg}");
398 assert!(msg.contains(&install), "{msg}");
399 assert!(msg.contains("rust-anything doctor"), "{msg}");
400 }
401
402 #[test]
403 fn existing_executable_with_not_found_keeps_launch_context() {
404 let dir = std::env::temp_dir().join(format!("ra-proc-exists-{}", std::process::id()));
405 let _ = std::fs::remove_dir_all(&dir);
406 std::fs::create_dir_all(&dir).unwrap();
407 let wrapper = dir.join("fake-cargo");
408 std::fs::write(&wrapper, "#!/missing/interpreter\n").unwrap();
409
410 let mut on_path = Command::new("fake-cargo");
411 on_path.env("PATH", &dir);
412 let err = spawn_error(
413 &on_path,
414 "cargo build",
415 std::io::Error::new(std::io::ErrorKind::NotFound, "no interpreter"),
416 );
417 let spawn = err.downcast_ref::<SpawnError>().unwrap();
418 assert!(!spawn.missing);
419 let msg = format!("{err:#}");
420 assert!(msg.starts_with("running cargo build"), "{msg}");
421 assert!(msg.contains("interpreter"), "{msg}");
422 assert!(msg.contains("no interpreter"), "{msg}");
423 assert!(!msg.contains("not found on PATH"), "{msg}");
424
425 let explicit = Command::new(&wrapper);
426 let explicit_err = spawn_error(
427 &explicit,
428 "fake-cargo",
429 std::io::Error::new(std::io::ErrorKind::NotFound, "no interpreter"),
430 );
431 assert!(!explicit_err.downcast_ref::<SpawnError>().unwrap().missing);
432
433 let _ = std::fs::remove_dir_all(&dir);
434 }
435
436 #[test]
437 fn relative_path_entry_resolves_against_child_cwd() {
438 let dir = std::env::temp_dir().join(format!("ra-proc-relpath-{}", std::process::id()));
439 let _ = std::fs::remove_dir_all(&dir);
440 let bin = dir.join("bin");
441 std::fs::create_dir_all(&bin).unwrap();
442 let name = if cfg!(windows) {
443 "fake-rel-tool.exe"
444 } else {
445 "fake-rel-tool"
446 };
447 std::fs::write(bin.join(name), "").unwrap();
448
449 let mut cmd = Command::new("fake-rel-tool");
450 cmd.current_dir(&dir).env("PATH", "bin");
451 let err = spawn_error(
452 &cmd,
453 "fake-rel-tool",
454 std::io::Error::new(std::io::ErrorKind::NotFound, "no interpreter"),
455 );
456 if cfg!(windows) {
457 assert!(
458 err.downcast_ref::<SpawnError>().unwrap().missing,
459 "on Windows, relative PATH entries resolve against the parent cwd, not child cwd"
460 );
461 } else {
462 assert!(
463 !err.downcast_ref::<SpawnError>().unwrap().missing,
464 "on Unix, relative PATH entries resolve against child cwd"
465 );
466 }
467
468 #[cfg(windows)]
469 {
470 std::fs::write(bin.join("only-cmd.cmd"), "@echo off\r\n").unwrap();
471 let mut cmd_only = Command::new("only-cmd");
472 cmd_only.env("PATH", &bin);
473 let err = spawn_error(
474 &cmd_only,
475 "only-cmd",
476 std::io::Error::new(std::io::ErrorKind::NotFound, "not found"),
477 );
478 assert!(
479 err.downcast_ref::<SpawnError>().unwrap().missing,
480 "bare extensionless lookup on Windows should not match .cmd via PATHEXT"
481 );
482 }
483
484 let _ = std::fs::remove_dir_all(&dir);
485 }
486
487 #[test]
488 fn missing_cwd_or_other_spawn_errors_keep_running_context() {
489 let mut bad_cwd = Command::new("cargo");
490 bad_cwd.env_remove("PATH");
491 bad_cwd.current_dir(std::env::temp_dir().join("rust-anything-no-such-dir-498"));
492 let err = spawn_error(
493 &bad_cwd,
494 "cargo build",
495 std::io::Error::new(std::io::ErrorKind::NotFound, "missing cwd"),
496 );
497 assert!(!err.downcast_ref::<SpawnError>().unwrap().missing);
498 let msg = format!("{err:#}");
499 assert!(msg.starts_with("running cargo build"), "{msg}");
500 assert!(!msg.contains("not found on PATH"), "{msg}");
501
502 let cmd = Command::new("cargo");
503 let perm = spawn_error(
504 &cmd,
505 "cargo build",
506 std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied"),
507 );
508 assert!(!perm.downcast_ref::<SpawnError>().unwrap().missing);
509 let perm_msg = format!("{perm:#}");
510 assert!(perm_msg.starts_with("running cargo build"), "{perm_msg}");
511 }
512}