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