use crate::StoragePath;
use crate::{Operation, Reason};
use std::fmt::{Display, Formatter};
use std::io;
use std::io::ErrorKind;
use std::path::Path;
#[derive(Debug)]
pub struct Error {
path: StoragePath,
operation: Operation,
reason: Reason,
source: Option<io::Error>,
}
impl Error {
pub fn new<P>(path: P, operation: Operation, reason: Reason) -> Self
where
P: Into<StoragePath>,
{
let path: StoragePath = path.into();
Self {
path,
operation,
reason,
source: None,
}
}
pub fn from_source<P, E>(path: P, operation: Operation, source: E) -> Self
where
P: Into<StoragePath>,
E: Into<io::Error>,
{
let path: StoragePath = path.into();
Self {
path,
operation,
reason: Reason::Other,
source: Some(source.into()),
}
}
pub fn from_message<P, S>(path: P, operation: Operation, message: S) -> Self
where
P: Into<StoragePath>,
S: Into<String>,
{
Error::from_source(path, operation, io::Error::other(message.into()))
}
}
impl Error {
pub fn unknown_file_system(path: &str) -> io::Error {
io::Error::other(format!("unknown file system for path: {}", path))
}
pub fn path_not_utf8(path: &Path) -> io::Error {
io::Error::new(
ErrorKind::InvalidInput,
format!("path not utf-8: {:?}", path),
)
}
}
impl Error {
pub fn path(&self) -> &StoragePath {
&self.path
}
pub fn export_path(self) -> StoragePath {
self.path
}
pub fn operation(&self) -> Operation {
self.operation
}
pub fn reason(&self) -> Reason {
self.reason
}
pub fn io_source(&self) -> Option<&io::Error> {
self.source.as_ref()
}
}
impl From<Error> for io::Error {
fn from(error: Error) -> Self {
let kind: ErrorKind = match error.reason() {
Reason::UnknownFileSystem => ErrorKind::Unsupported,
Reason::UnsupportedOperation => ErrorKind::Unsupported,
Reason::FileNotFound => ErrorKind::NotFound,
Reason::FileAlreadyExists => ErrorKind::AlreadyExists,
Reason::FileContentNotUTF8 => ErrorKind::InvalidData,
Reason::InvalidPath => ErrorKind::InvalidInput,
Reason::Other => ErrorKind::Other,
};
Self::new(kind, error)
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let file_or_folder: &str = if self.path.is_file() {
"file"
} else {
"folder"
};
write!(
f,
"{} error: op={} path={}",
file_or_folder, self.operation, self.path
)?;
if let Some(source) = self.io_source() {
write!(f, " source={}", source)?;
} else {
write!(f, " reason={}", self.reason)?;
}
Ok(())
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_ref().map(|e| e as &(dyn std::error::Error + 'static))
}
}