Skip to main content

didbot/
run.rs

1//! Running a verb's binary: the hand-off, and the version probe `--list`
2//! makes.
3
4use std::ffi::OsStr;
5use std::path::Path;
6use std::process::{Command, Stdio};
7use std::time::{Duration, Instant};
8
9use didbot_cli::Refusal;
10
11/// How long `--list` waits for one binary to answer `--version`. A verb
12/// that starts doing work instead of answering is killed, so one stray
13/// binary on `PATH` cannot hang the listing.
14const VERSION_PATIENCE: Duration = Duration::from_secs(3);
15
16/// The command as a verb receives it: `binary argv…`, this process's
17/// environment minus every credential variable, and nothing added.
18fn command<I, S>(binary: &Path, argv: I) -> Command
19where
20    I: IntoIterator<Item = S>,
21    S: AsRef<OsStr>,
22{
23    let mut command = Command::new(binary);
24    command.args(argv);
25    for variable in didbot_cli::env::CREDENTIALS {
26        command.env_remove(variable);
27    }
28    command
29}
30
31/// Replaces this process with `binary argv…`.
32///
33/// Returns only when the binary could not be started. On unix the verb's
34/// exit status is then the shell's directly; elsewhere this waits and
35/// exits with the same status.
36pub fn exec<I, S>(binary: &Path, argv: I) -> Result<(), Refusal>
37where
38    I: IntoIterator<Item = S>,
39    S: AsRef<OsStr>,
40{
41    let mut command = command(binary, argv);
42    let could_not_start = |error: std::io::Error| {
43        Refusal::failed(format!("could not run {}: {error}", binary.display()))
44    };
45    #[cfg(unix)]
46    {
47        use std::os::unix::process::CommandExt;
48        Err(could_not_start(command.exec()))
49    }
50    #[cfg(not(unix))]
51    {
52        let status = command.status().map_err(could_not_start)?;
53        std::process::exit(status.code().unwrap_or(1));
54    }
55}
56
57/// What `binary --version` prints on its first line, if it answers with
58/// exit 0 inside [`VERSION_PATIENCE`].
59pub fn version_of(binary: &Path) -> Option<String> {
60    let mut child = command(binary, ["--version"])
61        .stdin(Stdio::null())
62        .stdout(Stdio::piped())
63        .stderr(Stdio::null())
64        .spawn()
65        .ok()?;
66    let started = Instant::now();
67    let status = loop {
68        match child.try_wait() {
69            Ok(Some(status)) => break status,
70            Ok(None) if started.elapsed() < VERSION_PATIENCE => {
71                std::thread::sleep(Duration::from_millis(20));
72            }
73            _ => {
74                let _ = child.kill();
75                let _ = child.wait();
76                return None;
77            }
78        }
79    };
80    if !status.success() {
81        return None;
82    }
83    let mut stdout = child.stdout.take()?;
84    let mut output = String::new();
85    std::io::Read::read_to_string(&mut stdout, &mut output).ok()?;
86    output
87        .lines()
88        .next()
89        .map(str::trim)
90        .filter(|line| !line.is_empty())
91        .map(str::to_owned)
92}