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, 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 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 base_ref: &'a str,
226 pub cache_dir: Option<&'a Path>,
229 pub changed_files: FxHashSet<PathBuf>,
231 pub inherited_base_refs: &'a [String],
234}
235
236#[derive(Debug, Default)]
238pub struct AuditBase {
239 pub snapshot: Option<AuditKeySnapshot>,
241 pub skipped: bool,
244 pub inherited: Vec<AuditKeySnapshot>,
247}
248
249pub struct AuditAttributionInput<'a> {
251 pub root: &'a Path,
253 pub gate: AuditGate,
255 pub base_ref: &'a str,
257 pub base: AuditBase,
259 pub renames: &'a [RenamedFile],
261 pub shared_diff: Option<SharedDiff<'a>>,
263}
264
265#[derive(Debug)]
267pub struct AuditOutcome {
268 pub verdict: AuditVerdict,
270 pub summary: AuditSummary,
272 pub attribution: AuditAttribution,
274 pub comparison: AuditComparison,
276 pub base_snapshot: Option<AuditKeySnapshot>,
278 pub base_snapshot_skipped: bool,
280 pub dupe_demotion_diff_source: Option<DupeDemotionDiffSource>,
283 pub type_aware_degrade_warning: Option<String>,
286 pub diff_risk: fallow_output::DiffRiskReport,
289}
290
291impl AuditOutcome {
292 pub fn apply_diff_risk(&mut self, report: fallow_output::DiffRiskReport) {
296 if report.has_errors() {
297 self.verdict = AuditVerdict::Fail;
298 } else if !report.is_empty() && self.verdict == AuditVerdict::Pass {
299 self.verdict = AuditVerdict::Warn;
300 }
301 self.diff_risk = report;
302 }
303}
304
305pub(crate) fn programmatic_base_snapshot(
308 outcome: &AuditOutcome,
309) -> Option<crate::AuditProgrammaticKeySnapshot> {
310 outcome
311 .base_snapshot
312 .as_ref()
313 .map(AuditKeySnapshot::to_programmatic)
314}
315
316pub struct AuditRun<A> {
318 pub analyses: A,
321 pub changed_files: FxHashSet<PathBuf>,
323 pub outcome: AuditOutcome,
325}
326
327pub fn run<B: AuditBackend>(
334 backend: &B,
335 input: AuditRunInput<'_>,
336) -> Result<Option<AuditRun<B::Analyses>>, B::Error> {
337 let AuditRunInput {
338 root,
339 gate,
340 base_ref,
341 cache_dir,
342 changed_files,
343 inherited_base_refs,
344 } = input;
345 if changed_files.is_empty() {
346 return Ok(None);
347 }
348 backend.prepare();
349
350 let needs_real_base = matches!(gate, AuditGate::NewOnly)
351 && !can_reuse_current_as_base(root, cache_dir, base_ref, &changed_files);
352 let renames = if needs_real_base || !matches!(gate, AuditGate::NewOnly) {
355 renamed_files(root, base_ref)
356 } else {
357 Vec::new()
358 };
359 let focus = base_focus_files(&changed_files, &renames);
360 let cache_key = if needs_real_base {
361 backend.base_cache_key(base_ref, &focus)?
362 } else {
363 None
364 };
365 let cached = cache_key
366 .as_ref()
367 .and_then(|key| backend.load_cached_base(key));
368
369 let (head, fresh_base) = if needs_real_base && cached.is_none() {
370 let base_sha = cache_key
371 .as_ref()
372 .and_then(|key| backend.cached_base_sha(key));
373 let (head, base) = rayon::join(
374 || backend.run_head(&changed_files),
375 || base_snapshot(backend, root, base_ref, &focus, base_sha),
376 );
377 (head, Some(base))
378 } else {
379 (backend.run_head(&changed_files), None)
380 };
381 let mut analyses = head?;
382 scope_dependency_findings_of(&mut analyses, &changed_files);
383
384 let base = if !matches!(gate, AuditGate::NewOnly) {
385 AuditBase::default()
386 } else if let Some(snapshot) = cached {
387 AuditBase {
388 snapshot: Some(snapshot),
389 skipped: false,
390 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
391 }
392 } else if let Some(fresh) = fresh_base {
393 let snapshot = fresh?;
394 if let Some(key) = cache_key.as_ref() {
395 backend.save_cached_base(key, &snapshot);
396 }
397 AuditBase {
398 snapshot: Some(snapshot),
399 skipped: false,
400 inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
401 }
402 } else {
403 AuditBase {
404 snapshot: Some(AuditKeySnapshot::from_view(&analyses.view())),
405 skipped: true,
406 inherited: Vec::new(),
407 }
408 };
409
410 let mut outcome = attribute(
411 &mut analyses,
412 AuditAttributionInput {
413 root,
414 gate,
415 base_ref,
416 base,
417 renames: &renames,
418 shared_diff: backend.shared_diff(),
419 },
420 );
421 let diff_risk = diff_risk_of(
422 &analyses,
423 &outcome,
424 root,
425 base_ref,
426 &changed_files,
427 &renames,
428 );
429 outcome.apply_diff_risk(diff_risk);
430 Ok(Some(AuditRun {
431 analyses,
432 changed_files,
433 outcome,
434 }))
435}
436
437pub fn attribute<A: AuditAnalyses>(
440 analyses: &mut A,
441 input: AuditAttributionInput<'_>,
442) -> AuditOutcome {
443 let AuditAttributionInput {
444 root,
445 gate,
446 base_ref,
447 base,
448 renames,
449 shared_diff,
450 } = input;
451 let AuditBase {
452 snapshot: mut base_snapshot,
453 skipped,
454 inherited,
455 } = base;
456 if !skipped && let Some(snapshot) = base_snapshot.as_mut() {
458 snapshot.remap_for_renames(renames, root);
459 for inherited in inherited {
460 snapshot.absorb_inherited(inherited);
461 }
462 }
463 let degrade_reason = {
464 let view = analyses.view();
465 type_aware_attribution_degrade_reason(
466 base_snapshot.as_ref(),
467 view.dead_code
468 .as_ref()
469 .and_then(|dead_code| dead_code.type_aware),
470 )
471 };
472 let type_aware_degrade_warning = degrade_reason.map(type_aware_degrade_warning);
473 if let Some(warning) = type_aware_degrade_warning.as_deref() {
474 analyses.record_type_aware_warning(warning);
475 }
476
477 let (comparison, dupe_demotion_diff_source, (attribution, verdict, summary)) = {
478 let view = analyses.view();
479 let mut comparison = compare(&view, base_snapshot.as_ref(), degrade_reason.is_some());
480 let source = demote_preexisting_dupe_introductions(
481 &mut comparison,
482 &view,
483 root,
484 base_ref,
485 shared_diff,
486 );
487 let result = outcome(gate, &view, &comparison, base_snapshot.is_some());
488 (comparison, source, result)
489 };
490
491 if base_snapshot.is_some() {
492 if let Some(results) = analyses.dead_code_results_mut() {
493 comparison.dead_code.annotate_results(results);
494 }
495 if let Some(report) = analyses.health_report_mut() {
496 for (finding, introduced) in report
497 .findings
498 .iter_mut()
499 .zip(comparison.health.introduced())
500 {
501 finding.introduced = Some(introduced);
502 }
503 }
504 }
505
506 AuditOutcome {
507 verdict,
508 summary,
509 attribution,
510 comparison,
511 base_snapshot,
512 base_snapshot_skipped: skipped,
513 dupe_demotion_diff_source,
514 type_aware_degrade_warning,
515 diff_risk: fallow_output::DiffRiskReport::default(),
516 }
517}
518
519fn diff_risk_of<A: AuditAnalyses>(
521 analyses: &A,
522 outcome: &AuditOutcome,
523 root: &Path,
524 base_ref: &str,
525 changed_files: &FxHashSet<PathBuf>,
526 renames: &[RenamedFile],
527) -> fallow_output::DiffRiskReport {
528 let view = analyses.view();
529 let default_rules = RulesConfig::default();
530 let rules = if let Some(dead_code) = view.dead_code.as_ref() {
531 crate::diff_risk::DiffRiskRules::Config(dead_code.config)
532 } else if let Some(health) = view.health.as_ref() {
533 crate::diff_risk::DiffRiskRules::Rules(health.rules)
534 } else {
535 crate::diff_risk::DiffRiskRules::Rules(&default_rules)
536 };
537 let head_clone_groups = view
538 .duplication
539 .as_ref()
540 .map(|duplication| {
541 duplication
542 .clone_groups
543 .iter()
544 .map(|group| crate::diff_risk::clone_spans(group, duplication.root))
545 .collect()
546 })
547 .unwrap_or_default();
548 let base_clone_groups = if outcome.base_snapshot_skipped || view.duplication.is_none() {
550 None
551 } else {
552 outcome
553 .base_snapshot
554 .as_ref()
555 .map(|snapshot| snapshot.dupe_groups.as_slice())
556 };
557 crate::diff_risk::detect(&crate::diff_risk::DiffRiskInput {
558 root,
559 base_ref,
560 changed_files,
561 renames,
562 rules,
563 base_clone_groups,
564 head_clone_groups,
565 })
566}
567
568fn inherited_snapshots<B: AuditBackend>(
574 backend: &B,
575 root: &Path,
576 refs: &[String],
577 focus: &FxHashSet<PathBuf>,
578) -> Vec<AuditKeySnapshot> {
579 refs.iter()
580 .filter_map(|inherited_ref| inherited_snapshot(backend, root, inherited_ref, focus).ok())
581 .collect()
582}
583
584fn inherited_snapshot<B: AuditBackend>(
585 backend: &B,
586 root: &Path,
587 inherited_ref: &str,
588 focus: &FxHashSet<PathBuf>,
589) -> Result<AuditKeySnapshot, B::Error> {
590 let cache_key = backend.base_cache_key(inherited_ref, focus)?;
591 if let Some(cached) = cache_key
592 .as_ref()
593 .and_then(|key| backend.load_cached_base(key))
594 {
595 return Ok(remapped(cached, root, inherited_ref));
596 }
597 let base_sha = cache_key
598 .as_ref()
599 .and_then(|key| backend.cached_base_sha(key));
600 let snapshot = base_snapshot(backend, root, inherited_ref, focus, base_sha)?;
601 if let Some(key) = cache_key.as_ref() {
602 backend.save_cached_base(key, &snapshot);
603 }
604 Ok(remapped(snapshot, root, inherited_ref))
605}
606
607fn remapped(mut snapshot: AuditKeySnapshot, root: &Path, base_ref: &str) -> AuditKeySnapshot {
608 snapshot.remap_for_renames(&renamed_files(root, base_ref), root);
609 snapshot
610}
611
612fn base_snapshot<B: AuditBackend>(
614 backend: &B,
615 root: &Path,
616 base_ref: &str,
617 focus: &FxHashSet<PathBuf>,
618 base_sha: Option<&str>,
619) -> Result<AuditKeySnapshot, B::Error> {
620 let checkout = backend.create_base_checkout(base_ref, base_sha)?;
621 let base_root = match resolve_base_analysis_root(root, checkout.path()) {
622 BaseAnalysisRoot::Present(base_root) => {
626 dunce::canonicalize(&base_root).unwrap_or(base_root)
627 }
628 BaseAnalysisRoot::NewInHead(_) => return Ok(AuditKeySnapshot::default()),
632 };
633 let base_focus = remap_focus_files(focus, root, &base_root);
634 let mut base = backend.run_base(&base_root, base_focus.as_ref())?;
635 if let Some(focus) = base_focus.as_ref() {
636 scope_dependency_findings_of(&mut base, focus);
637 }
638 let snapshot = AuditKeySnapshot::from_view(&base.view());
639 drop(checkout);
640 Ok(snapshot)
641}
642
643fn scope_dependency_findings_of<A: AuditAnalyses>(
645 analyses: &mut A,
646 changed_files: &FxHashSet<PathBuf>,
647) {
648 let Some(root) = analyses
649 .view()
650 .dead_code
651 .map(|dead_code| dead_code.root.to_path_buf())
652 else {
653 return;
654 };
655 if let Some(results) = analyses.dead_code_results_mut() {
656 scope_dependency_findings(results, &root, changed_files);
657 }
658}