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    NotADirectoryError(PathBuf),
13    /// Expected symlink, but file type differs.
14    NotASymlinkError(PathBuf),
15    /// Unsupported file type found.
16    UnexpectedFileTypeError(FileType, PathBuf),
17    /// An error with reading or writing.
18    IoError(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            NotADirectoryError(path)
28            | NotASymlinkError(path)
29            | UnexpectedFileTypeError(_, path) => Some(path),
30            IoError(..) => None,
31        }
32    }
33}
34
35impl error::Error for Error {
36    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
37        match self {
38            IoError(source) => Some(source),
39            _ => None,
40        }
41    }
42}
43
44impl fmt::Display for Error {
45    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46        write!(f, "FsError: ")?;
47
48        match self {
49            NotADirectoryError(..) => write!(f, "not a directory"),
50            NotASymlinkError(..) => write!(f, "not a symlink"),
51            UnexpectedFileTypeError(..) => write!(f, "unexpected file type"),
52            IoError(inner) => inner.fmt(f),
53        }
54    }
55}
56
57impl From<io::Error> for Error {
58    fn from(err: io::Error) -> Self {
59        Error::IoError(err)
60    }
61}