Skip to main content

docsrs_cli/error/
detail.rs

1//! Typed catalogue of every product error, carrying data instead of prose.
2//!
3//! # Why a catalogue
4//!
5//! Localization used to work by matching the *English text* of a message with
6//! `starts_with`. That coupling is invisible to the compiler: rewording an
7//! English message silently dropped its pt-BR translation, and a brand-new
8//! message fell through to a fallback that returned English with no signal at
9//! all. Thirty-two match arms guarded well over a hundred construction sites.
10//!
11//! Here the data is the message. [`ErrorDetail`] carries the *values*; the two
12//! renderers in [`super::render`] own the words. Because their `match` has no
13//! `_` arm, a variant added without a translation is a **compile error** rather
14//! than a silent English leak. The compiler is the coverage gate.
15//!
16//! # Shape, not sentence
17//!
18//! Variants describe the *shape* of a failure ("this subject is empty", "this
19//! subject exceeds a limit") and name the subject through [`Subject`]. Eleven
20//! "X is empty" messages therefore share one variant instead of eleven.
21//!
22//! # Upstream text
23//!
24//! Failures from `reqwest`, `std::io`, `serde` and `toml` carry text we did not
25//! write. [`ErrorDetail::Io`] and [`ErrorDetail::Internal`] translate the
26//! *operation* and leave any upstream detail on the `source` chain, untouched.
27//! Inventing a translation for someone else's sentence would be worse than
28//! leaving it be.
29
30use super::suggestion::Suggestion;
31use super::vocab::{
32    AllowlistStage, ContentKind, DestructiveEffect, InternalOp, IoCause, IoOp, Subject, ValueSource,
33};
34use crate::error::ErrorKind;
35
36/// Every failure the product can report, as data.
37///
38/// Construct errors through [`super::AppError::of`] so the [`ErrorKind`] and the
39/// English wire message are both derived from one place.
40#[derive(Debug, Clone, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum ErrorDetail {
43    // ── Generic domain shapes ────────────────────────────────────────────────
44    /// `subject` was empty or blank.
45    Empty {
46        /// What was empty.
47        subject: Subject,
48    },
49    /// `subject` was longer than `limit` characters.
50    TooLong {
51        /// What was too long.
52        subject: Subject,
53        /// Maximum accepted length in characters.
54        limit: usize,
55    },
56    /// `subject` did not satisfy its format rule.
57    Invalid {
58        /// What was invalid.
59        subject: Subject,
60        /// The offending value, echoed back so the caller can see it.
61        value: String,
62    },
63    /// `subject` contained control or invisible characters.
64    ControlCharacters {
65        /// What carried the characters.
66        subject: Subject,
67    },
68    /// `subject` must be printable ASCII only.
69    NotVisibleAscii {
70        /// What must be ASCII.
71        subject: Subject,
72    },
73    /// `subject` contained whitespace where none is allowed.
74    ContainsWhitespace {
75        /// What carried the whitespace.
76        subject: Subject,
77        /// The offending value.
78        value: String,
79    },
80    /// A duration knob was set to zero.
81    MustBeAtLeastOneSecond {
82        /// Which duration.
83        subject: Subject,
84        /// Layer the value came from (decides `invalid_input` vs `config`).
85        source: ValueSource,
86    },
87    /// A byte budget was raised above the product's hard ceiling.
88    AboveHardMaximum {
89        /// Which budget.
90        subject: Subject,
91        /// The ceiling that cannot be raised.
92        hard_max: u64,
93        /// Layer the value came from (decides `invalid_input` vs `config`).
94        source: ValueSource,
95    },
96
97    // ── Path and reference shapes ────────────────────────────────────────────
98    /// An item path yielded no usable segments.
99    ItemPathNoSegments,
100    /// A non-module item path ended without an item name.
101    ItemPathMissingItemName,
102    /// A crate reference carried more than one `@`.
103    CrateRefMultipleAt,
104    /// A crate reference had nothing before its `@`.
105    CrateRefEmptyName,
106    /// A crate reference had nothing after its `@`.
107    CrateRefEmptyVersion,
108    /// A version carried `+build` metadata, which docs.rs does not resolve.
109    VersionBuildMetadata,
110    /// A version was written with the `v` prefix.
111    VersionVPrefix,
112
113    // ── Enumerated argument values ───────────────────────────────────────────
114    /// `--match` received a value outside the accepted set.
115    UnknownMatchMode {
116        /// What was passed.
117        value: String,
118    },
119    /// A kind alias was not recognized.
120    UnknownItemType {
121        /// What was passed.
122        value: String,
123    },
124    /// `--lang` received an unsupported BCP-47 tag.
125    UnsupportedLang {
126        /// What was passed.
127        tag: String,
128    },
129    /// `schema --cmd` named a document that does not exist.
130    UnknownSchemaCommand {
131        /// What was passed.
132        value: String,
133    },
134    /// `--json` was combined with a human output format.
135    JsonFormatConflict,
136    /// Argv failed `clap` parsing.
137    ///
138    /// The text is `clap`'s own rendering, not ours, so it is carried verbatim
139    /// and not translated — inventing a pt-BR version of someone else's usage
140    /// help would drift from what `--help` actually prints.
141    ClapUsage {
142        /// `clap`'s rendered message.
143        message: String,
144    },
145    /// `--filter` could not be parsed.
146    InvalidFilterExpression {
147        /// The expression as written.
148        expr: String,
149        /// Why it was rejected.
150        reason: String,
151    },
152    /// `search-in-crate --item-type module` has no catalogue to read.
153    ModuleFilterUnsupported,
154    /// A destructive verb resolved its target from ambient state, not from argv.
155    ///
156    /// This is the confused-deputy shape: the caller names the verb, the
157    /// environment names the victim, and the two are never compared. Refusing
158    /// here costs one flag; not refusing costs whichever cache root the process
159    /// happened to resolve.
160    AmbientTargetRefused {
161        /// The invocation that was refused, in wire spelling.
162        verb: String,
163        /// The target the environment resolved, so the caller sees the victim.
164        target: String,
165        /// The flag that names the target in argv instead.
166        target_flag: String,
167        /// The flag that explicitly accepts the ambient target.
168        waiver_flag: String,
169        /// What would have happened to the target.
170        ///
171        /// Carried as data because the harm differs by verb: the first version
172        /// of this message said "would delete" for every caller, which was
173        /// simply false once a verb that overwrites started using it.
174        effect: DestructiveEffect,
175    },
176
177    // ── Pagination ───────────────────────────────────────────────────────────
178    /// `--page` was zero or absent where one is required.
179    PageBelowOne,
180    /// `--per-page` fell outside its accepted range.
181    PerPageOutOfRange {
182        /// Highest accepted value.
183        max: u32,
184        /// What was passed.
185        got: u32,
186    },
187
188    // ── Origins and configuration ────────────────────────────────────────────
189    /// An origin URL used a scheme other than http or https.
190    OriginBadScheme {
191        /// The scheme as written.
192        scheme: String,
193    },
194    /// An origin URL carried no host component.
195    OriginMissingHost {
196        /// The URL as written.
197        url: String,
198    },
199    /// An origin host was outside the SSRF allowlist.
200    OriginNotAllowlisted {
201        /// The rejected host.
202        host: String,
203        /// Comma-separated allowlist, so the operator sees the accepted set.
204        allowed: String,
205    },
206    /// An item path segment used characters outside the accepted set.
207    ItemPathSegmentCharset {
208        /// The offending segment.
209        segment: String,
210    },
211    /// `crate@version` and `--crate-version` disagreed.
212    ConflictingVersions {
213        /// Version taken from the `crate@version` sugar.
214        from_ref: String,
215        /// Version taken from the explicit flag.
216        from_flag: String,
217    },
218    /// The XDG config directory could not be resolved.
219    ConfigDirUnresolved,
220    /// The XDG cache directory could not be resolved.
221    CacheDirUnresolved,
222    /// `config.toml` failed to parse as TOML.
223    ConfigTomlInvalid,
224    /// `config.toml` was not valid UTF-8.
225    ConfigTomlNotUtf8,
226    /// `config init` found an existing file and `--force` was absent.
227    ConfigAlreadyExists {
228        /// Absolute path that would have been overwritten.
229        path: String,
230    },
231    /// `config.toml` was larger than the read cap.
232    ConfigTomlTooLarge {
233        /// The cap in bytes.
234        max_bytes: u64,
235    },
236    /// The configured User-Agent was rejected as an HTTP header value.
237    UserAgentHeaderInvalid,
238
239    // ── HTTP transport and budgets ───────────────────────────────────────────
240    /// A remote returned a status that maps to a domain failure.
241    HttpStatus {
242        /// The HTTP status code.
243        status: u16,
244        /// Short non-sensitive context label (endpoint name, never a body).
245        hint: String,
246    },
247    /// A request or redirect targeted a host outside the allowlist.
248    HostNotAllowlisted {
249        /// The rejected host.
250        host: String,
251        /// Which stage rejected it, so the operator knows where to look.
252        stage: AllowlistStage,
253    },
254    /// The transport failed before any status was seen.
255    ///
256    /// Carries its own [`ErrorKind`] because the classification comes from
257    /// `reqwest` (timeout vs connect vs body), not from the shape of the call.
258    HttpRequestFailed {
259        /// The URL that was being fetched.
260        url: String,
261        /// Classification supplied by the transport layer.
262        kind: ErrorKind,
263    },
264    /// The redirect chain went past `max_redirects`.
265    RedirectLimitExceeded,
266    /// Building the HTTP client failed.
267    HttpClientBuild,
268    /// Reading the response body failed mid-stream.
269    BodyRead,
270    /// The response body passed the configured byte budget.
271    BodyOverBudget {
272        /// The budget in bytes.
273        max_bytes: u64,
274    },
275    /// A cached body no longer fits the current byte budget.
276    CachedBodyOverBudget {
277        /// The budget in bytes.
278        max_bytes: u64,
279    },
280    /// Reserving body capacity failed (allocation refused).
281    BodyReserveFailed {
282        /// Bytes that could not be reserved.
283        bytes: usize,
284    },
285    /// The response body was not valid UTF-8.
286    BodyNotUtf8,
287    /// The response advertised a content type the endpoint cannot use.
288    UnexpectedContentType {
289        /// Flavour the caller required.
290        expected: ContentKind,
291        /// What the remote advertised.
292        got: String,
293    },
294    /// The emitted payload passed `max_output_bytes`.
295    OutputOverBudget,
296
297    // ── Docs.rs extraction ───────────────────────────────────────────────────
298    /// HTML could not be converted to Markdown.
299    HtmlToMarkdown,
300    /// crates.io returned JSON the parser rejected.
301    CratesIoJson,
302    /// No parent page existed for an associated item.
303    AssocParentPageNotFound,
304    /// The parent page was found but carried no anchor for the member.
305    ///
306    /// The rendered text must keep the sentinel prefix, since both the live
307    /// probe and the recovery path match on it to stop walking parent kinds.
308    AssocAnchorMissing {
309        /// Comma-separated anchor ids that were tried.
310        anchors: String,
311    },
312    /// The member anchor existed but its docblock was empty.
313    AssocAnchorEmpty {
314        /// The anchor id that was found.
315        anchor_id: String,
316    },
317    /// A member-only kind was requested without a parent to anchor against.
318    MemberKindNeedsParent {
319        /// The kind as the user typed it.
320        kind: &'static str,
321        /// The leaf they supplied, echoed into the suggested rewrite.
322        member: String,
323        /// Comma-separated parent kinds that can host this member.
324        parent_kinds: String,
325    },
326    /// A hit href could not be joined against its origin.
327    HitJoinFailed,
328    /// A hit's `source_url` was not a usable join base.
329    HitBaseInvalid,
330
331    // ── Cancellation and deadlines ───────────────────────────────────────────
332    /// SIGINT / Ctrl-C.
333    Interrupted,
334    /// SIGTERM.
335    Terminated,
336    /// stdout was closed by the reader.
337    BrokenPipe,
338    /// The wall-clock deadline elapsed.
339    WallClockTimeout {
340        /// Deadline in seconds.
341        secs: u64,
342    },
343
344    // ── Infrastructure ───────────────────────────────────────────────────────
345    /// A filesystem operation failed; the cause is on the source chain.
346    ///
347    /// Build this with [`Self::io`] rather than by hand: the constructor is what
348    /// classifies the OS cause while the [`std::io::Error`] is still available,
349    /// and a hand-written `cause` is a guess about a value the caller already had.
350    Io {
351        /// What was being attempted.
352        op: IoOp,
353        /// Path involved, when one is known and safe to show.
354        path: Option<String>,
355        /// Whether waiting could plausibly change the outcome.
356        cause: IoCause,
357    },
358    /// An internal invariant or host facility failed.
359    Internal {
360        /// What was being attempted.
361        op: InternalOp,
362    },
363
364    // ── Composition ──────────────────────────────────────────────────────────
365    /// Another failure, with ranked `--suggest` alternatives appended.
366    WithSuggestions {
367        /// The failure being explained.
368        base: Box<ErrorDetail>,
369        /// Ranked alternatives, best first.
370        suggestions: Vec<Suggestion>,
371    },
372}