1use std::fmt;
2use std::process::ExitCode;
3
4use tea_coding::CodingErrorCode;
5
6const MAX_DIAGNOSTIC_BYTES: usize = 512;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10#[repr(u8)]
11pub enum ExitCategory {
12 Success = 0,
14 Usage = 2,
16 TrustOrConfig = 3,
18 Provider = 4,
20 PolicyDenied = 5,
22 Cancelled = 6,
24 Internal = 70,
26}
27
28impl ExitCategory {
29 #[must_use]
31 pub fn exit_code(self) -> ExitCode {
32 ExitCode::from(self as u8)
33 }
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct CliFailure {
39 category: ExitCategory,
40 message: String,
41}
42
43impl CliFailure {
44 #[must_use]
46 pub fn usage(message: impl Into<String>) -> Self {
47 Self::new(ExitCategory::Usage, message)
48 }
49
50 #[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 #[must_use]
72 pub const fn category(&self) -> ExitCategory {
73 self.category
74 }
75
76 #[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}