use std::{borrow::Cow, fmt, io};
const GENERAL_ERROR: u8 = 1;
const TIMEOUT_ERROR: u8 = 2;
const REDIRECT_ERROR: u8 = 6;
pub(crate) type Result<T> = std::result::Result<T, Error>;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Kind {
General,
Timeout,
Redirect,
BrokenPipe,
}
pub(crate) struct Error {
kind: Kind,
message: Cow<'static, str>,
}
impl Error {
pub(crate) const fn usage(message: &'static str) -> Self {
Self {
kind: Kind::General,
message: Cow::Borrowed(message),
}
}
pub(crate) fn io(message: &'static str, error: &io::Error) -> Self {
if error.kind() == io::ErrorKind::BrokenPipe {
return Self {
kind: Kind::BrokenPipe,
message: Cow::Borrowed("output pipe closed"),
};
}
Self {
kind: Kind::General,
message: Cow::Borrowed(message),
}
}
pub(crate) const fn timeout() -> Self {
Self {
kind: Kind::Timeout,
message: Cow::Borrowed("request deadline exceeded"),
}
}
pub(crate) const fn redirect(message: &'static str) -> Self {
Self {
kind: Kind::Redirect,
message: Cow::Borrowed(message),
}
}
pub(crate) const fn exit_code(&self) -> u8 {
match self.kind {
Kind::General | Kind::BrokenPipe => GENERAL_ERROR,
Kind::Timeout => TIMEOUT_ERROR,
Kind::Redirect => REDIRECT_ERROR,
}
}
pub(crate) fn is_broken_pipe(&self) -> bool {
self.kind == Kind::BrokenPipe
}
}
impl From<tez::Error> for Error {
fn from(error: tez::Error) -> Self {
let kind = if error.is_timeout() {
Kind::Timeout
} else if error.is_redirect() {
Kind::Redirect
} else {
Kind::General
};
Self {
kind,
message: Cow::Owned(error.to_string()),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.message)
}
}
impl fmt::Debug for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Error")
.field("kind", &self.kind)
.field("message", &self.message)
.finish()
}
}
impl std::error::Error for Error {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn broken_pipe_is_quiet() {
let error = Error::io(
"response could not be written",
&io::Error::from(io::ErrorKind::BrokenPipe),
);
assert!(error.is_broken_pipe());
assert_eq!(error.exit_code(), GENERAL_ERROR);
}
}