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
use std::error;
use std::fmt::{self, Formatter};
use std::path::{Path, PathBuf};

use crate::docfs::PathError;

#[derive(Debug)]
pub(crate) struct Error {
    pub(crate) file: PathBuf,
    pub(crate) error: String,
}

impl error::Error for Error {}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let file = self.file.display().to_string();
        if file.is_empty() {
            write!(f, "{}", self.error)
        } else {
            write!(f, "\"{}\": {}", self.file.display(), self.error)
        }
    }
}

impl PathError for Error {
    fn new<S, P: AsRef<Path>>(e: S, path: P) -> Error
    where
        S: ToString + Sized,
    {
        Error { file: path.as_ref().to_path_buf(), error: e.to_string() }
    }
}

#[macro_export]
macro_rules! try_none {
    ($e:expr, $file:expr) => {{
        use std::io;
        match $e {
            Some(e) => e,
            None => {
                return Err(<crate::error::Error as crate::docfs::PathError>::new(
                    io::Error::new(io::ErrorKind::Other, "not found"),
                    $file,
                ));
            }
        }
    }};
}

#[macro_export]
macro_rules! try_err {
    ($e:expr, $file:expr) => {{
        match $e {
            Ok(e) => e,
            Err(e) => return Err(Error::new(e, $file)),
        }
    }};
}