1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use std::{error::Error as StdError, fmt};
use crate::ExitCode;
pub mod cli;
pub mod wrap;
pub use cli::CliError;
pub use wrap::ErrorWrap;
pub struct Error {
pub(crate) inner: anyhow::Error,
pub(crate) help: Option<HelpMsg>,
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Error")
.field("inner", &self.inner.to_string())
.field("help", &self.help)
.finish()
}
}
impl Error {
pub fn help(&self) -> Option<&str> {
self.help.as_ref().map(AsRef::as_ref)
}
pub fn set_help_owned(&mut self, msg: String) {
self.help = Some(HelpMsg::Owned(msg));
}
pub fn set_help_static(&mut self, msg: &'static str) {
self.help = Some(HelpMsg::Static(msg));
}
}
impl ExitCode for Error {
fn exit_code(&self) -> i32 {
self.inner.exit_code()
}
}
impl<E> From<E> for Error
where
E: StdError + Send + Sync + 'static,
{
fn from(err: E) -> Self {
Self {
inner: anyhow::Error::from(err),
help: None,
}
}
}
#[derive(Debug)]
pub(crate) enum HelpMsg {
Owned(String),
Static(&'static str),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.help {
None => self.inner.fmt(f),
Some(ref help) => format_error_with_help(&self.inner, help, f),
}
}
}
impl AsRef<str> for HelpMsg {
fn as_ref(&self) -> &str {
match self {
HelpMsg::Owned(ref s) => s,
HelpMsg::Static(s) => s,
}
}
}
#[inline]
fn format_error_with_help(
err: &anyhow::Error,
help: &HelpMsg,
f: &mut fmt::Formatter<'_>,
) -> fmt::Result {
write!(f, "{}\n\n{}", err, help)
}
impl fmt::Display for HelpMsg {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
HelpMsg::Owned(help) => help.fmt(f),
HelpMsg::Static(help) => help.fmt(f),
}
}
}