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
62
63
64
65
66
67
68
69
70
71
use fast_walker::utils::to_unix_path;
use std::{
    error::Error,
    fmt::{Debug, Display, Formatter},
    path::Path,
};
mod from_std;
mod from_trash;
mod from_uuid;

pub type UnityResult<T> = Result<T, UnityError>;

#[derive(Clone)]
pub struct UnityError {
    kind: Box<UnityErrorKind>,
}

#[derive(Debug, Clone)]
pub enum UnityErrorKind {
    CustomError { message: String },
    SyntaxError { text: String, message: String },
    IOError { path: String, message: String },
}

impl Error for UnityError {}

impl Debug for UnityError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.kind, f)
    }
}

impl Display for UnityError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.kind, f)
    }
}

impl Display for UnityErrorKind {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            UnityErrorKind::CustomError { message } => {
                write!(f, "{}", message)
            }
            UnityErrorKind::IOError { path, message } => match path.as_str() {
                "" => write!(f, "{}", message),
                _ => write!(f, "{} at {}", message, path),
            },
            UnityErrorKind::SyntaxError { text, message } => {
                write!(f, "{} at {}", message, text)
            }
        }
    }
}

impl UnityError {
    pub fn custom_error<S>(message: S) -> Self
    where
        S: Into<String>,
    {
        Self { kind: Box::new(UnityErrorKind::CustomError { message: message.into() }) }
    }
    pub fn io_error<P, S>(path: P, message: S) -> Self
    where
        P: AsRef<Path>,
        S: Into<String>,
    {
        let path = to_unix_path(path.as_ref());
        Self { kind: Box::new(UnityErrorKind::IOError { path, message: message.into() }) }
    }
}