Skip to main content

fs_tree/
error.rs

1use std::{error, fmt, io, path::PathBuf};
2
3use file_type_enum::FileType;
4
5/// An alias for `Result<T, fs_tree::Error>`.
6pub type Result<T> = std::result::Result<T, Error>;
7
8/// An enum for all errors generated in the `fs-tree` crate.
9#[derive(Debug)]
10pub enum Error {
11    /// Expected directory, but file type differs.
12    NotADirectory(PathBuf),
13    /// Expected symlink, but file type differs.
14    NotASymlink(PathBuf),
15    /// Unsupported file type found.
16    UnexpectedFileType(FileType, PathBuf),
17    /// An error with reading or writing.
18    Io(io::Error),
19}
20
21use Error::*;
22
23impl Error {
24    /// The path related to this error, if any.
25    pub fn path(&self) -> Option<&PathBuf> {
26        match self {
27            NotADirectory(path) | NotASymlink(path) | UnexpectedFileType(_, path) => Some(path),
28            Io(..) => None,
29        }
30    }
31}
32
33impl error::Error for Error {
34    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
35        match self {
36            Io(source) => Some(source),
37            _ => None,
38        }
39    }
40}
41
42impl fmt::Display for Error {
43    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44        write!(f, "FsError: ")?;
45
46        match self {
47            NotADirectory(..) => write!(f, "not a directory"),
48            NotASymlink(..) => write!(f, "not a symlink"),
49            UnexpectedFileType(..) => write!(f, "unexpected file type"),
50            Io(inner) => inner.fmt(f),
51        }
52    }
53}
54
55impl From<io::Error> for Error {
56    fn from(err: io::Error) -> Self {
57        Error::Io(err)
58    }
59}