use std::io;
use crate::types::op::OpError;
use crate::types::project::PROJECT_FILE;
use crate::types::report::{Diagnostic, Location};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Exit {
Success,
Failure,
}
#[derive(Debug)]
pub enum AirslAnswer {
NotFound,
Printed(String),
Failed(String),
SpawnFailed(io::Error),
}
impl AirslAnswer {
#[must_use]
pub fn from_output(stdout: &[u8], status: Exit) -> Self {
let text = String::from_utf8_lossy(stdout).trim().to_owned();
match status {
Exit::Success => Self::Printed(text),
Exit::Failure => Self::Failed(text),
}
}
#[must_use]
pub fn spawn_refusal(&self) -> Option<Diagnostic> {
let Self::SpawnFailed(error) = self else {
return None;
};
let copy = io::Error::new(error.kind(), error.to_string());
Some(Diagnostic::new(
Location::file(PROJECT_FILE),
OpError::AirslSpawn(copy),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn airsl_answer_decodes_and_trims() {
let printed = AirslAnswer::from_output(b"airsl 0.1.4\n", Exit::Success);
assert!(matches!(&printed, AirslAnswer::Printed(text) if text == "airsl 0.1.4"));
let lossy = AirslAnswer::from_output(b"airsl \xFF\n", Exit::Success);
assert!(matches!(&lossy, AirslAnswer::Printed(text) if text == "airsl \u{FFFD}"));
let failed = AirslAnswer::from_output(b"airsl 0.1.4\n", Exit::Failure);
assert!(matches!(&failed, AirslAnswer::Failed(text) if text == "airsl 0.1.4"));
}
#[test]
fn spawn_refusal_only_for_a_failed_spawn() {
let error = io::Error::new(io::ErrorKind::PermissionDenied, "permission denied");
let refusal = AirslAnswer::SpawnFailed(error).spawn_refusal();
assert_eq!(
refusal.map(|d| d.to_string()).as_deref(),
Some("agentstacks.toml: airsl: permission denied")
);
assert!(AirslAnswer::NotFound.spawn_refusal().is_none());
assert!(
AirslAnswer::Printed(String::new())
.spawn_refusal()
.is_none()
);
}
}