1mod base_files;
22mod base_ref;
23mod clone_containment;
24mod outcome;
25mod own_config;
26mod scope;
27mod snapshot;
28#[cfg(test)]
29mod tests;
30
31use std::path::{Path, PathBuf};
32
33use fallow_config::{AuditGate, AuditWorsened, ResolvedConfig, RulesConfig};
34use fallow_engine::changed_files::RenamedFile;
35use fallow_engine::repo_refs::{BaseAnalysisRoot, resolve_base_analysis_root};
36use fallow_output::HealthReport;
37use fallow_types::duplicates::CloneGroup;
38use fallow_types::results::AnalysisResults;
39use rustc_hash::FxHashSet;
40
41pub use base_files::{BaseFileReader, BaseRead, can_reuse_current_as_base, export_names_at_base};
42pub use base_ref::{
43 AuditBaseError, AuditBaseOrigin, parse_audit_base_override, resolve_audit_base,
44 resolve_audit_base_decided,
45};
46pub use outcome::{
47 DupeBase, DupeDemotionDiffSource, RunChange, SharedDiff, compare,
48 demote_preexisting_dupe_introductions, outcome, realign_styling_introductions,
49 styling_finding_gates, styling_rule_severity,
50};
51pub use own_config::{config_path_under_root, own_config_unused_code_keys};
52pub use scope::{
53 BaseCoverageInputs, base_coverage_inputs, base_focus_files, remap_focus_files, renamed_files,
54 scope_dependency_findings, scope_unchanged_unused_code,
55};
56pub use snapshot::{
57 AuditKeySnapshot, branching_keys, type_aware_attribution_degrade_reason,
58 type_aware_degrade_warning, type_aware_gap_signature,
59};
60
61use crate::audit_keys::AuditComparison;
62use crate::{AuditAttribution, AuditSummary, AuditVerdict};
63
64pub struct DeadCodeView<'a> {
66 pub results: &'a AnalysisResults,
68 pub config: &'a ResolvedConfig,
70 pub root: &'a Path,
72 pub type_aware: Option<&'a fallow_types::envelope::TypeAwareMeta>,
74 pub syntactic_keys: Option<&'a FxHashSet<String>>,
77 pub public_api: Option<&'a FxHashSet<String>>,
79 pub own_config_unused_code: Option<&'a FxHashSet<String>>,
83}
84
85pub struct DuplicationView<'a> {
87 pub clone_groups: Vec<&'a CloneGroup>,
89 pub root: &'a Path,
91 pub duplication_percentage: f64,
93 pub threshold: f64,
96 pub config: &'a ResolvedConfig,
99}
100
101pub struct HealthView<'a> {
103 pub report: &'a HealthReport,
105 pub root: &'a Path,
107 pub rules: &'a RulesConfig,
109 pub branching: Option<&'a fallow_engine::health::BranchingByFile>,
111}
112
113#[derive(Default)]
116pub struct AuditAnalysesView<'a> {
117 pub dead_code: Option<DeadCodeView<'a>>,
119 pub duplication: Option<DuplicationView<'a>>,
121 pub health: Option<HealthView<'a>>,
123}
124
125pub trait AuditAnalyses {
127 fn view(&self) -> AuditAnalysesView<'_>;
129 fn dead_code_results_mut(&mut self) -> Option<&mut AnalysisResults>;
132 fn health_report_mut(&mut self) -> Option<&mut HealthReport>;
134 fn record_type_aware_warning(&mut self, warning: &str);
137}
138
139pub trait BaseCheckout {
141 fn path(&self) -> &Path;
143}
144
145impl BaseCheckout for fallow_engine::repo_refs::TemporaryBaseWorktree {
146 fn path(&self) -> &Path {
147 Self::path(self)
148 }
149}
150
151pub trait AuditBackend: Sync {
153 type Analyses: AuditAnalyses + Send;
155 type Checkout: BaseCheckout;
158 type CacheKey: Sync;
160 type Error: Send;
162
163 fn prepare(&self) {}
165
166 fn run_head(&self, changed_files: &FxHashSet<PathBuf>) -> Result<Self::Analyses, Self::Error>;
172
173 fn create_base_checkout(
180 &self,
181 base_ref: &str,
182 base_sha: Option<&str>,
183 ) -> Result<Self::Checkout, Self::Error>;
184
185 fn run_base(
192 &self,
193 base_root: &Path,
194 focus: Option<&FxHashSet<PathBuf>>,
195 ) -> Result<Self::Analyses, Self::Error>;
196
197 fn base_cache_key(
204 &self,
205 _base_ref: &str,
206 _focus: &FxHashSet<PathBuf>,
207 ) -> Result<Option<Self::CacheKey>, Self::Error> {
208 Ok(None)
209 }
210
211 fn cached_base_sha<'k>(&self, _key: &'k Self::CacheKey) -> Option<&'k str> {
213 None
214 }
215
216 fn load_cached_base(&self, _key: &Self::CacheKey) -> Option<AuditKeySnapshot> {
218 None
219 }
220
221 fn save_cached_base(&self, _key: &Self::CacheKey, _snapshot: &AuditKeySnapshot) {}
223
224 fn shared_diff(&self) -> Option<SharedDiff<'_>> {
226 None
227 }
228}
229
230pub struct AuditRunInput<'a> {
232 pub root: &'a Path,
234 pub gate: AuditGate,
236 pub worsened: AuditWorsened,
238 pub base_ref: &'a str,
240 pub cache_dir: Option<&'a Path>,
243 pub changed_files: FxHashSet<PathBuf>,
245 pub inherited_base_refs: &'a [String],
248 pub compare_line_counts: bool,
251}
252
253#[derive(Debug, Default)]
255pub struct AuditBase {
256 pub snapshot: Option<AuditKeySnapshot>,
258 pub skipped: bool,
261 pub inherited: Vec<AuditKeySnapshot>,
264}
265
266pub struct AuditAttributionInput<'a> {
268 pub root: &'a Path,
270 pub gate: AuditGate,
272 pub worsened: AuditWorsened,
274 pub base_ref: &'a str,
276 pub base: AuditBase,
278 pub renames: &'a [RenamedFile],
280 pub changed_files: &'a FxHashSet<PathBuf>,
283 pub shared_diff: Option<SharedDiff<'a>>,
285}
286
287#[derive(Debug)]
289pub struct AuditOutcome {
290 pub verdict: AuditVerdict,
292 pub summary: AuditSummary,
294 pub attribution: AuditAttribution,
296 pub comparison: AuditComparison,
298 pub base_snapshot: Option<AuditKeySnapshot>,
300 pub base_snapshot_skipped: bool,
302 pub dupe_demotion_diff_source: Option<DupeDemotionDiffSource>,
305 pub type_aware_degrade_warning: Option<String>,
308 pub diff_risk: fallow_output::DiffRiskReport,
311}
312
313impl AuditOutcome {
314 pub fn apply_diff_risk(&mut self, report: fallow_output::DiffRiskReport) {
318 if report.has_errors() {
319 self.verdict = AuditVerdict::Fail;
320 } else if !report.is_empty() && self.verdict == AuditVerdict::Pass {
321 self.verdict = AuditVerdict::Warn;
322 }
323 self.diff_risk = report;
324 }
325}
326
327pub(crate) fn programmatic_base_snapshot(
330 outcome: &AuditOutcome,
331) -> Option<crate::AuditProgrammaticKeySnapshot> {
332 outcome
333 .base_snapshot
334 .as_ref()
335 .map(AuditKeySnapshot::to_programmatic)
336}
337
338pub struct AuditRun<A> {
340 pub analyses: A,
343 pub changed_files: FxHashSet<PathBuf>,
345 pub outcome: AuditOutcome,
347}
348
349fn needs_real_base(input: &AuditRunInput<'_>) -> bool {
352 matches!(input.gate, AuditGate::NewOnly)
353 && !can_reuse_current_as_base(
354 input.root,
355 input.cache_dir,
356 input.base_ref,
357 &input.changed_files,
358 input.compare_line_counts,
359 )
360}
361
362pub fn run<B: AuditBackend>(
369 backend: &B,
370 input: AuditRunInput<'_>,
371) -> Result<Option<AuditRun<B::Analyses>>, B::Error> {
372 if input.changed_files.is_empty() {
373 return Ok(None);
374 }
375 backend.prepare();
376 let needs_real_base = needs_real_base(&input);
377 let AuditRunInput {
378 root,
379 gate,
380 worsened,
381 base_ref,
382 cache_dir: _,
383 changed_files,
384 inherited_base_refs,
385 compare_line_counts: _,
386 } = input;
387 let renames = if needs_real_base || !matches!(gate, AuditGate::NewOnly) {
390 renamed_files(root, base_ref)
391 } else {
392 Vec::new()
393 };
394 let focus = base_focus_files(&changed_files, &renames);
395 let cache_key = if needs_real_base {
396 backend.base_cache_key(base_ref, &focus)?
397 } else {
398 None
399 };
400 let cached = cache_key
401 .as_ref()
402 .and_then(|key| backend.load_cached_base(key));
403
404 let (head, fresh_base) = if needs_real_base && cached.is_none() {
405 let base_sha = cache_key
406 .as_ref()
407 .and_then(|key| backend.cached_base_sha(key));
408 let (head, base) = rayon::join(
409 || backend.run_head(&changed_files),
410 || base_snapshot(backend, root, base_ref, &focus, base_sha),
411 );
412 (head, Some(base))
413 } else {
414 (backend.run_head(&changed_files), None)
415 };
416 let mut analyses = head?;
417 scope_dependency_findings_of(&mut analyses, &changed_files);
418
419 let base = if !matches!(gate, AuditGate::NewOnly) {
420 AuditBase::default()
421 } else if let Some(snapshot) = cached {
422 AuditBase {
423 snapshot: Some(snapshot),
424 skipped: false,
425 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
426 }
427 } else if let Some(fresh) = fresh_base {
428 let snapshot = fresh?;
429 if let Some(key) = cache_key.as_ref() {
430 backend.save_cached_base(key, &snapshot);
431 }
432 AuditBase {
433 snapshot: Some(snapshot),
434 skipped: false,
435 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
436 }
437 } else {
438 AuditBase {
439 snapshot: Some(AuditKeySnapshot::from_view(&analyses.view())),
440 skipped: true,
441 inherited: Vec::new(),
442 }
443 };
444
445 let mut outcome = attribute(
446 &mut analyses,
447 AuditAttributionInput {
448 root,
449 gate,
450 worsened,
451 base_ref,
452 base,
453 renames: &renames,
454 changed_files: &changed_files,
455 shared_diff: backend.shared_diff(),
456 },
457 );
458 let diff_risk = diff_risk_of(
459 &analyses,
460 &outcome,
461 root,
462 base_ref,
463 &changed_files,
464 &renames,
465 );
466 outcome.apply_diff_risk(diff_risk);
467 Ok(Some(AuditRun {
468 analyses,
469 changed_files,
470 outcome,
471 }))
472}
473
474fn annotate_health_report(report: &mut HealthReport, comparison: &AuditComparison) {
476 for ((finding, introduced), class) in report
477 .findings
478 .iter_mut()
479 .zip(comparison.health.introduced())
480 .zip(&comparison.health_classes)
481 {
482 finding.introduced = Some(introduced);
483 let attribution = class.attribution();
484 finding.attribution = Some(attribution);
485 finding.worsened_metrics.clone_from(&class.worsened_metrics);
486 finding.audit_base = class
487 .base
488 .filter(|_| attribution == fallow_output::AuditFindingAttribution::Inherited);
489 }
490 for (finding, introduced) in report
491 .styling_findings
492 .iter_mut()
493 .zip(comparison.styling.introduced())
494 {
495 finding.internal.introduced = Some(introduced);
496 }
497}
498
499pub fn attribute<A: AuditAnalyses>(
507 analyses: &mut A,
508 input: AuditAttributionInput<'_>,
509) -> AuditOutcome {
510 let AuditAttributionInput {
511 root,
512 gate,
513 worsened,
514 base_ref,
515 base,
516 renames,
517 changed_files,
518 shared_diff,
519 } = input;
520 let AuditBase {
521 snapshot: mut base_snapshot,
522 skipped,
523 inherited,
524 } = base;
525 if matches!(gate, AuditGate::NewOnly)
526 && let Some(report) = analyses.health_report_mut()
527 {
528 crate::audit_complexity::demote_estimated_crap_gates(&mut report.findings);
529 }
530 if let Some(report) = analyses.health_report_mut() {
531 crate::audit_complexity::exempt_test_file_gates(&mut report.findings, root);
532 }
533 if !skipped && let Some(snapshot) = base_snapshot.as_mut() {
535 snapshot.remap_for_renames(renames, root);
536 for inherited in inherited {
537 snapshot.absorb_inherited(inherited);
538 }
539 if let Some(dead_code) = analyses.view().dead_code.as_ref() {
540 snapshot.forget_unused_code_used_under_own_config(dead_code);
541 snapshot.inherit_unprovable_dead_code(dead_code);
542 }
543 }
544 scope_unchanged_unused_code_of(analyses, changed_files, base_snapshot.as_ref());
545 let degrade_reason = {
546 let view = analyses.view();
547 type_aware_attribution_degrade_reason(
548 base_snapshot.as_ref(),
549 view.dead_code
550 .as_ref()
551 .and_then(|dead_code| dead_code.type_aware),
552 )
553 };
554 let type_aware_degrade_warning = degrade_reason.map(type_aware_degrade_warning);
555 if let Some(warning) = type_aware_degrade_warning.as_deref() {
556 analyses.record_type_aware_warning(warning);
557 }
558
559 let (comparison, dupe_demotion_diff_source, (attribution, verdict, summary)) = {
560 let view = analyses.view();
561 let change = RunChange::new(root, base_ref, shared_diff, changed_files);
562 let degraded = degrade_reason.is_some();
563 let mut comparison = compare(&view, base_snapshot.as_ref(), degraded, &change);
564 comparison.clear_worsened_when_off(worsened);
565 let source = demote_preexisting_dupe_introductions(
566 &mut comparison,
567 &view,
568 root,
569 base_ref,
570 shared_diff,
571 DupeBase {
572 groups: base_snapshot
574 .as_ref()
575 .filter(|_| !skipped)
576 .map_or(&[][..], |snapshot| snapshot.dupe_groups.as_slice()),
577 renames,
578 },
579 );
580 realign_styling_introductions(
581 &mut comparison,
582 &view,
583 base_snapshot.as_ref(),
584 root,
585 base_ref,
586 shared_diff,
587 );
588 let result = outcome(gate, worsened, &view, &comparison, base_snapshot.is_some());
589 (comparison, source, result)
590 };
591
592 if base_snapshot.is_some() {
593 if let Some(results) = analyses.dead_code_results_mut() {
594 comparison.dead_code.annotate_results(results);
595 }
596 if let Some(report) = analyses.health_report_mut() {
597 annotate_health_report(report, &comparison);
598 }
599 }
600
601 AuditOutcome {
602 verdict,
603 summary,
604 attribution,
605 comparison,
606 base_snapshot,
607 base_snapshot_skipped: skipped,
608 dupe_demotion_diff_source,
609 type_aware_degrade_warning,
610 diff_risk: fallow_output::DiffRiskReport::default(),
611 }
612}
613
614fn diff_risk_of<A: AuditAnalyses>(
616 analyses: &A,
617 outcome: &AuditOutcome,
618 root: &Path,
619 base_ref: &str,
620 changed_files: &FxHashSet<PathBuf>,
621 renames: &[RenamedFile],
622) -> fallow_output::DiffRiskReport {
623 let view = analyses.view();
624 let default_rules = RulesConfig::default();
625 let rules = if let Some(dead_code) = view.dead_code.as_ref() {
626 crate::diff_risk::DiffRiskRules::Config(dead_code.config)
627 } else if let Some(health) = view.health.as_ref() {
628 crate::diff_risk::DiffRiskRules::Rules(health.rules)
629 } else {
630 crate::diff_risk::DiffRiskRules::Rules(&default_rules)
631 };
632 let head_clone_groups = view
633 .duplication
634 .as_ref()
635 .map(|duplication| {
636 duplication
637 .clone_groups
638 .iter()
639 .map(|group| crate::diff_risk::clone_spans(group, duplication.root))
640 .collect()
641 })
642 .unwrap_or_default();
643 let base_clone_groups = if outcome.base_snapshot_skipped || view.duplication.is_none() {
645 None
646 } else {
647 outcome
648 .base_snapshot
649 .as_ref()
650 .map(|snapshot| snapshot.dupe_groups.as_slice())
651 };
652 crate::diff_risk::detect(&crate::diff_risk::DiffRiskInput {
653 root,
654 base_ref,
655 changed_files,
656 renames,
657 rules,
658 base_clone_groups,
659 head_clone_groups,
660 })
661}
662
663fn inherited_snapshots<B: AuditBackend>(
669 backend: &B,
670 root: &Path,
671 refs: &[String],
672 focus: &FxHashSet<PathBuf>,
673) -> Vec<AuditKeySnapshot> {
674 refs.iter()
675 .filter_map(|inherited_ref| inherited_snapshot(backend, root, inherited_ref, focus).ok())
676 .collect()
677}
678
679fn inherited_snapshot<B: AuditBackend>(
680 backend: &B,
681 root: &Path,
682 inherited_ref: &str,
683 focus: &FxHashSet<PathBuf>,
684) -> Result<AuditKeySnapshot, B::Error> {
685 let cache_key = backend.base_cache_key(inherited_ref, focus)?;
686 if let Some(cached) = cache_key
687 .as_ref()
688 .and_then(|key| backend.load_cached_base(key))
689 {
690 return Ok(remapped(cached, root, inherited_ref));
691 }
692 let base_sha = cache_key
693 .as_ref()
694 .and_then(|key| backend.cached_base_sha(key));
695 let snapshot = base_snapshot(backend, root, inherited_ref, focus, base_sha)?;
696 if let Some(key) = cache_key.as_ref() {
697 backend.save_cached_base(key, &snapshot);
698 }
699 Ok(remapped(snapshot, root, inherited_ref))
700}
701
702fn remapped(mut snapshot: AuditKeySnapshot, root: &Path, base_ref: &str) -> AuditKeySnapshot {
703 snapshot.remap_for_renames(&renamed_files(root, base_ref), root);
704 snapshot
705}
706
707fn base_snapshot<B: AuditBackend>(
709 backend: &B,
710 root: &Path,
711 base_ref: &str,
712 focus: &FxHashSet<PathBuf>,
713 base_sha: Option<&str>,
714) -> Result<AuditKeySnapshot, B::Error> {
715 let checkout = backend.create_base_checkout(base_ref, base_sha)?;
716 let base_root = match resolve_base_analysis_root(root, checkout.path()) {
717 BaseAnalysisRoot::Present(base_root) => {
721 dunce::canonicalize(&base_root).unwrap_or(base_root)
722 }
723 BaseAnalysisRoot::NewInHead(_) => return Ok(AuditKeySnapshot::default()),
727 };
728 let base_focus = remap_focus_files(focus, root, &base_root);
729 let mut base = backend.run_base(&base_root, base_focus.as_ref())?;
730 if let Some(focus) = base_focus.as_ref() {
731 scope_dependency_findings_of(&mut base, focus);
732 }
733 let snapshot = AuditKeySnapshot::from_view(&base.view());
734 drop(checkout);
735 Ok(snapshot)
736}
737
738fn scope_unchanged_unused_code_of<A: AuditAnalyses>(
741 analyses: &mut A,
742 changed_files: &FxHashSet<PathBuf>,
743 base: Option<&AuditKeySnapshot>,
744) {
745 let Some(root) = analyses
746 .view()
747 .dead_code
748 .map(|dead_code| dead_code.root.to_path_buf())
749 else {
750 return;
751 };
752 if let Some(results) = analyses.dead_code_results_mut() {
753 scope_unchanged_unused_code(results, &root, changed_files, base);
754 }
755}
756
757fn scope_dependency_findings_of<A: AuditAnalyses>(
759 analyses: &mut A,
760 changed_files: &FxHashSet<PathBuf>,
761) {
762 let Some(root) = analyses
763 .view()
764 .dead_code
765 .map(|dead_code| dead_code.root.to_path_buf())
766 else {
767 return;
768 };
769 if let Some(results) = analyses.dead_code_results_mut() {
770 scope_dependency_findings(results, &root, changed_files);
771 }
772}