Skip to main content

cuno_core/
error.rs

1//! Classifying errors into the exit codes of `docs/en/specs/commands.md`,
2//! "Exit codes".
3
4/// The kind of failure, which decides the exit code. Every error a crate
5/// returns says which kind it is, so the binary never has to know the
6/// crate's error types to choose an exit code.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum ExitClass {
9    /// A problem with the user's code or build artifacts (planned: a compile
10    /// error, a failing test, unformatted code under `fmt --check`, a problem
11    /// found by `doctor`).
12    Failure,
13    /// Incorrect usage of the command (an unknown option, a missing argument).
14    Usage,
15    /// A configuration or environment problem: the setup cuno runs in is
16    /// wrong, not the user's code (an error in `cuno.toml`, no compiler found,
17    /// a compiler version that does not satisfy a constraint).
18    Setup,
19    /// A bug in cuno itself.
20    Internal,
21}
22
23impl ExitClass {
24    /// The process exit code for this class.
25    pub fn code(self) -> i32 {
26        match self {
27            ExitClass::Failure => 1,
28            ExitClass::Usage => 2,
29            ExitClass::Setup => 3,
30            // The same value as a Rust panic.
31            ExitClass::Internal => 101,
32        }
33    }
34}
35
36/// An error any cuno crate can return to `cuno-cli`, which reports it in one
37/// place, `error: <Display>` then `help: <help>` when there is one, and
38/// returns [`ExitClass::code`] for the binary to exit with
39/// (`crates/cuno-cli/src/lib.rs`, `report`).
40pub trait CunoError: std::error::Error {
41    /// Which exit code this error leads to.
42    fn exit_class(&self) -> ExitClass;
43
44    /// How to fix the problem, shown on a `help:` line.
45    fn help(&self) -> Option<String> {
46        None
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    /// Mutation: change any code in `ExitClass::code`; this test fails.
55    #[test]
56    fn exit_codes_match_the_spec() {
57        assert_eq!(ExitClass::Failure.code(), 1);
58        assert_eq!(ExitClass::Usage.code(), 2);
59        assert_eq!(ExitClass::Setup.code(), 3);
60        assert_eq!(ExitClass::Internal.code(), 101);
61    }
62
63    #[derive(Debug)]
64    struct NoHelp;
65    impl std::fmt::Display for NoHelp {
66        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67            f.write_str("x")
68        }
69    }
70    impl std::error::Error for NoHelp {}
71    impl CunoError for NoHelp {
72        fn exit_class(&self) -> ExitClass {
73            ExitClass::Failure
74        }
75    }
76
77    /// Mutation: make the default `help` return `Some(..)`; every error
78    /// without its own help would then print an empty `help:` line, and this
79    /// test fails.
80    #[test]
81    fn errors_have_no_help_unless_they_give_one() {
82        assert_eq!(NoHelp.help(), None);
83    }
84}