Skip to main content

cornerstone/
error.rs

1//! Errors and exit codes.
2//!
3//! Two things live here:
4//!
5//! * [`Error`] — a plain, human-readable error with an associated exit code.
6//! * [`ErrorSet`] — the "collect all errors, report at the end" accumulator the
7//!   workflow standard calls for. A command can push many failures and still run
8//!   to completion, then the app prints them all and exits non-zero.
9
10use std::fmt;
11
12/// Conventional exit codes. Small, memorable, and stable across every CLI so
13/// scripts can rely on them.
14pub mod codes {
15    /// Everything succeeded.
16    pub const OK: i32 = 0;
17    /// A generic, unclassified failure.
18    pub const FAILURE: i32 = 1;
19    /// The user invoked the tool incorrectly (bad flag, missing arg, etc.).
20    pub const USAGE: i32 = 2;
21    /// A requested file or resource was not found.
22    pub const NOT_FOUND: i32 = 3;
23    /// Permission denied / not running as root when required.
24    pub const PERMISSION: i32 = 4;
25    /// The operation was cancelled or not confirmed.
26    pub const CANCELLED: i32 = 5;
27}
28
29/// A single, user-facing error. Carries a message and the exit code the process
30/// should return if this error is the one that ends the run.
31#[derive(Debug, Clone)]
32pub struct Error {
33    pub message: String,
34    pub code: i32,
35    /// Optional extra lines printed under the message, indented, for context.
36    pub notes: Vec<String>,
37}
38
39impl Error {
40    /// A generic failure (exit code 1).
41    pub fn msg<S: Into<String>>(message: S) -> Self {
42        Error {
43            message: message.into(),
44            code: codes::FAILURE,
45            notes: Vec::new(),
46        }
47    }
48
49    /// A usage error (exit code 2) — bad flags, missing arguments.
50    pub fn usage<S: Into<String>>(message: S) -> Self {
51        Error {
52            message: message.into(),
53            code: codes::USAGE,
54            notes: Vec::new(),
55        }
56    }
57
58    /// A not-found error (exit code 3).
59    pub fn not_found<S: Into<String>>(message: S) -> Self {
60        Error {
61            message: message.into(),
62            code: codes::NOT_FOUND,
63            notes: Vec::new(),
64        }
65    }
66
67    /// A permission error (exit code 4).
68    pub fn permission<S: Into<String>>(message: S) -> Self {
69        Error {
70            message: message.into(),
71            code: codes::PERMISSION,
72            notes: Vec::new(),
73        }
74    }
75
76    /// A cancelled/unconfirmed error (exit code 5).
77    pub fn cancelled<S: Into<String>>(message: S) -> Self {
78        Error {
79            message: message.into(),
80            code: codes::CANCELLED,
81            notes: Vec::new(),
82        }
83    }
84
85    /// Set a specific exit code.
86    pub fn with_code(mut self, code: i32) -> Self {
87        self.code = code;
88        self
89    }
90
91    /// Attach a contextual note line.
92    pub fn note<S: Into<String>>(mut self, note: S) -> Self {
93        self.notes.push(note.into());
94        self
95    }
96}
97
98impl fmt::Display for Error {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        write!(f, "{}", self.message)
101    }
102}
103
104impl std::error::Error for Error {}
105
106/// Common standard errors convert into a generic [`Error`], so `?` works on
107/// `io::Result` and friends inside command bodies. A blanket
108/// `impl<E: std::error::Error>` would collide with the standard library's
109/// reflexive `From<T> for T`, so we implement the ones that come up in practice
110/// and offer [`Error::wrap`] for anything else.
111macro_rules! from_std {
112    ($($ty:path),* $(,)?) => {
113        $(
114            impl From<$ty> for Error {
115                fn from(e: $ty) -> Self {
116                    Error::msg(e.to_string())
117                }
118            }
119        )*
120    };
121}
122
123from_std!(
124    std::io::Error,
125    std::num::ParseIntError,
126    std::num::ParseFloatError,
127    std::str::Utf8Error,
128    std::string::FromUtf8Error,
129    std::num::TryFromIntError,
130);
131
132impl Error {
133    /// Wrap any error type into a Cornerstone [`Error`]. Use when a `?` target
134    /// isn't covered by the built-in `From` impls: `something().map_err(Error::wrap)?`.
135    pub fn wrap<E: std::fmt::Display>(e: E) -> Self {
136        Error::msg(e.to_string())
137    }
138}
139
140/// The result type command bodies return.
141pub type Result<T> = std::result::Result<T, Error>;
142
143/// Accumulates multiple errors so a command can process every item and report
144/// all failures at once rather than stopping at the first.
145#[derive(Debug, Default, Clone)]
146pub struct ErrorSet {
147    errors: Vec<Error>,
148}
149
150impl ErrorSet {
151    pub fn new() -> Self {
152        ErrorSet { errors: Vec::new() }
153    }
154
155    /// Record a failure and keep going.
156    pub fn push(&mut self, e: Error) {
157        self.errors.push(e);
158    }
159
160    /// Record the `Err` of a result, returning the `Ok` value as an option.
161    /// Lets a loop body stay flat: `if let Some(v) = set.absorb(try_thing()) { ... }`
162    pub fn absorb<T>(&mut self, r: Result<T>) -> Option<T> {
163        match r {
164            Ok(v) => Some(v),
165            Err(e) => {
166                self.errors.push(e);
167                None
168            }
169        }
170    }
171
172    pub fn is_empty(&self) -> bool {
173        self.errors.is_empty()
174    }
175
176    pub fn len(&self) -> usize {
177        self.errors.len()
178    }
179
180    pub fn errors(&self) -> &[Error] {
181        &self.errors
182    }
183
184    /// Collapse the set into a single `Result`: `Ok(())` if empty, otherwise an
185    /// `Error` summarizing the count with each failure as a note, using the
186    /// highest exit code seen.
187    pub fn into_result(self) -> Result<()> {
188        if self.errors.is_empty() {
189            return Ok(());
190        }
191        let code = self.errors.iter().map(|e| e.code).max().unwrap_or(codes::FAILURE);
192        let mut summary = Error::msg(format!("{} operation(s) failed", self.errors.len()))
193            .with_code(code);
194        for e in &self.errors {
195            summary.notes.push(e.message.clone());
196            for n in &e.notes {
197                summary.notes.push(format!("  {}", n));
198            }
199        }
200        Err(summary)
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn constructors_set_codes() {
210        assert_eq!(Error::msg("x").code, codes::FAILURE);
211        assert_eq!(Error::usage("x").code, codes::USAGE);
212        assert_eq!(Error::not_found("x").code, codes::NOT_FOUND);
213        assert_eq!(Error::permission("x").code, codes::PERMISSION);
214        assert_eq!(Error::cancelled("x").code, codes::CANCELLED);
215    }
216
217    #[test]
218    fn error_set_collects_and_reports() {
219        let mut s = ErrorSet::new();
220        assert!(s.is_empty());
221        s.push(Error::usage("first"));
222        s.push(Error::not_found("second"));
223        assert_eq!(s.len(), 2);
224        let e = s.into_result().unwrap_err();
225        // Highest code wins: NOT_FOUND (3) > USAGE (2)
226        assert_eq!(e.code, codes::NOT_FOUND);
227        assert_eq!(e.notes.len(), 2);
228    }
229
230    #[test]
231    fn empty_error_set_is_ok() {
232        assert!(ErrorSet::new().into_result().is_ok());
233    }
234
235    #[test]
236    fn absorb_returns_ok_value() {
237        let mut s = ErrorSet::new();
238        let v = s.absorb(Ok::<i32, Error>(5));
239        assert_eq!(v, Some(5));
240        let n = s.absorb(Err::<i32, Error>(Error::msg("bad")));
241        assert_eq!(n, None);
242        assert_eq!(s.len(), 1);
243    }
244
245    #[test]
246    fn io_error_converts() {
247        let io = std::io::Error::new(std::io::ErrorKind::NotFound, "nope");
248        let e: Error = io.into();
249        assert_eq!(e.code, codes::FAILURE);
250    }
251}