1mod base_files;
22mod base_ref;
23mod clone_regions;
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, audit_base_override, parse_audit_base_override,
44 resolve_audit_base, resolve_audit_base_decided,
45};
46pub use clone_regions::{CloneChange, CloneRegion, CloneRegions, edits_base_clone};
47pub use outcome::{
48 DupeBase, DupeDemotionDiffSource, RunChange, SharedDiff, attribute_clone_regions, compare,
49 outcome, realign_styling_introductions, 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 ignored_groups: &'a [fallow_engine::duplicates::IgnoredCloneGroup],
91 pub root: &'a Path,
93 pub duplication_percentage: f64,
95 pub threshold: f64,
98 pub config: &'a ResolvedConfig,
101}
102
103pub struct HealthView<'a> {
105 pub report: &'a HealthReport,
107 pub root: &'a Path,
109 pub rules: &'a RulesConfig,
111 pub branching: Option<&'a fallow_engine::health::BranchingByFile>,
113}
114
115#[derive(Default)]
118pub struct AuditAnalysesView<'a> {
119 pub dead_code: Option<DeadCodeView<'a>>,
121 pub duplication: Option<DuplicationView<'a>>,
123 pub health: Option<HealthView<'a>>,
125}
126
127pub trait AuditAnalyses {
129 fn view(&self) -> AuditAnalysesView<'_>;
131 fn dead_code_results_mut(&mut self) -> Option<&mut AnalysisResults>;
134 fn health_report_mut(&mut self) -> Option<&mut HealthReport>;
136 fn record_type_aware_warning(&mut self, warning: &str);
139}
140
141pub trait BaseCheckout {
143 fn path(&self) -> &Path;
145}
146
147impl BaseCheckout for fallow_engine::repo_refs::TemporaryBaseWorktree {
148 fn path(&self) -> &Path {
149 Self::path(self)
150 }
151}
152
153pub trait AuditBackend: Sync {
155 type Analyses: AuditAnalyses + Send;
157 type Checkout: BaseCheckout;
160 type CacheKey: Sync;
162 type Error: Send;
164
165 fn prepare(&self) {}
167
168 fn run_head(&self, changed_files: &FxHashSet<PathBuf>) -> Result<Self::Analyses, Self::Error>;
174
175 fn create_base_checkout(
182 &self,
183 base_ref: &str,
184 base_sha: Option<&str>,
185 ) -> Result<Self::Checkout, Self::Error>;
186
187 fn run_base(
194 &self,
195 base_root: &Path,
196 focus: Option<&FxHashSet<PathBuf>>,
197 ) -> Result<Self::Analyses, Self::Error>;
198
199 fn base_cache_key(
206 &self,
207 _base_ref: &str,
208 _focus: &FxHashSet<PathBuf>,
209 ) -> Result<Option<Self::CacheKey>, Self::Error> {
210 Ok(None)
211 }
212
213 fn cached_base_sha<'k>(&self, _key: &'k Self::CacheKey) -> Option<&'k str> {
215 None
216 }
217
218 fn load_cached_base(&self, _key: &Self::CacheKey) -> Option<AuditKeySnapshot> {
220 None
221 }
222
223 fn save_cached_base(&self, _key: &Self::CacheKey, _snapshot: &AuditKeySnapshot) {}
225
226 fn shared_diff(&self) -> Option<SharedDiff<'_>> {
228 None
229 }
230}
231
232pub struct AuditRunInput<'a> {
234 pub root: &'a Path,
236 pub gate: AuditGate,
238 pub worsened: AuditWorsened,
240 pub base_ref: &'a str,
242 pub cache_dir: Option<&'a Path>,
245 pub changed_files: FxHashSet<PathBuf>,
247 pub inherited_base_refs: &'a [String],
250 pub compare_line_counts: bool,
253}
254
255#[derive(Debug, Default)]
257pub struct AuditBase {
258 pub snapshot: Option<AuditKeySnapshot>,
260 pub skipped: bool,
263 pub inherited: Vec<AuditKeySnapshot>,
266}
267
268pub struct AuditAttributionInput<'a> {
270 pub root: &'a Path,
272 pub gate: AuditGate,
274 pub worsened: AuditWorsened,
276 pub base_ref: &'a str,
278 pub base: AuditBase,
280 pub renames: &'a [RenamedFile],
282 pub changed_files: &'a FxHashSet<PathBuf>,
285 pub shared_diff: Option<SharedDiff<'a>>,
287}
288
289#[derive(Debug)]
291pub struct AuditOutcome {
292 pub verdict: AuditVerdict,
294 pub summary: AuditSummary,
296 pub attribution: AuditAttribution,
298 pub comparison: AuditComparison,
300 pub base_snapshot: Option<AuditKeySnapshot>,
302 pub base_snapshot_skipped: bool,
304 pub dupe_demotion_diff_source: Option<DupeDemotionDiffSource>,
307 pub type_aware_degrade_warning: Option<String>,
310 pub diff_risk: fallow_output::DiffRiskReport,
313}
314
315impl AuditOutcome {
316 pub fn apply_diff_risk(&mut self, report: fallow_output::DiffRiskReport) {
320 if report.has_errors() {
321 self.verdict = AuditVerdict::Fail;
322 } else if !report.is_empty() && self.verdict == AuditVerdict::Pass {
323 self.verdict = AuditVerdict::Warn;
324 }
325 self.diff_risk = report;
326 }
327}
328
329pub(crate) fn programmatic_base_snapshot(
332 outcome: &AuditOutcome,
333) -> Option<crate::AuditProgrammaticKeySnapshot> {
334 outcome
335 .base_snapshot
336 .as_ref()
337 .map(AuditKeySnapshot::to_programmatic)
338}
339
340pub struct AuditRun<A> {
342 pub analyses: A,
345 pub changed_files: FxHashSet<PathBuf>,
347 pub outcome: AuditOutcome,
349}
350
351fn needs_real_base(input: &AuditRunInput<'_>) -> bool {
354 matches!(input.gate, AuditGate::NewOnly)
355 && !can_reuse_current_as_base(
356 input.root,
357 input.cache_dir,
358 input.base_ref,
359 &input.changed_files,
360 input.compare_line_counts,
361 )
362}
363
364pub fn run<B: AuditBackend>(
371 backend: &B,
372 input: AuditRunInput<'_>,
373) -> Result<Option<AuditRun<B::Analyses>>, B::Error> {
374 if input.changed_files.is_empty() {
375 return Ok(None);
376 }
377 backend.prepare();
378 let needs_real_base = needs_real_base(&input);
379 let AuditRunInput {
380 root,
381 gate,
382 worsened,
383 base_ref,
384 cache_dir: _,
385 changed_files,
386 inherited_base_refs,
387 compare_line_counts: _,
388 } = input;
389 let renames = if needs_real_base || !matches!(gate, AuditGate::NewOnly) {
392 renamed_files(root, base_ref)
393 } else {
394 Vec::new()
395 };
396 let focus = base_focus_files(&changed_files, &renames);
397 let cache_key = if needs_real_base {
398 backend.base_cache_key(base_ref, &focus)?
399 } else {
400 None
401 };
402 let cached = cache_key
403 .as_ref()
404 .and_then(|key| backend.load_cached_base(key));
405
406 let (head, fresh_base) = if needs_real_base && cached.is_none() {
407 let base_sha = cache_key
408 .as_ref()
409 .and_then(|key| backend.cached_base_sha(key));
410 let (head, base) = rayon::join(
411 || backend.run_head(&changed_files),
412 || base_snapshot(backend, root, base_ref, &focus, base_sha),
413 );
414 (head, Some(base))
415 } else {
416 (backend.run_head(&changed_files), None)
417 };
418 let mut analyses = head?;
419 scope_dependency_findings_of(&mut analyses, &changed_files);
420
421 let base = if !matches!(gate, AuditGate::NewOnly) {
422 AuditBase::default()
423 } else if let Some(snapshot) = cached {
424 AuditBase {
425 snapshot: Some(snapshot),
426 skipped: false,
427 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
428 }
429 } else if let Some(fresh) = fresh_base {
430 let snapshot = fresh?;
431 if let Some(key) = cache_key.as_ref() {
432 backend.save_cached_base(key, &snapshot);
433 }
434 AuditBase {
435 snapshot: Some(snapshot),
436 skipped: false,
437 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
438 }
439 } else {
440 AuditBase {
441 snapshot: Some(AuditKeySnapshot::from_view(&analyses.view())),
442 skipped: true,
443 inherited: Vec::new(),
444 }
445 };
446
447 let mut outcome = attribute(
448 &mut analyses,
449 AuditAttributionInput {
450 root,
451 gate,
452 worsened,
453 base_ref,
454 base,
455 renames: &renames,
456 changed_files: &changed_files,
457 shared_diff: backend.shared_diff(),
458 },
459 );
460 let diff_risk = diff_risk_of(
461 &analyses,
462 &outcome,
463 root,
464 base_ref,
465 &changed_files,
466 &renames,
467 );
468 outcome.apply_diff_risk(diff_risk);
469 Ok(Some(AuditRun {
470 analyses,
471 changed_files,
472 outcome,
473 }))
474}
475
476fn annotate_health_report(report: &mut HealthReport, comparison: &AuditComparison) {
478 for ((finding, introduced), class) in report
479 .findings
480 .iter_mut()
481 .zip(comparison.health.introduced())
482 .zip(&comparison.health_classes)
483 {
484 finding.introduced = Some(introduced);
485 let attribution = class.attribution();
486 finding.attribution = Some(attribution);
487 finding.worsened_metrics.clone_from(&class.worsened_metrics);
488 finding.audit_base = class
489 .base
490 .filter(|_| attribution == fallow_output::AuditFindingAttribution::Inherited);
491 }
492 for (finding, introduced) in report
493 .styling_findings
494 .iter_mut()
495 .zip(comparison.styling.introduced())
496 {
497 finding.internal.introduced = Some(introduced);
498 }
499}
500
501pub fn attribute<A: AuditAnalyses>(
509 analyses: &mut A,
510 input: AuditAttributionInput<'_>,
511) -> AuditOutcome {
512 let AuditAttributionInput {
513 root,
514 gate,
515 worsened,
516 base_ref,
517 base,
518 renames,
519 changed_files,
520 shared_diff,
521 } = input;
522 let AuditBase {
523 snapshot: mut base_snapshot,
524 skipped,
525 inherited,
526 } = base;
527 if matches!(gate, AuditGate::NewOnly)
528 && let Some(report) = analyses.health_report_mut()
529 {
530 crate::audit_complexity::demote_estimated_crap_gates(&mut report.findings);
531 }
532 if let Some(report) = analyses.health_report_mut() {
533 crate::audit_complexity::exempt_test_file_gates(&mut report.findings, root);
534 }
535 if !skipped && let Some(snapshot) = base_snapshot.as_mut() {
537 snapshot.remap_for_renames(renames, root);
538 for inherited in inherited {
539 snapshot.absorb_inherited(inherited);
540 }
541 if let Some(dead_code) = analyses.view().dead_code.as_ref() {
542 snapshot.forget_unused_code_used_under_own_config(dead_code);
543 snapshot.inherit_unprovable_dead_code(dead_code);
544 }
545 }
546 scope_unchanged_unused_code_of(analyses, changed_files, base_snapshot.as_ref());
547 let degrade_reason = {
548 let view = analyses.view();
549 type_aware_attribution_degrade_reason(
550 base_snapshot.as_ref(),
551 view.dead_code
552 .as_ref()
553 .and_then(|dead_code| dead_code.type_aware),
554 )
555 };
556 let type_aware_degrade_warning = degrade_reason.map(type_aware_degrade_warning);
557 if let Some(warning) = type_aware_degrade_warning.as_deref() {
558 analyses.record_type_aware_warning(warning);
559 }
560
561 let (comparison, dupe_demotion_diff_source, (attribution, verdict, summary)) = {
562 let view = analyses.view();
563 let change = RunChange::new(root, base_ref, shared_diff, changed_files);
564 let degraded = degrade_reason.is_some();
565 let mut comparison = compare(&view, base_snapshot.as_ref(), degraded, &change);
566 comparison.clear_worsened_when_off(worsened);
567 let no_groups = (&[][..], &[][..]);
569 let source = attribute_clone_regions(
570 &mut comparison,
571 &view,
572 &change,
573 base_snapshot.as_ref().map(|snapshot| {
574 let (groups, accepted) = if skipped {
575 no_groups
576 } else {
577 (
578 snapshot.dupe_groups.as_slice(),
579 snapshot.accepted_dupe_groups.as_slice(),
580 )
581 };
582 DupeBase {
583 keys: &snapshot.dupes,
584 groups,
585 accepted,
586 renames,
587 }
588 }),
589 );
590 realign_styling_introductions(&mut comparison, &view, base_snapshot.as_ref(), &change);
591 let result = outcome(gate, worsened, &view, &comparison, base_snapshot.is_some());
592 (comparison, source, result)
593 };
594
595 if base_snapshot.is_some() {
596 if let Some(results) = analyses.dead_code_results_mut() {
597 comparison.dead_code.annotate_results(results);
598 }
599 if let Some(report) = analyses.health_report_mut() {
600 annotate_health_report(report, &comparison);
601 }
602 }
603
604 AuditOutcome {
605 verdict,
606 summary,
607 attribution,
608 comparison,
609 base_snapshot,
610 base_snapshot_skipped: skipped,
611 dupe_demotion_diff_source,
612 type_aware_degrade_warning,
613 diff_risk: fallow_output::DiffRiskReport::default(),
614 }
615}
616
617fn diff_risk_of<A: AuditAnalyses>(
619 analyses: &A,
620 outcome: &AuditOutcome,
621 root: &Path,
622 base_ref: &str,
623 changed_files: &FxHashSet<PathBuf>,
624 renames: &[RenamedFile],
625) -> fallow_output::DiffRiskReport {
626 let view = analyses.view();
627 let default_rules = RulesConfig::default();
628 let rules = if let Some(dead_code) = view.dead_code.as_ref() {
629 crate::diff_risk::DiffRiskRules::Config(dead_code.config)
630 } else if let Some(health) = view.health.as_ref() {
631 crate::diff_risk::DiffRiskRules::Rules(health.rules)
632 } else {
633 crate::diff_risk::DiffRiskRules::Rules(&default_rules)
634 };
635 let head_clone_groups = view
636 .duplication
637 .as_ref()
638 .map(|duplication| {
639 duplication
640 .clone_groups
641 .iter()
642 .map(|group| crate::diff_risk::clone_spans(group, duplication.root))
643 .collect()
644 })
645 .unwrap_or_default();
646 let base_clone_groups = if outcome.base_snapshot_skipped || view.duplication.is_none() {
648 None
649 } else {
650 outcome
651 .base_snapshot
652 .as_ref()
653 .map(|snapshot| snapshot.dupe_groups.as_slice())
654 };
655 crate::diff_risk::detect(&crate::diff_risk::DiffRiskInput {
656 root,
657 base_ref,
658 changed_files,
659 renames,
660 rules,
661 base_clone_groups,
662 head_clone_groups,
663 })
664}
665
666fn inherited_snapshots<B: AuditBackend>(
672 backend: &B,
673 root: &Path,
674 refs: &[String],
675 focus: &FxHashSet<PathBuf>,
676) -> Vec<AuditKeySnapshot> {
677 refs.iter()
678 .filter_map(|inherited_ref| inherited_snapshot(backend, root, inherited_ref, focus).ok())
679 .collect()
680}
681
682fn inherited_snapshot<B: AuditBackend>(
683 backend: &B,
684 root: &Path,
685 inherited_ref: &str,
686 focus: &FxHashSet<PathBuf>,
687) -> Result<AuditKeySnapshot, B::Error> {
688 let cache_key = backend.base_cache_key(inherited_ref, focus)?;
689 if let Some(cached) = cache_key
690 .as_ref()
691 .and_then(|key| backend.load_cached_base(key))
692 {
693 return Ok(remapped(cached, root, inherited_ref));
694 }
695 let base_sha = cache_key
696 .as_ref()
697 .and_then(|key| backend.cached_base_sha(key));
698 let snapshot = base_snapshot(backend, root, inherited_ref, focus, base_sha)?;
699 if let Some(key) = cache_key.as_ref() {
700 backend.save_cached_base(key, &snapshot);
701 }
702 Ok(remapped(snapshot, root, inherited_ref))
703}
704
705fn remapped(mut snapshot: AuditKeySnapshot, root: &Path, base_ref: &str) -> AuditKeySnapshot {
706 snapshot.remap_for_renames(&renamed_files(root, base_ref), root);
707 snapshot
708}
709
710fn base_snapshot<B: AuditBackend>(
712 backend: &B,
713 root: &Path,
714 base_ref: &str,
715 focus: &FxHashSet<PathBuf>,
716 base_sha: Option<&str>,
717) -> Result<AuditKeySnapshot, B::Error> {
718 let checkout = backend.create_base_checkout(base_ref, base_sha)?;
719 let base_root = match resolve_base_analysis_root(root, checkout.path()) {
720 BaseAnalysisRoot::Present(base_root) => {
724 dunce::canonicalize(&base_root).unwrap_or(base_root)
725 }
726 BaseAnalysisRoot::NewInHead(_) => return Ok(AuditKeySnapshot::default()),
730 };
731 let base_focus = remap_focus_files(focus, root, &base_root);
732 let mut base = backend.run_base(&base_root, base_focus.as_ref())?;
733 if let Some(focus) = base_focus.as_ref() {
734 scope_dependency_findings_of(&mut base, focus);
735 }
736 let snapshot = AuditKeySnapshot::from_view(&base.view());
737 drop(checkout);
738 Ok(snapshot)
739}
740
741fn scope_unchanged_unused_code_of<A: AuditAnalyses>(
744 analyses: &mut A,
745 changed_files: &FxHashSet<PathBuf>,
746 base: Option<&AuditKeySnapshot>,
747) {
748 let Some(root) = analyses
749 .view()
750 .dead_code
751 .map(|dead_code| dead_code.root.to_path_buf())
752 else {
753 return;
754 };
755 if let Some(results) = analyses.dead_code_results_mut() {
756 scope_unchanged_unused_code(results, &root, changed_files, base);
757 }
758}
759
760fn scope_dependency_findings_of<A: AuditAnalyses>(
762 analyses: &mut A,
763 changed_files: &FxHashSet<PathBuf>,
764) {
765 let Some(root) = analyses
766 .view()
767 .dead_code
768 .map(|dead_code| dead_code.root.to_path_buf())
769 else {
770 return;
771 };
772 if let Some(results) = analyses.dead_code_results_mut() {
773 scope_dependency_findings(results, &root, changed_files);
774 }
775}