snipgrep/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 fn error_with_message(message: &str) -> Self {
22 Self {
23 code: 1,
24 message: Some(format!("❗ {message}")),
25 }
26 }
27
28 /// Creates a new [`CmdExit`] instance with a success message and exit code
29 /// 0.
30 #[must_use]
31 pub fn ok_with_message(message: &str) -> Self {
32 Self {
33 code: 0,
34 message: Some(message.to_string()),
35 }
36 }
37
38 /// Creates a new [`CmdExit`] instance with a success message and exit code
39 /// 0 without any message.
40 #[must_use]
41 pub const fn ok() -> Self {
42 Self {
43 code: 0,
44 message: None,
45 }
46 }
47
48 /// Exits the command line with the configured message and exit code.
49 pub fn exit(&self) {
50 if let Some(message) = &self.message {
51 eprintln!("{message}");
52 };
53
54 exit(self.code);
55 }
56}