use std::fmt;
use std::io;
use std::path::PathBuf;
use thiserror::Error;
pub type Result<T> = std::result::Result<T, MinixError>;
#[derive(Debug, Error)]
pub enum MinixError {
#[error("{message}{path_suffix}")]
Io {
path: Option<PathBuf>,
message: String,
#[source]
source: io::Error,
path_suffix: PathSuffix,
},
#[error("{0}")]
InvalidArgument(String),
#[error("invalid image path `{0}`")]
InvalidPath(String),
#[error("path component `{name}` exceeds the {max_bytes}-byte Minix name limit")]
NameTooLong {
name: String,
max_bytes: usize,
},
#[error("{0}")]
Unsupported(String),
#[error("{0}")]
Corrupt(String),
#[error("{0}")]
NotFound(String),
#[error("{0}")]
AlreadyExists(String),
#[error("{0}")]
NotDirectory(String),
#[error("{0}")]
IsDirectory(String),
#[error("{0}")]
DirectoryNotEmpty(String),
#[error("{0}")]
NoSpace(String),
#[error("invalid size `{value}`")]
InvalidSize {
value: String,
},
#[error("invalid mode `{value}`")]
InvalidMode {
value: String,
},
#[error("invalid entry spec `{spec}`: {message}")]
InvalidEntrySpec {
spec: String,
message: String,
},
#[error("")]
SilentFailure(i32),
}
#[derive(Clone, Debug)]
pub struct PathSuffix(pub String);
impl fmt::Display for PathSuffix {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl MinixError {
pub fn io(path: Option<PathBuf>, message: impl Into<String>, source: io::Error) -> Self {
let path_suffix = match &path {
Some(value) => PathSuffix(format!(" ({})", value.display())),
None => PathSuffix(String::new()),
};
Self::Io {
path,
message: message.into(),
source,
path_suffix,
}
}
pub fn exit_code(&self) -> i32 {
match self {
Self::SilentFailure(code) => *code,
Self::InvalidArgument(_)
| Self::InvalidPath(_)
| Self::NameTooLong { .. }
| Self::InvalidSize { .. }
| Self::InvalidMode { .. }
| Self::InvalidEntrySpec { .. } => 2,
_ => 1,
}
}
pub fn should_print(&self) -> bool {
!matches!(self, Self::SilentFailure(_))
}
}