| 1 | use std::error::Error; |
| 2 | use std::fmt; |
| 3 | use std::path::PathBuf; |
| 4 | |
| 5 | use miette::Diagnostic; |
| 6 | |
| 7 | #[derive(Debug)] |
| 8 | pub struct ConfigParseResult<T, E> { |
| 9 | pub config: Result<T, E>, |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | pub includes: Vec<PathBuf>, |
| 20 | } |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | #[derive(Debug)] |
| 26 | pub struct ConfigIncludeError { |
| 27 | pub main: knuffel::Error, |
| 28 | pub includes: Vec<knuffel::Error>, |
| 29 | } |
| 30 | |
| 31 | impl<T, E> ConfigParseResult<T, E> { |
| 32 | pub fn from_err(err: E) -> Self { |
| 33 | Self { |
| 34 | config: Err(err), |
| 35 | includes: Vec::new(), |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | pub fn map_config_res<U, V>( |
| 40 | self, |
| 41 | f: impl FnOnce(Result<T, E>) -> Result<U, V>, |
| 42 | ) -> ConfigParseResult<U, V> { |
| 43 | ConfigParseResult { |
| 44 | config: f(self.config), |
| 45 | includes: self.includes, |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl fmt::Display for ConfigIncludeError { |
| 51 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 52 | fmt::Display::fmt(&self.main, f) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | impl Error for ConfigIncludeError { |
| 57 | fn source(&self) -> Option<&(dyn Error + 'static)> { |
| 58 | self.main.source() |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | impl Diagnostic for ConfigIncludeError { |
| 63 | fn code<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> { |
| 64 | self.main.code() |
| 65 | } |
| 66 | |
| 67 | fn severity(&self) -> Option<miette::Severity> { |
| 68 | self.main.severity() |
| 69 | } |
| 70 | |
| 71 | fn help<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> { |
| 72 | self.main.help() |
| 73 | } |
| 74 | |
| 75 | fn url<'a>(&'a self) -> Option<Box<dyn fmt::Display + 'a>> { |
| 76 | self.main.url() |
| 77 | } |
| 78 | |
| 79 | fn source_code(&self) -> Option<&dyn miette::SourceCode> { |
| 80 | self.main.source_code() |
| 81 | } |
| 82 | |
| 83 | fn labels(&self) -> Option<Box<dyn Iterator<Item = miette::LabeledSpan> + '_>> { |
| 84 | self.main.labels() |
| 85 | } |
| 86 | |
| 87 | fn diagnostic_source(&self) -> Option<&dyn Diagnostic> { |
| 88 | self.main.diagnostic_source() |
| 89 | } |
| 90 | |
| 91 | fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a>> { |
| 92 | let main_related = self.main.related(); |
| 93 | let includes_iter = self.includes.iter().map(|err| err as &'a dyn Diagnostic); |
| 94 | |
| 95 | let iter: Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a> = match main_related { |
| 96 | Some(main) => Box::new(main.chain(includes_iter)), |
| 97 | None => Box::new(includes_iter), |
| 98 | }; |
| 99 | |
| 100 | Some(iter) |
| 101 | } |
| 102 | } |