1use std::path::Path;
4
5use fallow_config::{AuditGate, AuditWorsened, RulesConfig, Severity};
6
7use super::{AuditAnalysesView, AuditKeySnapshot};
8use crate::audit_keys::{
9 AuditComparison, AuditDomainLedger, DeadCodeAuditLedger,
10 classify_complexity_attribution_against_all, complexity_ledger_keys, dead_code_audit_ledger,
11 dupe_group_key, preexisting_dupe_group_keys, styling_ledger_keys,
12 styling_ledger_keys_with_diff,
13};
14use crate::{AuditAttribution, AuditSummary, AuditVerdict};
15
16#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum DupeDemotionDiffSource {
20 Shared(String),
24 Worktree,
26 Skipped,
29}
30
31impl DupeDemotionDiffSource {
32 #[must_use]
34 pub fn label(&self, base_ref: &str) -> String {
35 match self {
36 Self::Shared(label) => label.clone(),
37 Self::Worktree => format!("merge-base worktree diff vs {base_ref}"),
38 Self::Skipped => "skipped: no diff available".to_string(),
39 }
40 }
41}
42
43#[derive(Clone, Copy)]
45pub struct SharedDiff<'a> {
46 pub index: &'a fallow_output::DiffIndex,
48 pub label: &'a str,
50}
51
52#[must_use]
59pub fn compare(
60 view: &AuditAnalysesView<'_>,
61 base: Option<&AuditKeySnapshot>,
62 syntactic_fallback: bool,
63) -> AuditComparison {
64 let dead_code =
65 view.dead_code
66 .as_ref()
67 .map_or_else(DeadCodeAuditLedger::default, |dead_code| {
68 let base_keys = base.map(|snapshot| {
71 if syntactic_fallback {
72 snapshot
73 .syntactic_dead_code
74 .as_ref()
75 .unwrap_or(&snapshot.dead_code)
76 } else {
77 &snapshot.dead_code
78 }
79 });
80 let mut ledger = dead_code_audit_ledger(
81 dead_code.results,
82 dead_code.root,
83 dead_code.config,
84 base_keys,
85 );
86 if syntactic_fallback && let Some(head_syntactic) = dead_code.syntactic_keys {
87 ledger.demote_unattributable_introductions(head_syntactic);
88 }
89 ledger
90 });
91 let health_classes =
92 view.health
93 .as_ref()
94 .zip(base)
95 .map_or_else(Vec::new, |(health, snapshot)| {
96 classify_complexity_attribution_against_all(
97 &health.report.findings,
98 health.root,
99 std::iter::once(&snapshot.health).chain(&snapshot.inherited_health),
100 )
101 });
102 let health = view
103 .health
104 .as_ref()
105 .map_or_else(AuditDomainLedger::default, |health| {
106 let findings = &health.report.findings;
107 let keys = complexity_ledger_keys(findings, health.root);
108 let introduced = (0..findings.len()).map(|index| {
109 health_classes
110 .get(index)
111 .is_some_and(|class| class.introduced)
112 });
113 AuditDomainLedger::from_classified(keys.into_iter().zip(introduced), base.is_some())
114 });
115 let dupes = AuditDomainLedger::compare(
116 view.duplication.iter().flat_map(|duplication| {
117 duplication
118 .clone_groups
119 .iter()
120 .map(|group| dupe_group_key(group, duplication.root))
121 }),
122 base.map(|snapshot| &snapshot.dupes),
123 );
124 let styling = AuditDomainLedger::compare(
125 view.health
126 .iter()
127 .flat_map(|health| styling_ledger_keys(&health.report.styling_findings, health.root)),
128 base.map(|snapshot| &snapshot.styling),
129 );
130 AuditComparison {
131 dead_code,
132 health,
133 health_classes,
134 dupes,
135 styling,
136 }
137}
138
139pub fn demote_preexisting_dupe_introductions(
148 comparison: &mut AuditComparison,
149 view: &AuditAnalysesView<'_>,
150 root: &Path,
151 base_ref: &str,
152 shared: Option<SharedDiff<'_>>,
153) -> Option<DupeDemotionDiffSource> {
154 if comparison.dupes.introduced_count() == 0 {
155 return None;
156 }
157 let duplication = view.duplication.as_ref()?;
158 let worktree_index;
159 let (index, source) = if let Some(shared) = shared {
160 (
161 shared.index,
162 DupeDemotionDiffSource::Shared(shared.label.to_owned()),
163 )
164 } else if let Ok(diff) = fallow_engine::changed_files::try_get_changed_diff(root, base_ref) {
165 worktree_index = fallow_output::DiffIndex::from_unified_diff(&diff);
166 (&worktree_index, DupeDemotionDiffSource::Worktree)
167 } else {
168 return Some(DupeDemotionDiffSource::Skipped);
169 };
170 let demote = preexisting_dupe_group_keys(
171 duplication.clone_groups.iter().copied(),
172 duplication.root,
173 index,
174 );
175 comparison.dupes.demote_introductions(&demote);
176 Some(source)
177}
178
179pub fn realign_styling_introductions(
188 comparison: &mut AuditComparison,
189 view: &AuditAnalysesView<'_>,
190 base: Option<&AuditKeySnapshot>,
191 root: &Path,
192 base_ref: &str,
193 shared: Option<SharedDiff<'_>>,
194) {
195 let (Some(base), Some(health)) = (base, view.health.as_ref()) else {
196 return;
197 };
198 if comparison.styling.introduced_count() == 0 {
199 return;
200 }
201 let worktree_index;
202 let index = if let Some(shared) = shared {
203 shared.index
204 } else if let Ok(diff) = fallow_engine::changed_files::try_get_changed_diff(root, base_ref) {
205 worktree_index = fallow_output::DiffIndex::from_unified_diff(&diff);
206 &worktree_index
207 } else {
208 return;
209 };
210 comparison.styling = AuditDomainLedger::compare(
211 styling_ledger_keys_with_diff(&health.report.styling_findings, health.root, Some(index)),
212 Some(&base.styling),
213 );
214}
215
216#[must_use]
219pub fn styling_rule_severity(rules: &RulesConfig, code: &str) -> Severity {
220 match code {
221 "css-token-drift" => rules.css_token_drift,
222 "css-duplicate-block" => rules.css_duplicate_block,
223 "css-selector-complexity" => rules.css_selector_complexity,
224 "css-dead-surface" => rules.css_dead_surface,
225 "css-broken-reference" => rules.css_broken_reference,
226 _ => Severity::Warn,
227 }
228}
229
230#[must_use]
232pub fn styling_finding_gates(rules: &RulesConfig, code: &str) -> bool {
233 styling_rule_severity(rules, code) == Severity::Error
234}
235
236#[must_use]
238pub fn outcome(
239 gate: AuditGate,
240 worsened: AuditWorsened,
241 view: &AuditAnalysesView<'_>,
242 comparison: &AuditComparison,
243 has_base: bool,
244) -> (AuditAttribution, AuditVerdict, AuditSummary) {
245 let summary = summary(view, comparison);
246 (
247 attribution(gate, worsened, comparison, has_base),
248 verdict(gate, worsened, view, comparison, &summary),
249 summary,
250 )
251}
252
253fn complexity_verdict_flags(
258 gate: AuditGate,
259 worsened: AuditWorsened,
260 view: &AuditAnalysesView<'_>,
261 comparison: &AuditComparison,
262) -> (bool, bool) {
263 let new_only = matches!(gate, AuditGate::NewOnly);
264 let Some(health) = view.health.as_ref() else {
265 return (false, false);
266 };
267 let mut errors = false;
268 let mut warnings = false;
269 for (index, (finding, introduced)) in health
270 .report
271 .findings
272 .iter()
273 .zip(comparison.health.introduced())
274 .enumerate()
275 {
276 let is_worsened = comparison
277 .health_classes
278 .get(index)
279 .is_some_and(crate::audit_keys::ComplexityClass::is_worsened);
280 let counts = !new_only || introduced || (is_worsened && worsened == AuditWorsened::Error);
281 if counts {
282 if finding.blocks() {
283 errors = true;
284 } else {
285 warnings = true;
286 }
287 } else if is_worsened {
288 warnings = true;
289 }
290 }
291 (errors, warnings)
292}
293
294fn verdict(
295 gate: AuditGate,
296 worsened: AuditWorsened,
297 view: &AuditAnalysesView<'_>,
298 comparison: &AuditComparison,
299 summary: &AuditSummary,
300) -> AuditVerdict {
301 let new_only = matches!(gate, AuditGate::NewOnly);
302 let dead_code_errors = if new_only {
303 comparison.dead_code.has_introduced_errors()
304 } else {
305 dead_code_has_errors(view)
306 };
307 let dead_code_warnings = if new_only {
308 comparison.dead_code.has_introduced_warnings()
309 } else {
310 comparison
311 .dead_code
312 .records()
313 .iter()
314 .any(|record| record.effective_severity == Severity::Warn)
315 };
316 let (complexity_errors, complexity_warnings) =
320 complexity_verdict_flags(gate, worsened, view, comparison);
321 let styling_errors = view.health.as_ref().is_some_and(|health| {
322 health
323 .report
324 .styling_findings
325 .iter()
326 .zip(comparison.styling.introduced())
327 .any(|(finding, introduced)| {
328 (!new_only || introduced) && styling_finding_gates(health.rules, &finding.code)
329 })
330 });
331 let duplication_findings = if new_only {
332 comparison.dupes.introduced_count()
333 } else {
334 summary.duplication_clone_groups
335 };
336 let duplication_errors = view.duplication.as_ref().is_some_and(|duplication| {
337 duplication_findings > 0
338 && duplication.threshold > 0.0
339 && duplication.duplication_percentage > duplication.threshold
340 });
341 if dead_code_errors || complexity_errors || styling_errors || duplication_errors {
342 AuditVerdict::Fail
343 } else if dead_code_warnings || complexity_warnings || duplication_findings > 0 {
344 AuditVerdict::Warn
345 } else {
346 AuditVerdict::Pass
347 }
348}
349
350fn dead_code_has_errors(view: &AuditAnalysesView<'_>) -> bool {
353 view.dead_code.as_ref().is_some_and(|dead_code| {
354 fallow_engine::error_severity::has_error_severity_issues(
355 dead_code.results,
356 &dead_code.config.rules,
357 Some(dead_code.config),
358 false,
359 )
360 })
361}
362
363fn attribution(
364 gate: AuditGate,
365 worsened: AuditWorsened,
366 comparison: &AuditComparison,
367 has_base: bool,
368) -> AuditAttribution {
369 if !has_base {
370 return AuditAttribution {
371 gate,
372 worsened,
373 ..AuditAttribution::default()
374 };
375 }
376 AuditAttribution {
377 gate,
378 worsened,
379 complexity_worsened: comparison.complexity_worsened_count(),
380 dead_code_introduced: comparison.dead_code.introduced_count(),
381 dead_code_inherited: comparison.dead_code.inherited_count(),
382 complexity_introduced: comparison.health.introduced_count(),
383 complexity_inherited: comparison.health.inherited_count(),
384 duplication_introduced: comparison.dupes.introduced_count(),
385 duplication_inherited: comparison.dupes.inherited_count(),
386 }
387}
388
389fn summary(view: &AuditAnalysesView<'_>, comparison: &AuditComparison) -> AuditSummary {
390 AuditSummary {
391 dead_code_issues: comparison.dead_code.visible_count(),
392 dead_code_has_errors: dead_code_has_errors(view),
393 dead_code_skipped: view.dead_code.is_none(),
394 complexity_skipped: view.health.is_none(),
395 duplication_skipped: view.duplication.is_none(),
396 complexity_findings: view
397 .health
398 .as_ref()
399 .map_or(0, |health| health.report.findings.len()),
400 max_cyclomatic: view.health.as_ref().and_then(|health| {
401 health
402 .report
403 .findings
404 .iter()
405 .map(|finding| finding.cyclomatic)
406 .max()
407 }),
408 duplication_clone_groups: view
409 .duplication
410 .as_ref()
411 .map_or(0, |duplication| duplication.clone_groups.len()),
412 }
413}