spec_driven_docs/domain/
finding.rs1use std::fmt;
9
10use camino::Utf8PathBuf;
11
12use crate::domain::rule_id::RuleId;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct Finding {
17 pub rule: RuleId,
19 pub path: Option<Utf8PathBuf>,
21 pub line: Option<usize>,
23 pub detail: String,
25}
26
27impl Finding {
28 #[must_use]
30 pub fn on_file(rule: RuleId, path: impl Into<Utf8PathBuf>, detail: impl Into<String>) -> Self {
31 Self {
32 rule,
33 path: Some(path.into()),
34 line: None,
35 detail: detail.into(),
36 }
37 }
38
39 #[must_use]
41 pub fn on_line(
42 rule: RuleId,
43 path: impl Into<Utf8PathBuf>,
44 line: usize,
45 detail: impl Into<String>,
46 ) -> Self {
47 Self {
48 rule,
49 path: Some(path.into()),
50 line: Some(line),
51 detail: detail.into(),
52 }
53 }
54
55 #[must_use]
57 pub fn global(rule: RuleId, detail: impl Into<String>) -> Self {
58 Self {
59 rule,
60 path: None,
61 line: None,
62 detail: detail.into(),
63 }
64 }
65}
66
67impl Finding {
68 #[must_use]
71 pub fn as_warning(&self) -> String {
72 let line = self.to_string();
73 line.strip_prefix("FAIL")
74 .map_or_else(|| line.clone(), |rest| format!("WARN{rest}"))
75 }
76}
77
78impl fmt::Display for Finding {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 write!(f, "FAIL {}", self.rule)?;
81 if let Some(path) = &self.path {
82 write!(f, " {path}")?;
83 if let Some(line) = self.line {
84 write!(f, ":{line}")?;
85 }
86 }
87 if self.detail.is_empty() {
88 return Ok(());
89 }
90 write!(f, ": {}", self.detail)
91 }
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97
98 #[test]
99 fn renders_with_path_and_line() {
100 let finding = Finding::on_line(
101 RuleId::BugzillaReportBodyFitsReportWidth,
102 "_docs/reference/known-issues/KI-vendor-500.md",
103 12,
104 "83 columns",
105 );
106 assert_eq!(
107 finding.to_string(),
108 "FAIL known-issues:a-bugzilla-report-body-fits-in-79-columns \
109 _docs/reference/known-issues/KI-vendor-500.md:12: 83 columns"
110 );
111 }
112
113 #[test]
114 fn renders_without_a_path() {
115 let finding = Finding::global(
116 RuleId::GateMessageCitesTheRule,
117 "x:y resolves to no requirement",
118 );
119 assert_eq!(
120 finding.to_string(),
121 "FAIL spec-to-code:a-gate-message-cites-the-rule: x:y resolves to no requirement"
122 );
123 }
124}