mitex_cli/
utils.rs

1//! Utility functions and types.
2
3/// A wrapper around `Box<str>` that implements `std::error::Error`.
4pub struct Error(Box<str>);
5
6impl std::fmt::Display for Error {
7    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8        f.write_str(&self.0)
9    }
10}
11
12impl std::fmt::Debug for Error {
13    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14        f.write_str(&self.0)
15    }
16}
17
18impl std::error::Error for Error {}
19
20impl From<String> for Error {
21    fn from(s: String) -> Self {
22        Self(s.into_boxed_str())
23    }
24}
25
26impl From<&str> for Error {
27    fn from(s: &str) -> Self {
28        Self(s.to_owned().into_boxed_str())
29    }
30}
31
32impl From<anyhow::Error> for Error {
33    fn from(err: anyhow::Error) -> Self {
34        Self(err.to_string().into_boxed_str())
35    }
36}
37
38impl From<std::io::Error> for Error {
39    fn from(err: std::io::Error) -> Self {
40        Self(err.to_string().into_boxed_str())
41    }
42}
43
44/// Exit with an error message.
45pub fn exit_with_error<E: std::error::Error>(err: E) -> ! {
46    clap::Error::raw(
47        clap::error::ErrorKind::ValueValidation,
48        format!("mitex error: {err}"),
49    )
50    .exit()
51}
52
53/// Exit with an error message.
54pub trait UnwrapOrExit<T> {
55    /// Unwrap the result or exit with an error message.
56    fn unwrap_or_exit(self) -> T;
57}
58
59impl<T, E: std::error::Error> UnwrapOrExit<T> for Result<T, E> {
60    fn unwrap_or_exit(self) -> T {
61        self.map_err(exit_with_error).unwrap()
62    }
63}