1use std::ffi::OsStr;
5use std::path::Path;
6use std::process::{Command, Stdio};
7use std::time::{Duration, Instant};
8
9use didbot_cli::Refusal;
10
11const VERSION_PATIENCE: Duration = Duration::from_secs(3);
15
16fn 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
31pub 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
57pub 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}