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    resolve_audit_base_decided,
45};
46pub use outcome::{
47    DupeBase, DupeDemotionDiffSource, RunChange, SharedDiff, compare,
48    demote_preexisting_dupe_introductions, outcome, realign_styling_introductions,
49    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
64/// The dead-code analysis of one audit side, as the audit reads it.
65pub struct DeadCodeView<'a> {
66    /// Findings after change scoping.
67    pub results: &'a AnalysisResults,
68    /// Config that decides the effective severity of each finding.
69    pub config: &'a ResolvedConfig,
70    /// Root that key paths are relative to.
71    pub root: &'a Path,
72    /// Type-aware metadata of the pass, when it ran type-aware analysis.
73    pub type_aware: Option<&'a fallow_types::envelope::TypeAwareMeta>,
74    /// Dead-code keys before type-aware refinement, when the surface captured
75    /// them.
76    pub syntactic_keys: Option<&'a FxHashSet<String>>,
77    /// Exports-aware public-export keys, when the surface computed them.
78    pub public_api: Option<&'a FxHashSet<String>>,
79    /// Keys of the unused files and unused exports that a base side reports
80    /// under the config of the base commit, when the change touched the config
81    /// (see [`AuditKeySnapshot::own_config_unused_code`]).
82    pub own_config_unused_code: Option<&'a FxHashSet<String>>,
83}
84
85/// The duplication analysis of one audit side, as the audit reads it.
86pub struct DuplicationView<'a> {
87    /// Clone groups in output order.
88    pub clone_groups: Vec<&'a CloneGroup>,
89    /// Root that key paths are relative to.
90    pub root: &'a Path,
91    /// Duplicated share of the analyzed code, in percent.
92    pub duplication_percentage: f64,
93    /// Duplication percentage above which an introduced group fails the
94    /// audit; `0.0` turns the threshold off.
95    pub threshold: f64,
96    /// Config whose `introduced-clone-group` rule and `overrides` decide how
97    /// a clone group takes part in the verdict.
98    pub config: &'a ResolvedConfig,
99}
100
101/// The health analysis of one audit side, as the audit reads it.
102pub struct HealthView<'a> {
103    /// Health report with complexity and styling findings.
104    pub report: &'a HealthReport,
105    /// Root that key paths are relative to.
106    pub root: &'a Path,
107    /// Rules that decide whether a styling finding gates the verdict.
108    pub rules: &'a RulesConfig,
109    /// Branching totals per file, when the surface computed them.
110    pub branching: Option<&'a fallow_engine::health::BranchingByFile>,
111}
112
113/// The analyses of one audit side. An analysis the surface did not run is
114/// `None`.
115#[derive(Default)]
116pub struct AuditAnalysesView<'a> {
117    /// Dead-code analysis.
118    pub dead_code: Option<DeadCodeView<'a>>,
119    /// Duplication analysis.
120    pub duplication: Option<DuplicationView<'a>>,
121    /// Health analysis.
122    pub health: Option<HealthView<'a>>,
123}
124
125/// The analyses a surface ran for one audit side.
126pub trait AuditAnalyses {
127    /// A read view of the analyses.
128    fn view(&self) -> AuditAnalysesView<'_>;
129    /// The dead-code findings, for the dependency scope and the introduced
130    /// flags.
131    fn dead_code_results_mut(&mut self) -> Option<&mut AnalysisResults>;
132    /// The health report, for the introduced flags.
133    fn health_report_mut(&mut self) -> Option<&mut HealthReport>;
134    /// Record the warning of a degraded type-aware comparison on the
135    /// type-aware metadata of the run.
136    fn record_type_aware_warning(&mut self, warning: &str);
137}
138
139/// A checkout of the base commit.
140pub trait BaseCheckout {
141    /// Root of the checkout.
142    fn path(&self) -> &Path;
143}
144
145impl BaseCheckout for fallow_engine::repo_refs::TemporaryBaseWorktree {
146    fn path(&self) -> &Path {
147        Self::path(self)
148    }
149}
150
151/// How one surface runs the analyses of an audit.
152pub trait AuditBackend: Sync {
153    /// The analyses of one side.
154    type Analyses: AuditAnalyses + Send;
155    /// A checkout of the base commit. The base pass keeps it until the base
156    /// analyses complete.
157    type Checkout: BaseCheckout;
158    /// Key of a cached base snapshot.
159    type CacheKey: Sync;
160    /// The error of the surface.
161    type Error: Send;
162
163    /// Called once when the run has changed files, before any base work.
164    fn prepare(&self) {}
165
166    /// Run the head analyses, scoped to `changed_files`.
167    ///
168    /// # Errors
169    ///
170    /// Returns the surface error when an analysis fails.
171    fn run_head(&self, changed_files: &FxHashSet<PathBuf>) -> Result<Self::Analyses, Self::Error>;
172
173    /// Create a checkout of `base_ref`. `base_sha` is the full SHA when a
174    /// cache key resolved it.
175    ///
176    /// # Errors
177    ///
178    /// Returns the surface error when the checkout cannot be created.
179    fn create_base_checkout(
180        &self,
181        base_ref: &str,
182        base_sha: Option<&str>,
183    ) -> Result<Self::Checkout, Self::Error>;
184
185    /// Run the base analyses in `base_root`. With `focus`, scope the findings
186    /// to those files; without it, leave them unscoped.
187    ///
188    /// # Errors
189    ///
190    /// Returns the surface error when an analysis fails.
191    fn run_base(
192        &self,
193        base_root: &Path,
194        focus: Option<&FxHashSet<PathBuf>>,
195    ) -> Result<Self::Analyses, Self::Error>;
196
197    /// The cache key of the base snapshot for `base_ref` and `focus`, or
198    /// `None` when the surface keeps no cache.
199    ///
200    /// # Errors
201    ///
202    /// Returns the surface error when the key inputs cannot be read.
203    fn base_cache_key(
204        &self,
205        _base_ref: &str,
206        _focus: &FxHashSet<PathBuf>,
207    ) -> Result<Option<Self::CacheKey>, Self::Error> {
208        Ok(None)
209    }
210
211    /// The full base SHA that `key` records.
212    fn cached_base_sha<'k>(&self, _key: &'k Self::CacheKey) -> Option<&'k str> {
213        None
214    }
215
216    /// A cached base snapshot for `key`.
217    fn load_cached_base(&self, _key: &Self::CacheKey) -> Option<AuditKeySnapshot> {
218        None
219    }
220
221    /// Store a fresh base snapshot under `key`.
222    fn save_cached_base(&self, _key: &Self::CacheKey, _snapshot: &AuditKeySnapshot) {}
223
224    /// The opt-in shared diff of the run, when one is active.
225    fn shared_diff(&self) -> Option<SharedDiff<'_>> {
226        None
227    }
228}
229
230/// Inputs of one audit run.
231pub struct AuditRunInput<'a> {
232    /// Head analysis root.
233    pub root: &'a Path,
234    /// Gate mode. `new-only` compares with the base snapshot.
235    pub gate: AuditGate,
236    /// How a worsened complexity finding affects the verdict.
237    pub worsened: AuditWorsened,
238    /// Resolved base ref.
239    pub base_ref: &'a str,
240    /// Cache directory of the run. A changed file inside it never blocks the
241    /// reuse of the head run as the base snapshot.
242    pub cache_dir: Option<&'a Path>,
243    /// Changed files of the run, after any narrowing of the surface.
244    pub changed_files: FxHashSet<PathBuf>,
245    /// Commits whose findings are inherited in addition to the base, see
246    /// [`fallow_engine::repo_refs::merged_default_branch_refs`].
247    pub inherited_base_refs: &'a [String],
248    /// The file-length check (`health.maxFileLines`) is on, so a change that
249    /// keeps the tokens but changes the line count still needs a real base.
250    pub compare_line_counts: bool,
251}
252
253/// The base snapshot that attribution compares with.
254#[derive(Debug, Default)]
255pub struct AuditBase {
256    /// The snapshot; `None` under `--gate all`.
257    pub snapshot: Option<AuditKeySnapshot>,
258    /// `true` when the head keys stand in for the base (no finding can have
259    /// changed), so every finding is inherited.
260    pub skipped: bool,
261    /// Snapshots of the inherited bases, with head paths. Attribution absorbs
262    /// them into `snapshot` after the rename remap of the primary base.
263    pub inherited: Vec<AuditKeySnapshot>,
264}
265
266/// Inputs of [`attribute`].
267pub struct AuditAttributionInput<'a> {
268    /// Head analysis root.
269    pub root: &'a Path,
270    /// Gate mode.
271    pub gate: AuditGate,
272    /// How a worsened complexity finding affects the verdict.
273    pub worsened: AuditWorsened,
274    /// Resolved base ref, for the demotion diff.
275    pub base_ref: &'a str,
276    /// The base snapshot.
277    pub base: AuditBase,
278    /// Renames between base and head.
279    pub renames: &'a [RenamedFile],
280    /// Changed files of the run. An unused file or unused export outside them
281    /// stays only when the base does not report it.
282    pub changed_files: &'a FxHashSet<PathBuf>,
283    /// The opt-in shared diff of the run.
284    pub shared_diff: Option<SharedDiff<'a>>,
285}
286
287/// Attribution result of one audit run.
288#[derive(Debug)]
289pub struct AuditOutcome {
290    /// Overall verdict.
291    pub verdict: AuditVerdict,
292    /// Per-domain counts.
293    pub summary: AuditSummary,
294    /// Introduced and inherited counts, and the gate.
295    pub attribution: AuditAttribution,
296    /// The classification of every head finding.
297    pub comparison: AuditComparison,
298    /// The base snapshot after the rename remap.
299    pub base_snapshot: Option<AuditKeySnapshot>,
300    /// `true` when the head keys stood in for the base.
301    pub base_snapshot_skipped: bool,
302    /// Which diff decided the clone-group demotion; `None` when it did not
303    /// run.
304    pub dupe_demotion_diff_source: Option<DupeDemotionDiffSource>,
305    /// The warning of a degraded type-aware comparison, already recorded on
306    /// the head analyses.
307    pub type_aware_degrade_warning: Option<String>,
308    /// Diff-risk findings. Every one is introduced by the change. Empty until
309    /// [`run`] computes them, and in [`attribute`] alone.
310    pub diff_risk: fallow_output::DiffRiskReport,
311}
312
313impl AuditOutcome {
314    /// Store the diff-risk findings and fold their severity into the verdict:
315    /// an `error` finding fails the audit, a `warn` finding turns a pass into
316    /// a warn.
317    pub fn apply_diff_risk(&mut self, report: fallow_output::DiffRiskReport) {
318        if report.has_errors() {
319            self.verdict = AuditVerdict::Fail;
320        } else if !report.is_empty() && self.verdict == AuditVerdict::Pass {
321            self.verdict = AuditVerdict::Warn;
322        }
323        self.diff_risk = report;
324    }
325}
326
327/// The base snapshot of the typed audit output. When the head keys stood in
328/// for the base, the head keys are the base snapshot, so this keeps them.
329pub(crate) fn programmatic_base_snapshot(
330    outcome: &AuditOutcome,
331) -> Option<crate::AuditProgrammaticKeySnapshot> {
332    outcome
333        .base_snapshot
334        .as_ref()
335        .map(AuditKeySnapshot::to_programmatic)
336}
337
338/// One completed audit run.
339pub struct AuditRun<A> {
340    /// Head analyses, with introduced flags on dead-code and health findings
341    /// when a base snapshot exists.
342    pub analyses: A,
343    /// Changed files of the run.
344    pub changed_files: FxHashSet<PathBuf>,
345    /// Attribution result.
346    pub outcome: AuditOutcome,
347}
348
349/// Whether the `new-only` gate needs a base pass, because a changed file can
350/// change a finding (see [`can_reuse_current_as_base`]).
351fn needs_real_base(input: &AuditRunInput<'_>) -> bool {
352    matches!(input.gate, AuditGate::NewOnly)
353        && !can_reuse_current_as_base(
354            input.root,
355            input.cache_dir,
356            input.base_ref,
357            &input.changed_files,
358            input.compare_line_counts,
359        )
360}
361
362/// Run one audit. Returns `None` when the run has no changed files.
363///
364/// # Errors
365///
366/// Returns the error of the backend when an analysis or the base checkout
367/// fails.
368pub fn run<B: AuditBackend>(
369    backend: &B,
370    input: AuditRunInput<'_>,
371) -> Result<Option<AuditRun<B::Analyses>>, B::Error> {
372    if input.changed_files.is_empty() {
373        return Ok(None);
374    }
375    backend.prepare();
376    let needs_real_base = needs_real_base(&input);
377    let AuditRunInput {
378        root,
379        gate,
380        worsened,
381        base_ref,
382        cache_dir: _,
383        changed_files,
384        inherited_base_refs,
385        compare_line_counts: _,
386    } = input;
387    // The diff-risk pass also needs the renames under `--gate all`, so a moved
388    // test file does not read as removed tests.
389    let renames = if needs_real_base || !matches!(gate, AuditGate::NewOnly) {
390        renamed_files(root, base_ref)
391    } else {
392        Vec::new()
393    };
394    let focus = base_focus_files(&changed_files, &renames);
395    let cache_key = if needs_real_base {
396        backend.base_cache_key(base_ref, &focus)?
397    } else {
398        None
399    };
400    let cached = cache_key
401        .as_ref()
402        .and_then(|key| backend.load_cached_base(key));
403
404    let (head, fresh_base) = if needs_real_base && cached.is_none() {
405        let base_sha = cache_key
406            .as_ref()
407            .and_then(|key| backend.cached_base_sha(key));
408        let (head, base) = rayon::join(
409            || backend.run_head(&changed_files),
410            || base_snapshot(backend, root, base_ref, &focus, base_sha),
411        );
412        (head, Some(base))
413    } else {
414        (backend.run_head(&changed_files), None)
415    };
416    let mut analyses = head?;
417    scope_dependency_findings_of(&mut analyses, &changed_files);
418
419    let base = if !matches!(gate, AuditGate::NewOnly) {
420        AuditBase::default()
421    } else if let Some(snapshot) = cached {
422        AuditBase {
423            snapshot: Some(snapshot),
424            skipped: false,
425            inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
426        }
427    } else if let Some(fresh) = fresh_base {
428        let snapshot = fresh?;
429        if let Some(key) = cache_key.as_ref() {
430            backend.save_cached_base(key, &snapshot);
431        }
432        AuditBase {
433            snapshot: Some(snapshot),
434            skipped: false,
435            inherited: inherited_snapshots(backend, root, inherited_base_refs, &focus),
436        }
437    } else {
438        AuditBase {
439            snapshot: Some(AuditKeySnapshot::from_view(&analyses.view())),
440            skipped: true,
441            inherited: Vec::new(),
442        }
443    };
444
445    let mut outcome = attribute(
446        &mut analyses,
447        AuditAttributionInput {
448            root,
449            gate,
450            worsened,
451            base_ref,
452            base,
453            renames: &renames,
454            changed_files: &changed_files,
455            shared_diff: backend.shared_diff(),
456        },
457    );
458    let diff_risk = diff_risk_of(
459        &analyses,
460        &outcome,
461        root,
462        base_ref,
463        &changed_files,
464        &renames,
465    );
466    outcome.apply_diff_risk(diff_risk);
467    Ok(Some(AuditRun {
468        analyses,
469        changed_files,
470        outcome,
471    }))
472}
473
474/// Copy the comparison result onto the complexity and styling findings.
475fn annotate_health_report(report: &mut HealthReport, comparison: &AuditComparison) {
476    for ((finding, introduced), class) in report
477        .findings
478        .iter_mut()
479        .zip(comparison.health.introduced())
480        .zip(&comparison.health_classes)
481    {
482        finding.introduced = Some(introduced);
483        let attribution = class.attribution();
484        finding.attribution = Some(attribution);
485        finding.worsened_metrics.clone_from(&class.worsened_metrics);
486        finding.audit_base = class
487            .base
488            .filter(|_| attribution == fallow_output::AuditFindingAttribution::Inherited);
489    }
490    for (finding, introduced) in report
491        .styling_findings
492        .iter_mut()
493        .zip(comparison.styling.introduced())
494    {
495        finding.internal.introduced = Some(introduced);
496    }
497}
498
499/// Compare head analyses with a base snapshot, decide the verdict, and set
500/// the introduced flags on the dead-code, complexity and styling findings.
501///
502/// Under the `new-only` gate, a complexity finding that exceeds only CRAP from
503/// estimated coverage gets the gate severity `warn` first, so it does not fail
504/// the verdict. Under every gate, a complexity finding in a test file gets the
505/// gate severity `warn` and the gate exemption `test-file`.
506pub fn attribute<A: AuditAnalyses>(
507    analyses: &mut A,
508    input: AuditAttributionInput<'_>,
509) -> AuditOutcome {
510    let AuditAttributionInput {
511        root,
512        gate,
513        worsened,
514        base_ref,
515        base,
516        renames,
517        changed_files,
518        shared_diff,
519    } = input;
520    let AuditBase {
521        snapshot: mut base_snapshot,
522        skipped,
523        inherited,
524    } = base;
525    if matches!(gate, AuditGate::NewOnly)
526        && let Some(report) = analyses.health_report_mut()
527    {
528        crate::audit_complexity::demote_estimated_crap_gates(&mut report.findings);
529    }
530    if let Some(report) = analyses.health_report_mut() {
531        crate::audit_complexity::exempt_test_file_gates(&mut report.findings, root);
532    }
533    // The head keys that stand in for a skipped base are head paths already.
534    if !skipped && let Some(snapshot) = base_snapshot.as_mut() {
535        snapshot.remap_for_renames(renames, root);
536        for inherited in inherited {
537            snapshot.absorb_inherited(inherited);
538        }
539        if let Some(dead_code) = analyses.view().dead_code.as_ref() {
540            snapshot.forget_unused_code_used_under_own_config(dead_code);
541            snapshot.inherit_unprovable_dead_code(dead_code);
542        }
543    }
544    scope_unchanged_unused_code_of(analyses, changed_files, base_snapshot.as_ref());
545    let degrade_reason = {
546        let view = analyses.view();
547        type_aware_attribution_degrade_reason(
548            base_snapshot.as_ref(),
549            view.dead_code
550                .as_ref()
551                .and_then(|dead_code| dead_code.type_aware),
552        )
553    };
554    let type_aware_degrade_warning = degrade_reason.map(type_aware_degrade_warning);
555    if let Some(warning) = type_aware_degrade_warning.as_deref() {
556        analyses.record_type_aware_warning(warning);
557    }
558
559    let (comparison, dupe_demotion_diff_source, (attribution, verdict, summary)) = {
560        let view = analyses.view();
561        let change = RunChange::new(root, base_ref, shared_diff, changed_files);
562        let degraded = degrade_reason.is_some();
563        let mut comparison = compare(&view, base_snapshot.as_ref(), degraded, &change);
564        comparison.clear_worsened_when_off(worsened);
565        let source = demote_preexisting_dupe_introductions(
566            &mut comparison,
567            &view,
568            root,
569            base_ref,
570            shared_diff,
571            DupeBase {
572                // A skipped base reuses the head keys, so no group is introduced.
573                groups: base_snapshot
574                    .as_ref()
575                    .filter(|_| !skipped)
576                    .map_or(&[][..], |snapshot| snapshot.dupe_groups.as_slice()),
577                renames,
578            },
579        );
580        realign_styling_introductions(
581            &mut comparison,
582            &view,
583            base_snapshot.as_ref(),
584            root,
585            base_ref,
586            shared_diff,
587        );
588        let result = outcome(gate, worsened, &view, &comparison, base_snapshot.is_some());
589        (comparison, source, result)
590    };
591
592    if base_snapshot.is_some() {
593        if let Some(results) = analyses.dead_code_results_mut() {
594            comparison.dead_code.annotate_results(results);
595        }
596        if let Some(report) = analyses.health_report_mut() {
597            annotate_health_report(report, &comparison);
598        }
599    }
600
601    AuditOutcome {
602        verdict,
603        summary,
604        attribution,
605        comparison,
606        base_snapshot,
607        base_snapshot_skipped: skipped,
608        dupe_demotion_diff_source,
609        type_aware_degrade_warning,
610        diff_risk: fallow_output::DiffRiskReport::default(),
611    }
612}
613
614/// Run the diff-risk rules over the changed files of one audit.
615fn diff_risk_of<A: AuditAnalyses>(
616    analyses: &A,
617    outcome: &AuditOutcome,
618    root: &Path,
619    base_ref: &str,
620    changed_files: &FxHashSet<PathBuf>,
621    renames: &[RenamedFile],
622) -> fallow_output::DiffRiskReport {
623    let view = analyses.view();
624    let default_rules = RulesConfig::default();
625    let rules = if let Some(dead_code) = view.dead_code.as_ref() {
626        crate::diff_risk::DiffRiskRules::Config(dead_code.config)
627    } else if let Some(health) = view.health.as_ref() {
628        crate::diff_risk::DiffRiskRules::Rules(health.rules)
629    } else {
630        crate::diff_risk::DiffRiskRules::Rules(&default_rules)
631    };
632    let head_clone_groups = view
633        .duplication
634        .as_ref()
635        .map(|duplication| {
636            duplication
637                .clone_groups
638                .iter()
639                .map(|group| crate::diff_risk::clone_spans(group, duplication.root))
640                .collect()
641        })
642        .unwrap_or_default();
643    // A skipped base pass reuses the head keys, so no clone copy can differ.
644    let base_clone_groups = if outcome.base_snapshot_skipped || view.duplication.is_none() {
645        None
646    } else {
647        outcome
648            .base_snapshot
649            .as_ref()
650            .map(|snapshot| snapshot.dupe_groups.as_slice())
651    };
652    crate::diff_risk::detect(&crate::diff_risk::DiffRiskInput {
653        root,
654        base_ref,
655        changed_files,
656        renames,
657        rules,
658        base_clone_groups,
659        head_clone_groups,
660    })
661}
662
663/// Take the snapshot of each inherited base, with its keys on head paths.
664///
665/// An inherited base only lowers the introduced count, so a base that fails
666/// (no worktree, a failed analysis) is left out. The audit then keeps the
667/// stricter comparison with the primary base.
668fn inherited_snapshots<B: AuditBackend>(
669    backend: &B,
670    root: &Path,
671    refs: &[String],
672    focus: &FxHashSet<PathBuf>,
673) -> Vec<AuditKeySnapshot> {
674    refs.iter()
675        .filter_map(|inherited_ref| inherited_snapshot(backend, root, inherited_ref, focus).ok())
676        .collect()
677}
678
679fn inherited_snapshot<B: AuditBackend>(
680    backend: &B,
681    root: &Path,
682    inherited_ref: &str,
683    focus: &FxHashSet<PathBuf>,
684) -> Result<AuditKeySnapshot, B::Error> {
685    let cache_key = backend.base_cache_key(inherited_ref, focus)?;
686    if let Some(cached) = cache_key
687        .as_ref()
688        .and_then(|key| backend.load_cached_base(key))
689    {
690        return Ok(remapped(cached, root, inherited_ref));
691    }
692    let base_sha = cache_key
693        .as_ref()
694        .and_then(|key| backend.cached_base_sha(key));
695    let snapshot = base_snapshot(backend, root, inherited_ref, focus, base_sha)?;
696    if let Some(key) = cache_key.as_ref() {
697        backend.save_cached_base(key, &snapshot);
698    }
699    Ok(remapped(snapshot, root, inherited_ref))
700}
701
702fn remapped(mut snapshot: AuditKeySnapshot, root: &Path, base_ref: &str) -> AuditKeySnapshot {
703    snapshot.remap_for_renames(&renamed_files(root, base_ref), root);
704    snapshot
705}
706
707/// Analyze the base checkout and take its attribution keys.
708fn base_snapshot<B: AuditBackend>(
709    backend: &B,
710    root: &Path,
711    base_ref: &str,
712    focus: &FxHashSet<PathBuf>,
713    base_sha: Option<&str>,
714) -> Result<AuditKeySnapshot, B::Error> {
715    let checkout = backend.create_base_checkout(base_ref, base_sha)?;
716    let base_root = match resolve_base_analysis_root(root, checkout.path()) {
717        // The canonical spelling: an analysis session canonicalizes its root,
718        // so a focus set spelled through a symbolic link (the macOS temporary
719        // directory) would match no finding and empty the base snapshot.
720        BaseAnalysisRoot::Present(base_root) => {
721            dunce::canonicalize(&base_root).unwrap_or(base_root)
722        }
723        // A root that the base commit does not contain (a package added on
724        // the branch) has an empty base snapshot, so every finding under it
725        // is introduced.
726        BaseAnalysisRoot::NewInHead(_) => return Ok(AuditKeySnapshot::default()),
727    };
728    let base_focus = remap_focus_files(focus, root, &base_root);
729    let mut base = backend.run_base(&base_root, base_focus.as_ref())?;
730    if let Some(focus) = base_focus.as_ref() {
731        scope_dependency_findings_of(&mut base, focus);
732    }
733    let snapshot = AuditKeySnapshot::from_view(&base.view());
734    drop(checkout);
735    Ok(snapshot)
736}
737
738/// Apply [`scope_unchanged_unused_code`] to the dead-code findings of the
739/// head.
740fn scope_unchanged_unused_code_of<A: AuditAnalyses>(
741    analyses: &mut A,
742    changed_files: &FxHashSet<PathBuf>,
743    base: Option<&AuditKeySnapshot>,
744) {
745    let Some(root) = analyses
746        .view()
747        .dead_code
748        .map(|dead_code| dead_code.root.to_path_buf())
749    else {
750        return;
751    };
752    if let Some(results) = analyses.dead_code_results_mut() {
753        scope_unchanged_unused_code(results, &root, changed_files, base);
754    }
755}
756
757/// Apply [`scope_dependency_findings`] to the dead-code findings of one side.
758fn scope_dependency_findings_of<A: AuditAnalyses>(
759    analyses: &mut A,
760    changed_files: &FxHashSet<PathBuf>,
761) {
762    let Some(root) = analyses
763        .view()
764        .dead_code
765        .map(|dead_code| dead_code.root.to_path_buf())
766    else {
767        return;
768    };
769    if let Some(results) = analyses.dead_code_results_mut() {
770        scope_dependency_findings(results, &root, changed_files);
771    }
772}