1use std::collections::BTreeMap;
2use std::fmt;
3
4use codeint_model::SourceSet;
5use serde::{Deserialize, Serialize};
6
7use crate::baseline::{Baseline, BaselineEntry};
8use crate::finding_anchor::match_anchors_with_renames;
9use crate::ratchet::{Ratchet, RatchetEntry, round_ratchet_ratio};
10
11#[cfg(test)]
12mod tests;
13
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
15#[serde(tag = "kind", rename_all = "snake_case")]
16pub enum StateCheckViolation {
17 RatchetFileDeleted {
18 path: String,
19 },
20 RatchetEntryRemoved {
21 #[serde(default, skip_serializing_if = "Option::is_none")]
22 source_set: Option<String>,
23 metric: String,
24 base_ceiling: f64,
25 metric_version: u32,
26 },
27 RatchetCeilingRaised {
28 #[serde(default, skip_serializing_if = "Option::is_none")]
29 source_set: Option<String>,
30 metric: String,
31 base_ceiling: f64,
32 head_ceiling: f64,
33 metric_version: u32,
34 },
35 BaselineFindingsAdded {
36 #[serde(default, skip_serializing_if = "Option::is_none")]
37 source_set: Option<String>,
38 metric: String,
39 base_count: usize,
40 head_count: usize,
41 added_count: usize,
42 added_ids: Vec<String>,
43 metric_version: u32,
44 },
45}
46
47impl StateCheckViolation {
48 pub fn metric_label(&self) -> Option<String> {
49 match self {
50 StateCheckViolation::RatchetFileDeleted { .. } => None,
51 StateCheckViolation::RatchetEntryRemoved {
52 source_set, metric, ..
53 }
54 | StateCheckViolation::RatchetCeilingRaised {
55 source_set, metric, ..
56 }
57 | StateCheckViolation::BaselineFindingsAdded {
58 source_set, metric, ..
59 } => Some(format_metric_label(source_set.as_deref(), metric)),
60 }
61 }
62}
63
64impl fmt::Display for StateCheckViolation {
65 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
66 match self {
67 StateCheckViolation::RatchetFileDeleted { path } => {
68 write!(formatter, "Ratchet file {path} was deleted")
69 }
70 StateCheckViolation::RatchetEntryRemoved {
71 source_set,
72 metric,
73 base_ceiling,
74 metric_version,
75 } => write!(
76 formatter,
77 "Ratchet entry {} (ceiling {base_ceiling}, Metric version {metric_version}) was removed",
78 format_metric_label(source_set.as_deref(), metric)
79 ),
80 StateCheckViolation::RatchetCeilingRaised {
81 source_set,
82 metric,
83 base_ceiling,
84 head_ceiling,
85 metric_version,
86 } => write!(
87 formatter,
88 "Ratchet ceiling for {} was raised from {base_ceiling} to {head_ceiling} (Metric version {metric_version})",
89 format_metric_label(source_set.as_deref(), metric)
90 ),
91 StateCheckViolation::BaselineFindingsAdded {
92 source_set,
93 metric,
94 base_count,
95 head_count,
96 added_count,
97 metric_version,
98 ..
99 } => {
100 let noun = if *added_count == 1 {
101 "Finding"
102 } else {
103 "Findings"
104 };
105 write!(
106 formatter,
107 "Baseline for {} added {added_count} {noun} ({base_count} to {head_count}, Metric version {metric_version})",
108 format_metric_label(source_set.as_deref(), metric)
109 )
110 }
111 }
112 }
113}
114
115#[derive(Debug, Clone, Default, PartialEq)]
116pub struct StateCheckComparison {
117 pub violations: Vec<StateCheckViolation>,
118}
119
120impl StateCheckComparison {
121 pub fn passed(&self) -> bool {
122 self.violations.is_empty()
123 }
124}
125
126pub fn compare_state(
127 ratchet_path: &str,
128 base_ratchet: Option<&Ratchet>,
129 head_ratchet: Option<&Ratchet>,
130 base_baseline: Option<&Baseline>,
131 head_baseline: Option<&Baseline>,
132 renames: &BTreeMap<String, String>,
133) -> StateCheckComparison {
134 let mut violations = Vec::new();
135 compare_ratchet(ratchet_path, base_ratchet, head_ratchet, &mut violations);
136 compare_baseline(base_baseline, head_baseline, renames, &mut violations);
137 StateCheckComparison { violations }
138}
139
140fn compare_ratchet(
141 ratchet_path: &str,
142 base_ratchet: Option<&Ratchet>,
143 head_ratchet: Option<&Ratchet>,
144 violations: &mut Vec<StateCheckViolation>,
145) {
146 let Some(base) = base_ratchet else {
147 return;
148 };
149 let Some(head) = head_ratchet else {
150 violations.push(StateCheckViolation::RatchetFileDeleted {
151 path: ratchet_path.to_owned(),
152 });
153 return;
154 };
155 for (source_set, entries) in base.source_sets.iter() {
156 for (metric, &base_entry) in entries {
157 compare_ratchet_entry(
158 Some(source_set),
159 metric,
160 base_entry,
161 head.entry(Some(source_set), metric),
162 violations,
163 );
164 }
165 }
166 for (metric, &base_entry) in &base.dependencies {
167 compare_ratchet_entry(
168 None,
169 metric,
170 base_entry,
171 head.entry(None, metric),
172 violations,
173 );
174 }
175}
176
177fn compare_ratchet_entry(
178 source_set: Option<SourceSet>,
179 metric: &str,
180 base_entry: RatchetEntry,
181 head_entry: Option<RatchetEntry>,
182 violations: &mut Vec<StateCheckViolation>,
183) {
184 let source_set_key = source_set.map(|set| set.key().to_owned());
185 let base_ceiling = round_ratchet_ratio(base_entry.ceiling);
186 let Some(head_entry) = head_entry else {
187 violations.push(StateCheckViolation::RatchetEntryRemoved {
188 source_set: source_set_key,
189 metric: metric.to_owned(),
190 base_ceiling,
191 metric_version: base_entry.metric_version,
192 });
193 return;
194 };
195 if head_entry.metric_version != base_entry.metric_version {
196 return;
197 }
198 let head_ceiling = round_ratchet_ratio(head_entry.ceiling);
199 if head_ceiling > base_ceiling {
200 violations.push(StateCheckViolation::RatchetCeilingRaised {
201 source_set: source_set_key,
202 metric: metric.to_owned(),
203 base_ceiling,
204 head_ceiling,
205 metric_version: base_entry.metric_version,
206 });
207 }
208}
209
210fn compare_baseline(
211 base_baseline: Option<&Baseline>,
212 head_baseline: Option<&Baseline>,
213 renames: &BTreeMap<String, String>,
214 violations: &mut Vec<StateCheckViolation>,
215) {
216 let (Some(base), Some(head)) = (base_baseline, head_baseline) else {
217 return;
218 };
219 for (source_set, entries) in head.source_sets.iter() {
220 for (metric, head_entry) in entries {
221 compare_baseline_entry(
222 Some(source_set),
223 metric,
224 base.entry(Some(source_set), metric),
225 head_entry,
226 renames,
227 violations,
228 );
229 }
230 }
231 for (metric, head_entry) in &head.dependencies {
232 compare_baseline_entry(
233 None,
234 metric,
235 base.entry(None, metric),
236 head_entry,
237 renames,
238 violations,
239 );
240 }
241}
242
243fn compare_baseline_entry(
244 source_set: Option<SourceSet>,
245 metric: &str,
246 base_entry: Option<&BaselineEntry>,
247 head_entry: &BaselineEntry,
248 renames: &BTreeMap<String, String>,
249 violations: &mut Vec<StateCheckViolation>,
250) {
251 let source_set_key = source_set.map(|set| set.key().to_owned());
252 let Some(base_entry) = base_entry else {
253 if !head_entry.findings.is_empty() {
254 let mut added_ids: Vec<String> = head_entry
255 .findings
256 .iter()
257 .map(|finding| finding.id.clone())
258 .collect();
259 added_ids.sort();
260 violations.push(StateCheckViolation::BaselineFindingsAdded {
261 source_set: source_set_key,
262 metric: metric.to_owned(),
263 base_count: 0,
264 head_count: head_entry.findings.len(),
265 added_count: added_ids.len(),
266 added_ids,
267 metric_version: head_entry.metric_version,
268 });
269 }
270 return;
271 };
272 if head_entry.metric_version != base_entry.metric_version {
273 return;
274 }
275 let matched = match_anchors_with_renames(&base_entry.findings, &head_entry.findings, renames);
276 let mut matched_head = vec![None; head_entry.findings.len()];
277 for (base, head) in matched.matched_pairs {
278 matched_head[head] = Some(&base_entry.findings[base]);
279 }
280 let covered_clone_lines = base_entry.covered_clone_lines(renames);
281 let mut added_ids: Vec<String> = head_entry
282 .findings
283 .iter()
284 .enumerate()
285 .filter(|&(index, finding)| {
286 if finding.clone_lines.is_empty() {
287 return matched_head[index].is_none_or(|old| !old.clone_lines.is_empty());
288 }
289 matched_head[index].is_none()
290 || finding
291 .clone_lines
292 .iter()
293 .any(|line| !covered_clone_lines.contains(line))
294 })
295 .map(|(_, finding)| finding.id.clone())
296 .collect();
297 if !added_ids.is_empty() {
298 added_ids.sort();
299 violations.push(StateCheckViolation::BaselineFindingsAdded {
300 source_set: source_set_key,
301 metric: metric.to_owned(),
302 base_count: base_entry.findings.len(),
303 head_count: head_entry.findings.len(),
304 added_count: added_ids.len(),
305 added_ids,
306 metric_version: head_entry.metric_version,
307 });
308 }
309}
310
311fn format_metric_label(source_set: Option<&str>, metric: &str) -> String {
312 match source_set {
313 Some(source_set) => format!("{source_set}.{metric}"),
314 None => metric.to_owned(),
315 }
316}