fallow_api/audit_run/
base_files.rs1use std::io::Write as _;
5use std::path::{Path, PathBuf};
6
7use rustc_hash::{FxHashMap, FxHashSet};
8
9#[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 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, ¤t, &base) {
78 return false;
79 }
80 }
81 true
82}
83
84#[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
129pub struct BaseFileReader {
140 child: Option<fallow_process::ScopedChild>,
144 stdin: Option<std::process::ChildStdin>,
147 stdout: std::io::BufReader<std::process::ChildStdout>,
148}
149
150impl BaseFileReader {
151 #[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 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 if header.trim_end().ends_with(" missing") {
201 return BaseRead::Missing;
202 }
203 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 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#[derive(Debug, PartialEq, Eq)]
231pub enum BaseRead {
232 Content(String),
234 Missing,
237 Error,
240}
241
242impl Drop for BaseFileReader {
243 fn drop(&mut self) {
244 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
290const 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 #[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}