use std::{fmt, io, process::ExitCode};
use webpkit::lossless::Error as CodecError;
#[derive(Debug)]
pub enum CliError {
Usage(String),
ReadInput {
label: String,
kind: io::ErrorKind,
},
WriteOutput {
label: String,
kind: io::ErrorKind,
},
Codec(CodecError),
Format(String),
RawConfig(String),
}
impl CliError {
#[must_use]
pub fn read_input(label: String, err: &io::Error) -> Self {
Self::ReadInput {
label,
kind: err.kind(),
}
}
#[must_use]
pub fn write_output(label: String, err: &io::Error) -> Self {
Self::WriteOutput {
label,
kind: err.kind(),
}
}
#[must_use]
pub fn exit_code(&self) -> ExitCode {
ExitCode::from(self.code())
}
const fn code(&self) -> u8 {
match self {
Self::Usage(_) => 2,
Self::ReadInput { .. } => 3,
Self::WriteOutput { .. } => 4,
Self::Format(_) => 9,
Self::RawConfig(_) => 8,
Self::Codec(err) => match err {
CodecError::UnsupportedFeature => 6,
CodecError::LimitExceeded { .. } => 7,
CodecError::InvalidDimensions | CodecError::PixelBufferMismatch => 8,
_ => 5,
},
}
}
}
impl fmt::Display for CliError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Usage(msg) | Self::Format(msg) | Self::RawConfig(msg) => f.write_str(msg),
Self::ReadInput { label, kind } => write!(f, "reading {label}: {kind}"),
Self::WriteOutput { label, kind } => write!(f, "writing {label}: {kind}"),
Self::Codec(err) => write!(f, "{err}"),
}
}
}
impl std::error::Error for CliError {}
impl From<CodecError> for CliError {
fn from(err: CodecError) -> Self {
Self::Codec(err)
}
}