Skip to main content

scrusted_yaml/
problem.rs

1//! Problems: what is wrong with a file, where (SPEC 5.3).
2
3use std::fmt;
4
5/// How bad a problem is.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
7#[serde(rename_all = "lowercase")]
8pub enum Severity {
9    /// The file does not load.
10    Error,
11    /// The file loads; with `strict`, it does not.
12    Warning,
13}
14
15impl fmt::Display for Severity {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        f.write_str(match self {
18            Severity::Error => "error",
19            Severity::Warning => "warning",
20        })
21    }
22}
23
24/// One thing wrong with a file: where it is, and what.
25#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
26pub struct Problem {
27    /// The name of the file.
28    pub file: String,
29    /// 1-based; 0 when the source was data, not text.
30    pub line: u32,
31    /// 1-based column.
32    pub column: u32,
33    /// The path of the key, as written: `stages.explore.when!`.
34    pub key: String,
35    /// What is wrong.
36    pub message: String,
37    /// Error or warning.
38    pub severity: Severity,
39}
40
41impl fmt::Display for Problem {
42    /// `file:line  key  message`, as scripted-yaml prints it.
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        let mut parts = Vec::with_capacity(3);
45        parts.push(if self.line > 0 { format!("{}:{}", self.file, self.line) } else { self.file.clone() });
46        if !self.key.is_empty() {
47            parts.push(self.key.clone());
48        }
49        if !self.message.is_empty() {
50            parts.push(self.message.clone());
51        }
52        f.write_str(&parts.join("  "))
53    }
54}
55
56/// A place a problem can point at.
57#[derive(Debug, Clone, PartialEq, Eq, Default)]
58pub struct Place {
59    /// The file.
60    pub file: String,
61    /// 1-based line, 0 for data.
62    pub line: u32,
63    /// 1-based column.
64    pub column: u32,
65    /// The path of the key.
66    pub key: String,
67}
68
69/// The problems of one validation or one resolve.
70#[derive(Debug, Clone, Default)]
71pub struct Problems {
72    /// In the order found; `sort` puts them in reading order.
73    pub list: Vec<Problem>,
74}
75
76impl Problems {
77    /// An error at a place.
78    pub fn error(&mut self, at: &Place, message: impl Into<String>) {
79        self.add(at, message, Severity::Error);
80    }
81
82    /// A warning at a place.
83    pub fn warning(&mut self, at: &Place, message: impl Into<String>) {
84        self.add(at, message, Severity::Warning);
85    }
86
87    /// A problem at a place.
88    pub fn add(&mut self, at: &Place, message: impl Into<String>, severity: Severity) {
89        self.list.push(Problem {
90            file: at.file.clone(),
91            line: at.line,
92            column: at.column,
93            key: at.key.clone(),
94            message: message.into(),
95            severity,
96        });
97    }
98
99    /// Reading order: file by file as first met, then by line.
100    pub fn sort(&mut self) {
101        let mut files: Vec<String> = Vec::new();
102        for p in &self.list {
103            if !files.contains(&p.file) {
104                files.push(p.file.clone());
105            }
106        }
107        self.list.sort_by_key(|p| (files.iter().position(|f| *f == p.file).unwrap_or(0), p.line));
108    }
109
110    /// Makes every warning an error.
111    pub fn strict(&mut self) {
112        for p in &mut self.list {
113            p.severity = Severity::Error;
114        }
115    }
116
117    /// True when there is an error.
118    pub fn failed(&self) -> bool {
119        self.list.iter().any(|p| p.severity == Severity::Error)
120    }
121}
122
123/// Joins the errors of a list of problems into one text, one per line.
124pub fn error_text(problems: &[Problem]) -> String {
125    problems.iter().filter(|p| p.severity == Severity::Error).map(|p| p.to_string()).collect::<Vec<_>>().join("\n")
126}