use std::{
fs, io,
path::{Path, PathBuf},
process::Stdio,
time::Duration,
};
use super::platform::{self, FileIdentity};
const PROBE_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Debug)]
pub(crate) struct Executable {
path: PathBuf,
started: Option<FileIdentity>,
running: Option<FileIdentity>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Replacement {
pub(crate) identity: FileIdentity,
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum ProbeError {
#[error("could not run it: {0}")]
Spawn(io::Error),
#[error("it did not print its version within PROBE_TIMEOUT ({PROBE_TIMEOUT:?})")]
TimedOut,
#[error("`--version` failed with {0}")]
Failed(std::process::ExitStatus),
#[error("`--version` printed {0:?}, not a rho version")]
NotRho(String),
}
impl ProbeError {
pub(crate) fn is_transient(&self) -> bool {
match self {
Self::Spawn(_) | Self::TimedOut => true,
Self::Failed(_) | Self::NotRho(_) => false,
}
}
}
impl Executable {
pub(crate) fn of_this_process() -> io::Result<Self> {
let path = match std::env::args_os().next().map(PathBuf::from) {
Some(path) if path.components().count() > 1 => std::path::absolute(path)?,
_ => std::env::current_exe()?,
};
let started = identity(&path);
Ok(Self {
running: platform::running_identity().or(started),
started,
path,
})
}
pub(crate) fn path(&self) -> &Path {
&self.path
}
pub(crate) fn replacement(&self) -> Option<Replacement> {
let started = self.started?;
let identity = identity(&self.path)?;
(identity != started && Some(identity) != self.running).then_some(Replacement { identity })
}
pub(crate) async fn probe(&self) -> Result<String, ProbeError> {
let child = tokio::process::Command::new(&self.path)
.arg("--version")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.kill_on_drop(true)
.spawn()
.map_err(ProbeError::Spawn)?;
let output = tokio::time::timeout(PROBE_TIMEOUT, child.wait_with_output())
.await
.map_err(|_| ProbeError::TimedOut)?
.map_err(ProbeError::Spawn)?;
if !output.status.success() {
return Err(ProbeError::Failed(output.status));
}
let printed = String::from_utf8_lossy(&output.stdout).trim().to_owned();
match printed.strip_prefix("rho ") {
Some(version) if !version.is_empty() => Ok(version.to_owned()),
_ => Err(ProbeError::NotRho(printed)),
}
}
}
fn identity(path: &Path) -> Option<FileIdentity> {
fs::metadata(path)
.ok()
.map(|metadata| FileIdentity::of(&metadata))
}