|
| 1 | +use anyhow::Result; |
| 2 | +use std::error::Error; |
| 3 | +use std::fmt; |
| 4 | + |
| 5 | +type ExitMessage = Option<String>; |
| 6 | + |
| 7 | +#[derive(Debug)] |
| 8 | +pub enum ExitStatus { |
| 9 | + Success, |
| 10 | + Error, |
| 11 | +} |
| 12 | + |
| 13 | +impl ExitStatus { |
| 14 | + pub fn as_raw(&self) -> i32 { |
| 15 | + match self { |
| 16 | + ExitStatus::Success => 0, |
| 17 | + ExitStatus::Error => 1, |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + pub fn as_str(&self) -> &str { |
| 22 | + match self { |
| 23 | + ExitStatus::Success => "Command succeeded", |
| 24 | + ExitStatus::Error => "Command error", |
| 25 | + } |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +impl From<ExitStatus> for i32 { |
| 30 | + fn from(status: ExitStatus) -> Self { |
| 31 | + status.as_raw() |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +impl fmt::Display for ExitStatus { |
| 36 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 37 | + let msg = self.as_str(); |
| 38 | + write!(f, "{}", msg) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +#[derive(Debug)] |
| 43 | +pub struct Exit { |
| 44 | + status: ExitStatus, |
| 45 | + message: ExitMessage, |
| 46 | +} |
| 47 | + |
| 48 | +impl Exit { |
| 49 | + fn new(status: ExitStatus) -> Self { |
| 50 | + Self { |
| 51 | + status, |
| 52 | + message: None, |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + pub fn success() -> Self { |
| 57 | + Self::new(ExitStatus::Success) |
| 58 | + } |
| 59 | + |
| 60 | + pub fn error() -> Self { |
| 61 | + Self::new(ExitStatus::Error) |
| 62 | + } |
| 63 | + |
| 64 | + pub fn with_message<S: Into<String>>(mut self, message: S) -> Self { |
| 65 | + self.message = Some(message.into()); |
| 66 | + self |
| 67 | + } |
| 68 | + |
| 69 | + pub fn process_exit(self) -> ! { |
| 70 | + if let Some(message) = self.message { |
| 71 | + println!("{}", message) |
| 72 | + } |
| 73 | + std::process::exit(self.status.as_raw()) |
| 74 | + } |
| 75 | + |
| 76 | + #[allow(dead_code)] |
| 77 | + pub fn ok(self) -> Result<()> { |
| 78 | + match self.status { |
| 79 | + ExitStatus::Success => Ok(()), |
| 80 | + _ => Err(self.into()), |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + #[allow(dead_code)] |
| 85 | + pub fn as_raw(&self) -> i32 { |
| 86 | + self.status.as_raw() |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +impl fmt::Display for Exit { |
| 91 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 92 | + let status_str = self.status.as_str(); |
| 93 | + match &self.message { |
| 94 | + Some(msg) => write!(f, "{}: {}", status_str, msg), |
| 95 | + None => write!(f, "{}", status_str), |
| 96 | + } |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +impl Error for Exit {} |
0 commit comments