use std::time::Duration;
use isothrum_runner::{Captured, ErrorCode, ProcessError, ProcessSpec};
use crate::context::Context;
use crate::exec::{self, Unanswered};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Refusal {
CredentialsExpired,
Denied,
NotFound,
NotEnabled,
QuotaExceeded,
Other,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Failure {
Missing {
program: String,
},
TimedOut {
program: String,
limit: Duration,
},
NotStarted {
program: String,
reason: String,
},
Refused {
program: String,
refusal: Refusal,
said: String,
},
Unreadable {
program: String,
why: String,
},
}
impl Failure {
#[must_use]
pub fn code(&self) -> ErrorCode {
match self {
Failure::Missing { .. } => ErrorCode::ToolMissing,
Failure::TimedOut { .. } => ErrorCode::Timeout,
Failure::NotStarted { .. } | Failure::Unreadable { .. } => ErrorCode::ToolFailed,
Failure::Refused { refusal, .. } => match refusal {
Refusal::CredentialsExpired => ErrorCode::CredentialsExpired,
Refusal::Denied => ErrorCode::ToolDenied,
Refusal::NotFound | Refusal::NotEnabled | Refusal::QuotaExceeded | Refusal::Other => ErrorCode::ToolFailed,
},
}
}
#[must_use]
pub fn refusal(&self) -> Option<Refusal> {
match self {
Failure::Refused { refusal, .. } => Some(*refusal),
_ => None,
}
}
#[must_use]
pub fn program(&self) -> &str {
match self {
Failure::Missing { program }
| Failure::TimedOut { program, .. }
| Failure::NotStarted { program, .. }
| Failure::Refused { program, .. }
| Failure::Unreadable { program, .. } => program,
}
}
}
impl std::fmt::Display for Failure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Failure::Missing { program } => write!(f, "`{program}` isn't installed or isn't on PATH"),
Failure::TimedOut { program, limit } => write!(f, "`{program}` gave no answer within {} s", limit.as_secs()),
Failure::NotStarted { program, reason } => write!(f, "`{program}` couldn't be started: {reason}"),
Failure::Refused { said, .. } => f.write_str(said),
Failure::Unreadable { program, why } => write!(f, "`{program}`'s answer couldn't be read: {why}"),
}
}
}
impl std::error::Error for Failure {}
pub(crate) async fn answer(cx: &Context, limit: Duration, spec: &ProcessSpec, read: fn(&str) -> Refusal) -> Result<String, Failure> {
let program = spec.program.clone();
let captured = cx.probe_within(limit, spec).await.map_err(|unanswered| match unanswered {
Unanswered::NotStarted(ProcessError::Missing { .. }) => Failure::Missing { program: program.clone() },
Unanswered::NotStarted(other) => Failure::NotStarted {
program: program.clone(),
reason: other.to_string(),
},
Unanswered::TimedOut(given) => Failure::TimedOut {
program: program.clone(),
limit: given,
},
})?;
if captured.success() {
return Ok(captured.stdout.join("\n"));
}
Err(Failure::Refused {
refusal: read(&exec::all_lines(&captured)),
said: reason(&captured),
program,
})
}
fn reason(captured: &Captured) -> String {
let last = |lines: &[String]| lines.iter().rev().map(|l| l.trim()).find(|l| !l.is_empty()).map(str::to_owned);
last(&captured.stderr_tail)
.or_else(|| last(&captured.stdout))
.unwrap_or_else(|| captured.exit.to_string())
}
pub async fn ask(cx: &Context, (program, args): (&str, &[&str])) -> Result<String, Failure> {
answer(cx, cx.probe_timeout, &ProcessSpec::new(program, args.iter().copied()), |_| Refusal::Other).await
}
#[cfg(test)]
mod tests;