Skip to main content

sweet_potator/recipe/
errors.rs

1use std::{
2    fmt,
3    path::{Path, PathBuf},
4};
5
6pub type ParseResult<T> = std::result::Result<T, ParseError>;
7
8#[derive(thiserror::Error, Debug)]
9pub struct ParseError {
10    message: String,
11    path: Option<PathBuf>,
12}
13
14impl fmt::Display for ParseError {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        if let Some(path) = &self.path {
17            let recipe_dir = path
18                .parent()
19                .and_then(Path::parent)
20                .expect("invalid recipe path");
21            write!(
22                f,
23                "invalid recipe format in file '{}': {}",
24                path.strip_prefix(recipe_dir).unwrap().to_string_lossy(),
25                self.message
26            )
27        } else {
28            write!(f, "invalid recipe format: {}", self.message)
29        }
30    }
31}
32
33impl ParseError {
34    pub fn empty(name: &str) -> Self {
35        format!("{name} must contain non-whitespace characters").into()
36    }
37
38    pub fn set_path(&mut self, path: &Path) {
39        self.path = Some(path.into());
40    }
41}
42
43impl From<&str> for ParseError {
44    fn from(message: &str) -> Self {
45        Self {
46            message: message.into(),
47            path: None,
48        }
49    }
50}
51
52impl From<String> for ParseError {
53    fn from(message: String) -> Self {
54        Self {
55            message,
56            path: None,
57        }
58    }
59}