Skip to main content

fallow_api/audit_run/
scope.rs

1//! Which files and findings one audit run covers.
2
3use std::path::{Path, PathBuf};
4
5use fallow_engine::changed_files::RenamedFile;
6use fallow_types::results::AnalysisResults;
7use rustc_hash::FxHashSet;
8
9use super::AuditKeySnapshot;
10
11/// Keep a dependency-level finding only when its manifest is in `changed_files`.
12///
13/// A dependency finding (unused, type-only, test-only or misplaced
14/// dependency, unused catalog entry) is anchored to the package manifest or
15/// the catalog file that declares it. `--changed-since` keeps these findings
16/// whatever changed, because whether a dependency is used is a fact about the
17/// whole graph. An audit reviews a changeset, so it reports them only when the
18/// changeset touched the file that declares them. The rule covers the root
19/// manifest and each workspace package manifest. A relative anchor (a catalog
20/// file) is relative to `root`, the root of the analysis.
21#[expect(
22    clippy::implicit_hasher,
23    reason = "fallow standardizes on FxHashSet across the workspace"
24)]
25pub fn scope_dependency_findings(
26    results: &mut AnalysisResults,
27    root: &Path,
28    changed_files: &FxHashSet<PathBuf>,
29) {
30    let changed = ChangedPaths::new(changed_files);
31    let declared_in_change = |path: &Path| changed.contains(root, path);
32    results
33        .unused_dependencies
34        .retain(|finding| declared_in_change(&finding.dep.path));
35    results
36        .unused_dev_dependencies
37        .retain(|finding| declared_in_change(&finding.dep.path));
38    results
39        .unused_optional_dependencies
40        .retain(|finding| declared_in_change(&finding.dep.path));
41    results
42        .type_only_dependencies
43        .retain(|finding| declared_in_change(&finding.dep.path));
44    results
45        .test_only_dependencies
46        .retain(|finding| declared_in_change(&finding.dep.path));
47    results
48        .dev_dependencies_in_production
49        .retain(|finding| declared_in_change(&finding.dep.path));
50    results
51        .unused_catalog_entries
52        .retain(|finding| declared_in_change(&finding.entry.path));
53}
54
55/// The changed files of one audit, for a membership test of finding paths.
56struct ChangedPaths(FxHashSet<PathBuf>);
57
58impl ChangedPaths {
59    fn new(changed_files: &FxHashSet<PathBuf>) -> Self {
60        Self(
61            changed_files
62                .iter()
63                .map(|path| dunce::simplified(path).to_path_buf())
64                .collect(),
65        )
66    }
67
68    /// Whether `path` is a changed file. A relative `path` is relative to
69    /// `root`. Git reports changed files under the canonical top level, while
70    /// a root can be spelled through a symbolic link, so the canonical form is
71    /// tried as well.
72    fn contains(&self, root: &Path, path: &Path) -> bool {
73        let anchored = if path.is_absolute() {
74            path.to_path_buf()
75        } else {
76            root.join(path)
77        };
78        self.0.contains(dunce::simplified(&anchored))
79            || dunce::canonicalize(&anchored).is_ok_and(|canonical| self.0.contains(&canonical))
80    }
81}
82
83/// Keep an unused file or unused export outside `changed_files` only when the
84/// base does not report it.
85///
86/// The surface keeps these findings outside the changed files, because a
87/// change can make code unused without a change to that code: it removes the
88/// last import, or a config change removes an entry point. A finding that the
89/// base also reports did not come from the change, so it leaves the report.
90/// Without a base (`--gate all`), every such finding leaves the report.
91/// `base` must already use head paths.
92#[expect(
93    clippy::implicit_hasher,
94    reason = "fallow standardizes on FxHashSet across the workspace"
95)]
96pub fn scope_unchanged_unused_code(
97    results: &mut AnalysisResults,
98    root: &Path,
99    changed_files: &FxHashSet<PathBuf>,
100    base: Option<&AuditKeySnapshot>,
101) {
102    let changed = ChangedPaths::new(changed_files);
103    let keep = |path: &Path, key: &String| {
104        changed.contains(root, path) || base.is_some_and(|base| !base.reports_dead_code(key))
105    };
106    let file_keys = crate::audit_keys::collection_keys(&results.unused_files, root);
107    let mut file_keys = file_keys.iter();
108    results.unused_files.retain(|finding| {
109        file_keys
110            .next()
111            .is_some_and(|key| keep(&finding.file.path, key))
112    });
113    let export_keys = crate::audit_keys::collection_keys(&results.unused_exports, root);
114    let mut export_keys = export_keys.iter();
115    results.unused_exports.retain(|finding| {
116        export_keys
117            .next()
118            .is_some_and(|key| keep(&finding.export.path, key))
119    });
120}
121
122/// Detect base..head renames for rename-aware attribution.
123///
124/// Best effort: when git fails, the audit uses plain path-keyed attribution,
125/// which reports findings that moved with a file as introduced.
126#[must_use]
127pub fn renamed_files(root: &Path, base_ref: &str) -> Vec<RenamedFile> {
128    fallow_engine::changed_files::try_get_renamed_files(root, base_ref).unwrap_or_default()
129}
130
131/// The files the base pass covers: the changed files plus the pre-rename path
132/// of each rename, so base findings on moved files are in the base snapshot and
133/// the rename remap can move them onto their head paths.
134#[must_use]
135#[expect(
136    clippy::implicit_hasher,
137    reason = "fallow standardizes on FxHashSet across the workspace"
138)]
139pub fn base_focus_files(
140    changed_files: &FxHashSet<PathBuf>,
141    renames: &[RenamedFile],
142) -> FxHashSet<PathBuf> {
143    changed_files
144        .iter()
145        .cloned()
146        .chain(renames.iter().map(|rename| rename.from.clone()))
147        .collect()
148}
149
150/// Express `files` (absolute paths under `from_root`) under `to_root`.
151///
152/// Returns `None` when no path maps. The caller then leaves the base results
153/// unfiltered: a filter with an empty set would remove every base finding and
154/// make every inherited head finding look introduced.
155///
156/// The focus set comes from `git rev-parse --show-toplevel`, whose spelling
157/// can differ from the canonical root of the caller (Windows 8.3 components,
158/// drive-letter case, verbatim `\\?\` prefixes), so the simplified and the
159/// canonical forms are both tried before a path is given up.
160#[must_use]
161#[expect(
162    clippy::implicit_hasher,
163    reason = "fallow standardizes on FxHashSet across the workspace"
164)]
165pub fn remap_focus_files(
166    files: &FxHashSet<PathBuf>,
167    from_root: &Path,
168    to_root: &Path,
169) -> Option<FxHashSet<PathBuf>> {
170    let simple_from = dunce::simplified(from_root).to_path_buf();
171    let canonical_from = dunce::canonicalize(from_root).unwrap_or_else(|_| simple_from.clone());
172    let mut remapped = FxHashSet::default();
173    for file in files {
174        let simple_file = dunce::simplified(file);
175        let relative = simple_file
176            .strip_prefix(&simple_from)
177            .or_else(|_| simple_file.strip_prefix(&canonical_from))
178            .map(Path::to_path_buf)
179            .ok()
180            .or_else(|| {
181                let canonical_file = dunce::canonicalize(file).ok()?;
182                canonical_file
183                    .strip_prefix(&canonical_from)
184                    .map(Path::to_path_buf)
185                    .ok()
186            });
187        if let Some(relative) = relative {
188            remapped.insert(to_root.join(relative));
189        }
190    }
191    if remapped.is_empty() {
192        return None;
193    }
194    Some(remapped)
195}
196
197/// Istanbul coverage inputs of the base pass.
198#[derive(Debug, Clone, Default, PartialEq, Eq)]
199pub struct BaseCoverageInputs {
200    /// Coverage map path, resolved against the head root.
201    pub coverage: Option<PathBuf>,
202    /// Prefix to strip from recorded paths before they rebase onto the base
203    /// worktree.
204    pub coverage_root: Option<PathBuf>,
205}
206
207/// Coverage inputs for the base-worktree pass.
208///
209/// The Istanbul map records head-checkout paths, while the base pass analyzes
210/// a temporary worktree. Without a rebase no coverage entry matches a base
211/// file, base CRAP falls back to the reachability estimate, and unchanged
212/// functions flip to `introduced` (#2347). Without an explicit map, the head
213/// pass auto-detects `coverage/coverage-final.json` against the head root,
214/// which the base worktree never has, so the same detection runs here. When no
215/// explicit `coverage_root` exists, the canonical head root becomes the strip
216/// prefix, so every entry rebases onto the base worktree. An explicit
217/// `coverage_root` stays as it is: the base pass rebases it onto its own root.
218#[must_use]
219pub fn base_coverage_inputs(
220    root: &Path,
221    coverage: Option<&Path>,
222    coverage_root: Option<&Path>,
223) -> BaseCoverageInputs {
224    let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
225    let coverage = coverage.map_or_else(
226        || fallow_engine::health::scoring::auto_detect_coverage(&canonical_root),
227        |coverage| {
228            Some(fallow_engine::health::scoring::resolve_relative_to_root(
229                coverage,
230                Some(&canonical_root),
231            ))
232        },
233    );
234    let coverage_root = match (&coverage, coverage_root) {
235        (_, Some(explicit)) => Some(explicit.to_path_buf()),
236        (Some(_), None) => Some(canonical_root),
237        (None, None) => None,
238    };
239    BaseCoverageInputs {
240        coverage,
241        coverage_root,
242    }
243}