1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use std::io::Write;

/// For use in `fn run() -> ExitResult {}`
pub type ExitResult = Result<(), Exit>;

/// Error type for exiting programs.
pub struct Exit {
    code: crate::Code,
    msg: Option<Box<dyn std::fmt::Display>>,
}

impl Exit {
    #[inline]
    pub fn new(code: crate::Code) -> Self {
        Self { code, msg: None }
    }

    #[inline]
    pub fn with_message<D: std::fmt::Display + 'static>(mut self, msg: D) -> Self {
        self.msg = Some(Box::new(msg));
        self
    }
}

impl std::fmt::Display for Exit {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        if let Some(msg) = self.msg.as_ref() {
            msg.fmt(f)
        } else {
            Ok(())
        }
    }
}

impl std::process::Termination for Exit {
    #[inline]
    fn report(self) -> std::process::ExitCode {
        self.code
            .as_exit_code()
            .unwrap_or(std::process::ExitCode::FAILURE)
    }
}

impl std::fmt::Debug for Exit {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        // For compatibility with `std::process::Termination`
        std::fmt::Display::fmt(self, f)
    }
}

/// Extension for converting errors to `Exit`.
pub trait WithCodeResultExt<T> {
    /// Convert an Error into an `Exit`
    fn with_code(self, code: crate::Code) -> Result<T, Exit>;
}

impl<T, E: std::fmt::Display + 'static> WithCodeResultExt<T> for Result<T, E> {
    #[inline]
    fn with_code(self, code: crate::Code) -> Result<T, Exit> {
        self.map_err(|e| Exit::new(code).with_message(e))
    }
}

/// Report any error message and exit.
#[inline]
pub fn exit(result: ExitResult) -> ! {
    let code = report(result);
    code.process_exit()
}

/// Report, delegating exiting to the caller.
#[inline]
pub fn report(result: ExitResult) -> crate::Code {
    match result {
        Ok(()) => crate::Code::SUCCESS,
        Err(err) => {
            if let Some(msg) = err.msg {
                // At this point, we might be exiting due to a broken pipe, just do our best and
                // move on.
                let _ = writeln!(std::io::stderr(), "{}", msg);
            }
            err.code
        }
    }
}