1use std::path::Path;
4
5use fallow_config::{AuditGate, AuditWorsened, RulesConfig, Severity};
6
7use fallow_engine::changed_files::RenamedFile;
8
9use super::clone_containment::base_contained_dupe_group_keys;
10use super::{AuditAnalysesView, AuditKeySnapshot};
11use crate::audit_keys::{
12 AuditComparison, AuditDomainLedger, DeadCodeAuditLedger,
13 classify_complexity_attribution_against_all, complexity_ledger_keys, dead_code_audit_ledger,
14 dupe_group_key, preexisting_dupe_group_keys, styling_ledger_keys,
15 styling_ledger_keys_with_diff,
16};
17use crate::diff_risk::clones::BaseCloneGroup;
18use crate::{AuditAttribution, AuditSummary, AuditVerdict};
19
20#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum DupeDemotionDiffSource {
24 Shared(String),
28 Worktree,
30 Skipped,
33}
34
35impl DupeDemotionDiffSource {
36 #[must_use]
38 pub fn label(&self, base_ref: &str) -> String {
39 match self {
40 Self::Shared(label) => label.clone(),
41 Self::Worktree => format!("merge-base worktree diff vs {base_ref}"),
42 Self::Skipped => "skipped: no diff available".to_string(),
43 }
44 }
45}
46
47#[derive(Clone, Copy)]
49pub struct SharedDiff<'a> {
50 pub index: &'a fallow_output::DiffIndex,
52 pub label: &'a str,
54}
55
56#[must_use]
63pub fn compare(
64 view: &AuditAnalysesView<'_>,
65 base: Option<&AuditKeySnapshot>,
66 syntactic_fallback: bool,
67) -> AuditComparison {
68 let dead_code =
69 view.dead_code
70 .as_ref()
71 .map_or_else(DeadCodeAuditLedger::default, |dead_code| {
72 let base_keys = base.map(|snapshot| {
75 if syntactic_fallback {
76 snapshot
77 .syntactic_dead_code
78 .as_ref()
79 .unwrap_or(&snapshot.dead_code)
80 } else {
81 &snapshot.dead_code
82 }
83 });
84 let mut ledger = dead_code_audit_ledger(
85 dead_code.results,
86 dead_code.root,
87 dead_code.config,
88 base_keys,
89 );
90 if syntactic_fallback && let Some(head_syntactic) = dead_code.syntactic_keys {
91 ledger.demote_unattributable_introductions(head_syntactic);
92 }
93 ledger
94 });
95 let health_classes =
96 view.health
97 .as_ref()
98 .zip(base)
99 .map_or_else(Vec::new, |(health, snapshot)| {
100 classify_complexity_attribution_against_all(
101 &health.report.findings,
102 health.root,
103 std::iter::once(&snapshot.health).chain(&snapshot.inherited_health),
104 )
105 });
106 let health = view
107 .health
108 .as_ref()
109 .map_or_else(AuditDomainLedger::default, |health| {
110 let findings = &health.report.findings;
111 let keys = complexity_ledger_keys(findings, health.root);
112 let introduced = (0..findings.len()).map(|index| {
113 health_classes
114 .get(index)
115 .is_some_and(|class| class.introduced)
116 });
117 AuditDomainLedger::from_classified(keys.into_iter().zip(introduced), base.is_some())
118 });
119 let dupes = AuditDomainLedger::compare(
120 view.duplication.iter().flat_map(|duplication| {
121 duplication
122 .clone_groups
123 .iter()
124 .map(|group| dupe_group_key(group, duplication.root))
125 }),
126 base.map(|snapshot| &snapshot.dupes),
127 );
128 let styling = AuditDomainLedger::compare(
129 view.health
130 .iter()
131 .flat_map(|health| styling_ledger_keys(&health.report.styling_findings, health.root)),
132 base.map(|snapshot| &snapshot.styling),
133 );
134 AuditComparison {
135 dead_code,
136 health,
137 health_classes,
138 dupes,
139 styling,
140 }
141}
142
143#[derive(Clone, Copy)]
145pub struct DupeBase<'a> {
146 pub groups: &'a [BaseCloneGroup],
148 pub renames: &'a [RenamedFile],
150}
151
152pub fn demote_preexisting_dupe_introductions(
170 comparison: &mut AuditComparison,
171 view: &AuditAnalysesView<'_>,
172 root: &Path,
173 base_ref: &str,
174 shared: Option<SharedDiff<'_>>,
175 base: DupeBase<'_>,
176) -> Option<DupeDemotionDiffSource> {
177 if comparison.dupes.introduced_count() == 0 {
178 return None;
179 }
180 let duplication = view.duplication.as_ref()?;
181 let worktree_index;
182 let (index, source) = if let Some(shared) = shared {
183 (
184 shared.index,
185 DupeDemotionDiffSource::Shared(shared.label.to_owned()),
186 )
187 } else if let Ok(diff) = fallow_engine::changed_files::try_get_changed_diff(root, base_ref) {
188 worktree_index = fallow_output::DiffIndex::from_unified_diff(&diff);
189 (&worktree_index, DupeDemotionDiffSource::Worktree)
190 } else {
191 return Some(DupeDemotionDiffSource::Skipped);
192 };
193 let demote = preexisting_dupe_group_keys(
194 duplication.clone_groups.iter().copied(),
195 duplication.root,
196 index,
197 );
198 comparison.dupes.demote_introductions(&demote);
199 let inherit = base_contained_dupe_group_keys(
203 duplication.clone_groups.iter().copied().filter(|group| {
204 comparison
205 .dupes
206 .is_introduced(&dupe_group_key(group, duplication.root))
207 }),
208 duplication.root,
209 index,
210 base.groups,
211 base.renames,
212 );
213 comparison.dupes.inherit_introductions(&inherit);
214 Some(source)
215}
216
217pub fn realign_styling_introductions(
226 comparison: &mut AuditComparison,
227 view: &AuditAnalysesView<'_>,
228 base: Option<&AuditKeySnapshot>,
229 root: &Path,
230 base_ref: &str,
231 shared: Option<SharedDiff<'_>>,
232) {
233 let (Some(base), Some(health)) = (base, view.health.as_ref()) else {
234 return;
235 };
236 if comparison.styling.introduced_count() == 0 {
237 return;
238 }
239 let worktree_index;
240 let index = if let Some(shared) = shared {
241 shared.index
242 } else if let Ok(diff) = fallow_engine::changed_files::try_get_changed_diff(root, base_ref) {
243 worktree_index = fallow_output::DiffIndex::from_unified_diff(&diff);
244 &worktree_index
245 } else {
246 return;
247 };
248 comparison.styling = AuditDomainLedger::compare(
249 styling_ledger_keys_with_diff(&health.report.styling_findings, health.root, Some(index)),
250 Some(&base.styling),
251 );
252}
253
254#[must_use]
257pub fn styling_rule_severity(rules: &RulesConfig, code: &str) -> Severity {
258 match code {
259 "css-token-drift" => rules.css_token_drift,
260 "css-duplicate-block" => rules.css_duplicate_block,
261 "css-selector-complexity" => rules.css_selector_complexity,
262 "css-dead-surface" => rules.css_dead_surface,
263 "css-broken-reference" => rules.css_broken_reference,
264 _ => Severity::Warn,
265 }
266}
267
268#[must_use]
270pub fn styling_finding_gates(rules: &RulesConfig, code: &str) -> bool {
271 styling_rule_severity(rules, code) == Severity::Error
272}
273
274#[must_use]
276pub fn outcome(
277 gate: AuditGate,
278 worsened: AuditWorsened,
279 view: &AuditAnalysesView<'_>,
280 comparison: &AuditComparison,
281 has_base: bool,
282) -> (AuditAttribution, AuditVerdict, AuditSummary) {
283 let summary = summary(view, comparison);
284 (
285 attribution(gate, worsened, comparison, has_base),
286 verdict(gate, worsened, view, comparison, &summary),
287 summary,
288 )
289}
290
291fn complexity_verdict_flags(
296 gate: AuditGate,
297 worsened: AuditWorsened,
298 view: &AuditAnalysesView<'_>,
299 comparison: &AuditComparison,
300) -> (bool, bool) {
301 let new_only = matches!(gate, AuditGate::NewOnly);
302 let Some(health) = view.health.as_ref() else {
303 return (false, false);
304 };
305 let mut errors = false;
306 let mut warnings = false;
307 for (index, (finding, introduced)) in health
308 .report
309 .findings
310 .iter()
311 .zip(comparison.health.introduced())
312 .enumerate()
313 {
314 let is_worsened = comparison
315 .health_classes
316 .get(index)
317 .is_some_and(crate::audit_keys::ComplexityClass::is_worsened);
318 let counts = !new_only || introduced || (is_worsened && worsened == AuditWorsened::Error);
319 if counts {
320 if finding.blocks() {
321 errors = true;
322 } else {
323 warnings = true;
324 }
325 } else if is_worsened {
326 warnings = true;
327 }
328 }
329 (errors, warnings)
330}
331
332fn verdict(
333 gate: AuditGate,
334 worsened: AuditWorsened,
335 view: &AuditAnalysesView<'_>,
336 comparison: &AuditComparison,
337 summary: &AuditSummary,
338) -> AuditVerdict {
339 let new_only = matches!(gate, AuditGate::NewOnly);
340 let dead_code_errors = if new_only {
341 comparison.dead_code.has_introduced_errors()
342 } else {
343 dead_code_has_errors(view)
344 };
345 let dead_code_warnings = if new_only {
346 comparison.dead_code.has_introduced_warnings()
347 } else {
348 comparison
349 .dead_code
350 .records()
351 .iter()
352 .any(|record| record.effective_severity == Severity::Warn)
353 };
354 let (complexity_errors, complexity_warnings) =
358 complexity_verdict_flags(gate, worsened, view, comparison);
359 let styling_errors = view.health.as_ref().is_some_and(|health| {
360 health
361 .report
362 .styling_findings
363 .iter()
364 .zip(comparison.styling.introduced())
365 .any(|(finding, introduced)| {
366 (!new_only || introduced) && styling_finding_gates(health.rules, &finding.code)
367 })
368 });
369 let duplication_findings = if new_only {
370 comparison.dupes.introduced_count()
371 } else {
372 summary.duplication_clone_groups
373 };
374 let duplication_errors = view.duplication.as_ref().is_some_and(|duplication| {
375 duplication_findings > 0
376 && duplication.threshold > 0.0
377 && duplication.duplication_percentage > duplication.threshold
378 });
379 if dead_code_errors || complexity_errors || styling_errors || duplication_errors {
380 AuditVerdict::Fail
381 } else if dead_code_warnings || complexity_warnings || duplication_findings > 0 {
382 AuditVerdict::Warn
383 } else {
384 AuditVerdict::Pass
385 }
386}
387
388fn dead_code_has_errors(view: &AuditAnalysesView<'_>) -> bool {
391 view.dead_code.as_ref().is_some_and(|dead_code| {
392 fallow_engine::error_severity::has_error_severity_issues(
393 dead_code.results,
394 &dead_code.config.rules,
395 Some(dead_code.config),
396 false,
397 )
398 })
399}
400
401fn attribution(
402 gate: AuditGate,
403 worsened: AuditWorsened,
404 comparison: &AuditComparison,
405 has_base: bool,
406) -> AuditAttribution {
407 if !has_base {
408 return AuditAttribution {
409 gate,
410 worsened,
411 ..AuditAttribution::default()
412 };
413 }
414 AuditAttribution {
415 gate,
416 worsened,
417 complexity_worsened: comparison.complexity_worsened_count(),
418 dead_code_introduced: comparison.dead_code.introduced_count(),
419 dead_code_inherited: comparison.dead_code.inherited_count(),
420 complexity_introduced: comparison.health.introduced_count(),
421 complexity_inherited: comparison.health.inherited_count(),
422 duplication_introduced: comparison.dupes.introduced_count(),
423 duplication_inherited: comparison.dupes.inherited_count(),
424 }
425}
426
427fn summary(view: &AuditAnalysesView<'_>, comparison: &AuditComparison) -> AuditSummary {
428 AuditSummary {
429 dead_code_issues: comparison.dead_code.visible_count(),
430 dead_code_has_errors: dead_code_has_errors(view),
431 dead_code_skipped: view.dead_code.is_none(),
432 complexity_skipped: view.health.is_none(),
433 duplication_skipped: view.duplication.is_none(),
434 complexity_findings: view
435 .health
436 .as_ref()
437 .map_or(0, |health| health.report.findings.len()),
438 max_cyclomatic: view.health.as_ref().and_then(|health| {
439 health
440 .report
441 .findings
442 .iter()
443 .map(|finding| finding.cyclomatic)
444 .max()
445 }),
446 duplication_clone_groups: view
447 .duplication
448 .as_ref()
449 .map_or(0, |duplication| duplication.clone_groups.len()),
450 }
451}