cli-engine 0.9.3

Rust CLI framework for consistent command modules
Documentation
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use std::borrow::Cow;

use thiserror::Error;

use crate::NextAction;

/// Crate-wide result type.
pub type Result<T> = std::result::Result<T, CliCoreError>;

/// Error trait for values that carry a process exit code.
pub trait ExitCoder {
    /// Returns the process-style exit code for the error.
    fn exit_code(&self) -> i32;
}

/// Error trait for values that carry structured output-envelope metadata.
pub trait DetailedError: std::error::Error {
    /// Stable error code.
    fn error_code(&self) -> Cow<'static, str>;
    /// Optional backend/system id.
    fn error_system(&self) -> Option<Cow<'static, str>>;
    /// Optional backend request id.
    fn error_request_id(&self) -> Option<Cow<'static, str>>;
    /// Optional recovery hint for the envelope's top-level `fix` (defaults to [`None`]).
    fn error_fix(&self) -> Option<Cow<'static, str>> {
        None
    }
    /// Structured follow-up actions for the envelope's `next_actions` (defaults to empty).
    fn error_next_actions(&self) -> Vec<NextAction> {
        Vec::new()
    }
}

/// Framework error type.
#[derive(Debug, Error)]
pub enum CliCoreError {
    /// Requested auth provider has not been registered.
    #[error("auth: no provider registered with name {0:?}")]
    MissingAuthProvider(String),
    /// Auth provider failed.
    #[error("auth: provider {provider:?}: {source}")]
    AuthProvider {
        /// Provider name.
        provider: String,
        /// Source error.
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },
    /// Output format is not supported.
    #[error("invalid output format {0:?}: must be one of toon, json, human")]
    InvalidOutputFormat(String),
    /// Plain message error.
    #[error("{0}")]
    Message(String),
    /// Structured message with explicit envelope metadata.
    #[error("{message}")]
    SystemMessage {
        /// Error message.
        message: String,
        /// Backend/system id.
        system: String,
        /// Stable error code.
        code: String,
        /// Optional request id.
        request_id: String,
    },
    /// Wrapped source error with backend/system attribution.
    #[error("{source}")]
    System {
        /// Backend/system id.
        system: String,
        /// Source error.
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },
    /// Wrapped source error with structured metadata captured up front.
    #[error("{source}")]
    Detailed {
        /// Stable error code.
        code: String,
        /// Backend/system id.
        system: String,
        /// Optional request id.
        request_id: String,
        /// Structured follow-up actions captured from the source's
        /// [`DetailedError::error_next_actions`] at wrap time — the source is
        /// erased to `Box<dyn Error>` immediately below, so this can't be
        /// recovered later by downcasting.
        next_actions: Vec<NextAction>,
        /// Source error.
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },
    /// Wrapped source error with explicit process exit code.
    #[error("{source}")]
    ExitCode {
        /// Process-style exit code.
        code: i32,
        /// Source error.
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },
    /// Wrapped source error with a recovery hint for the output envelope.
    #[error("{source}")]
    Fix {
        /// Recovery guidance shown as the envelope's top-level `fix`.
        fix: String,
        /// Source error.
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },
    /// IO error.
    #[error(transparent)]
    Io(#[from] std::io::Error),
    /// JSON serialization or decoding error.
    #[error(transparent)]
    Json(#[from] serde_json::Error),
    /// Structured HTTP transport error.
    #[error(transparent)]
    Transport(#[from] crate::transport::Error),
    /// An [`EnvConfig`](crate::env_config::EnvConfig) struct failed to
    /// assemble from its [`SourceChain`](crate::env_config::SourceChain).
    #[error(transparent)]
    EnvConfig(#[from] crate::env_config::EnvConfigError),
}

impl CliCoreError {
    /// Creates a plain message error.
    #[must_use]
    pub fn message(message: impl Into<String>) -> Self {
        Self::Message(message.into())
    }

    /// Creates a structured message attributed to a backend/system id.
    #[must_use]
    pub fn message_for_system(system: impl Into<String>, message: impl Into<String>) -> Self {
        Self::SystemMessage {
            message: message.into(),
            system: system.into(),
            code: "ERROR".to_owned(),
            request_id: String::new(),
        }
    }

    /// Wraps a source error with backend/system attribution.
    #[must_use]
    pub fn with_system(
        system: impl Into<String>,
        source: impl std::error::Error + Send + Sync + 'static,
    ) -> Self {
        Self::System {
            system: system.into(),
            source: Box::new(source),
        }
    }

    /// Wraps a source error with an explicit process exit code.
    #[must_use]
    pub fn with_exit_code(
        code: i32,
        source: impl std::error::Error + Send + Sync + 'static,
    ) -> Self {
        Self::ExitCode {
            code,
            source: Box::new(source),
        }
    }

    /// Wraps a source error with a recovery hint for the output envelope.
    ///
    /// Empty hints do not wrap: a [`CliCoreError`] source is returned as-is.
    #[must_use]
    pub fn with_fix(
        fix: impl Into<String>,
        source: impl std::error::Error + Send + Sync + 'static,
    ) -> Self {
        let fix = fix.into();
        if fix.is_empty() {
            let source: Box<dyn std::error::Error + Send + Sync> = Box::new(source);
            return match source.downcast::<Self>() {
                Ok(inner) => *inner,
                Err(source) => Self::Message(source.to_string()),
            };
        }
        Self::Fix {
            fix,
            source: Box::new(source),
        }
    }

    /// Captures structured metadata from a detailed source error.
    #[must_use]
    pub fn with_detailed_error(source: impl DetailedError + Send + Sync + 'static) -> Self {
        let code = source.error_code().into_owned();
        let system = source
            .error_system()
            .map_or_else(String::new, Cow::into_owned);
        let request_id = source
            .error_request_id()
            .map_or_else(String::new, Cow::into_owned);
        let fix = source.error_fix().map_or_else(String::new, Cow::into_owned);
        let next_actions = source.error_next_actions();
        Self::with_fix(
            fix,
            Self::Detailed {
                code,
                system,
                request_id,
                next_actions,
                source: Box::new(source),
            },
        )
    }

    /// Reports whether this error originates from credential resolution.
    ///
    /// True for [`MissingAuthProvider`](Self::MissingAuthProvider) and
    /// [`AuthProvider`](Self::AuthProvider), including when those variants are
    /// wrapped by [`Fix`](Self::Fix) or [`ExitCode`](Self::ExitCode). The engine
    /// uses this to classify a command outcome as `auth-error` rather than a
    /// generic command error, based on the error a handler actually returns — so
    /// a handler that swallows a resolution failure and then fails for another
    /// reason is not misclassified.
    #[must_use]
    pub fn is_auth(&self) -> bool {
        match self {
            Self::MissingAuthProvider(_) | Self::AuthProvider { .. } => true,
            Self::ExitCode { source, .. } | Self::Fix { source, .. } => {
                source.downcast_ref::<Self>().is_some_and(Self::is_auth)
            }
            _ => false,
        }
    }

    /// Returns backend/system attribution when the error carries one.
    ///
    /// [`Fix`](Self::Fix) / [`ExitCode`](Self::ExitCode) wrappers delegate to their source.
    #[must_use]
    pub fn system(&self) -> Option<&str> {
        match self {
            Self::SystemMessage { system, .. }
            | Self::System { system, .. }
            | Self::Detailed { system, .. }
                if !system.is_empty() =>
            {
                Some(system)
            }
            Self::ExitCode { source, .. } | Self::Fix { source, .. } => {
                source.downcast_ref::<Self>().and_then(Self::system)
            }
            Self::MissingAuthProvider(_)
            | Self::AuthProvider { .. }
            | Self::InvalidOutputFormat(_)
            | Self::Message(_)
            | Self::SystemMessage { .. }
            | Self::System { .. }
            | Self::Detailed { .. }
            | Self::Io(_)
            | Self::Json(_)
            | Self::Transport(_)
            | Self::EnvConfig(_) => None,
        }
    }
}

impl ExitCoder for CliCoreError {
    fn exit_code(&self) -> i32 {
        exit_code_for_error(self)
    }
}

/// Returns the exit code carried by an [`ExitCoder`].
#[must_use]
pub fn exit_code_for_exit_coder(err: &dyn ExitCoder) -> i32 {
    err.exit_code()
}

/// Maps an error chain to the framework's process-style exit code.
#[must_use]
pub fn exit_code_for_error(err: &(dyn std::error::Error + 'static)) -> i32 {
    let mut current = Some(err);
    while let Some(error) = current {
        if let Some(CliCoreError::ExitCode { code, .. }) = error.downcast_ref::<CliCoreError>() {
            return *code;
        }
        current = error.source();
    }

    let mut current = Some(err);
    while let Some(error) = current {
        if let Some(cli_err) = error.downcast_ref::<CliCoreError>() {
            match cli_err {
                CliCoreError::MissingAuthProvider(_) | CliCoreError::AuthProvider { .. } => {
                    return 2;
                }
                CliCoreError::InvalidOutputFormat(_) => return 3,
                CliCoreError::System { .. }
                | CliCoreError::Detailed { .. }
                | CliCoreError::ExitCode { .. }
                | CliCoreError::Fix { .. }
                | CliCoreError::Message(_)
                | CliCoreError::SystemMessage { .. }
                | CliCoreError::Io(_)
                | CliCoreError::Json(_)
                | CliCoreError::Transport(_)
                | CliCoreError::EnvConfig(_) => {}
            }
        }
        current = error.source();
    }

    let msg = err.to_string().to_lowercase();
    if msg.contains("auth") {
        2
    } else if msg.contains("validation") || msg.contains("invalid") {
        3
    } else if msg.contains("not found") {
        4
    } else if msg.contains("permission") || msg.contains("forbidden") {
        5
    } else if msg.contains("denied") {
        6
    } else {
        1
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn system_walks_through_fix_and_exit_code_wrappers() {
        let err = CliCoreError::with_exit_code(
            2,
            CliCoreError::with_fix(
                "Run auth login",
                CliCoreError::message_for_system("auth", "not logged in"),
            ),
        );
        assert_eq!(err.system(), Some("auth"));
    }

    #[test]
    fn with_detailed_error_fix_preserves_system() {
        #[derive(Debug, thiserror::Error)]
        #[error("not logged in")]
        struct AuthRequired;

        impl DetailedError for AuthRequired {
            fn error_code(&self) -> Cow<'static, str> {
                Cow::Borrowed("AUTH_REQUIRED")
            }

            fn error_system(&self) -> Option<Cow<'static, str>> {
                Some(Cow::Borrowed("auth"))
            }

            fn error_request_id(&self) -> Option<Cow<'static, str>> {
                None
            }

            fn error_fix(&self) -> Option<Cow<'static, str>> {
                Some(Cow::Borrowed("Run auth login"))
            }
        }

        let err = CliCoreError::with_detailed_error(AuthRequired);
        assert!(matches!(err, CliCoreError::Fix { .. }));
        assert_eq!(err.system(), Some("auth"));
    }

    #[test]
    fn with_detailed_error_captures_next_actions_before_erasure() {
        #[derive(Debug, thiserror::Error)]
        #[error("'/businesses' matches 2 operations")]
        struct Ambiguous;

        impl DetailedError for Ambiguous {
            fn error_code(&self) -> Cow<'static, str> {
                Cow::Borrowed("AMBIGUOUS_MATCH")
            }

            fn error_system(&self) -> Option<Cow<'static, str>> {
                None
            }

            fn error_request_id(&self) -> Option<Cow<'static, str>> {
                None
            }

            fn error_next_actions(&self) -> Vec<NextAction> {
                vec![NextAction::new(
                    "api operation get /businesses --method GET",
                    "Get all businesses",
                )]
            }
        }

        let err = CliCoreError::with_detailed_error(Ambiguous);
        assert!(matches!(err, CliCoreError::Detailed { .. }));
        let CliCoreError::Detailed { next_actions, .. } = &err else {
            unreachable!("just asserted this is Detailed");
        };
        assert_eq!(next_actions.len(), 1);
        assert_eq!(
            next_actions[0].command,
            "api operation get /businesses --method GET"
        );
    }

    #[test]
    fn empty_with_fix_does_not_wrap() {
        let inner = CliCoreError::message_for_system("auth", "not logged in");
        let err = CliCoreError::with_fix("", inner);
        assert!(matches!(err, CliCoreError::SystemMessage { .. }));
        assert_eq!(err.system(), Some("auth"));
        assert!(!matches!(err, CliCoreError::Fix { .. }));
    }

    #[test]
    fn is_auth_walks_through_fix_and_exit_code_wrappers() {
        let err = CliCoreError::with_exit_code(
            2,
            CliCoreError::with_fix(
                "Run auth login",
                CliCoreError::MissingAuthProvider("primary".to_owned()),
            ),
        );
        assert!(err.is_auth());
        assert!(!CliCoreError::with_fix("hint", CliCoreError::message("boom")).is_auth());
    }
}