1use std::fmt::{Display, Formatter, Result as FmtResult};
8
9use oxdock_parser::KEYWORD_EXIT;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct ExitRequest(pub i64);
16
17impl Display for ExitRequest {
18 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
19 write!(f, "{KEYWORD_EXIT} requested with code {}", self.0)
20 }
21}
22
23impl std::error::Error for ExitRequest {}
24
25pub fn exit_code_of(err: &anyhow::Error) -> Option<i64> {
29 err.chain()
30 .find_map(|cause| cause.downcast_ref::<ExitRequest>().map(|exit| exit.0))
31}
32
33#[cfg(test)]
34mod tests {
35 use super::{ExitRequest, exit_code_of};
36
37 #[test]
38 fn display_matches_historic_message() {
39 assert_eq!(ExitRequest(3).to_string(), "EXIT requested with code 3");
40 }
41
42 #[test]
43 fn finds_code_through_context_wrappers() {
44 let err = anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' failed");
45 assert_eq!(exit_code_of(&err), Some(3));
46 }
47
48 #[test]
49 fn none_without_exit() {
50 let err = anyhow::anyhow!("boom").context("wrapped");
51 assert_eq!(exit_code_of(&err), None);
52 }
53}