Skip to main content

spec_driven_docs/
error.rs

1//! Crate-level error type and exit-code mapping.
2//!
3//! [`AppError`] aggregates errors from every layer via `#[from]`, and
4//! [`AppError::exit_code`] maps each variant to its process exit code. No
5//! other module decides exit codes. Exit `1` is reserved for one meaning —
6//! a check ran and found violations — while the BSD sysexits range covers
7//! the tool failing to do its job at all.
8
9use camino::Utf8PathBuf;
10use thiserror::Error;
11
12use crate::domain::debt::DebtError;
13use crate::domain::marker::MarkerError;
14
15/// Every failure the binary can exit with.
16#[derive(Debug, Error)]
17pub enum AppError {
18    /// Semantically invalid arguments clap cannot reject on shape alone.
19    #[error("usage: {0}")]
20    Usage(String),
21
22    /// A check ran to completion and found violations; the findings are
23    /// already on stdout, so the process only carries the red exit.
24    #[error("{count} violation(s) found")]
25    Violations {
26        /// How many findings were reported.
27        count: usize,
28    },
29
30    /// The target has no instance manifest where one is required.
31    #[error("missing manifest: {0}")]
32    ManifestMissing(Utf8PathBuf),
33
34    /// The manifest exists but does not parse as a supported schema.
35    #[error("invalid manifest: {0}")]
36    ManifestInvalid(String),
37
38    /// The managed pre-commit block or its host file is malformed.
39    #[error(transparent)]
40    Marker(#[from] MarkerError),
41
42    /// The instance's debt file cannot be trusted, or a debt verb was asked
43    /// for a state it refuses.
44    #[error(transparent)]
45    Debt(#[from] DebtError),
46
47    /// The install or upgrade refused to touch the target as found, and the
48    /// target was left (or restored) unchanged.
49    #[error("{0}")]
50    Refused(String),
51
52    /// Another process holds the lock this run needs. Nothing was written.
53    #[error("busy: {0}")]
54    Busy(String),
55
56    /// A run the process did not finish could not be put back, so the
57    /// destinations it names are in an unknown state and no new work may
58    /// start over them.
59    #[error("unrecovered: {0}")]
60    Unrecovered(String),
61
62    /// The apply could not write the record that vouches for what it wrote.
63    /// The files were put back, because a landing this tool cannot vouch
64    /// for is a landing it will refuse to take back.
65    #[error("receipt: {0}")]
66    Receipt(String),
67
68    /// A tracked-upstream lookup failed. The code is the sysexit the failure
69    /// class maps to, chosen where the `git` adapter is called.
70    #[error("git: {message}")]
71    Git {
72        /// The redacted failure reason.
73        message: String,
74        /// The sysexit code for this failure class.
75        code: u8,
76    },
77
78    /// A program the verb runs on the operator's host is not there to run,
79    /// so the check it serves could not be made.
80    #[error("unavailable: {0}")]
81    Unavailable(String),
82
83    /// Filesystem failure, classified by its I/O kind.
84    #[error("io: {0}")]
85    Io(#[from] std::io::Error),
86
87    /// Escape hatch for ad-hoc contexts at the binary boundary.
88    #[error(transparent)]
89    Other(#[from] anyhow::Error),
90}
91
92impl AppError {
93    /// Map to the process exit code.
94    ///
95    /// `1` means a completed check found violations; `64..=78` follow BSD
96    /// `sysexits(3)` and mean the tool itself could not do its job.
97    #[must_use]
98    pub fn exit_code(&self) -> u8 {
99        match self {
100            Self::Violations { .. } => 1,
101            Self::Usage(_) => 64,
102            Self::ManifestInvalid(_)
103            | Self::Marker(_)
104            | Self::Debt(
105                DebtError::Shape(_) | DebtError::Malformed { .. } | DebtError::TwoFormats,
106            ) => 65,
107            Self::ManifestMissing(_) => 66,
108            Self::Refused(_)
109            | Self::Busy(_)
110            | Self::Unrecovered(_)
111            | Self::Receipt(_)
112            | Self::Debt(_) => 73,
113            Self::Git { code, .. } => *code,
114            Self::Unavailable(_) => 69,
115            Self::Io(e) if e.kind() == std::io::ErrorKind::NotFound => 66,
116            Self::Io(e) if e.kind() == std::io::ErrorKind::PermissionDenied => 77,
117            Self::Io(_) => 74,
118            Self::Other(_) => 70,
119        }
120    }
121
122    /// Stable machine-readable kind for the error envelope.
123    #[must_use]
124    pub const fn kind(&self) -> &'static str {
125        match self {
126            Self::Usage(_) => "Usage",
127            Self::Violations { .. } => "Violations",
128            Self::ManifestMissing(_) => "ManifestMissing",
129            Self::ManifestInvalid(_) => "ManifestInvalid",
130            Self::Marker(_) => "Marker",
131            Self::Debt(_) => "Debt",
132            Self::Refused(_) => "Refused",
133            Self::Busy(_) => "Busy",
134            Self::Unrecovered(_) => "Unrecovered",
135            Self::Receipt(_) => "Receipt",
136            Self::Git { .. } => "Git",
137            Self::Unavailable(_) => "Unavailable",
138            Self::Io(_) => "Io",
139            Self::Other(_) => "Other",
140        }
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    fn io(kind: std::io::ErrorKind) -> AppError {
149        AppError::Io(std::io::Error::from(kind))
150    }
151
152    #[test]
153    fn violations_are_one() {
154        assert_eq!(AppError::Violations { count: 3 }.exit_code(), 1);
155    }
156
157    #[test]
158    fn usage_is_sixty_four() {
159        assert_eq!(AppError::Usage("bad target".into()).exit_code(), 64);
160    }
161
162    #[test]
163    fn invalid_manifest_is_sixty_five() {
164        assert_eq!(
165            AppError::ManifestInvalid("schema_version 3".into()).exit_code(),
166            65
167        );
168    }
169
170    #[test]
171    fn malformed_marker_is_sixty_five() {
172        assert_eq!(AppError::Marker(MarkerError::Malformed).exit_code(), 65);
173    }
174
175    #[test]
176    fn a_malformed_debt_file_is_sixty_five_and_a_refused_debt_verb_is_seventy_three() {
177        assert_eq!(
178            AppError::Debt(DebtError::Shape("not yaml".into())).exit_code(),
179            65
180        );
181        assert_eq!(AppError::Debt(DebtError::TwoFormats).exit_code(), 65);
182        assert_eq!(AppError::Debt(DebtError::AlreadyBaselined).exit_code(), 73);
183        assert_eq!(AppError::Debt(DebtError::NothingToMigrate).exit_code(), 73);
184    }
185
186    #[test]
187    fn missing_manifest_is_sixty_six() {
188        assert_eq!(
189            AppError::ManifestMissing("x/.spec-driven-docs/manifest.json".into()).exit_code(),
190            66
191        );
192    }
193
194    #[test]
195    fn refused_is_seventy_three() {
196        assert_eq!(
197            AppError::Refused("apply aborted; the target was restored".into()).exit_code(),
198            73
199        );
200    }
201
202    #[test]
203    fn an_unavailable_program_is_sixty_nine() {
204        assert_eq!(
205            AppError::Unavailable("pre-commit could not run".into()).exit_code(),
206            69
207        );
208    }
209
210    #[test]
211    fn not_found_io_is_sixty_six() {
212        assert_eq!(io(std::io::ErrorKind::NotFound).exit_code(), 66);
213    }
214
215    #[test]
216    fn permission_denied_io_is_seventy_seven() {
217        assert_eq!(io(std::io::ErrorKind::PermissionDenied).exit_code(), 77);
218    }
219
220    #[test]
221    fn other_io_is_seventy_four() {
222        assert_eq!(io(std::io::ErrorKind::BrokenPipe).exit_code(), 74);
223    }
224
225    #[test]
226    fn anyhow_is_seventy() {
227        assert_eq!(AppError::Other(anyhow::anyhow!("boom")).exit_code(), 70);
228    }
229}