kutil_cli/run/
exit.rs

1use std::{error, fmt};
2
3//
4// Exit
5//
6
7/// Information on how to exit a program.
8#[derive(Debug)]
9pub struct Exit {
10    /// Exit code.
11    pub code: u8,
12
13    /// Optional goodbye message.
14    pub message: Option<String>,
15}
16
17impl Exit {
18    /// Constructor.
19    pub fn new(code: u8, message: Option<&str>) -> Self {
20        let message = message.map(|message| message.into());
21        Self { code, message }
22    }
23
24    /// Successful exit (code 0) without a message.
25    pub fn success() -> Self {
26        0.into()
27    }
28}
29
30impl error::Error for Exit {}
31
32impl fmt::Display for Exit {
33    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match &self.message {
35            Some(message) => write!(formatter, "{}: {}", self.code, message),
36            None => fmt::Display::fmt(&self.code, formatter),
37        }
38    }
39}
40
41// Conversions
42
43impl From<u8> for Exit {
44    fn from(value: u8) -> Self {
45        Self::new(value, None)
46    }
47}
48
49//
50// HasExit
51//
52
53/// For types that can optionally have an [Exit].
54pub trait HasExit: fmt::Display {
55    /// Return the [Exit] if it exists.
56    fn get_exit(&self) -> Option<&Exit>;
57}