1use std::path::{Path, PathBuf};
4
5use fallow_config::{AuditGate, AuditWorsened, ResolvedConfig, RulesConfig, Severity};
6
7use fallow_engine::changed_files::RenamedFile;
8use fallow_engine::module_graph::relative_key_path;
9use fallow_types::duplicates::CloneGroup;
10use rustc_hash::FxHashSet;
11
12use super::clone_containment::base_contained_dupe_group_keys;
13use super::{AuditAnalysesView, AuditKeySnapshot};
14use crate::audit_keys::{
15 AuditComparison, AuditDomainLedger, ChangedPaths, DeadCodeAuditLedger,
16 classify_complexity_attribution_against_all_with_moves, complexity_ledger_keys,
17 dead_code_audit_ledger, dupe_group_key, preexisting_dupe_group_keys, styling_ledger_keys,
18 styling_ledger_keys_with_diff,
19};
20use crate::audit_moved::{MovedDeadCode, moved_dead_code_keys, moved_dupe_group_keys};
21use crate::diff_risk::clones::BaseCloneGroup;
22use crate::{AuditAttribution, AuditSummary, AuditVerdict};
23
24#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum DupeDemotionDiffSource {
28 Shared(String),
32 Worktree,
34 Skipped,
37}
38
39impl DupeDemotionDiffSource {
40 #[must_use]
42 pub fn label(&self, base_ref: &str) -> String {
43 match self {
44 Self::Shared(label) => label.clone(),
45 Self::Worktree => format!("merge-base worktree diff vs {base_ref}"),
46 Self::Skipped => "skipped: no diff available".to_string(),
47 }
48 }
49}
50
51#[derive(Clone, Copy)]
53pub struct SharedDiff<'a> {
54 pub index: &'a fallow_output::DiffIndex,
56 pub label: &'a str,
58}
59
60pub struct RunChange<'a> {
62 pub root: &'a Path,
64 pub base_ref: &'a str,
66 pub shared: Option<SharedDiff<'a>>,
68 pub changed_files: &'a FxHashSet<PathBuf>,
70 worktree: std::cell::OnceCell<Option<fallow_output::DiffIndex>>,
73}
74
75impl<'a> RunChange<'a> {
76 #[must_use]
78 pub const fn new(
79 root: &'a Path,
80 base_ref: &'a str,
81 shared: Option<SharedDiff<'a>>,
82 changed_files: &'a FxHashSet<PathBuf>,
83 ) -> Self {
84 Self {
85 root,
86 base_ref,
87 shared,
88 changed_files,
89 worktree: std::cell::OnceCell::new(),
90 }
91 }
92
93 pub(super) fn diff_index(&self) -> Option<&fallow_output::DiffIndex> {
98 if let Some(shared) = self.shared {
99 return Some(shared.index);
100 }
101 self.worktree
102 .get_or_init(|| {
103 fallow_engine::changed_files::try_get_changed_diff(self.root, self.base_ref)
104 .ok()
105 .map(|diff| fallow_output::DiffIndex::from_unified_diff(&diff))
106 })
107 .as_ref()
108 }
109}
110
111fn added_line_names(
114 diff: &fallow_output::DiffIndex,
115 root: &Path,
116 path: &str,
117 symbol: &str,
118) -> bool {
119 let file = root.join(path);
120 let Some(added) = diff
121 .key_for(&file, root)
122 .and_then(|key| diff.added_lines_in(&key))
123 else {
124 return false;
125 };
126 let Ok(source) = std::fs::read_to_string(&file) else {
127 return false;
128 };
129 source
130 .lines()
131 .zip(1_u64..)
132 .any(|(line, number)| added.contains(&number) && line.contains(symbol))
133}
134
135#[must_use]
149pub fn compare(
150 view: &AuditAnalysesView<'_>,
151 base: Option<&AuditKeySnapshot>,
152 syntactic_fallback: bool,
153 change: &RunChange<'_>,
154) -> AuditComparison {
155 let dead_code =
156 view.dead_code
157 .as_ref()
158 .map_or_else(DeadCodeAuditLedger::default, |dead_code| {
159 let base_keys = base.map(|snapshot| {
162 if syntactic_fallback {
163 snapshot
164 .syntactic_dead_code
165 .as_ref()
166 .unwrap_or(&snapshot.dead_code)
167 } else {
168 &snapshot.dead_code
169 }
170 });
171 let mut ledger = dead_code_audit_ledger(
172 dead_code.results,
173 dead_code.root,
174 dead_code.config,
175 base_keys,
176 );
177 if syntactic_fallback && let Some(head_syntactic) = dead_code.syntactic_keys {
178 ledger.demote_unattributable_introductions(head_syntactic);
179 }
180 if let Some(base_keys) = base_keys {
181 let moved = moved_dead_code_keys(
182 &ledger,
183 &MovedDeadCode {
184 base: base_keys,
185 changed: &changed_paths_of(change.changed_files, dead_code.root),
186 also_reported: dead_code.syntactic_keys.filter(|_| syntactic_fallback),
187 added_line_names: &|path, symbol| {
188 change.diff_index().is_some_and(|index| {
189 added_line_names(index, dead_code.root, path, symbol)
190 })
191 },
192 },
193 );
194 ledger.inherit_introductions(&moved);
195 }
196 ledger
197 });
198 let health_classes =
199 view.health
200 .as_ref()
201 .zip(base)
202 .map_or_else(Vec::new, |(health, snapshot)| {
203 let changed_paths = changed_paths_of(change.changed_files, health.root);
204 classify_complexity_attribution_against_all_with_moves(
205 &health.report.findings,
206 health.root,
207 std::iter::once(&snapshot.health).chain(&snapshot.inherited_health),
208 &changed_paths,
209 )
210 });
211 let health = view
212 .health
213 .as_ref()
214 .map_or_else(AuditDomainLedger::default, |health| {
215 let findings = &health.report.findings;
216 let keys = complexity_ledger_keys(findings, health.root);
217 let introduced = (0..findings.len()).map(|index| {
218 health_classes
219 .get(index)
220 .is_some_and(|class| class.introduced)
221 });
222 AuditDomainLedger::from_classified(keys.into_iter().zip(introduced), base.is_some())
223 });
224 let dupes = dupes_ledger(view, base, change.changed_files);
225 let styling = AuditDomainLedger::compare(
226 view.health
227 .iter()
228 .flat_map(|health| styling_ledger_keys(&health.report.styling_findings, health.root)),
229 base.map(|snapshot| &snapshot.styling),
230 );
231 AuditComparison {
232 dead_code,
233 health,
234 health_classes,
235 dupes,
236 styling,
237 }
238}
239
240fn dupes_ledger(
244 view: &AuditAnalysesView<'_>,
245 base: Option<&AuditKeySnapshot>,
246 changed_files: &FxHashSet<PathBuf>,
247) -> AuditDomainLedger {
248 let Some(duplication) = view.duplication.as_ref() else {
249 return AuditDomainLedger::compare(std::iter::empty(), base.map(|base| &base.dupes));
250 };
251 let keys: Vec<String> = duplication
252 .clone_groups
253 .iter()
254 .map(|group| dupe_group_key(group, duplication.root))
255 .collect();
256 let mut ledger = AuditDomainLedger::compare(keys.iter().cloned(), base.map(|base| &base.dupes));
257 if let Some(base) = base
258 && ledger.introduced_count() > 0
259 {
260 let moved = moved_dupe_group_keys(
261 keys.iter()
262 .map(String::as_str)
263 .filter(|key| ledger.is_introduced(key)),
264 &keys.iter().map(String::as_str).collect(),
265 &base.dupes,
266 &changed_paths_of(changed_files, duplication.root),
267 );
268 ledger.inherit_introductions(&moved);
269 }
270 ledger
271}
272
273fn changed_paths_of(changed_files: &FxHashSet<PathBuf>, root: &Path) -> ChangedPaths {
275 let mut paths = ChangedPaths::default();
276 for path in changed_files {
277 let key = relative_key_path(path, root);
278 if !path.exists() {
279 paths.deleted.insert(key.clone());
280 }
281 paths.changed.insert(key);
282 }
283 paths
284}
285
286#[derive(Clone, Copy)]
288pub struct DupeBase<'a> {
289 pub groups: &'a [BaseCloneGroup],
291 pub renames: &'a [RenamedFile],
293}
294
295pub fn demote_preexisting_dupe_introductions(
313 comparison: &mut AuditComparison,
314 view: &AuditAnalysesView<'_>,
315 change: &RunChange<'_>,
316 base: DupeBase<'_>,
317) -> Option<DupeDemotionDiffSource> {
318 if comparison.dupes.introduced_count() == 0 {
319 return None;
320 }
321 let duplication = view.duplication.as_ref()?;
322 let Some(index) = change.diff_index() else {
323 return Some(DupeDemotionDiffSource::Skipped);
324 };
325 let source = change
326 .shared
327 .map_or(DupeDemotionDiffSource::Worktree, |shared| {
328 DupeDemotionDiffSource::Shared(shared.label.to_owned())
329 });
330 let demote = preexisting_dupe_group_keys(
331 duplication.clone_groups.iter().copied(),
332 duplication.root,
333 index,
334 );
335 comparison.dupes.demote_introductions(&demote);
336 let inherit = base_contained_dupe_group_keys(
340 duplication.clone_groups.iter().copied().filter(|group| {
341 comparison
342 .dupes
343 .is_introduced(&dupe_group_key(group, duplication.root))
344 }),
345 duplication.root,
346 index,
347 base.groups,
348 base.renames,
349 );
350 comparison.dupes.inherit_introductions(&inherit);
351 Some(source)
352}
353
354pub fn realign_styling_introductions(
363 comparison: &mut AuditComparison,
364 view: &AuditAnalysesView<'_>,
365 base: Option<&AuditKeySnapshot>,
366 change: &RunChange<'_>,
367) {
368 let (Some(base), Some(health)) = (base, view.health.as_ref()) else {
369 return;
370 };
371 if comparison.styling.introduced_count() == 0 {
372 return;
373 }
374 let Some(index) = change.diff_index() else {
375 return;
376 };
377 comparison.styling = AuditDomainLedger::compare(
378 styling_ledger_keys_with_diff(&health.report.styling_findings, health.root, Some(index)),
379 Some(&base.styling),
380 );
381}
382
383#[must_use]
386pub fn styling_rule_severity(rules: &RulesConfig, code: &str) -> Severity {
387 match code {
388 "css-token-drift" => rules.css_token_drift,
389 "css-duplicate-block" => rules.css_duplicate_block,
390 "css-selector-complexity" => rules.css_selector_complexity,
391 "css-dead-surface" => rules.css_dead_surface,
392 "css-broken-reference" => rules.css_broken_reference,
393 _ => Severity::Warn,
394 }
395}
396
397#[must_use]
399pub fn styling_finding_gates(rules: &RulesConfig, code: &str) -> bool {
400 styling_rule_severity(rules, code) == Severity::Error
401}
402
403fn clone_group_severity(config: &ResolvedConfig, group: &CloneGroup) -> Severity {
410 if config.overrides.is_empty() {
411 return config.rules.introduced_clone_group;
412 }
413 group
414 .instances
415 .iter()
416 .map(|instance| {
417 config
418 .resolve_rules_for_path(&instance.file)
419 .introduced_clone_group
420 })
421 .max_by_key(|severity| match severity {
422 Severity::Error => 2,
423 Severity::Warn => 1,
424 Severity::Off => 0,
425 })
426 .unwrap_or(config.rules.introduced_clone_group)
427}
428
429#[must_use]
431pub fn outcome(
432 gate: AuditGate,
433 worsened: AuditWorsened,
434 view: &AuditAnalysesView<'_>,
435 comparison: &AuditComparison,
436 has_base: bool,
437) -> (AuditAttribution, AuditVerdict, AuditSummary) {
438 let summary = summary(view, comparison);
439 (
440 attribution(gate, worsened, comparison, has_base),
441 verdict(gate, worsened, view, comparison, &summary),
442 summary,
443 )
444}
445
446fn complexity_verdict_flags(
451 gate: AuditGate,
452 worsened: AuditWorsened,
453 view: &AuditAnalysesView<'_>,
454 comparison: &AuditComparison,
455) -> (bool, bool) {
456 let new_only = matches!(gate, AuditGate::NewOnly);
457 let Some(health) = view.health.as_ref() else {
458 return (false, false);
459 };
460 let mut errors = false;
461 let mut warnings = false;
462 for (index, (finding, introduced)) in health
463 .report
464 .findings
465 .iter()
466 .zip(comparison.health.introduced())
467 .enumerate()
468 {
469 let is_worsened = comparison
470 .health_classes
471 .get(index)
472 .is_some_and(crate::audit_keys::ComplexityClass::is_worsened);
473 let counts = !new_only || introduced || (is_worsened && worsened == AuditWorsened::Error);
474 if counts {
475 if finding.blocks() {
476 errors = true;
477 } else {
478 warnings = true;
479 }
480 } else if is_worsened {
481 warnings = true;
482 }
483 }
484 (errors, warnings)
485}
486
487fn duplication_verdict_flags(
493 new_only: bool,
494 view: &AuditAnalysesView<'_>,
495 comparison: &AuditComparison,
496) -> (bool, bool) {
497 let Some(duplication) = view.duplication.as_ref() else {
498 return (false, false);
499 };
500 let introduced: Vec<bool> = comparison.dupes.introduced().collect();
501 let mut errors = false;
502 let mut warnings = false;
503 for (index, group) in duplication.clone_groups.iter().enumerate() {
504 if new_only && !introduced.get(index).copied().unwrap_or(false) {
505 continue;
506 }
507 match clone_group_severity(duplication.config, group) {
508 Severity::Error => errors = true,
509 Severity::Warn => warnings = true,
510 Severity::Off => {}
511 }
512 }
513 (errors, warnings)
514}
515
516fn verdict(
517 gate: AuditGate,
518 worsened: AuditWorsened,
519 view: &AuditAnalysesView<'_>,
520 comparison: &AuditComparison,
521 summary: &AuditSummary,
522) -> AuditVerdict {
523 let new_only = matches!(gate, AuditGate::NewOnly);
524 let dead_code_errors = if new_only {
525 comparison.dead_code.has_introduced_errors()
526 } else {
527 dead_code_has_errors(view)
528 };
529 let dead_code_warnings = if new_only {
530 comparison.dead_code.has_introduced_warnings()
531 } else {
532 comparison
533 .dead_code
534 .records()
535 .iter()
536 .any(|record| record.effective_severity == Severity::Warn)
537 };
538 let (complexity_errors, complexity_warnings) =
542 complexity_verdict_flags(gate, worsened, view, comparison);
543 let styling_errors = view.health.as_ref().is_some_and(|health| {
544 health
545 .report
546 .styling_findings
547 .iter()
548 .zip(comparison.styling.introduced())
549 .any(|(finding, introduced)| {
550 (!new_only || introduced) && styling_finding_gates(health.rules, &finding.code)
551 })
552 });
553 let (clone_errors, clone_warnings) = duplication_verdict_flags(new_only, view, comparison);
554 let duplication_findings = if new_only {
557 comparison.dupes.introduced_count()
558 } else {
559 summary.duplication_clone_groups
560 };
561 let duplication_errors = view.duplication.as_ref().is_some_and(|duplication| {
562 duplication_findings > 0
563 && duplication.threshold > 0.0
564 && duplication.duplication_percentage > duplication.threshold
565 });
566 if dead_code_errors || complexity_errors || styling_errors || duplication_errors || clone_errors
567 {
568 AuditVerdict::Fail
569 } else if dead_code_warnings || complexity_warnings || clone_warnings {
570 AuditVerdict::Warn
571 } else {
572 AuditVerdict::Pass
573 }
574}
575
576fn dead_code_has_errors(view: &AuditAnalysesView<'_>) -> bool {
579 view.dead_code.as_ref().is_some_and(|dead_code| {
580 fallow_engine::error_severity::has_error_severity_issues(
581 dead_code.results,
582 &dead_code.config.rules,
583 Some(dead_code.config),
584 false,
585 )
586 })
587}
588
589fn attribution(
590 gate: AuditGate,
591 worsened: AuditWorsened,
592 comparison: &AuditComparison,
593 has_base: bool,
594) -> AuditAttribution {
595 if !has_base {
596 return AuditAttribution {
597 gate,
598 worsened,
599 ..AuditAttribution::default()
600 };
601 }
602 AuditAttribution {
603 gate,
604 worsened,
605 complexity_worsened: comparison.complexity_worsened_count(),
606 dead_code_introduced: comparison.dead_code.introduced_count(),
607 dead_code_inherited: comparison.dead_code.inherited_count(),
608 complexity_introduced: comparison.health.introduced_count(),
609 complexity_inherited: comparison.health.inherited_count(),
610 duplication_introduced: comparison.dupes.introduced_count(),
611 duplication_inherited: comparison.dupes.inherited_count(),
612 }
613}
614
615fn summary(view: &AuditAnalysesView<'_>, comparison: &AuditComparison) -> AuditSummary {
616 AuditSummary {
617 dead_code_issues: comparison.dead_code.visible_count(),
618 dead_code_has_errors: dead_code_has_errors(view),
619 dead_code_skipped: view.dead_code.is_none(),
620 complexity_skipped: view.health.is_none(),
621 duplication_skipped: view.duplication.is_none(),
622 complexity_findings: view
623 .health
624 .as_ref()
625 .map_or(0, |health| health.report.findings.len()),
626 max_cyclomatic: view.health.as_ref().and_then(|health| {
627 health
628 .report
629 .findings
630 .iter()
631 .map(|finding| finding.cyclomatic)
632 .max()
633 }),
634 duplication_clone_groups: view
635 .duplication
636 .as_ref()
637 .map_or(0, |duplication| duplication.clone_groups.len()),
638 }
639}