use std::fmt;
use std::process::ExitCode;
use tea_coding::CodingErrorCode;
const MAX_DIAGNOSTIC_BYTES: usize = 512;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ExitCategory {
Success = 0,
Usage = 2,
TrustOrConfig = 3,
Provider = 4,
PolicyDenied = 5,
Cancelled = 6,
Internal = 70,
}
impl ExitCategory {
#[must_use]
pub fn exit_code(self) -> ExitCode {
ExitCode::from(self as u8)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CliFailure {
category: ExitCategory,
message: String,
}
impl CliFailure {
#[must_use]
pub fn usage(message: impl Into<String>) -> Self {
Self::new(ExitCategory::Usage, message)
}
#[must_use]
pub fn new(category: ExitCategory, message: impl Into<String>) -> Self {
let mut message = message.into();
message.retain(|character| character != '\0' && character != '\r');
if message.is_empty() {
"tea operation failed".clone_into(&mut message);
}
if message.len() > MAX_DIAGNOSTIC_BYTES {
let boundary = message
.char_indices()
.map(|(index, _)| index)
.take_while(|index| *index <= MAX_DIAGNOSTIC_BYTES)
.last()
.unwrap_or(0);
message.truncate(boundary);
}
Self { category, message }
}
#[must_use]
pub const fn category(&self) -> ExitCategory {
self.category
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for CliFailure {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl std::error::Error for CliFailure {}
impl From<tea_coding::CodingError> for CliFailure {
fn from(error: tea_coding::CodingError) -> Self {
let category = match error.code() {
CodingErrorCode::InvalidInput
| CodingErrorCode::NotFound
| CodingErrorCode::ProjectNotTrusted => ExitCategory::TrustOrConfig,
CodingErrorCode::Credential | CodingErrorCode::Provider => ExitCategory::Provider,
CodingErrorCode::PolicyDenied => ExitCategory::PolicyDenied,
CodingErrorCode::Cancelled => ExitCategory::Cancelled,
CodingErrorCode::Persistence | CodingErrorCode::Runtime => ExitCategory::Internal,
};
Self::new(category, error.message())
}
}