Skip to main content

fallow_api/audit_run/
mod.rs

1//! The changed-code audit.
2//!
3//! `fallow audit`, the MCP `audit` tool and [`crate::run_audit`] all run an
4//! audit through [`run`], so they give the same introduced and inherited split
5//! and the same verdict. A surface supplies an [`AuditBackend`]: it runs the
6//! three analyses (dead code, duplication, health) and creates the base
7//! checkout. This module owns the rest:
8//!
9//! - the base ref: explicit, then `FALLOW_AUDIT_BASE`, then auto-detection
10//!   ([`resolve_audit_base`]),
11//! - the check that lets the head run stand in for the base
12//!   ([`can_reuse_current_as_base`]),
13//! - rename detection, and the base focus set of changed files plus pre-rename
14//!   paths,
15//! - the base snapshot: checkout, analysis root, focus remap, dependency scope,
16//!   and keys,
17//! - the rename remap of base keys, the degraded type-aware comparison, the
18//!   clone-group demotion, the verdict, and the introduced flags on the head
19//!   findings.
20
21mod 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
63/// The dead-code analysis of one audit side, as the audit reads it.
64pub struct DeadCodeView<'a> {
65    /// Findings after change scoping.
66    pub results: &'a AnalysisResults,
67    /// Config that decides the effective severity of each finding.
68    pub config: &'a ResolvedConfig,
69    /// Root that key paths are relative to.
70    pub root: &'a Path,
71    /// Type-aware metadata of the pass, when it ran type-aware analysis.
72    pub type_aware: Option<&'a fallow_types::envelope::TypeAwareMeta>,
73    /// Dead-code keys before type-aware refinement, when the surface captured
74    /// them.
75    pub syntactic_keys: Option<&'a FxHashSet<String>>,
76    /// Exports-aware public-export keys, when the surface computed them.
77    pub public_api: Option<&'a FxHashSet<String>>,
78    /// Keys of the unused files and unused exports that a base side reports
79    /// under the config of the base commit, when the change touched the config
80    /// (see [`AuditKeySnapshot::own_config_unused_code`]).
81    pub own_config_unused_code: Option<&'a FxHashSet<String>>,
82}
83
84/// The duplication analysis of one audit side, as the audit reads it.
85pub struct DuplicationView<'a> {
86    /// Clone groups in output order.
87    pub clone_groups: Vec<&'a CloneGroup>,
88    /// Root that key paths are relative to.
89    pub root: &'a Path,
90    /// Duplicated share of the analyzed code, in percent.
91    pub duplication_percentage: f64,
92    /// Duplication percentage above which an introduced group fails the
93    /// audit; `0.0` turns the threshold off.
94    pub threshold: f64,
95    /// Config whose `introduced-clone-group` rule and `overrides` decide how
96    /// a clone group takes part in the verdict.
97    pub config: &'a ResolvedConfig,
98}
99
100/// The health analysis of one audit side, as the audit reads it.
101pub struct HealthView<'a> {
102    /// Health report with complexity and styling findings.
103    pub report: &'a HealthReport,
104    /// Root that key paths are relative to.
105    pub root: &'a Path,
106    /// Rules that decide whether a styling finding gates the verdict.
107    pub rules: &'a RulesConfig,
108    /// Branching totals per file, when the surface computed them.
109    pub branching: Option<&'a fallow_engine::health::BranchingByFile>,
110}
111
112/// The analyses of one audit side. An analysis the surface did not run is
113/// `None`.
114#[derive(Default)]
115pub struct AuditAnalysesView<'a> {
116    /// Dead-code analysis.
117    pub dead_code: Option<DeadCodeView<'a>>,
118    /// Duplication analysis.
119    pub duplication: Option<DuplicationView<'a>>,
120    /// Health analysis.
121    pub health: Option<HealthView<'a>>,
122}
123
124/// The analyses a surface ran for one audit side.
125pub trait AuditAnalyses {
126    /// A read view of the analyses.
127    fn view(&self) -> AuditAnalysesView<'_>;
128    /// The dead-code findings, for the dependency scope and the introduced
129    /// flags.
130    fn dead_code_results_mut(&mut self) -> Option<&mut AnalysisResults>;
131    /// The health report, for the introduced flags.
132    fn health_report_mut(&mut self) -> Option<&mut HealthReport>;
133    /// Record the warning of a degraded type-aware comparison on the
134    /// type-aware metadata of the run.
135    fn record_type_aware_warning(&mut self, warning: &str);
136}
137
138/// A checkout of the base commit.
139pub trait BaseCheckout {
140    /// Root of the checkout.
141    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
150/// How one surface runs the analyses of an audit.
151pub trait AuditBackend: Sync {
152    /// The analyses of one side.
153    type Analyses: AuditAnalyses + Send;
154    /// A checkout of the base commit. The base pass keeps it until the base
155    /// analyses complete.
156    type Checkout: BaseCheckout;
157    /// Key of a cached base snapshot.
158    type CacheKey: Sync;
159    /// The error of the surface.
160    type Error: Send;
161
162    /// Called once when the run has changed files, before any base work.
163    fn prepare(&self) {}
164
165    /// Run the head analyses, scoped to `changed_files`.
166    ///
167    /// # Errors
168    ///
169    /// Returns the surface error when an analysis fails.
170    fn run_head(&self, changed_files: &FxHashSet<PathBuf>) -> Result<Self::Analyses, Self::Error>;
171
172    /// Create a checkout of `base_ref`. `base_sha` is the full SHA when a
173    /// cache key resolved it.
174    ///
175    /// # Errors
176    ///
177    /// Returns the surface error when the checkout cannot be created.
178    fn create_base_checkout(
179        &self,
180        base_ref: &str,
181        base_sha: Option<&str>,
182    ) -> Result<Self::Checkout, Self::Error>;
183
184    /// Run the base analyses in `base_root`. With `focus`, scope the findings
185    /// to those files; without it, leave them unscoped.
186    ///
187    /// # Errors
188    ///
189    /// Returns the surface error when an analysis fails.
190    fn run_base(
191        &self,
192        base_root: &Path,
193        focus: Option<&FxHashSet<PathBuf>>,
194    ) -> Result<Self::Analyses, Self::Error>;
195
196    /// The cache key of the base snapshot for `base_ref` and `focus`, or
197    /// `None` when the surface keeps no cache.
198    ///
199    /// # Errors
200    ///
201    /// Returns the surface error when the key inputs cannot be read.
202    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    /// The full base SHA that `key` records.
211    fn cached_base_sha<'k>(&self, _key: &'k Self::CacheKey) -> Option<&'k str> {
212        None
213    }
214
215    /// A cached base snapshot for `key`.
216    fn load_cached_base(&self, _key: &Self::CacheKey) -> Option<AuditKeySnapshot> {
217        None
218    }
219
220    /// Store a fresh base snapshot under `key`.
221    fn save_cached_base(&self, _key: &Self::CacheKey, _snapshot: &AuditKeySnapshot) {}
222
223    /// The opt-in shared diff of the run, when one is active.
224    fn shared_diff(&self) -> Option<SharedDiff<'_>> {
225        None
226    }
227}
228
229/// Inputs of one audit run.
230pub struct AuditRunInput<'a> {
231    /// Head analysis root.
232    pub root: &'a Path,
233    /// Gate mode. `new-only` compares with the base snapshot.
234    pub gate: AuditGate,
235    /// How a worsened complexity finding affects the verdict.
236    pub worsened: AuditWorsened,
237    /// Resolved base ref.
238    pub base_ref: &'a str,
239    /// Cache directory of the run. A changed file inside it never blocks the
240    /// reuse of the head run as the base snapshot.
241    pub cache_dir: Option<&'a Path>,
242    /// Changed files of the run, after any narrowing of the surface.
243    pub changed_files: FxHashSet<PathBuf>,
244    /// Commits whose findings are inherited in addition to the base, see
245    /// [`fallow_engine::repo_refs::merged_default_branch_refs`].
246    pub inherited_base_refs: &'a [String],
247    /// The file-length check (`health.maxFileLines`) is on, so a change that
248    /// keeps the tokens but changes the line count still needs a real base.
249    pub compare_line_counts: bool,
250}
251
252/// The base snapshot that attribution compares with.
253#[derive(Debug, Default)]
254pub struct AuditBase {
255    /// The snapshot; `None` under `--gate all`.
256    pub snapshot: Option<AuditKeySnapshot>,
257    /// `true` when the head keys stand in for the base (no finding can have
258    /// changed), so every finding is inherited.
259    pub skipped: bool,
260    /// Snapshots of the inherited bases, with head paths. Attribution absorbs
261    /// them into `snapshot` after the rename remap of the primary base.
262    pub inherited: Vec<AuditKeySnapshot>,
263}
264
265/// Inputs of [`attribute`].
266pub struct AuditAttributionInput<'a> {
267    /// Head analysis root.
268    pub root: &'a Path,
269    /// Gate mode.
270    pub gate: AuditGate,
271    /// How a worsened complexity finding affects the verdict.
272    pub worsened: AuditWorsened,
273    /// Resolved base ref, for the demotion diff.
274    pub base_ref: &'a str,
275    /// The base snapshot.
276    pub base: AuditBase,
277    /// Renames between base and head.
278    pub renames: &'a [RenamedFile],
279    /// Changed files of the run. An unused file or unused export outside them
280    /// stays only when the base does not report it.
281    pub changed_files: &'a FxHashSet<PathBuf>,
282    /// The opt-in shared diff of the run.
283    pub shared_diff: Option<SharedDiff<'a>>,
284}
285
286/// Attribution result of one audit run.
287#[derive(Debug)]
288pub struct AuditOutcome {
289    /// Overall verdict.
290    pub verdict: AuditVerdict,
291    /// Per-domain counts.
292    pub summary: AuditSummary,
293    /// Introduced and inherited counts, and the gate.
294    pub attribution: AuditAttribution,
295    /// The classification of every head finding.
296    pub comparison: AuditComparison,
297    /// The base snapshot after the rename remap.
298    pub base_snapshot: Option<AuditKeySnapshot>,
299    /// `true` when the head keys stood in for the base.
300    pub base_snapshot_skipped: bool,
301    /// Which diff decided the clone-group demotion; `None` when it did not
302    /// run.
303    pub dupe_demotion_diff_source: Option<DupeDemotionDiffSource>,
304    /// The warning of a degraded type-aware comparison, already recorded on
305    /// the head analyses.
306    pub type_aware_degrade_warning: Option<String>,
307    /// Diff-risk findings. Every one is introduced by the change. Empty until
308    /// [`run`] computes them, and in [`attribute`] alone.
309    pub diff_risk: fallow_output::DiffRiskReport,
310}
311
312impl AuditOutcome {
313    /// Store the diff-risk findings and fold their severity into the verdict:
314    /// an `error` finding fails the audit, a `warn` finding turns a pass into
315    /// a warn.
316    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
326/// The base snapshot of the typed audit output. When the head keys stood in
327/// for the base, the head keys are the base snapshot, so this keeps them.
328pub(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
337/// One completed audit run.
338pub struct AuditRun<A> {
339    /// Head analyses, with introduced flags on dead-code and health findings
340    /// when a base snapshot exists.
341    pub analyses: A,
342    /// Changed files of the run.
343    pub changed_files: FxHashSet<PathBuf>,
344    /// Attribution result.
345    pub outcome: AuditOutcome,
346}
347
348/// Whether the `new-only` gate needs a base pass, because a changed file can
349/// change a finding (see [`can_reuse_current_as_base`]).
350fn 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
361/// Run one audit. Returns `None` when the run has no changed files.
362///
363/// # Errors
364///
365/// Returns the error of the backend when an analysis or the base checkout
366/// fails.
367pub 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    // The diff-risk pass also needs the renames under `--gate all`, so a moved
387    // test file does not read as removed tests.
388    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
473/// Copy the comparison result onto the complexity and styling findings.
474fn 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
498/// Compare head analyses with a base snapshot, decide the verdict, and set
499/// the introduced flags on the dead-code, complexity and styling findings.
500///
501/// Under the `new-only` gate, a complexity finding that exceeds only CRAP from
502/// estimated coverage gets the gate severity `warn` first, so it does not fail
503/// the verdict. Under every gate, a complexity finding in a test file gets the
504/// gate severity `warn` and the gate exemption `test-file`.
505pub 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    // The head keys that stand in for a skipped base are head paths already.
533    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                // A skipped base reuses the head keys, so no group is introduced.
572                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
613/// Run the diff-risk rules over the changed files of one audit.
614fn 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    // A skipped base pass reuses the head keys, so no clone copy can differ.
643    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
662/// Take the snapshot of each inherited base, with its keys on head paths.
663///
664/// An inherited base only lowers the introduced count, so a base that fails
665/// (no worktree, a failed analysis) is left out. The audit then keeps the
666/// stricter comparison with the primary base.
667fn 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
706/// Analyze the base checkout and take its attribution keys.
707fn 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        // The canonical spelling: an analysis session canonicalizes its root,
717        // so a focus set spelled through a symbolic link (the macOS temporary
718        // directory) would match no finding and empty the base snapshot.
719        BaseAnalysisRoot::Present(base_root) => {
720            dunce::canonicalize(&base_root).unwrap_or(base_root)
721        }
722        // A root that the base commit does not contain (a package added on
723        // the branch) has an empty base snapshot, so every finding under it
724        // is introduced.
725        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
737/// Apply [`scope_unchanged_unused_code`] to the dead-code findings of the
738/// head.
739fn 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
756/// Apply [`scope_dependency_findings`] to the dead-code findings of one side.
757fn 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}