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, SharedDiff, compare, demote_preexisting_dupe_introductions,
47 outcome, realign_styling_introductions, styling_finding_gates, styling_rule_severity,
48};
49pub use own_config::{config_path_under_root, own_config_unused_code_keys};
50pub use scope::{
51 BaseCoverageInputs, base_coverage_inputs, base_focus_files, remap_focus_files, renamed_files,
52 scope_dependency_findings, scope_unchanged_unused_code,
53};
54pub use snapshot::{
55 AuditKeySnapshot, branching_keys, type_aware_attribution_degrade_reason,
56 type_aware_degrade_warning, type_aware_gap_signature,
57};
58
59use crate::audit_keys::AuditComparison;
60use crate::{AuditAttribution, AuditSummary, AuditVerdict};
61
62pub struct DeadCodeView<'a> {
64 pub results: &'a AnalysisResults,
66 pub config: &'a ResolvedConfig,
68 pub root: &'a Path,
70 pub type_aware: Option<&'a fallow_types::envelope::TypeAwareMeta>,
72 pub syntactic_keys: Option<&'a FxHashSet<String>>,
75 pub public_api: Option<&'a FxHashSet<String>>,
77 pub own_config_unused_code: Option<&'a FxHashSet<String>>,
81}
82
83pub struct DuplicationView<'a> {
85 pub clone_groups: Vec<&'a CloneGroup>,
87 pub root: &'a Path,
89 pub duplication_percentage: f64,
91 pub threshold: f64,
94}
95
96pub struct HealthView<'a> {
98 pub report: &'a HealthReport,
100 pub root: &'a Path,
102 pub rules: &'a RulesConfig,
104 pub branching: Option<&'a fallow_engine::health::BranchingByFile>,
106}
107
108#[derive(Default)]
111pub struct AuditAnalysesView<'a> {
112 pub dead_code: Option<DeadCodeView<'a>>,
114 pub duplication: Option<DuplicationView<'a>>,
116 pub health: Option<HealthView<'a>>,
118}
119
120pub trait AuditAnalyses {
122 fn view(&self) -> AuditAnalysesView<'_>;
124 fn dead_code_results_mut(&mut self) -> Option<&mut AnalysisResults>;
127 fn health_report_mut(&mut self) -> Option<&mut HealthReport>;
129 fn record_type_aware_warning(&mut self, warning: &str);
132}
133
134pub trait BaseCheckout {
136 fn path(&self) -> &Path;
138}
139
140impl BaseCheckout for fallow_engine::repo_refs::TemporaryBaseWorktree {
141 fn path(&self) -> &Path {
142 Self::path(self)
143 }
144}
145
146pub trait AuditBackend: Sync {
148 type Analyses: AuditAnalyses + Send;
150 type Checkout: BaseCheckout;
153 type CacheKey: Sync;
155 type Error: Send;
157
158 fn prepare(&self) {}
160
161 fn run_head(&self, changed_files: &FxHashSet<PathBuf>) -> Result<Self::Analyses, Self::Error>;
167
168 fn create_base_checkout(
175 &self,
176 base_ref: &str,
177 base_sha: Option<&str>,
178 ) -> Result<Self::Checkout, Self::Error>;
179
180 fn run_base(
187 &self,
188 base_root: &Path,
189 focus: Option<&FxHashSet<PathBuf>>,
190 ) -> Result<Self::Analyses, Self::Error>;
191
192 fn base_cache_key(
199 &self,
200 _base_ref: &str,
201 _focus: &FxHashSet<PathBuf>,
202 ) -> Result<Option<Self::CacheKey>, Self::Error> {
203 Ok(None)
204 }
205
206 fn cached_base_sha<'k>(&self, _key: &'k Self::CacheKey) -> Option<&'k str> {
208 None
209 }
210
211 fn load_cached_base(&self, _key: &Self::CacheKey) -> Option<AuditKeySnapshot> {
213 None
214 }
215
216 fn save_cached_base(&self, _key: &Self::CacheKey, _snapshot: &AuditKeySnapshot) {}
218
219 fn shared_diff(&self) -> Option<SharedDiff<'_>> {
221 None
222 }
223}
224
225pub struct AuditRunInput<'a> {
227 pub root: &'a Path,
229 pub gate: AuditGate,
231 pub worsened: AuditWorsened,
233 pub base_ref: &'a str,
235 pub cache_dir: Option<&'a Path>,
238 pub changed_files: FxHashSet<PathBuf>,
240 pub inherited_base_refs: &'a [String],
243 pub compare_line_counts: bool,
246}
247
248#[derive(Debug, Default)]
250pub struct AuditBase {
251 pub snapshot: Option<AuditKeySnapshot>,
253 pub skipped: bool,
256 pub inherited: Vec<AuditKeySnapshot>,
259}
260
261pub struct AuditAttributionInput<'a> {
263 pub root: &'a Path,
265 pub gate: AuditGate,
267 pub worsened: AuditWorsened,
269 pub base_ref: &'a str,
271 pub base: AuditBase,
273 pub renames: &'a [RenamedFile],
275 pub changed_files: &'a FxHashSet<PathBuf>,
278 pub shared_diff: Option<SharedDiff<'a>>,
280}
281
282#[derive(Debug)]
284pub struct AuditOutcome {
285 pub verdict: AuditVerdict,
287 pub summary: AuditSummary,
289 pub attribution: AuditAttribution,
291 pub comparison: AuditComparison,
293 pub base_snapshot: Option<AuditKeySnapshot>,
295 pub base_snapshot_skipped: bool,
297 pub dupe_demotion_diff_source: Option<DupeDemotionDiffSource>,
300 pub type_aware_degrade_warning: Option<String>,
303 pub diff_risk: fallow_output::DiffRiskReport,
306}
307
308impl AuditOutcome {
309 pub fn apply_diff_risk(&mut self, report: fallow_output::DiffRiskReport) {
313 if report.has_errors() {
314 self.verdict = AuditVerdict::Fail;
315 } else if !report.is_empty() && self.verdict == AuditVerdict::Pass {
316 self.verdict = AuditVerdict::Warn;
317 }
318 self.diff_risk = report;
319 }
320}
321
322pub(crate) fn programmatic_base_snapshot(
325 outcome: &AuditOutcome,
326) -> Option<crate::AuditProgrammaticKeySnapshot> {
327 outcome
328 .base_snapshot
329 .as_ref()
330 .map(AuditKeySnapshot::to_programmatic)
331}
332
333pub struct AuditRun<A> {
335 pub analyses: A,
338 pub changed_files: FxHashSet<PathBuf>,
340 pub outcome: AuditOutcome,
342}
343
344fn needs_real_base(input: &AuditRunInput<'_>) -> bool {
347 matches!(input.gate, AuditGate::NewOnly)
348 && !can_reuse_current_as_base(
349 input.root,
350 input.cache_dir,
351 input.base_ref,
352 &input.changed_files,
353 input.compare_line_counts,
354 )
355}
356
357pub fn run<B: AuditBackend>(
364 backend: &B,
365 input: AuditRunInput<'_>,
366) -> Result<Option<AuditRun<B::Analyses>>, B::Error> {
367 if input.changed_files.is_empty() {
368 return Ok(None);
369 }
370 backend.prepare();
371 let needs_real_base = needs_real_base(&input);
372 let AuditRunInput {
373 root,
374 gate,
375 worsened,
376 base_ref,
377 cache_dir: _,
378 changed_files,
379 inherited_base_refs,
380 compare_line_counts: _,
381 } = input;
382 let renames = if needs_real_base || !matches!(gate, AuditGate::NewOnly) {
385 renamed_files(root, base_ref)
386 } else {
387 Vec::new()
388 };
389 let focus = base_focus_files(&changed_files, &renames);
390 let cache_key = if needs_real_base {
391 backend.base_cache_key(base_ref, &focus)?
392 } else {
393 None
394 };
395 let cached = cache_key
396 .as_ref()
397 .and_then(|key| backend.load_cached_base(key));
398
399 let (head, fresh_base) = if needs_real_base && cached.is_none() {
400 let base_sha = cache_key
401 .as_ref()
402 .and_then(|key| backend.cached_base_sha(key));
403 let (head, base) = rayon::join(
404 || backend.run_head(&changed_files),
405 || base_snapshot(backend, root, base_ref, &focus, base_sha),
406 );
407 (head, Some(base))
408 } else {
409 (backend.run_head(&changed_files), None)
410 };
411 let mut analyses = head?;
412 scope_dependency_findings_of(&mut analyses, &changed_files);
413
414 let base = if !matches!(gate, AuditGate::NewOnly) {
415 AuditBase::default()
416 } else if let Some(snapshot) = cached {
417 AuditBase {
418 snapshot: Some(snapshot),
419 skipped: false,
420 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
421 }
422 } else if let Some(fresh) = fresh_base {
423 let snapshot = fresh?;
424 if let Some(key) = cache_key.as_ref() {
425 backend.save_cached_base(key, &snapshot);
426 }
427 AuditBase {
428 snapshot: Some(snapshot),
429 skipped: false,
430 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
431 }
432 } else {
433 AuditBase {
434 snapshot: Some(AuditKeySnapshot::from_view(&analyses.view())),
435 skipped: true,
436 inherited: Vec::new(),
437 }
438 };
439
440 let mut outcome = attribute(
441 &mut analyses,
442 AuditAttributionInput {
443 root,
444 gate,
445 worsened,
446 base_ref,
447 base,
448 renames: &renames,
449 changed_files: &changed_files,
450 shared_diff: backend.shared_diff(),
451 },
452 );
453 let diff_risk = diff_risk_of(
454 &analyses,
455 &outcome,
456 root,
457 base_ref,
458 &changed_files,
459 &renames,
460 );
461 outcome.apply_diff_risk(diff_risk);
462 Ok(Some(AuditRun {
463 analyses,
464 changed_files,
465 outcome,
466 }))
467}
468
469fn annotate_health_report(report: &mut HealthReport, comparison: &AuditComparison) {
471 for ((finding, introduced), class) in report
472 .findings
473 .iter_mut()
474 .zip(comparison.health.introduced())
475 .zip(&comparison.health_classes)
476 {
477 finding.introduced = Some(introduced);
478 let attribution = class.attribution();
479 finding.attribution = Some(attribution);
480 finding.worsened_metrics.clone_from(&class.worsened_metrics);
481 finding.audit_base = class
482 .base
483 .filter(|_| attribution == fallow_output::AuditFindingAttribution::Inherited);
484 }
485 for (finding, introduced) in report
486 .styling_findings
487 .iter_mut()
488 .zip(comparison.styling.introduced())
489 {
490 finding.internal.introduced = Some(introduced);
491 }
492}
493
494pub fn attribute<A: AuditAnalyses>(
502 analyses: &mut A,
503 input: AuditAttributionInput<'_>,
504) -> AuditOutcome {
505 let AuditAttributionInput {
506 root,
507 gate,
508 worsened,
509 base_ref,
510 base,
511 renames,
512 changed_files,
513 shared_diff,
514 } = input;
515 let AuditBase {
516 snapshot: mut base_snapshot,
517 skipped,
518 inherited,
519 } = base;
520 if matches!(gate, AuditGate::NewOnly)
521 && let Some(report) = analyses.health_report_mut()
522 {
523 crate::audit_complexity::demote_estimated_crap_gates(&mut report.findings);
524 }
525 if let Some(report) = analyses.health_report_mut() {
526 crate::audit_complexity::exempt_test_file_gates(&mut report.findings, root);
527 }
528 if !skipped && let Some(snapshot) = base_snapshot.as_mut() {
530 snapshot.remap_for_renames(renames, root);
531 for inherited in inherited {
532 snapshot.absorb_inherited(inherited);
533 }
534 if let Some(dead_code) = analyses.view().dead_code.as_ref() {
535 snapshot.forget_unused_code_used_under_own_config(dead_code);
536 snapshot.inherit_unprovable_dead_code(dead_code);
537 }
538 }
539 scope_unchanged_unused_code_of(analyses, changed_files, base_snapshot.as_ref());
540 let degrade_reason = {
541 let view = analyses.view();
542 type_aware_attribution_degrade_reason(
543 base_snapshot.as_ref(),
544 view.dead_code
545 .as_ref()
546 .and_then(|dead_code| dead_code.type_aware),
547 )
548 };
549 let type_aware_degrade_warning = degrade_reason.map(type_aware_degrade_warning);
550 if let Some(warning) = type_aware_degrade_warning.as_deref() {
551 analyses.record_type_aware_warning(warning);
552 }
553
554 let (comparison, dupe_demotion_diff_source, (attribution, verdict, summary)) = {
555 let view = analyses.view();
556 let mut comparison = compare(&view, base_snapshot.as_ref(), degrade_reason.is_some());
557 if worsened == AuditWorsened::Off {
558 comparison.clear_worsened();
559 }
560 let source = demote_preexisting_dupe_introductions(
561 &mut comparison,
562 &view,
563 root,
564 base_ref,
565 shared_diff,
566 DupeBase {
567 groups: base_snapshot
569 .as_ref()
570 .filter(|_| !skipped)
571 .map_or(&[][..], |snapshot| snapshot.dupe_groups.as_slice()),
572 renames,
573 },
574 );
575 realign_styling_introductions(
576 &mut comparison,
577 &view,
578 base_snapshot.as_ref(),
579 root,
580 base_ref,
581 shared_diff,
582 );
583 let result = outcome(gate, worsened, &view, &comparison, base_snapshot.is_some());
584 (comparison, source, result)
585 };
586
587 if base_snapshot.is_some() {
588 if let Some(results) = analyses.dead_code_results_mut() {
589 comparison.dead_code.annotate_results(results);
590 }
591 if let Some(report) = analyses.health_report_mut() {
592 annotate_health_report(report, &comparison);
593 }
594 }
595
596 AuditOutcome {
597 verdict,
598 summary,
599 attribution,
600 comparison,
601 base_snapshot,
602 base_snapshot_skipped: skipped,
603 dupe_demotion_diff_source,
604 type_aware_degrade_warning,
605 diff_risk: fallow_output::DiffRiskReport::default(),
606 }
607}
608
609fn diff_risk_of<A: AuditAnalyses>(
611 analyses: &A,
612 outcome: &AuditOutcome,
613 root: &Path,
614 base_ref: &str,
615 changed_files: &FxHashSet<PathBuf>,
616 renames: &[RenamedFile],
617) -> fallow_output::DiffRiskReport {
618 let view = analyses.view();
619 let default_rules = RulesConfig::default();
620 let rules = if let Some(dead_code) = view.dead_code.as_ref() {
621 crate::diff_risk::DiffRiskRules::Config(dead_code.config)
622 } else if let Some(health) = view.health.as_ref() {
623 crate::diff_risk::DiffRiskRules::Rules(health.rules)
624 } else {
625 crate::diff_risk::DiffRiskRules::Rules(&default_rules)
626 };
627 let head_clone_groups = view
628 .duplication
629 .as_ref()
630 .map(|duplication| {
631 duplication
632 .clone_groups
633 .iter()
634 .map(|group| crate::diff_risk::clone_spans(group, duplication.root))
635 .collect()
636 })
637 .unwrap_or_default();
638 let base_clone_groups = if outcome.base_snapshot_skipped || view.duplication.is_none() {
640 None
641 } else {
642 outcome
643 .base_snapshot
644 .as_ref()
645 .map(|snapshot| snapshot.dupe_groups.as_slice())
646 };
647 crate::diff_risk::detect(&crate::diff_risk::DiffRiskInput {
648 root,
649 base_ref,
650 changed_files,
651 renames,
652 rules,
653 base_clone_groups,
654 head_clone_groups,
655 })
656}
657
658fn inherited_snapshots<B: AuditBackend>(
664 backend: &B,
665 root: &Path,
666 refs: &[String],
667 focus: &FxHashSet<PathBuf>,
668) -> Vec<AuditKeySnapshot> {
669 refs.iter()
670 .filter_map(|inherited_ref| inherited_snapshot(backend, root, inherited_ref, focus).ok())
671 .collect()
672}
673
674fn inherited_snapshot<B: AuditBackend>(
675 backend: &B,
676 root: &Path,
677 inherited_ref: &str,
678 focus: &FxHashSet<PathBuf>,
679) -> Result<AuditKeySnapshot, B::Error> {
680 let cache_key = backend.base_cache_key(inherited_ref, focus)?;
681 if let Some(cached) = cache_key
682 .as_ref()
683 .and_then(|key| backend.load_cached_base(key))
684 {
685 return Ok(remapped(cached, root, inherited_ref));
686 }
687 let base_sha = cache_key
688 .as_ref()
689 .and_then(|key| backend.cached_base_sha(key));
690 let snapshot = base_snapshot(backend, root, inherited_ref, focus, base_sha)?;
691 if let Some(key) = cache_key.as_ref() {
692 backend.save_cached_base(key, &snapshot);
693 }
694 Ok(remapped(snapshot, root, inherited_ref))
695}
696
697fn remapped(mut snapshot: AuditKeySnapshot, root: &Path, base_ref: &str) -> AuditKeySnapshot {
698 snapshot.remap_for_renames(&renamed_files(root, base_ref), root);
699 snapshot
700}
701
702fn base_snapshot<B: AuditBackend>(
704 backend: &B,
705 root: &Path,
706 base_ref: &str,
707 focus: &FxHashSet<PathBuf>,
708 base_sha: Option<&str>,
709) -> Result<AuditKeySnapshot, B::Error> {
710 let checkout = backend.create_base_checkout(base_ref, base_sha)?;
711 let base_root = match resolve_base_analysis_root(root, checkout.path()) {
712 BaseAnalysisRoot::Present(base_root) => {
716 dunce::canonicalize(&base_root).unwrap_or(base_root)
717 }
718 BaseAnalysisRoot::NewInHead(_) => return Ok(AuditKeySnapshot::default()),
722 };
723 let base_focus = remap_focus_files(focus, root, &base_root);
724 let mut base = backend.run_base(&base_root, base_focus.as_ref())?;
725 if let Some(focus) = base_focus.as_ref() {
726 scope_dependency_findings_of(&mut base, focus);
727 }
728 let snapshot = AuditKeySnapshot::from_view(&base.view());
729 drop(checkout);
730 Ok(snapshot)
731}
732
733fn scope_unchanged_unused_code_of<A: AuditAnalyses>(
736 analyses: &mut A,
737 changed_files: &FxHashSet<PathBuf>,
738 base: Option<&AuditKeySnapshot>,
739) {
740 let Some(root) = analyses
741 .view()
742 .dead_code
743 .map(|dead_code| dead_code.root.to_path_buf())
744 else {
745 return;
746 };
747 if let Some(results) = analyses.dead_code_results_mut() {
748 scope_unchanged_unused_code(results, &root, changed_files, base);
749 }
750}
751
752fn scope_dependency_findings_of<A: AuditAnalyses>(
754 analyses: &mut A,
755 changed_files: &FxHashSet<PathBuf>,
756) {
757 let Some(root) = analyses
758 .view()
759 .dead_code
760 .map(|dead_code| dead_code.root.to_path_buf())
761 else {
762 return;
763 };
764 if let Some(results) = analyses.dead_code_results_mut() {
765 scope_dependency_findings(results, &root, changed_files);
766 }
767}