Skip to main content

fallow_api/audit_run/
base_files.rs

1//! Base-side file reads, and the check that lets an audit reuse the head run
2//! as its base snapshot.
3
4use std::io::Write as _;
5use std::path::{Path, PathBuf};
6
7use rustc_hash::{FxHashMap, FxHashSet};
8
9/// Whether the head run can stand in for the base snapshot.
10///
11/// True when no changed file can change a finding: each one is a Fallow cache
12/// artifact, a documentation file, or a JS/TS source whose base version has
13/// the same token stream (whitespace and comment changes). The audit then
14/// reuses the head keys as the base keys, which attributes every finding as
15/// inherited, without a base worktree.
16///
17/// With `compare_line_counts`, a JS/TS source must also keep its line count.
18/// The file-length check (`health.maxFileLines`) counts blank and comment
19/// lines, so a comment-only change can make a file-length finding introduced
20/// or worsened.
21#[must_use]
22#[expect(
23    clippy::implicit_hasher,
24    reason = "fallow standardizes on FxHashSet across the workspace"
25)]
26pub fn can_reuse_current_as_base(
27    root: &Path,
28    cache_dir: Option<&Path>,
29    base_ref: &str,
30    changed_files: &FxHashSet<PathBuf>,
31    compare_line_counts: bool,
32) -> bool {
33    let Ok(git_root) = fallow_engine::changed_files::resolve_git_toplevel(root) else {
34        return false;
35    };
36    let canonical_cache_dir = cache_dir.and_then(|dir| dunce::canonicalize(dir).ok());
37    // Spawn the batched base-file reader lazily: a changeset of only cache
38    // artifacts or docs never touches git, so it spawns zero processes.
39    let mut reader: Option<BaseFileReader> = None;
40    for path in changed_files {
41        if cache_dir
42            .is_some_and(|dir| is_fallow_cache_artifact(path, dir, canonical_cache_dir.as_deref()))
43        {
44            continue;
45        }
46        if !is_analysis_input(path) {
47            if is_non_behavioral_doc(path) {
48                continue;
49            }
50            return false;
51        }
52        let Ok(current) = std::fs::read_to_string(path) else {
53            return false;
54        };
55        let Ok(relative) = path.strip_prefix(&git_root) else {
56            return false;
57        };
58        let reader = match reader.as_mut() {
59            Some(reader) => reader,
60            None => {
61                let Some(spawned) = BaseFileReader::spawn(root) else {
62                    return false;
63                };
64                reader.insert(spawned)
65            }
66        };
67        let base = match reader.read(base_ref, relative) {
68            BaseRead::Content(base) => base,
69            BaseRead::Missing | BaseRead::Error => return false,
70        };
71        if current == base {
72            continue;
73        }
74        if compare_line_counts && current.lines().count() != base.lines().count() {
75            return false;
76        }
77        if !js_ts_tokens_equivalent(path, &current, &base) {
78            return false;
79        }
80    }
81    true
82}
83
84/// The export names of changed files at the merge base of `base_ref` and
85/// `HEAD`, the base side of the audit diff.
86///
87/// `files` pairs the head path of each file with its base path (the path
88/// before a rename), both relative to `root`. The result maps each head path
89/// that git could read to the export names of its base version. A file that
90/// did not exist at the base maps to an empty set. A file that git cannot
91/// read is left out, and a read error stops the remaining reads, so a broken
92/// pipe never reads as a file without exports.
93#[must_use]
94pub fn export_names_at_base(
95    root: &Path,
96    base_ref: &str,
97    files: &[(String, String)],
98) -> FxHashMap<String, FxHashSet<String>> {
99    let mut names = FxHashMap::default();
100    if files.is_empty() {
101        return names;
102    }
103    let Ok(git_root) = fallow_engine::changed_files::resolve_git_toplevel(root) else {
104        return names;
105    };
106    let git_root = dunce::canonicalize(&git_root).unwrap_or(git_root);
107    let root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
108    let Some(mut reader) = BaseFileReader::spawn(&root) else {
109        return names;
110    };
111    let commit = crate::diff_risk::merge_base(&root, base_ref);
112    for (head, base) in files {
113        let base_path = root.join(base);
114        let Ok(relative) = base_path.strip_prefix(&git_root) else {
115            continue;
116        };
117        let exports = match reader.read(&commit, relative) {
118            BaseRead::Content(source) => {
119                fallow_engine::module_graph::export_names_in_source(&base_path, &source)
120            }
121            BaseRead::Missing => FxHashSet::default(),
122            BaseRead::Error => break,
123        };
124        names.insert(head.clone(), exports);
125    }
126    names
127}
128
129/// A long-lived `git cat-file --batch` child process that reads the base
130/// version of changed files without one `git show` for each file.
131///
132/// Requests and responses are strictly lockstep (one request line, one
133/// response), so the pipe buffers cannot deadlock. A missing object yields
134/// [`BaseRead::Missing`], and content is read with lossy UTF-8 conversion.
135///
136/// The child is a [`fallow_process::ScopedChild`], so an interrupt
137/// (SIGINT/SIGTERM) during a large read loop kills the `cat-file` process
138/// through the signal registry instead of leaving it orphaned.
139pub struct BaseFileReader {
140    /// The registered `cat-file --batch` child. `Drop` takes it and calls the
141    /// consuming wait after it closes stdin, which reaps the child and
142    /// deregisters its PID.
143    child: Option<fallow_process::ScopedChild>,
144    /// `Drop` takes and drops it before the blocking wait, which closes the
145    /// pipe so the wait cannot block.
146    stdin: Option<std::process::ChildStdin>,
147    stdout: std::io::BufReader<std::process::ChildStdout>,
148}
149
150impl BaseFileReader {
151    /// Spawn one `git cat-file --batch` process in `root`.
152    ///
153    /// Returns `None` when the spawn fails or the stdio pipes are not
154    /// available. The caller then treats the files as not reusable.
155    #[must_use]
156    pub fn spawn(root: &Path) -> Option<Self> {
157        let mut command = fallow_engine::changed_files::git_command_in(root);
158        command
159            .args(["cat-file", "--batch"])
160            .stdin(std::process::Stdio::piped())
161            .stdout(std::process::Stdio::piped())
162            .stderr(std::process::Stdio::null());
163        let mut child = fallow_process::ScopedChild::spawn(&mut command).ok()?;
164        let stdin = child.take_stdin()?;
165        let stdout = child.take_stdout()?;
166        Some(Self {
167            child: Some(child),
168            stdin: Some(stdin),
169            stdout: std::io::BufReader::new(stdout),
170        })
171    }
172
173    /// Read the base version of the repository-relative path `relative` at
174    /// `base_ref`.
175    ///
176    /// Writes one `<base_ref>:<path>` request line (forward slashes) and reads
177    /// exactly one response. A ` missing` header yields [`BaseRead::Missing`].
178    /// A parse or IO error, or a path with a newline (which would corrupt the
179    /// request stream), yields [`BaseRead::Error`].
180    pub fn read(&mut self, base_ref: &str, relative: &Path) -> BaseRead {
181        use std::io::{BufRead, Read};
182
183        let relative = relative.to_string_lossy().replace('\\', "/");
184        if relative.contains('\n') {
185            return BaseRead::Error;
186        }
187
188        let Some(stdin) = self.stdin.as_mut() else {
189            return BaseRead::Error;
190        };
191        if writeln!(stdin, "{base_ref}:{relative}").is_err() || stdin.flush().is_err() {
192            return BaseRead::Error;
193        }
194
195        let mut header = String::new();
196        if !matches!(self.stdout.read_line(&mut header), Ok(n) if n > 0) {
197            return BaseRead::Error;
198        }
199        // `git cat-file --batch` reports a missing object as `<spec> missing\n`.
200        if header.trim_end().ends_with(" missing") {
201            return BaseRead::Missing;
202        }
203        // Otherwise the header is `<oid> <type> <size>\n`.
204        let Some(size) = header
205            .trim_end()
206            .rsplit(' ')
207            .next()
208            .and_then(|raw| raw.parse::<usize>().ok())
209        else {
210            return BaseRead::Error;
211        };
212        let mut buf = vec![0u8; size];
213        if self.stdout.read_exact(&mut buf).is_err() {
214            return BaseRead::Error;
215        }
216        // Consume the one newline after the object content. An off-by-one
217        // here corrupts every later read in the batch.
218        let mut newline = [0u8; 1];
219        if self.stdout.read_exact(&mut newline).is_err() {
220            return BaseRead::Error;
221        }
222
223        BaseRead::Content(String::from_utf8_lossy(&buf).into_owned())
224    }
225}
226
227/// Outcome of one batched base-file read. "The object does not exist at base"
228/// and "the pipe or parse failed" stay apart, so a transient `git cat-file`
229/// failure never reads as an empty base file.
230#[derive(Debug, PartialEq, Eq)]
231pub enum BaseRead {
232    /// The object exists at base; lossy UTF-8 content.
233    Content(String),
234    /// `git cat-file` reported the object as ` missing`: the file is new
235    /// relative to base.
236    Missing,
237    /// A pipe write or read, or a header parse, failed (or the path cannot be
238    /// requested). Later reads from this reader are not reliable.
239    Error,
240}
241
242impl Drop for BaseFileReader {
243    fn drop(&mut self) {
244        // Close stdin so the child sees EOF and exits, then reap it through the
245        // blocking wait of the scoped child, which also deregisters the PID.
246        self.stdin.take();
247        if let Some(child) = self.child.take() {
248            let _ = child.wait();
249        }
250    }
251}
252
253fn is_fallow_cache_artifact(
254    path: &Path,
255    cache_dir: &Path,
256    canonical_cache_dir: Option<&Path>,
257) -> bool {
258    path.starts_with(cache_dir)
259        || canonical_cache_dir.is_some_and(|canonical| path.starts_with(canonical))
260}
261
262pub(super) fn is_analysis_input(path: &Path) -> bool {
263    matches!(
264        path.extension().and_then(|ext| ext.to_str()),
265        Some(
266            "js" | "jsx"
267                | "ts"
268                | "tsx"
269                | "mjs"
270                | "mts"
271                | "cjs"
272                | "cts"
273                | "vue"
274                | "svelte"
275                | "astro"
276                | "mdx"
277                | "css"
278                | "scss"
279        )
280    )
281}
282
283pub(super) fn is_non_behavioral_doc(path: &Path) -> bool {
284    matches!(
285        path.extension().and_then(|ext| ext.to_str()),
286        Some("md" | "markdown" | "txt" | "rst" | "adoc")
287    )
288}
289
290/// Text that fallow reads outside the token stream. The token comparison
291/// skips comments, so a change to a suppression comment, a JSDoc visibility
292/// tag or a JSDoc `import()` type can change the findings with no token
293/// change. Keep `import(` for imports in comments even though executable
294/// template literals are compared by their source spans.
295const REUSE_BLOCKING_MARKERS: &[&str] = &[
296    "fallow-ignore",
297    "@expected-unused",
298    "@public",
299    "@internal",
300    "@beta",
301    "@alpha",
302    "@api",
303    "import(",
304];
305
306fn has_reuse_blocking_marker(source: &str) -> bool {
307    REUSE_BLOCKING_MARKERS
308        .iter()
309        .any(|marker| source.contains(marker))
310}
311
312pub(super) fn js_ts_tokens_equivalent(path: &Path, current: &str, base: &str) -> bool {
313    if has_reuse_blocking_marker(current) || has_reuse_blocking_marker(base) {
314        return false;
315    }
316    if !matches!(
317        path.extension().and_then(|ext| ext.to_str()),
318        Some("js" | "jsx" | "ts" | "tsx" | "mjs" | "mts" | "cjs" | "cts")
319    ) {
320        return false;
321    }
322    fallow_engine::duplicates::source_token_kinds_equivalent(path, current, base, false)
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    /// A severed request pipe is an error, never a missing object or empty
330    /// content, so a caller stops its scan instead of reading every later
331    /// file as empty at base.
332    #[test]
333    fn a_severed_request_pipe_is_an_error() {
334        let tmp = tempfile::TempDir::new().expect("temp dir should be created");
335        let mut reader = BaseFileReader::spawn(tmp.path()).expect("reader should spawn");
336
337        reader.stdin.take();
338
339        assert_eq!(reader.read("HEAD", Path::new("README.md")), BaseRead::Error);
340    }
341}