Skip to main content

weavatrix_rust/model/
error.rs

1use std::fmt::{Display, Formatter};
2use std::path::PathBuf;
3
4#[derive(Debug)]
5pub enum Error {
6    Io {
7        path: PathBuf,
8        source: std::io::Error,
9    },
10    InvalidRepository(PathBuf),
11    Parse {
12        language: &'static str,
13        path: String,
14        message: String,
15    },
16    Graph(weavatrix_graph::GraphError),
17    Json(blazingly_json::Error),
18    Scan(weavatrix_scan::Error),
19    Analysis(String),
20}
21
22impl Error {
23    pub(crate) fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
24        Self::Io {
25            path: path.into(),
26            source,
27        }
28    }
29}
30
31impl Display for Error {
32    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
33        match self {
34            Self::Io { path, source } => {
35                write!(formatter, "I/O error at {}: {source}", path.display())
36            }
37            Self::InvalidRepository(path) => {
38                write!(
39                    formatter,
40                    "repository root is not a readable directory: {}",
41                    path.display()
42                )
43            }
44            Self::Parse {
45                language,
46                path,
47                message,
48            } => write!(formatter, "{language} parse failed for {path}: {message}"),
49            Self::Graph(source) => write!(formatter, "invalid graph: {source}"),
50            Self::Json(source) => write!(formatter, "JSON serialization failed: {source}"),
51            Self::Scan(source) => write!(formatter, "repository scan failed: {source}"),
52            Self::Analysis(message) => write!(formatter, "repository analysis failed: {message}"),
53        }
54    }
55}
56
57impl std::error::Error for Error {
58    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
59        match self {
60            Self::Io { source, .. } => Some(source),
61            Self::Graph(source) => Some(source),
62            Self::Json(source) => Some(source),
63            Self::Scan(source) => Some(source),
64            _ => None,
65        }
66    }
67}
68
69impl From<blazingly_json::Error> for Error {
70    fn from(value: blazingly_json::Error) -> Self {
71        Self::Json(value)
72    }
73}
74
75impl From<weavatrix_graph::GraphError> for Error {
76    fn from(value: weavatrix_graph::GraphError) -> Self {
77        Self::Graph(value)
78    }
79}
80
81impl From<weavatrix_scan::Error> for Error {
82    fn from(value: weavatrix_scan::Error) -> Self {
83        Self::Scan(value)
84    }
85}
86
87pub type Result<T> = std::result::Result<T, Error>;