1mod base_files;
22mod base_ref;
23mod outcome;
24mod scope;
25mod snapshot;
26#[cfg(test)]
27mod tests;
28
29use std::path::{Path, PathBuf};
30
31use fallow_config::{AuditGate, AuditWorsened, ResolvedConfig, RulesConfig};
32use fallow_engine::changed_files::RenamedFile;
33use fallow_engine::repo_refs::{BaseAnalysisRoot, resolve_base_analysis_root};
34use fallow_output::HealthReport;
35use fallow_types::duplicates::CloneGroup;
36use fallow_types::results::AnalysisResults;
37use rustc_hash::FxHashSet;
38
39pub use base_files::{BaseFileReader, BaseRead, can_reuse_current_as_base, export_names_at_base};
40pub use base_ref::{
41 AuditBaseError, AuditBaseOrigin, parse_audit_base_override, resolve_audit_base,
42};
43pub use outcome::{
44 DupeDemotionDiffSource, SharedDiff, compare, demote_preexisting_dupe_introductions, outcome,
45 realign_styling_introductions, styling_finding_gates, styling_rule_severity,
46};
47pub use scope::{
48 BaseCoverageInputs, base_coverage_inputs, base_focus_files, remap_focus_files, renamed_files,
49 scope_dependency_findings,
50};
51pub use snapshot::{
52 AuditKeySnapshot, branching_keys, type_aware_attribution_degrade_reason,
53 type_aware_degrade_warning, type_aware_gap_signature,
54};
55
56use crate::audit_keys::AuditComparison;
57use crate::{AuditAttribution, AuditSummary, AuditVerdict};
58
59pub struct DeadCodeView<'a> {
61 pub results: &'a AnalysisResults,
63 pub config: &'a ResolvedConfig,
65 pub root: &'a Path,
67 pub type_aware: Option<&'a fallow_types::envelope::TypeAwareMeta>,
69 pub syntactic_keys: Option<&'a FxHashSet<String>>,
72 pub public_api: Option<&'a FxHashSet<String>>,
74}
75
76pub struct DuplicationView<'a> {
78 pub clone_groups: Vec<&'a CloneGroup>,
80 pub root: &'a Path,
82 pub duplication_percentage: f64,
84 pub threshold: f64,
87}
88
89pub struct HealthView<'a> {
91 pub report: &'a HealthReport,
93 pub root: &'a Path,
95 pub rules: &'a RulesConfig,
97 pub branching: Option<&'a fallow_engine::health::BranchingByFile>,
99}
100
101#[derive(Default)]
104pub struct AuditAnalysesView<'a> {
105 pub dead_code: Option<DeadCodeView<'a>>,
107 pub duplication: Option<DuplicationView<'a>>,
109 pub health: Option<HealthView<'a>>,
111}
112
113pub trait AuditAnalyses {
115 fn view(&self) -> AuditAnalysesView<'_>;
117 fn dead_code_results_mut(&mut self) -> Option<&mut AnalysisResults>;
120 fn health_report_mut(&mut self) -> Option<&mut HealthReport>;
122 fn record_type_aware_warning(&mut self, warning: &str);
125}
126
127pub trait BaseCheckout {
129 fn path(&self) -> &Path;
131}
132
133impl BaseCheckout for fallow_engine::repo_refs::TemporaryBaseWorktree {
134 fn path(&self) -> &Path {
135 Self::path(self)
136 }
137}
138
139pub trait AuditBackend: Sync {
141 type Analyses: AuditAnalyses + Send;
143 type Checkout: BaseCheckout;
146 type CacheKey: Sync;
148 type Error: Send;
150
151 fn prepare(&self) {}
153
154 fn run_head(&self, changed_files: &FxHashSet<PathBuf>) -> Result<Self::Analyses, Self::Error>;
160
161 fn create_base_checkout(
168 &self,
169 base_ref: &str,
170 base_sha: Option<&str>,
171 ) -> Result<Self::Checkout, Self::Error>;
172
173 fn run_base(
180 &self,
181 base_root: &Path,
182 focus: Option<&FxHashSet<PathBuf>>,
183 ) -> Result<Self::Analyses, Self::Error>;
184
185 fn base_cache_key(
192 &self,
193 _base_ref: &str,
194 _focus: &FxHashSet<PathBuf>,
195 ) -> Result<Option<Self::CacheKey>, Self::Error> {
196 Ok(None)
197 }
198
199 fn cached_base_sha<'k>(&self, _key: &'k Self::CacheKey) -> Option<&'k str> {
201 None
202 }
203
204 fn load_cached_base(&self, _key: &Self::CacheKey) -> Option<AuditKeySnapshot> {
206 None
207 }
208
209 fn save_cached_base(&self, _key: &Self::CacheKey, _snapshot: &AuditKeySnapshot) {}
211
212 fn shared_diff(&self) -> Option<SharedDiff<'_>> {
214 None
215 }
216}
217
218pub struct AuditRunInput<'a> {
220 pub root: &'a Path,
222 pub gate: AuditGate,
224 pub worsened: AuditWorsened,
226 pub base_ref: &'a str,
228 pub cache_dir: Option<&'a Path>,
231 pub changed_files: FxHashSet<PathBuf>,
233 pub inherited_base_refs: &'a [String],
236 pub compare_line_counts: bool,
239}
240
241#[derive(Debug, Default)]
243pub struct AuditBase {
244 pub snapshot: Option<AuditKeySnapshot>,
246 pub skipped: bool,
249 pub inherited: Vec<AuditKeySnapshot>,
252}
253
254pub struct AuditAttributionInput<'a> {
256 pub root: &'a Path,
258 pub gate: AuditGate,
260 pub worsened: AuditWorsened,
262 pub base_ref: &'a str,
264 pub base: AuditBase,
266 pub renames: &'a [RenamedFile],
268 pub shared_diff: Option<SharedDiff<'a>>,
270}
271
272#[derive(Debug)]
274pub struct AuditOutcome {
275 pub verdict: AuditVerdict,
277 pub summary: AuditSummary,
279 pub attribution: AuditAttribution,
281 pub comparison: AuditComparison,
283 pub base_snapshot: Option<AuditKeySnapshot>,
285 pub base_snapshot_skipped: bool,
287 pub dupe_demotion_diff_source: Option<DupeDemotionDiffSource>,
290 pub type_aware_degrade_warning: Option<String>,
293 pub diff_risk: fallow_output::DiffRiskReport,
296}
297
298impl AuditOutcome {
299 pub fn apply_diff_risk(&mut self, report: fallow_output::DiffRiskReport) {
303 if report.has_errors() {
304 self.verdict = AuditVerdict::Fail;
305 } else if !report.is_empty() && self.verdict == AuditVerdict::Pass {
306 self.verdict = AuditVerdict::Warn;
307 }
308 self.diff_risk = report;
309 }
310}
311
312pub(crate) fn programmatic_base_snapshot(
315 outcome: &AuditOutcome,
316) -> Option<crate::AuditProgrammaticKeySnapshot> {
317 outcome
318 .base_snapshot
319 .as_ref()
320 .map(AuditKeySnapshot::to_programmatic)
321}
322
323pub struct AuditRun<A> {
325 pub analyses: A,
328 pub changed_files: FxHashSet<PathBuf>,
330 pub outcome: AuditOutcome,
332}
333
334fn needs_real_base(input: &AuditRunInput<'_>) -> bool {
337 matches!(input.gate, AuditGate::NewOnly)
338 && !can_reuse_current_as_base(
339 input.root,
340 input.cache_dir,
341 input.base_ref,
342 &input.changed_files,
343 input.compare_line_counts,
344 )
345}
346
347pub fn run<B: AuditBackend>(
354 backend: &B,
355 input: AuditRunInput<'_>,
356) -> Result<Option<AuditRun<B::Analyses>>, B::Error> {
357 if input.changed_files.is_empty() {
358 return Ok(None);
359 }
360 backend.prepare();
361 let needs_real_base = needs_real_base(&input);
362 let AuditRunInput {
363 root,
364 gate,
365 worsened,
366 base_ref,
367 cache_dir: _,
368 changed_files,
369 inherited_base_refs,
370 compare_line_counts: _,
371 } = input;
372 let renames = if needs_real_base || !matches!(gate, AuditGate::NewOnly) {
375 renamed_files(root, base_ref)
376 } else {
377 Vec::new()
378 };
379 let focus = base_focus_files(&changed_files, &renames);
380 let cache_key = if needs_real_base {
381 backend.base_cache_key(base_ref, &focus)?
382 } else {
383 None
384 };
385 let cached = cache_key
386 .as_ref()
387 .and_then(|key| backend.load_cached_base(key));
388
389 let (head, fresh_base) = if needs_real_base && cached.is_none() {
390 let base_sha = cache_key
391 .as_ref()
392 .and_then(|key| backend.cached_base_sha(key));
393 let (head, base) = rayon::join(
394 || backend.run_head(&changed_files),
395 || base_snapshot(backend, root, base_ref, &focus, base_sha),
396 );
397 (head, Some(base))
398 } else {
399 (backend.run_head(&changed_files), None)
400 };
401 let mut analyses = head?;
402 scope_dependency_findings_of(&mut analyses, &changed_files);
403
404 let base = if !matches!(gate, AuditGate::NewOnly) {
405 AuditBase::default()
406 } else if let Some(snapshot) = cached {
407 AuditBase {
408 snapshot: Some(snapshot),
409 skipped: false,
410 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
411 }
412 } else if let Some(fresh) = fresh_base {
413 let snapshot = fresh?;
414 if let Some(key) = cache_key.as_ref() {
415 backend.save_cached_base(key, &snapshot);
416 }
417 AuditBase {
418 snapshot: Some(snapshot),
419 skipped: false,
420 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
421 }
422 } else {
423 AuditBase {
424 snapshot: Some(AuditKeySnapshot::from_view(&analyses.view())),
425 skipped: true,
426 inherited: Vec::new(),
427 }
428 };
429
430 let mut outcome = attribute(
431 &mut analyses,
432 AuditAttributionInput {
433 root,
434 gate,
435 worsened,
436 base_ref,
437 base,
438 renames: &renames,
439 shared_diff: backend.shared_diff(),
440 },
441 );
442 let diff_risk = diff_risk_of(
443 &analyses,
444 &outcome,
445 root,
446 base_ref,
447 &changed_files,
448 &renames,
449 );
450 outcome.apply_diff_risk(diff_risk);
451 Ok(Some(AuditRun {
452 analyses,
453 changed_files,
454 outcome,
455 }))
456}
457
458fn annotate_health_report(report: &mut HealthReport, comparison: &AuditComparison) {
460 for ((finding, introduced), class) in report
461 .findings
462 .iter_mut()
463 .zip(comparison.health.introduced())
464 .zip(&comparison.health_classes)
465 {
466 finding.introduced = Some(introduced);
467 finding.attribution = Some(class.attribution());
468 finding.worsened_metrics.clone_from(&class.worsened_metrics);
469 }
470 for (finding, introduced) in report
471 .styling_findings
472 .iter_mut()
473 .zip(comparison.styling.introduced())
474 {
475 finding.internal.introduced = Some(introduced);
476 }
477}
478
479pub fn attribute<A: AuditAnalyses>(
487 analyses: &mut A,
488 input: AuditAttributionInput<'_>,
489) -> AuditOutcome {
490 let AuditAttributionInput {
491 root,
492 gate,
493 worsened,
494 base_ref,
495 base,
496 renames,
497 shared_diff,
498 } = input;
499 let AuditBase {
500 snapshot: mut base_snapshot,
501 skipped,
502 inherited,
503 } = base;
504 if matches!(gate, AuditGate::NewOnly)
505 && let Some(report) = analyses.health_report_mut()
506 {
507 crate::audit_complexity::demote_estimated_crap_gates(&mut report.findings);
508 }
509 if let Some(report) = analyses.health_report_mut() {
510 crate::audit_complexity::exempt_test_file_gates(&mut report.findings, root);
511 }
512 if !skipped && let Some(snapshot) = base_snapshot.as_mut() {
514 snapshot.remap_for_renames(renames, root);
515 for inherited in inherited {
516 snapshot.absorb_inherited(inherited);
517 }
518 if let Some(dead_code) = analyses.view().dead_code.as_ref() {
519 snapshot.inherit_unprovable_dead_code(dead_code);
520 }
521 }
522 let degrade_reason = {
523 let view = analyses.view();
524 type_aware_attribution_degrade_reason(
525 base_snapshot.as_ref(),
526 view.dead_code
527 .as_ref()
528 .and_then(|dead_code| dead_code.type_aware),
529 )
530 };
531 let type_aware_degrade_warning = degrade_reason.map(type_aware_degrade_warning);
532 if let Some(warning) = type_aware_degrade_warning.as_deref() {
533 analyses.record_type_aware_warning(warning);
534 }
535
536 let (comparison, dupe_demotion_diff_source, (attribution, verdict, summary)) = {
537 let view = analyses.view();
538 let mut comparison = compare(&view, base_snapshot.as_ref(), degrade_reason.is_some());
539 if worsened == AuditWorsened::Off {
540 comparison.clear_worsened();
541 }
542 let source = demote_preexisting_dupe_introductions(
543 &mut comparison,
544 &view,
545 root,
546 base_ref,
547 shared_diff,
548 );
549 realign_styling_introductions(
550 &mut comparison,
551 &view,
552 base_snapshot.as_ref(),
553 root,
554 base_ref,
555 shared_diff,
556 );
557 let result = outcome(gate, worsened, &view, &comparison, base_snapshot.is_some());
558 (comparison, source, result)
559 };
560
561 if base_snapshot.is_some() {
562 if let Some(results) = analyses.dead_code_results_mut() {
563 comparison.dead_code.annotate_results(results);
564 }
565 if let Some(report) = analyses.health_report_mut() {
566 annotate_health_report(report, &comparison);
567 }
568 }
569
570 AuditOutcome {
571 verdict,
572 summary,
573 attribution,
574 comparison,
575 base_snapshot,
576 base_snapshot_skipped: skipped,
577 dupe_demotion_diff_source,
578 type_aware_degrade_warning,
579 diff_risk: fallow_output::DiffRiskReport::default(),
580 }
581}
582
583fn diff_risk_of<A: AuditAnalyses>(
585 analyses: &A,
586 outcome: &AuditOutcome,
587 root: &Path,
588 base_ref: &str,
589 changed_files: &FxHashSet<PathBuf>,
590 renames: &[RenamedFile],
591) -> fallow_output::DiffRiskReport {
592 let view = analyses.view();
593 let default_rules = RulesConfig::default();
594 let rules = if let Some(dead_code) = view.dead_code.as_ref() {
595 crate::diff_risk::DiffRiskRules::Config(dead_code.config)
596 } else if let Some(health) = view.health.as_ref() {
597 crate::diff_risk::DiffRiskRules::Rules(health.rules)
598 } else {
599 crate::diff_risk::DiffRiskRules::Rules(&default_rules)
600 };
601 let head_clone_groups = view
602 .duplication
603 .as_ref()
604 .map(|duplication| {
605 duplication
606 .clone_groups
607 .iter()
608 .map(|group| crate::diff_risk::clone_spans(group, duplication.root))
609 .collect()
610 })
611 .unwrap_or_default();
612 let base_clone_groups = if outcome.base_snapshot_skipped || view.duplication.is_none() {
614 None
615 } else {
616 outcome
617 .base_snapshot
618 .as_ref()
619 .map(|snapshot| snapshot.dupe_groups.as_slice())
620 };
621 crate::diff_risk::detect(&crate::diff_risk::DiffRiskInput {
622 root,
623 base_ref,
624 changed_files,
625 renames,
626 rules,
627 base_clone_groups,
628 head_clone_groups,
629 })
630}
631
632fn inherited_snapshots<B: AuditBackend>(
638 backend: &B,
639 root: &Path,
640 refs: &[String],
641 focus: &FxHashSet<PathBuf>,
642) -> Vec<AuditKeySnapshot> {
643 refs.iter()
644 .filter_map(|inherited_ref| inherited_snapshot(backend, root, inherited_ref, focus).ok())
645 .collect()
646}
647
648fn inherited_snapshot<B: AuditBackend>(
649 backend: &B,
650 root: &Path,
651 inherited_ref: &str,
652 focus: &FxHashSet<PathBuf>,
653) -> Result<AuditKeySnapshot, B::Error> {
654 let cache_key = backend.base_cache_key(inherited_ref, focus)?;
655 if let Some(cached) = cache_key
656 .as_ref()
657 .and_then(|key| backend.load_cached_base(key))
658 {
659 return Ok(remapped(cached, root, inherited_ref));
660 }
661 let base_sha = cache_key
662 .as_ref()
663 .and_then(|key| backend.cached_base_sha(key));
664 let snapshot = base_snapshot(backend, root, inherited_ref, focus, base_sha)?;
665 if let Some(key) = cache_key.as_ref() {
666 backend.save_cached_base(key, &snapshot);
667 }
668 Ok(remapped(snapshot, root, inherited_ref))
669}
670
671fn remapped(mut snapshot: AuditKeySnapshot, root: &Path, base_ref: &str) -> AuditKeySnapshot {
672 snapshot.remap_for_renames(&renamed_files(root, base_ref), root);
673 snapshot
674}
675
676fn base_snapshot<B: AuditBackend>(
678 backend: &B,
679 root: &Path,
680 base_ref: &str,
681 focus: &FxHashSet<PathBuf>,
682 base_sha: Option<&str>,
683) -> Result<AuditKeySnapshot, B::Error> {
684 let checkout = backend.create_base_checkout(base_ref, base_sha)?;
685 let base_root = match resolve_base_analysis_root(root, checkout.path()) {
686 BaseAnalysisRoot::Present(base_root) => {
690 dunce::canonicalize(&base_root).unwrap_or(base_root)
691 }
692 BaseAnalysisRoot::NewInHead(_) => return Ok(AuditKeySnapshot::default()),
696 };
697 let base_focus = remap_focus_files(focus, root, &base_root);
698 let mut base = backend.run_base(&base_root, base_focus.as_ref())?;
699 if let Some(focus) = base_focus.as_ref() {
700 scope_dependency_findings_of(&mut base, focus);
701 }
702 let snapshot = AuditKeySnapshot::from_view(&base.view());
703 drop(checkout);
704 Ok(snapshot)
705}
706
707fn scope_dependency_findings_of<A: AuditAnalyses>(
709 analyses: &mut A,
710 changed_files: &FxHashSet<PathBuf>,
711) {
712 let Some(root) = analyses
713 .view()
714 .dead_code
715 .map(|dead_code| dead_code.root.to_path_buf())
716 else {
717 return;
718 };
719 if let Some(results) = analyses.dead_code_results_mut() {
720 scope_dependency_findings(results, &root, changed_files);
721 }
722}