1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use std::{error, fmt, io, path::PathBuf, result};

pub type Result<T> = result::Result<T, FileStructureError>;

#[derive(Debug)]
pub enum FileStructureError {
    ReadError { source: io::Error },
    WriteError { source: io::Error },
    NotFoundError { path: PathBuf },
    NotADirectoryError { path: PathBuf },
    NotASymlinkError { path: PathBuf },
    IoError(io::Error),
}

use FileStructureError::*;

impl error::Error for FileStructureError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            ReadError { source } | WriteError { source } => Some(source),
            _ => None,
        }
    }
}

/// Ready for displaying errors to end users!
/// Format:
///     "error name: more details: more details"
impl fmt::Display for FileStructureError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ReadError { source } => {
                write!(f, "Read error: ")?;
                source.fmt(f)
            },
            WriteError { source } => {
                write!(f, "Write error: ")?;
                source.fmt(f)
            },
            NotFoundError { path } => {
                write!(f, "error: ")?;
                path.display().fmt(f)
            },
            NotADirectoryError { path } => {
                write!(f, "error: ")?;
                path.display().fmt(f)
            },
            NotASymlinkError { path } => {
                write!(f, "error: ")?;
                path.display().fmt(f)
            },
            IoError(err) => err.fmt(f), // NotFoundInFilesystem => write!(f, "File not found"),
        }
    }
}

impl From<io::Error> for FileStructureError {
    fn from(err: io::Error) -> Self {
        FileStructureError::IoError(err)
    }
}