1use serde::{Deserialize, Serialize};
5
6use crate::RepoPath;
7
8#[derive(
12 Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
13)]
14pub enum Severity {
15 #[default]
17 Error,
18 Warning,
20}
21impl Severity {
25 pub fn as_str(self) -> &'static str {
27 match self {
30 Severity::Error => "error",
31 Severity::Warning => "warning",
32 }
33 }
34}
35
36#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Locator {
42 pub schema: String,
44 pub rule: Option<String>,
46}
47impl Locator {
50 pub fn schema(id: impl Into<String>) -> Locator {
52 Locator {
53 schema: id.into(),
54 rule: None,
55 }
56 }
57
58 #[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 None => format!("(schema {})", self.schema),
71 Some(at) => format!("(schema {}, {at})", self.schema),
76 }
77 }
78}
79
80#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
86pub struct Finding {
87 pub path: RepoPath,
89 pub line: Option<usize>,
91 pub severity: Severity,
93 pub criterion: String,
95 pub message: String,
98 #[serde(skip)]
102 pub rule_line: Option<usize>,
103}
104impl Finding {
107 pub fn new(
112 path: RepoPath,
113 line: Option<usize>,
114 severity: Severity,
115 criterion: &str,
116 message: impl Into<String>,
117 ) -> Self {
118 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 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 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 #[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 #[must_use]
167 pub fn at(mut self, locator: &Locator) -> Self {
168 self.message = format!("{} {}", self.message, locator.suffix());
169 self
170 }
171}
172
173fn 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#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct Problem {
198 pub criterion: &'static str,
200 pub message: String,
202}
203
204impl Problem {
205 pub fn new(criterion: &'static str, message: impl Into<String>) -> Self {
207 Problem {
208 criterion,
209 message: message.into(),
210 }
211 }
212
213 #[must_use]
215 pub fn prefixed(mut self, prefix: &str) -> Self {
216 self.message = format!("{prefix}{}", self.message);
217 self
218 }
219
220 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 #[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 #[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 #[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}