use std::fmt;
pub const AUTH_REQUIRED: i32 = 4;
pub const PENDING: i32 = 8;
#[derive(Debug)]
pub struct Exit {
pub code: i32,
pub msg: String,
}
impl Exit {
pub fn new(code: i32, msg: impl Into<String>) -> anyhow::Error {
anyhow::Error::new(Exit { code, msg: msg.into() })
}
}
impl fmt::Display for Exit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.msg)
}
}
impl std::error::Error for Exit {}
pub fn code(e: &anyhow::Error) -> i32 {
e.chain().find_map(|c| c.downcast_ref::<Exit>()).map_or(1, |x| x.code)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn codes() {
assert_eq!(code(&anyhow::anyhow!("plain")), 1);
assert_eq!(code(&Exit::new(PENDING, "2 pending")), 8);
assert_eq!(code(&Exit::new(AUTH_REQUIRED, "login").context("while listing")), 4);
assert_eq!(Exit::new(4, "not logged in").to_string(), "not logged in");
}
}