use std::fmt::{Display, Formatter, Result as FmtResult};
use oxdock_parser::KEYWORD_EXIT;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExitRequest(pub i64);
impl Display for ExitRequest {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
write!(f, "{KEYWORD_EXIT} requested with code {}", self.0)
}
}
impl std::error::Error for ExitRequest {}
pub fn exit_code_of(err: &anyhow::Error) -> Option<i64> {
err.chain()
.find_map(|cause| cause.downcast_ref::<ExitRequest>().map(|exit| exit.0))
}
#[cfg(test)]
mod tests {
use super::{ExitRequest, exit_code_of};
#[test]
fn display_matches_historic_message() {
assert_eq!(ExitRequest(3).to_string(), "EXIT requested with code 3");
}
#[test]
fn finds_code_through_context_wrappers() {
let err = anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' failed");
assert_eq!(exit_code_of(&err), Some(3));
}
#[test]
fn none_without_exit() {
let err = anyhow::anyhow!("boom").context("wrapped");
assert_eq!(exit_code_of(&err), None);
}
}