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