use std::{error, fmt, io, path::PathBuf};
use file_type_enum::FileType;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
NotADirectory(PathBuf),
NotARegularFile(PathBuf),
NotASymlink(PathBuf),
SymlinkTargetMismatch {
path: PathBuf,
expected: PathBuf,
found: PathBuf,
},
UnexpectedFileType(FileType, PathBuf),
Io(io::Error),
}
use Error::*;
impl Error {
pub fn path(&self) -> Option<&PathBuf> {
match self {
NotADirectory(path)
| NotARegularFile(path)
| NotASymlink(path)
| SymlinkTargetMismatch { path, .. }
| UnexpectedFileType(_, path) => Some(path),
Io(..) => None,
}
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Io(source) => source.source(),
_ => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
NotADirectory(path) => write!(f, "not a directory: {}", path.display()),
NotARegularFile(path) => write!(f, "not a regular file: {}", path.display()),
NotASymlink(path) => write!(f, "not a symlink: {}", path.display()),
SymlinkTargetMismatch {
path,
expected,
found,
} => {
write!(
f,
"symlink target mismatch at {}: expected {}, found {}",
path.display(),
expected.display(),
found.display(),
)
},
UnexpectedFileType(file_type, path) => {
write!(
f,
"unexpected file type {:?}: {}",
file_type,
path.display(),
)
},
Io(inner) => inner.fmt(f),
}
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}