kutil_cli/
exit.rs

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
use std::fmt;

//
// Exit
//

/// Information on how to exit a program.
#[derive(Debug)]
pub struct Exit {
    /// Exit code.
    pub code: u8,

    /// Optional goodbye message.
    pub message: Option<String>,
}

impl Exit {
    /// Constructor.
    pub fn new(code: u8, message: Option<String>) -> Self {
        Self { code, message }
    }

    /// Successful exit (code 0) without a message.
    pub fn success() -> Self {
        0.into()
    }
}

impl From<u8> for Exit {
    fn from(value: u8) -> Self {
        Self::new(value, None)
    }
}

impl fmt::Display for Exit {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.message {
            Some(message) => write!(formatter, "{}: {}", self.code, message),
            None => self.code.fmt(formatter),
        }
    }
}

//
// HasExit
//

/// For types that can optionally have an [Exit].
pub trait HasExit: fmt::Display {
    /// Return the [Exit] if it exists.
    fn get_exit(&self) -> Option<&Exit>;
}