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};
45pub use outcome::{
46 DupeBase, DupeDemotionDiffSource, RunChange, SharedDiff, compare,
47 demote_preexisting_dupe_introductions, outcome, realign_styling_introductions,
48 styling_finding_gates, styling_rule_severity,
49};
50pub use own_config::{config_path_under_root, own_config_unused_code_keys};
51pub use scope::{
52 BaseCoverageInputs, base_coverage_inputs, base_focus_files, remap_focus_files, renamed_files,
53 scope_dependency_findings, scope_unchanged_unused_code,
54};
55pub use snapshot::{
56 AuditKeySnapshot, branching_keys, type_aware_attribution_degrade_reason,
57 type_aware_degrade_warning, type_aware_gap_signature,
58};
59
60use crate::audit_keys::AuditComparison;
61use crate::{AuditAttribution, AuditSummary, AuditVerdict};
62
63pub struct DeadCodeView<'a> {
65 pub results: &'a AnalysisResults,
67 pub config: &'a ResolvedConfig,
69 pub root: &'a Path,
71 pub type_aware: Option<&'a fallow_types::envelope::TypeAwareMeta>,
73 pub syntactic_keys: Option<&'a FxHashSet<String>>,
76 pub public_api: Option<&'a FxHashSet<String>>,
78 pub own_config_unused_code: Option<&'a FxHashSet<String>>,
82}
83
84pub struct DuplicationView<'a> {
86 pub clone_groups: Vec<&'a CloneGroup>,
88 pub root: &'a Path,
90 pub duplication_percentage: f64,
92 pub threshold: f64,
95 pub config: &'a ResolvedConfig,
98}
99
100pub struct HealthView<'a> {
102 pub report: &'a HealthReport,
104 pub root: &'a Path,
106 pub rules: &'a RulesConfig,
108 pub branching: Option<&'a fallow_engine::health::BranchingByFile>,
110}
111
112#[derive(Default)]
115pub struct AuditAnalysesView<'a> {
116 pub dead_code: Option<DeadCodeView<'a>>,
118 pub duplication: Option<DuplicationView<'a>>,
120 pub health: Option<HealthView<'a>>,
122}
123
124pub trait AuditAnalyses {
126 fn view(&self) -> AuditAnalysesView<'_>;
128 fn dead_code_results_mut(&mut self) -> Option<&mut AnalysisResults>;
131 fn health_report_mut(&mut self) -> Option<&mut HealthReport>;
133 fn record_type_aware_warning(&mut self, warning: &str);
136}
137
138pub trait BaseCheckout {
140 fn path(&self) -> &Path;
142}
143
144impl BaseCheckout for fallow_engine::repo_refs::TemporaryBaseWorktree {
145 fn path(&self) -> &Path {
146 Self::path(self)
147 }
148}
149
150pub trait AuditBackend: Sync {
152 type Analyses: AuditAnalyses + Send;
154 type Checkout: BaseCheckout;
157 type CacheKey: Sync;
159 type Error: Send;
161
162 fn prepare(&self) {}
164
165 fn run_head(&self, changed_files: &FxHashSet<PathBuf>) -> Result<Self::Analyses, Self::Error>;
171
172 fn create_base_checkout(
179 &self,
180 base_ref: &str,
181 base_sha: Option<&str>,
182 ) -> Result<Self::Checkout, Self::Error>;
183
184 fn run_base(
191 &self,
192 base_root: &Path,
193 focus: Option<&FxHashSet<PathBuf>>,
194 ) -> Result<Self::Analyses, Self::Error>;
195
196 fn base_cache_key(
203 &self,
204 _base_ref: &str,
205 _focus: &FxHashSet<PathBuf>,
206 ) -> Result<Option<Self::CacheKey>, Self::Error> {
207 Ok(None)
208 }
209
210 fn cached_base_sha<'k>(&self, _key: &'k Self::CacheKey) -> Option<&'k str> {
212 None
213 }
214
215 fn load_cached_base(&self, _key: &Self::CacheKey) -> Option<AuditKeySnapshot> {
217 None
218 }
219
220 fn save_cached_base(&self, _key: &Self::CacheKey, _snapshot: &AuditKeySnapshot) {}
222
223 fn shared_diff(&self) -> Option<SharedDiff<'_>> {
225 None
226 }
227}
228
229pub struct AuditRunInput<'a> {
231 pub root: &'a Path,
233 pub gate: AuditGate,
235 pub worsened: AuditWorsened,
237 pub base_ref: &'a str,
239 pub cache_dir: Option<&'a Path>,
242 pub changed_files: FxHashSet<PathBuf>,
244 pub inherited_base_refs: &'a [String],
247 pub compare_line_counts: bool,
250}
251
252#[derive(Debug, Default)]
254pub struct AuditBase {
255 pub snapshot: Option<AuditKeySnapshot>,
257 pub skipped: bool,
260 pub inherited: Vec<AuditKeySnapshot>,
263}
264
265pub struct AuditAttributionInput<'a> {
267 pub root: &'a Path,
269 pub gate: AuditGate,
271 pub worsened: AuditWorsened,
273 pub base_ref: &'a str,
275 pub base: AuditBase,
277 pub renames: &'a [RenamedFile],
279 pub changed_files: &'a FxHashSet<PathBuf>,
282 pub shared_diff: Option<SharedDiff<'a>>,
284}
285
286#[derive(Debug)]
288pub struct AuditOutcome {
289 pub verdict: AuditVerdict,
291 pub summary: AuditSummary,
293 pub attribution: AuditAttribution,
295 pub comparison: AuditComparison,
297 pub base_snapshot: Option<AuditKeySnapshot>,
299 pub base_snapshot_skipped: bool,
301 pub dupe_demotion_diff_source: Option<DupeDemotionDiffSource>,
304 pub type_aware_degrade_warning: Option<String>,
307 pub diff_risk: fallow_output::DiffRiskReport,
310}
311
312impl AuditOutcome {
313 pub fn apply_diff_risk(&mut self, report: fallow_output::DiffRiskReport) {
317 if report.has_errors() {
318 self.verdict = AuditVerdict::Fail;
319 } else if !report.is_empty() && self.verdict == AuditVerdict::Pass {
320 self.verdict = AuditVerdict::Warn;
321 }
322 self.diff_risk = report;
323 }
324}
325
326pub(crate) fn programmatic_base_snapshot(
329 outcome: &AuditOutcome,
330) -> Option<crate::AuditProgrammaticKeySnapshot> {
331 outcome
332 .base_snapshot
333 .as_ref()
334 .map(AuditKeySnapshot::to_programmatic)
335}
336
337pub struct AuditRun<A> {
339 pub analyses: A,
342 pub changed_files: FxHashSet<PathBuf>,
344 pub outcome: AuditOutcome,
346}
347
348fn needs_real_base(input: &AuditRunInput<'_>) -> bool {
351 matches!(input.gate, AuditGate::NewOnly)
352 && !can_reuse_current_as_base(
353 input.root,
354 input.cache_dir,
355 input.base_ref,
356 &input.changed_files,
357 input.compare_line_counts,
358 )
359}
360
361pub fn run<B: AuditBackend>(
368 backend: &B,
369 input: AuditRunInput<'_>,
370) -> Result<Option<AuditRun<B::Analyses>>, B::Error> {
371 if input.changed_files.is_empty() {
372 return Ok(None);
373 }
374 backend.prepare();
375 let needs_real_base = needs_real_base(&input);
376 let AuditRunInput {
377 root,
378 gate,
379 worsened,
380 base_ref,
381 cache_dir: _,
382 changed_files,
383 inherited_base_refs,
384 compare_line_counts: _,
385 } = input;
386 let renames = if needs_real_base || !matches!(gate, AuditGate::NewOnly) {
389 renamed_files(root, base_ref)
390 } else {
391 Vec::new()
392 };
393 let focus = base_focus_files(&changed_files, &renames);
394 let cache_key = if needs_real_base {
395 backend.base_cache_key(base_ref, &focus)?
396 } else {
397 None
398 };
399 let cached = cache_key
400 .as_ref()
401 .and_then(|key| backend.load_cached_base(key));
402
403 let (head, fresh_base) = if needs_real_base && cached.is_none() {
404 let base_sha = cache_key
405 .as_ref()
406 .and_then(|key| backend.cached_base_sha(key));
407 let (head, base) = rayon::join(
408 || backend.run_head(&changed_files),
409 || base_snapshot(backend, root, base_ref, &focus, base_sha),
410 );
411 (head, Some(base))
412 } else {
413 (backend.run_head(&changed_files), None)
414 };
415 let mut analyses = head?;
416 scope_dependency_findings_of(&mut analyses, &changed_files);
417
418 let base = if !matches!(gate, AuditGate::NewOnly) {
419 AuditBase::default()
420 } else if let Some(snapshot) = cached {
421 AuditBase {
422 snapshot: Some(snapshot),
423 skipped: false,
424 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
425 }
426 } else if let Some(fresh) = fresh_base {
427 let snapshot = fresh?;
428 if let Some(key) = cache_key.as_ref() {
429 backend.save_cached_base(key, &snapshot);
430 }
431 AuditBase {
432 snapshot: Some(snapshot),
433 skipped: false,
434 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
435 }
436 } else {
437 AuditBase {
438 snapshot: Some(AuditKeySnapshot::from_view(&analyses.view())),
439 skipped: true,
440 inherited: Vec::new(),
441 }
442 };
443
444 let mut outcome = attribute(
445 &mut analyses,
446 AuditAttributionInput {
447 root,
448 gate,
449 worsened,
450 base_ref,
451 base,
452 renames: &renames,
453 changed_files: &changed_files,
454 shared_diff: backend.shared_diff(),
455 },
456 );
457 let diff_risk = diff_risk_of(
458 &analyses,
459 &outcome,
460 root,
461 base_ref,
462 &changed_files,
463 &renames,
464 );
465 outcome.apply_diff_risk(diff_risk);
466 Ok(Some(AuditRun {
467 analyses,
468 changed_files,
469 outcome,
470 }))
471}
472
473fn annotate_health_report(report: &mut HealthReport, comparison: &AuditComparison) {
475 for ((finding, introduced), class) in report
476 .findings
477 .iter_mut()
478 .zip(comparison.health.introduced())
479 .zip(&comparison.health_classes)
480 {
481 finding.introduced = Some(introduced);
482 let attribution = class.attribution();
483 finding.attribution = Some(attribution);
484 finding.worsened_metrics.clone_from(&class.worsened_metrics);
485 finding.audit_base = class
486 .base
487 .filter(|_| attribution == fallow_output::AuditFindingAttribution::Inherited);
488 }
489 for (finding, introduced) in report
490 .styling_findings
491 .iter_mut()
492 .zip(comparison.styling.introduced())
493 {
494 finding.internal.introduced = Some(introduced);
495 }
496}
497
498pub fn attribute<A: AuditAnalyses>(
506 analyses: &mut A,
507 input: AuditAttributionInput<'_>,
508) -> AuditOutcome {
509 let AuditAttributionInput {
510 root,
511 gate,
512 worsened,
513 base_ref,
514 base,
515 renames,
516 changed_files,
517 shared_diff,
518 } = input;
519 let AuditBase {
520 snapshot: mut base_snapshot,
521 skipped,
522 inherited,
523 } = base;
524 if matches!(gate, AuditGate::NewOnly)
525 && let Some(report) = analyses.health_report_mut()
526 {
527 crate::audit_complexity::demote_estimated_crap_gates(&mut report.findings);
528 }
529 if let Some(report) = analyses.health_report_mut() {
530 crate::audit_complexity::exempt_test_file_gates(&mut report.findings, root);
531 }
532 if !skipped && let Some(snapshot) = base_snapshot.as_mut() {
534 snapshot.remap_for_renames(renames, root);
535 for inherited in inherited {
536 snapshot.absorb_inherited(inherited);
537 }
538 if let Some(dead_code) = analyses.view().dead_code.as_ref() {
539 snapshot.forget_unused_code_used_under_own_config(dead_code);
540 snapshot.inherit_unprovable_dead_code(dead_code);
541 }
542 }
543 scope_unchanged_unused_code_of(analyses, changed_files, base_snapshot.as_ref());
544 let degrade_reason = {
545 let view = analyses.view();
546 type_aware_attribution_degrade_reason(
547 base_snapshot.as_ref(),
548 view.dead_code
549 .as_ref()
550 .and_then(|dead_code| dead_code.type_aware),
551 )
552 };
553 let type_aware_degrade_warning = degrade_reason.map(type_aware_degrade_warning);
554 if let Some(warning) = type_aware_degrade_warning.as_deref() {
555 analyses.record_type_aware_warning(warning);
556 }
557
558 let (comparison, dupe_demotion_diff_source, (attribution, verdict, summary)) = {
559 let view = analyses.view();
560 let change = RunChange::new(root, base_ref, shared_diff, changed_files);
561 let degraded = degrade_reason.is_some();
562 let mut comparison = compare(&view, base_snapshot.as_ref(), degraded, &change);
563 comparison.clear_worsened_when_off(worsened);
564 let source = demote_preexisting_dupe_introductions(
565 &mut comparison,
566 &view,
567 root,
568 base_ref,
569 shared_diff,
570 DupeBase {
571 groups: base_snapshot
573 .as_ref()
574 .filter(|_| !skipped)
575 .map_or(&[][..], |snapshot| snapshot.dupe_groups.as_slice()),
576 renames,
577 },
578 );
579 realign_styling_introductions(
580 &mut comparison,
581 &view,
582 base_snapshot.as_ref(),
583 root,
584 base_ref,
585 shared_diff,
586 );
587 let result = outcome(gate, worsened, &view, &comparison, base_snapshot.is_some());
588 (comparison, source, result)
589 };
590
591 if base_snapshot.is_some() {
592 if let Some(results) = analyses.dead_code_results_mut() {
593 comparison.dead_code.annotate_results(results);
594 }
595 if let Some(report) = analyses.health_report_mut() {
596 annotate_health_report(report, &comparison);
597 }
598 }
599
600 AuditOutcome {
601 verdict,
602 summary,
603 attribution,
604 comparison,
605 base_snapshot,
606 base_snapshot_skipped: skipped,
607 dupe_demotion_diff_source,
608 type_aware_degrade_warning,
609 diff_risk: fallow_output::DiffRiskReport::default(),
610 }
611}
612
613fn diff_risk_of<A: AuditAnalyses>(
615 analyses: &A,
616 outcome: &AuditOutcome,
617 root: &Path,
618 base_ref: &str,
619 changed_files: &FxHashSet<PathBuf>,
620 renames: &[RenamedFile],
621) -> fallow_output::DiffRiskReport {
622 let view = analyses.view();
623 let default_rules = RulesConfig::default();
624 let rules = if let Some(dead_code) = view.dead_code.as_ref() {
625 crate::diff_risk::DiffRiskRules::Config(dead_code.config)
626 } else if let Some(health) = view.health.as_ref() {
627 crate::diff_risk::DiffRiskRules::Rules(health.rules)
628 } else {
629 crate::diff_risk::DiffRiskRules::Rules(&default_rules)
630 };
631 let head_clone_groups = view
632 .duplication
633 .as_ref()
634 .map(|duplication| {
635 duplication
636 .clone_groups
637 .iter()
638 .map(|group| crate::diff_risk::clone_spans(group, duplication.root))
639 .collect()
640 })
641 .unwrap_or_default();
642 let base_clone_groups = if outcome.base_snapshot_skipped || view.duplication.is_none() {
644 None
645 } else {
646 outcome
647 .base_snapshot
648 .as_ref()
649 .map(|snapshot| snapshot.dupe_groups.as_slice())
650 };
651 crate::diff_risk::detect(&crate::diff_risk::DiffRiskInput {
652 root,
653 base_ref,
654 changed_files,
655 renames,
656 rules,
657 base_clone_groups,
658 head_clone_groups,
659 })
660}
661
662fn inherited_snapshots<B: AuditBackend>(
668 backend: &B,
669 root: &Path,
670 refs: &[String],
671 focus: &FxHashSet<PathBuf>,
672) -> Vec<AuditKeySnapshot> {
673 refs.iter()
674 .filter_map(|inherited_ref| inherited_snapshot(backend, root, inherited_ref, focus).ok())
675 .collect()
676}
677
678fn inherited_snapshot<B: AuditBackend>(
679 backend: &B,
680 root: &Path,
681 inherited_ref: &str,
682 focus: &FxHashSet<PathBuf>,
683) -> Result<AuditKeySnapshot, B::Error> {
684 let cache_key = backend.base_cache_key(inherited_ref, focus)?;
685 if let Some(cached) = cache_key
686 .as_ref()
687 .and_then(|key| backend.load_cached_base(key))
688 {
689 return Ok(remapped(cached, root, inherited_ref));
690 }
691 let base_sha = cache_key
692 .as_ref()
693 .and_then(|key| backend.cached_base_sha(key));
694 let snapshot = base_snapshot(backend, root, inherited_ref, focus, base_sha)?;
695 if let Some(key) = cache_key.as_ref() {
696 backend.save_cached_base(key, &snapshot);
697 }
698 Ok(remapped(snapshot, root, inherited_ref))
699}
700
701fn remapped(mut snapshot: AuditKeySnapshot, root: &Path, base_ref: &str) -> AuditKeySnapshot {
702 snapshot.remap_for_renames(&renamed_files(root, base_ref), root);
703 snapshot
704}
705
706fn base_snapshot<B: AuditBackend>(
708 backend: &B,
709 root: &Path,
710 base_ref: &str,
711 focus: &FxHashSet<PathBuf>,
712 base_sha: Option<&str>,
713) -> Result<AuditKeySnapshot, B::Error> {
714 let checkout = backend.create_base_checkout(base_ref, base_sha)?;
715 let base_root = match resolve_base_analysis_root(root, checkout.path()) {
716 BaseAnalysisRoot::Present(base_root) => {
720 dunce::canonicalize(&base_root).unwrap_or(base_root)
721 }
722 BaseAnalysisRoot::NewInHead(_) => return Ok(AuditKeySnapshot::default()),
726 };
727 let base_focus = remap_focus_files(focus, root, &base_root);
728 let mut base = backend.run_base(&base_root, base_focus.as_ref())?;
729 if let Some(focus) = base_focus.as_ref() {
730 scope_dependency_findings_of(&mut base, focus);
731 }
732 let snapshot = AuditKeySnapshot::from_view(&base.view());
733 drop(checkout);
734 Ok(snapshot)
735}
736
737fn scope_unchanged_unused_code_of<A: AuditAnalyses>(
740 analyses: &mut A,
741 changed_files: &FxHashSet<PathBuf>,
742 base: Option<&AuditKeySnapshot>,
743) {
744 let Some(root) = analyses
745 .view()
746 .dead_code
747 .map(|dead_code| dead_code.root.to_path_buf())
748 else {
749 return;
750 };
751 if let Some(results) = analyses.dead_code_results_mut() {
752 scope_unchanged_unused_code(results, &root, changed_files, base);
753 }
754}
755
756fn scope_dependency_findings_of<A: AuditAnalyses>(
758 analyses: &mut A,
759 changed_files: &FxHashSet<PathBuf>,
760) {
761 let Some(root) = analyses
762 .view()
763 .dead_code
764 .map(|dead_code| dead_code.root.to_path_buf())
765 else {
766 return;
767 };
768 if let Some(results) = analyses.dead_code_results_mut() {
769 scope_dependency_findings(results, &root, changed_files);
770 }
771}