| 1 | use std::borrow::Cow; |
| 2 | |
| 3 | /// An error around some option-setting, and the reason. |
| 4 | /// |
| 5 | /// These are meant to potentially be user-facing (e.g. explain |
| 6 | /// why it's broken and what to fix), and as so treat it as such! |
| 7 | /// |
| 8 | /// For stylistic and consistency reasons, use _single quotes_ (e.g. `'bad'`) |
| 9 | /// for highlighting error values. You can use (".*`.+`.*") as a regex to check |
| 10 | /// for this. |
| 11 | #[derive(Debug, PartialEq)] |
| 12 | pub enum OptionError { |
| 13 | Config(Cow<'static, str>), |
| 14 | Argument(Cow<'static, str>), |
| 15 | Other(Cow<'static, str>), |
| 16 | } |
| 17 | |
| 18 | impl OptionError { |
| 19 | /// Create a new [`OptionError::Config`]. |
| 20 | pub(crate) fn config<R: Into<Cow<'static, str>>>(reason: R) -> Self { |
| 21 | OptionError::Config(reason.into()) |
| 22 | } |
| 23 | |
| 24 | /// Create a new [`OptionError::Config`] for an invalid value. |
| 25 | pub(crate) fn invalid_config_value(value: &str) -> Self { |
| 26 | OptionError::Config(Cow::Owned(format!( |
| 27 | "'{value}' was set with an invalid value, please update it in your config file." |
| 28 | ))) |
| 29 | } |
| 30 | |
| 31 | /// Create a new [`OptionError::Argument`]. |
| 32 | pub(crate) fn arg<R: Into<Cow<'static, str>>>(reason: R) -> Self { |
| 33 | OptionError::Argument(reason.into()) |
| 34 | } |
| 35 | |
| 36 | /// Create a new [`OptionError::Argument`] for an invalid value. |
| 37 | pub(crate) fn invalid_arg_value(value: &str) -> Self { |
| 38 | OptionError::Argument(Cow::Owned(format!( |
| 39 | "'--{value}' was set with an invalid value, please update your arguments." |
| 40 | ))) |
| 41 | } |
| 42 | |
| 43 | /// Create a new [`OptionError::Other`]. |
| 44 | pub(crate) fn other<R: Into<Cow<'static, str>>>(reason: R) -> Self { |
| 45 | OptionError::Other(reason.into()) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | pub(crate) type OptionResult<T> = Result<T, OptionError>; |
| 50 | |
| 51 | impl std::fmt::Display for OptionError { |
| 52 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 53 | match self { |
| 54 | OptionError::Config(reason) => write!(f, "Configuration file error: {reason}"), |
| 55 | OptionError::Argument(reason) => write!(f, "Argument error: {reason}"), |
| 56 | OptionError::Other(reason) => { |
| 57 | write!(f, "Error with the config file or the arguments: {reason}") |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | impl std::error::Error for OptionError {} |
| 64 | |
| 65 | impl From<toml_edit::de::Error> for OptionError { |
| 66 | fn from(err: toml_edit::de::Error) -> Self { |
| 67 | OptionError::Config(err.to_string().into()) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | impl From<std::io::Error> for OptionError { |
| 72 | fn from(err: std::io::Error) -> Self { |
| 73 | OptionError::Other(err.to_string().into()) |
| 74 | } |
| 75 | } |