Skip to main content

tea_cli/
exit.rs

1use std::fmt;
2use std::process::ExitCode;
3
4use tea_coding::CodingErrorCode;
5
6const MAX_DIAGNOSTIC_BYTES: usize = 512;
7
8/// Stable CLI process exit categories.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10#[repr(u8)]
11pub enum ExitCategory {
12    /// Successful completion.
13    Success = 0,
14    /// Invalid command line or prompt input.
15    Usage = 2,
16    /// Configuration, state path, or project trust failure.
17    TrustOrConfig = 3,
18    /// Provider credentials, transport, or model failure.
19    Provider = 4,
20    /// Policy denial or unresolved approval.
21    PolicyDenied = 5,
22    /// User-requested cancellation.
23    Cancelled = 6,
24    /// Unexpected internal/persistence failure.
25    Internal = 70,
26}
27
28impl ExitCategory {
29    /// Returns the stable process exit code.
30    #[must_use]
31    pub fn exit_code(self) -> ExitCode {
32        ExitCode::from(self as u8)
33    }
34}
35
36/// Bounded secret-independent CLI failure.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct CliFailure {
39    category: ExitCategory,
40    message: String,
41}
42
43impl CliFailure {
44    /// Creates a usage failure.
45    #[must_use]
46    pub fn usage(message: impl Into<String>) -> Self {
47        Self::new(ExitCategory::Usage, message)
48    }
49
50    /// Creates a bounded failure in one stable category.
51    #[must_use]
52    pub fn new(category: ExitCategory, message: impl Into<String>) -> Self {
53        let mut message = message.into();
54        message.retain(|character| character != '\0' && character != '\r');
55        if message.is_empty() {
56            "tea operation failed".clone_into(&mut message);
57        }
58        if message.len() > MAX_DIAGNOSTIC_BYTES {
59            let boundary = message
60                .char_indices()
61                .map(|(index, _)| index)
62                .take_while(|index| *index <= MAX_DIAGNOSTIC_BYTES)
63                .last()
64                .unwrap_or(0);
65            message.truncate(boundary);
66        }
67        Self { category, message }
68    }
69
70    /// Returns the stable category.
71    #[must_use]
72    pub const fn category(&self) -> ExitCategory {
73        self.category
74    }
75
76    /// Returns the bounded diagnostic text.
77    #[must_use]
78    pub fn message(&self) -> &str {
79        &self.message
80    }
81}
82
83impl fmt::Display for CliFailure {
84    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
85        formatter.write_str(&self.message)
86    }
87}
88
89impl std::error::Error for CliFailure {}
90
91impl From<tea_coding::CodingError> for CliFailure {
92    fn from(error: tea_coding::CodingError) -> Self {
93        let category = match error.code() {
94            CodingErrorCode::InvalidInput
95            | CodingErrorCode::NotFound
96            | CodingErrorCode::ProjectNotTrusted => ExitCategory::TrustOrConfig,
97            CodingErrorCode::Credential | CodingErrorCode::Provider => ExitCategory::Provider,
98            CodingErrorCode::PolicyDenied => ExitCategory::PolicyDenied,
99            CodingErrorCode::Cancelled => ExitCategory::Cancelled,
100            CodingErrorCode::Persistence | CodingErrorCode::Runtime => ExitCategory::Internal,
101        };
102        Self::new(category, error.message())
103    }
104}