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