Skip to main content

aft_base/
process_spawn.rs

1/// Add path context only after an operating-system process spawn has failed.
2///
3/// Spawn errors can mean that the child working directory is missing, or that
4/// the executable itself cannot be found. Checking here keeps filesystem
5/// probes off the successful process-launch path.
6pub fn format_spawn_failure(
7    context: &str,
8    program: &std::path::Path,
9    workdir: &std::path::Path,
10    error: impl std::fmt::Display,
11) -> String {
12    let workdir_problem = match std::fs::metadata(workdir) {
13        Ok(metadata) if !metadata.is_dir() => Some("is not a directory"),
14        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Some("does not exist"),
15        _ => None,
16    };
17    let program_exists = if program.is_absolute() {
18        program.exists()
19    } else if program.components().count() > 1 {
20        workdir.join(program).exists()
21    } else {
22        which::which(program.as_os_str()).is_ok()
23    };
24
25    if let Some(problem) = workdir_problem {
26        format!(
27            "{context}: working directory {problem}: {}: {error}",
28            workdir.display()
29        )
30    } else if !program_exists {
31        format!(
32            "{context}: program not found: {}: {error}",
33            program.display()
34        )
35    } else {
36        format!("{context}: {error}")
37    }
38}
39
40#[cfg(test)]
41mod spawn_failure_tests {
42    #[test]
43    fn bash_background_spawn_error_names_missing_program() {
44        let workdir = tempfile::tempdir().unwrap();
45        let missing_program = workdir.path().join("missing-shell");
46        let error = std::process::Command::new(&missing_program)
47            .current_dir(workdir.path())
48            .spawn()
49            .unwrap_err();
50
51        let message = super::format_spawn_failure(
52            "failed to spawn background bash command",
53            &missing_program,
54            workdir.path(),
55            error,
56        );
57        assert!(
58            message.contains(&format!("program not found: {}", missing_program.display())),
59            "spawn error did not identify the missing program: {message}"
60        );
61    }
62}