snipdoc/
cli.rs

1//! A module for handling command line exits with custom messages and exit
2//! codes.
3//!
4//! This module provides a convenient way to handle command line exits with
5//! custom messages and exit codes.
6use std::process::exit;
7
8/// Represents a command exit object with a custom message and exit code.
9#[derive(Debug)]
10pub struct CmdExit {
11    /// The exit code associated with the exit.
12    pub code: i32,
13    /// The optional message associated with the exit.
14    pub message: Option<String>,
15}
16
17impl CmdExit {
18    /// Creates a new [`CmdExit`] instance with an error message and exit code
19    /// 1.
20    #[must_use]
21    pub const fn error() -> Self {
22        Self {
23            code: 1,
24            message: None,
25        }
26    }
27    /// Creates a new [`CmdExit`] instance with an error message and exit code
28    /// 1.
29    #[must_use]
30    pub fn error_with_message(message: &str) -> Self {
31        Self {
32            code: 1,
33            message: Some(format!("❗ {message}")),
34        }
35    }
36
37    /// Creates a new [`CmdExit`] instance with a success message and exit code
38    /// 0.
39    #[must_use]
40    pub fn ok_with_message(message: &str) -> Self {
41        Self {
42            code: 0,
43            message: Some(message.to_string()),
44        }
45    }
46
47    /// Creates a new [`CmdExit`] instance with a success message and exit code
48    /// 0 without any message.
49    #[must_use]
50    pub const fn ok() -> Self {
51        Self {
52            code: 0,
53            message: None,
54        }
55    }
56
57    /// Exits the command line with the configured message and exit code.
58    pub fn exit(&self) {
59        if let Some(message) = &self.message {
60            eprintln!("{message}");
61        };
62
63        exit(self.code);
64    }
65}