Skip to main content

tramlines_core/
finding.rs

1//! `Finding`, `Severity` and `Locator`: plain data that passes through
2//! the cache.
3
4use serde::{Deserialize, Serialize};
5
6use crate::RepoPath;
7
8// sokf-implements: CORE-8_AC-8
9// sokf:begin finding
10/// How a finding is reported.
11#[derive(
12    Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
13)]
14pub enum Severity {
15    /// A failure. Exit 1.
16    #[default]
17    Error,
18    /// What the validator cannot settle alone.
19    Warning,
20}
21// sokf:end finding
22
23// sokf:begin finding
24impl Severity {
25    /// How a finding line names the severity: `error` or `warning`.
26    pub fn as_str(self) -> &'static str {
27        // sokf:end finding
28        // sokf-implements: CORE-8_AC-10
29        match self {
30            Severity::Error => "error",
31            Severity::Warning => "warning",
32        }
33    }
34}
35
36// sokf:begin finding
37/// Where in a schema the rule that failed sits: the `id` of the schema,
38/// and the rule's `rule-id`, else its section and block position. A
39/// finding that a schema rule raises ends with it.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Locator {
42    /// The `id` of the schema.
43    pub schema: String,
44    /// Where the rule sits in the schema, when the check knows.
45    pub rule: Option<String>,
46}
47// sokf:end finding
48
49impl Locator {
50    /// The schema `id`, with no rule named.
51    pub fn schema(id: impl Into<String>) -> Locator {
52        Locator {
53            schema: id.into(),
54            rule: None,
55        }
56    }
57
58    /// The same schema, at the rule `at`.
59    #[must_use]
60    pub fn at(&self, at: impl Into<String>) -> Locator {
61        Locator {
62            schema: self.schema.clone(),
63            rule: Some(at.into()),
64        }
65    }
66
67    fn suffix(&self) -> String {
68        match &self.rule {
69            // sokf-implements: CORE-8_AC-2
70            None => format!("(schema {})", self.schema),
71            // The reader the finding sends to the schema lands in a
72            // schema of hundreds of lines; the locator says where.
73            // sokf-implements: CORE-8_AC-3
74            // sokf-implements: TL_73
75            Some(at) => format!("(schema {}, {at})", self.schema),
76        }
77    }
78}
79
80// Each finding names the criterion of its one fault, which the
81// specification keeps to one fault with one fix.
82// sokf-implements: TL_100
83// sokf:begin finding
84/// One line of the report.
85#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
86pub struct Finding {
87    /// The file the finding is on.
88    pub path: RepoPath,
89    /// The line, when one applies.
90    pub line: Option<usize>,
91    /// Error or warning.
92    pub severity: Severity,
93    /// The key of the criterion that the finding breaks, as `TLMD_57`.
94    pub criterion: String,
95    /// The message, ending with the location of its rule in the schema
96    /// when a schema rule raised it.
97    pub message: String,
98    /// The line in the schema of the rule that raised it, where the check
99    /// knows one: what a finding on the schema itself sits on when the
100    /// schema's own scaffold fails the rule. The report does not print it.
101    #[serde(skip)]
102    pub rule_line: Option<usize>,
103}
104// sokf:end finding
105
106impl Finding {
107    /// Build a finding that breaks `criterion`.
108    // sokf-implements: TL_72
109    // sokf-implements: CORE-8_AC-1
110    // sokf:begin finding
111    pub fn new(
112        path: RepoPath,
113        line: Option<usize>,
114        severity: Severity,
115        criterion: &str,
116        message: impl Into<String>,
117    ) -> Self {
118        // sokf:end finding
119        // sokf-implements: CORE-8_AC-9
120        debug_assert!(
121            is_criterion(criterion),
122            "`{criterion}` is not a criterion key"
123        );
124        Finding {
125            path,
126            line,
127            severity,
128            criterion: criterion.to_owned(),
129            message: message.into(),
130            rule_line: None,
131        }
132    }
133
134    /// An error finding.
135    // sokf-implements: CORE-8_AC-7
136    pub fn error(
137        path: RepoPath,
138        line: Option<usize>,
139        criterion: &str,
140        message: impl Into<String>,
141    ) -> Self {
142        Self::new(path, line, Severity::Error, criterion, message)
143    }
144
145    /// A warning finding.
146    // sokf-implements: CORE-8_AC-7
147    pub fn warning(
148        path: RepoPath,
149        line: Option<usize>,
150        criterion: &str,
151        message: impl Into<String>,
152    ) -> Self {
153        Self::new(path, line, Severity::Warning, criterion, message)
154    }
155
156    /// The finding, raised by the schema rule on line `line` of the
157    /// schema; a rule with no line of its own, at `0`, names none.
158    #[must_use]
159    pub fn of_rule(mut self, line: usize) -> Self {
160        self.rule_line = (line > 0).then_some(line);
161        self
162    }
163
164    /// The finding, with the location of the schema rule that raised it
165    /// appended to its message.
166    #[must_use]
167    pub fn at(mut self, locator: &Locator) -> Self {
168        self.message = format!("{} {}", self.message, locator.suffix());
169        self
170    }
171}
172
173/// Whether `key` has the form of a criterion key: upper-case words joined
174/// by `_`, an optional `-n` part, then `_n`, `_AC-n` or `_P-n`, as
175/// `TLMD_57`, `CLI-4_AC-5` or `SOKF_FORMAT_53`.
176fn is_criterion(key: &str) -> bool {
177    let Some((head, tail)) = key.rsplit_once('_') else {
178        return false;
179    };
180    let number = tail
181        .strip_prefix("AC-")
182        .or_else(|| tail.strip_prefix("P-"))
183        .unwrap_or(tail);
184    let (words, part) = head.split_once('-').unwrap_or((head, "1"));
185    !number.is_empty()
186        && number.bytes().all(|b| b.is_ascii_digit())
187        && !part.is_empty()
188        && part.bytes().all(|b| b.is_ascii_digit())
189        && words
190            .split('_')
191            .all(|w| !w.is_empty() && w.bytes().all(|b| b.is_ascii_uppercase()))
192}
193
194/// A failure found before the file it is on is known: the criterion it
195/// breaks, and what failed.
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct Problem {
198    /// The key of the criterion, as `TL_25`.
199    pub criterion: &'static str,
200    /// What failed.
201    pub message: String,
202}
203
204impl Problem {
205    /// A problem that breaks `criterion`.
206    pub fn new(criterion: &'static str, message: impl Into<String>) -> Self {
207        Problem {
208            criterion,
209            message: message.into(),
210        }
211    }
212
213    /// The problem, with `prefix` before its message.
214    #[must_use]
215    pub fn prefixed(mut self, prefix: &str) -> Self {
216        self.message = format!("{prefix}{}", self.message);
217        self
218    }
219
220    /// The problem as an error finding on `path` at `line`.
221    pub fn error(self, path: RepoPath, line: Option<usize>) -> Finding {
222        Finding::error(path, line, self.criterion, self.message)
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    fn p(s: &str) -> RepoPath {
231        RepoPath::parse(s).unwrap()
232    }
233
234    // sokf-tests: TL_72
235    // sokf-tests: TL_73
236    #[test]
237    fn a_finding_carries_its_criterion_and_its_rule() {
238        let f = Finding::error(p("/a.md"), Some(3), "TLMD_109", "bad");
239        assert_eq!(
240            (f.criterion.as_str(), f.message.as_str()),
241            ("TLMD_109", "bad")
242        );
243        assert_eq!(f.severity, Severity::Error);
244        let readme = Locator::schema("readme");
245        let f = Finding::warning(p("/a.md"), None, "TL_74", "bad").at(&readme);
246        assert_eq!(f.message, "bad (schema readme)");
247        assert_eq!(f.severity, Severity::Warning);
248        let f = Finding::error(p("/a.md"), None, "TL_74", "bad").at(&readme.at("section \"A\""));
249        assert_eq!(f.message, "bad (schema readme, section \"A\")");
250    }
251
252    #[test]
253    fn a_criterion_key_has_its_form() {
254        for key in [
255            "TL_1",
256            "TLMD_57",
257            "CLI-4_AC-5",
258            "CORE_P-2",
259            "SOKF_FORMAT_53",
260        ] {
261            assert!(is_criterion(key), "{key}");
262        }
263        for key in ["unit", "TL", "TL_", "tl_1", "CLI-4", "CLI-x_AC-1", "_1"] {
264            assert!(!is_criterion(key), "{key}");
265        }
266    }
267
268    proptest::proptest! {
269        // sokf-tests: CORE_P-5
270        #[test]
271        fn a_locator_ends_the_message(message in "[ -~]{0,40}", schema in "[a-z]{1,8}") {
272            let f = Finding::error(p("/a.md"), None, "TL_74", message.clone())
273                .at(&Locator::schema(schema.clone()));
274            proptest::prop_assert_eq!(f.criterion.as_str(), "TL_74");
275            proptest::prop_assert!(f.message.starts_with(&message));
276            let suffix = format!("(schema {schema})");
277            proptest::prop_assert!(f.message.ends_with(&suffix));
278        }
279    }
280
281    // sokf-tests: CORE_P-1
282    // sokf-tests: CORE-10_AC-2
283    #[test]
284    fn findings_round_trip_through_serde() {
285        let f = Finding::error(p("/a.md"), Some(3), "TL_53", "bad");
286        let json = serde_json::to_string(&f).unwrap();
287        let back: Finding = serde_json::from_str(&json).unwrap();
288        assert_eq!(back, f);
289    }
290}