Skip to main content

fallow_engine/
changed_files.rs

1//! Changed-file helpers owned by the engine boundary.
2
3use std::path::{Path, PathBuf};
4use std::process::{Command, Output};
5use std::sync::OnceLock;
6use std::sync::atomic::{AtomicBool, Ordering};
7
8use fallow_types::{
9    output_dead_code::{
10        CircularDependencyFinding, DuplicateExportFinding, DuplicatePropShapeFinding,
11        PackageCycleFinding, PropDrillingChainFinding, ReExportCycleFinding,
12        UnlistedDependencyFinding,
13    },
14    results::{AnalysisResults, SecurityFinding},
15};
16use rustc_hash::FxHashSet;
17
18use crate::duplicates::{self, DuplicationReport};
19
20pub use crate::git_env::{
21    AMBIENT_GIT_ENV_VARS, clear_ambient_git_env, git_command as git_command_in,
22};
23
24/// Function pointer signature used to intercept short-running git
25/// subprocesses spawned by changed-file helpers.
26pub type ChangedFilesSpawnHook = fn(&mut std::process::Command) -> std::io::Result<Output>;
27
28static SPAWN_HOOK: OnceLock<ChangedFilesSpawnHook> = OnceLock::new();
29
30/// Classification of a changed-file git failure.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum ChangedFilesError {
33    /// Git ref failed validation before invoking `git`.
34    InvalidRef(String),
35    /// `git` binary not found or not executable.
36    GitMissing(String),
37    /// Command ran but the directory is not a git repository.
38    NotARepository,
39    /// Command ran but the ref is invalid or another git error occurred.
40    GitFailed(String),
41}
42
43impl ChangedFilesError {
44    /// Human-readable clause suitable for embedding in an error message.
45    #[must_use]
46    pub fn describe(&self) -> String {
47        match self {
48            Self::InvalidRef(err) => format!("invalid git ref: {err}"),
49            Self::GitMissing(err) => format!("failed to run git: {err}"),
50            Self::NotARepository => "not a git repository".to_owned(),
51            Self::GitFailed(stderr) => augment_git_failed(stderr),
52        }
53    }
54
55    /// Stable kebab-case token naming this failure, for machine consumers.
56    ///
57    /// One token per variant, so a consumer can branch on the cause without
58    /// matching prose. Published on the wire as
59    /// `request_outcomes["changed-since"].reason`.
60    #[must_use]
61    pub const fn reason(&self) -> &'static str {
62        match self {
63            Self::InvalidRef(_) => "invalid-ref",
64            Self::GitMissing(_) => "git-missing",
65            Self::NotARepository => "not-a-repository",
66            Self::GitFailed(_) => "git-failed",
67        }
68    }
69
70    /// The full sentence for a run whose `--changed-since` request could not be
71    /// applied: what was asked, what happened instead, and the next step.
72    ///
73    /// The one prose source for this fact. The CLI writes it to stderr and
74    /// publishes the same string on the envelope, so a log a human read and a
75    /// report a script read cannot say different things.
76    ///
77    /// Git's own stderr is folded onto one line: the sentence travels into a
78    /// jq-rendered CI annotation and into a rendered pull-request comment, and
79    /// a multi-line value there splits one fact across two log records.
80    #[must_use]
81    pub fn changed_since_message(&self, git_ref: &str) -> String {
82        let cause = self
83            .describe()
84            .split_whitespace()
85            .collect::<Vec<_>>()
86            .join(" ");
87        format!(
88            "--changed-since '{git_ref}' was ignored because {cause}, so this report covers \
89             the whole project instead of the changed files. {}",
90            self.changed_since_remedy()
91        )
92    }
93
94    /// The next step for [`Self::changed_since_message`], one per cause.
95    const fn changed_since_remedy(&self) -> &'static str {
96        match self {
97            Self::InvalidRef(_) => {
98                "Pass a ref git can resolve, such as a branch name or a commit sha."
99            }
100            Self::GitMissing(_) => {
101                "Install git and make it available on PATH, or drop --changed-since."
102            }
103            Self::NotARepository => {
104                "Run fallow from inside the repository, or drop --changed-since."
105            }
106            Self::GitFailed(_) => {
107                "Verify the ref exists in this repository, and check out with full history."
108            }
109        }
110    }
111}
112
113fn augment_git_failed(stderr: &str) -> String {
114    let lower = stderr.to_ascii_lowercase();
115    if lower.contains("not a valid object name")
116        || lower.contains("unknown revision")
117        || lower.contains("ambiguous argument")
118    {
119        format!(
120            "{stderr} (shallow clone? try `git fetch --unshallow`, or set `fetch-depth: 0` on actions/checkout / `GIT_DEPTH: 0` in GitLab CI)"
121        )
122    } else {
123        stderr.to_owned()
124    }
125}
126
127static EXCLUDE_UNTRACKED: AtomicBool = AtomicBool::new(false);
128
129/// Leave untracked files out of every changed-file set and changed diff of
130/// this process.
131///
132/// `fallow audit --staged` sets this switch. It audits a temporary worktree
133/// that holds the staged index. The only untracked entries in that worktree
134/// are the dependency links that the audit adds, and they are not changes.
135pub fn exclude_untracked_files() {
136    EXCLUDE_UNTRACKED.store(true, Ordering::Relaxed);
137}
138
139fn untracked_files_excluded() -> bool {
140    EXCLUDE_UNTRACKED.load(Ordering::Relaxed)
141}
142
143/// Install a spawn-hook for changed-file git subprocesses.
144pub fn set_spawn_hook(hook: ChangedFilesSpawnHook) {
145    let _ = SPAWN_HOOK.set(hook);
146}
147
148/// Validate a user-supplied git ref before passing it to git.
149pub(crate) fn validate_git_ref(s: &str) -> Result<&str, String> {
150    if s.is_empty() {
151        return Err("git ref cannot be empty".to_string());
152    }
153    if s.starts_with('-') {
154        return Err("git ref cannot start with '-'".to_string());
155    }
156    let mut in_braces = false;
157    for c in s.chars() {
158        match c {
159            '{' => in_braces = true,
160            '}' => in_braces = false,
161            ':' | ' ' if in_braces => {}
162            c if c.is_ascii_alphanumeric()
163                || matches!(c, '.' | '_' | '-' | '/' | '~' | '^' | '@' | '{' | '}') => {}
164            _ => return Err(format!("git ref contains disallowed character: '{c}'")),
165        }
166    }
167    if in_braces {
168        return Err("git ref has unclosed '{'".to_string());
169    }
170    Ok(s)
171}
172
173/// Resolve the canonical git toplevel for `cwd`.
174pub fn resolve_git_toplevel(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
175    let output = spawn_output(&mut git_command(cwd, &["rev-parse", "--show-toplevel"]))
176        .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
177
178    if !output.status.success() {
179        let stderr = String::from_utf8_lossy(&output.stderr);
180        return Err(if stderr.contains("not a git repository") {
181            ChangedFilesError::NotARepository
182        } else {
183            ChangedFilesError::GitFailed(stderr.trim().to_owned())
184        });
185    }
186
187    let raw = String::from_utf8_lossy(&output.stdout);
188    let trimmed = raw.trim();
189    if trimmed.is_empty() {
190        return Err(ChangedFilesError::GitFailed(
191            "git rev-parse --show-toplevel returned empty output".to_owned(),
192        ));
193    }
194
195    let path = PathBuf::from(trimmed);
196    Ok(dunce::canonicalize(&path).unwrap_or(path))
197}
198
199/// Resolve the canonical git common directory for `cwd`.
200pub fn resolve_git_common_dir(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
201    let output = spawn_output(&mut git_command(
202        cwd,
203        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
204    ))
205    .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
206
207    if !output.status.success() {
208        let stderr = String::from_utf8_lossy(&output.stderr);
209        return Err(if stderr.contains("not a git repository") {
210            ChangedFilesError::NotARepository
211        } else {
212            ChangedFilesError::GitFailed(stderr.trim().to_owned())
213        });
214    }
215
216    let raw = String::from_utf8_lossy(&output.stdout);
217    let trimmed = raw.trim();
218    if trimmed.is_empty() {
219        return Err(ChangedFilesError::GitFailed(
220            "git rev-parse --git-common-dir returned empty output".to_owned(),
221        ));
222    }
223
224    let path = PathBuf::from(trimmed);
225    Ok(dunce::canonicalize(&path).unwrap_or(path))
226}
227
228/// Resolve the canonical git common directory and toplevel for `cwd` with
229/// one `git rev-parse` call.
230///
231/// The result equals [`resolve_git_common_dir`] and [`resolve_git_toplevel`],
232/// at the cost of one subprocess instead of two. It fails where either single
233/// probe fails, for example in a bare repository, which has no toplevel, and
234/// when git prints anything other than two paths. A caller that needs one of
235/// the two paths in that case calls the single probe.
236///
237/// # Errors
238///
239/// Returns the reason when git is missing, `cwd` is not in a work tree, or the
240/// output is not two paths.
241pub fn resolve_git_common_dir_and_toplevel(
242    cwd: &Path,
243) -> Result<(PathBuf, PathBuf), ChangedFilesError> {
244    let output = spawn_output(&mut git_command(
245        cwd,
246        &[
247            "rev-parse",
248            "--path-format=absolute",
249            "--git-common-dir",
250            "--show-toplevel",
251        ],
252    ))
253    .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
254
255    if !output.status.success() {
256        let stderr = String::from_utf8_lossy(&output.stderr);
257        return Err(if stderr.contains("not a git repository") {
258            ChangedFilesError::NotARepository
259        } else {
260            ChangedFilesError::GitFailed(stderr.trim().to_owned())
261        });
262    }
263
264    let raw = String::from_utf8_lossy(&output.stdout);
265    let mut lines = raw.lines();
266    let (Some(common), Some(toplevel), None) = (lines.next(), lines.next(), lines.next()) else {
267        return Err(ChangedFilesError::GitFailed(
268            "git rev-parse did not print one common dir and one toplevel".to_owned(),
269        ));
270    };
271    let canonical = |line: &str| {
272        let path = PathBuf::from(line.trim());
273        dunce::canonicalize(&path).unwrap_or(path)
274    };
275    if common.trim().is_empty() || toplevel.trim().is_empty() {
276        return Err(ChangedFilesError::GitFailed(
277            "git rev-parse returned an empty path".to_owned(),
278        ));
279    }
280    Ok((canonical(common), canonical(toplevel)))
281}
282
283/// Get files changed since a git ref.
284fn try_get_changed_files(
285    root: &Path,
286    git_ref: &str,
287) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
288    validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
289    let toplevel = resolve_git_toplevel(root)?;
290    try_get_changed_files_with_toplevel(root, &toplevel, git_ref)
291}
292
293/// Resolve changed files for a git ref relative to a project root.
294///
295/// # Errors
296///
297/// Returns an error when git cannot resolve the ref or repository state.
298pub fn changed_files(root: &Path, git_ref: &str) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
299    try_get_changed_files(root, git_ref)
300}
301
302/// Resolve several refs against one working tree. The HEAD diff and untracked
303/// inventory do not depend on the ref, so a package-baseline run reads them
304/// once while still resolving each ref's committed diff independently.
305pub(crate) struct ChangedFilesBatch<'a> {
306    cwd: &'a Path,
307    toplevel: PathBuf,
308    working_tree: Option<FxHashSet<PathBuf>>,
309}
310
311impl<'a> ChangedFilesBatch<'a> {
312    pub(crate) fn new(cwd: &'a Path, first_ref: &str) -> Result<Self, ChangedFilesError> {
313        validate_git_ref(first_ref).map_err(ChangedFilesError::InvalidRef)?;
314        Ok(Self {
315            cwd,
316            toplevel: resolve_git_toplevel(cwd)?,
317            working_tree: None,
318        })
319    }
320
321    pub(crate) fn changed_files(
322        &mut self,
323        git_ref: &str,
324    ) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
325        let mut files = committed_changed_files(self.cwd, &self.toplevel, git_ref)?;
326        if self.working_tree.is_none() {
327            self.working_tree = Some(working_tree_changed_files(self.cwd, &self.toplevel)?);
328        }
329        if let Some(working_tree) = &self.working_tree {
330            files.extend(working_tree.iter().cloned());
331        }
332        Ok(files)
333    }
334}
335
336/// Get changed files and the git toplevel used to resolve them.
337pub fn try_get_changed_files_with_toplevel(
338    cwd: &Path,
339    toplevel: &Path,
340    git_ref: &str,
341) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
342    let mut files = committed_changed_files(cwd, toplevel, git_ref)?;
343    files.extend(working_tree_changed_files(cwd, toplevel)?);
344    Ok(files)
345}
346
347fn committed_changed_files(
348    cwd: &Path,
349    toplevel: &Path,
350    git_ref: &str,
351) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
352    validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
353    collect_git_paths(
354        cwd,
355        toplevel,
356        &[
357            "diff",
358            "--name-only",
359            "-z",
360            "--end-of-options",
361            &format!("{git_ref}...HEAD"),
362        ],
363    )
364}
365
366fn working_tree_changed_files(
367    cwd: &Path,
368    toplevel: &Path,
369) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
370    let mut files = collect_git_paths(cwd, toplevel, &["diff", "--name-only", "-z", "HEAD"])?;
371    if untracked_files_excluded() {
372        return Ok(files);
373    }
374    files.extend(collect_git_paths(
375        cwd,
376        toplevel,
377        &[
378            "ls-files",
379            "--full-name",
380            "--others",
381            "--exclude-standard",
382            "-z",
383        ],
384    )?);
385    Ok(files)
386}
387
388/// A file rename detected between a git ref's merge base and the working
389/// tree, with absolute paths joined onto the git toplevel.
390#[derive(Debug, Clone, PartialEq, Eq)]
391pub struct RenamedFile {
392    /// Absolute pre-rename path (exists in the base tree).
393    pub from: PathBuf,
394    /// Absolute post-rename path (exists in the current tree).
395    pub to: PathBuf,
396}
397
398/// Detect renamed files between a git ref's merge base and the current tree.
399///
400/// Covers the committed range (`<ref>...HEAD`) plus renames staged against
401/// `HEAD`, mirroring the tracked scope of [`try_get_changed_files_with_toplevel`].
402/// A rename committed as `a -> b` and then staged as `b -> c` is composed into
403/// one `a -> c` entry. Copies are intentionally not reported: a copy leaves
404/// the original in place, so findings on the copy are genuinely new.
405///
406/// # Errors
407///
408/// Returns an error when git cannot resolve the ref or repository state.
409pub fn try_get_renamed_files(
410    root: &Path,
411    git_ref: &str,
412) -> Result<Vec<RenamedFile>, ChangedFilesError> {
413    validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
414    let toplevel = resolve_git_toplevel(root)?;
415    let mut renames = collect_git_rename_pairs(
416        root,
417        &toplevel,
418        &[
419            "diff",
420            "--name-status",
421            "-z",
422            "--find-renames",
423            "--end-of-options",
424            &format!("{git_ref}...HEAD"),
425        ],
426    )?;
427    let staged = collect_git_rename_pairs(
428        root,
429        &toplevel,
430        &["diff", "--name-status", "-z", "--find-renames", "HEAD"],
431    )?;
432    for pair in staged {
433        if let Some(chained) = renames.iter_mut().find(|rename| rename.to == pair.from) {
434            chained.to = pair.to;
435        } else {
436            renames.push(pair);
437        }
438    }
439    Ok(renames)
440}
441
442/// Run a `--name-status -z` diff and collect its `R` (rename) pairs.
443///
444/// The `-z` stream alternates status and path fields separated by NUL; rename
445/// and copy statuses (`R<score>` / `C<score>`) carry two path fields (old then
446/// new), every other status carries one.
447fn collect_git_rename_pairs(
448    cwd: &Path,
449    toplevel: &Path,
450    args: &[&str],
451) -> Result<Vec<RenamedFile>, ChangedFilesError> {
452    let output = spawn_output(&mut git_command(cwd, args))
453        .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
454
455    if !output.status.success() {
456        return Err(changed_files_error_from_output(&output));
457    }
458
459    let mut fields = output
460        .stdout
461        .split(|byte| *byte == 0)
462        .filter(|field| !field.is_empty());
463    let mut renames = Vec::new();
464    while let Some(status) = fields.next() {
465        let Some(first_path) = fields.next() else {
466            break;
467        };
468        match status.first() {
469            Some(b'R') => {
470                let Some(second_path) = fields.next() else {
471                    break;
472                };
473                renames.push(RenamedFile {
474                    from: toplevel.join(git_path_from_bytes(first_path)),
475                    to: toplevel.join(git_path_from_bytes(second_path)),
476                });
477            }
478            // Copies also carry two path fields but are conservatively treated
479            // as new files, so only the extra field is consumed.
480            Some(b'C') => {
481                let _ = fields.next();
482            }
483            _ => {}
484        }
485    }
486    Ok(renames)
487}
488
489/// Return the raw git diff from a ref's merge base through the working tree.
490///
491/// The result includes committed, staged, unstaged, and untracked changes so it
492/// covers the same scope as `try_get_changed_files`.
493pub fn try_get_changed_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
494    changed_diff(root, git_ref, false)
495}
496
497/// Return a mutation scope diff with explicit rename and copy detection.
498///
499/// Ordinary copy detection considers modified sources without searching every
500/// unchanged file. Git's configured similarity limit still applies.
501pub fn try_get_mutation_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
502    changed_diff(root, git_ref, true)
503}
504
505fn changed_diff(
506    root: &Path,
507    git_ref: &str,
508    detect_copies: bool,
509) -> Result<String, ChangedFilesError> {
510    validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
511    let toplevel = resolve_git_toplevel(root)?;
512    let merge_base_output = spawn_output(&mut git_command(root, &["merge-base", git_ref, "HEAD"]))
513        .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
514    if !merge_base_output.status.success() {
515        return Err(changed_files_error_from_output(&merge_base_output));
516    }
517    let merge_base = String::from_utf8_lossy(&merge_base_output.stdout)
518        .trim()
519        .to_owned();
520    if merge_base.is_empty() {
521        return Err(ChangedFilesError::GitFailed(
522            "git merge-base returned empty output".to_owned(),
523        ));
524    }
525
526    let mut args = vec!["diff", "--relative", "--unified=0"];
527    if detect_copies {
528        args.extend(["-M", "-C"]);
529    }
530    args.extend(["--end-of-options", &merge_base]);
531    let output = spawn_output(&mut git_command(root, &args))
532        .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
533
534    if !output.status.success() {
535        return Err(changed_files_error_from_output(&output));
536    }
537
538    let mut diff = String::from_utf8_lossy(&output.stdout).into_owned();
539    append_untracked_diffs(root, &toplevel, &mut diff)?;
540    Ok(diff)
541}
542
543fn append_untracked_diffs(
544    root: &Path,
545    toplevel: &Path,
546    diff: &mut String,
547) -> Result<(), ChangedFilesError> {
548    if untracked_files_excluded() {
549        return Ok(());
550    }
551    let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
552    let mut untracked: Vec<PathBuf> = collect_git_paths(
553        root,
554        toplevel,
555        &[
556            "ls-files",
557            "--full-name",
558            "--others",
559            "--exclude-standard",
560            "-z",
561        ],
562    )?
563    .into_iter()
564    .filter_map(|path| {
565        path.strip_prefix(&canonical_root)
566            .ok()
567            .map(Path::to_path_buf)
568    })
569    .collect();
570    untracked.sort_unstable();
571
572    #[cfg(windows)]
573    let empty_file = "NUL";
574    #[cfg(not(windows))]
575    let empty_file = "/dev/null";
576
577    for path in untracked {
578        let mut command = git_command(root, &["diff", "--no-index", "--unified=0", "--"]);
579        command.arg(empty_file).arg(untracked_path_arg(&path));
580        let output =
581            spawn_output(&mut command).map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
582        if !output.status.success() && output.status.code() != Some(1) {
583            return Err(changed_files_error_from_output(&output));
584        }
585        if !diff.is_empty() && !diff.ends_with('\n') {
586            diff.push('\n');
587        }
588        diff.push_str(&String::from_utf8_lossy(&output.stdout));
589    }
590    Ok(())
591}
592
593/// Forward-slashed relative path for the `git diff --no-index` argument.
594/// Passing the native form on Windows makes git echo backslashes into the
595/// `+++ b/` header, so every consumer keyed on forward-slashed diff paths
596/// (added-line lookups included) silently misses the file.
597fn untracked_path_arg(path: &Path) -> String {
598    path.to_string_lossy().replace('\\', "/")
599}
600
601fn changed_files_error_from_output(output: &Output) -> ChangedFilesError {
602    let stderr = String::from_utf8_lossy(&output.stderr);
603    if stderr.contains("not a git repository") {
604        ChangedFilesError::NotARepository
605    } else {
606        ChangedFilesError::GitFailed(stderr.trim().to_owned())
607    }
608}
609
610/// Get changed files if git can resolve them, otherwise return `None`.
611#[must_use]
612#[expect(
613    clippy::print_stderr,
614    reason = "intentional user-facing warning for the CLI's --changed-since fallback path; typed callers use try_get_changed_files instead"
615)]
616pub fn get_changed_files(root: &Path, git_ref: &str) -> Option<FxHashSet<PathBuf>> {
617    match try_get_changed_files(root, git_ref) {
618        Ok(files) => Some(files),
619        Err(err) => {
620            eprintln!("Warning: {}", err.changed_since_message(git_ref));
621            None
622        }
623    }
624}
625
626fn spawn_output(command: &mut Command) -> std::io::Result<Output> {
627    if let Some(hook) = SPAWN_HOOK.get() {
628        hook(command)
629    } else {
630        command.output()
631    }
632}
633
634fn collect_git_paths(
635    cwd: &Path,
636    toplevel: &Path,
637    args: &[&str],
638) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
639    let output = spawn_output(&mut git_command(cwd, args))
640        .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
641
642    if !output.status.success() {
643        let stderr = String::from_utf8_lossy(&output.stderr);
644        return Err(if stderr.contains("not a git repository") {
645            ChangedFilesError::NotARepository
646        } else {
647            ChangedFilesError::GitFailed(stderr.trim().to_owned())
648        });
649    }
650
651    let files = output
652        .stdout
653        .split(|byte| *byte == 0)
654        .filter(|path| !path.is_empty())
655        .map(git_path_from_bytes)
656        .map(|path| toplevel.join(path))
657        .collect();
658
659    Ok(files)
660}
661
662/// Decode one NUL-separated `git` output path into a `PathBuf`.
663///
664/// Unix keeps the raw bytes, so a non-UTF-8 tree path survives intact.
665/// Shared with `crate::churn`, which decodes the same `git` byte output under
666/// the same semantics.
667#[cfg(unix)]
668pub(crate) fn git_path_from_bytes(path: &[u8]) -> PathBuf {
669    use std::ffi::OsString;
670    use std::os::unix::ffi::OsStringExt;
671
672    PathBuf::from(OsString::from_vec(path.to_vec()))
673}
674
675/// Windows counterpart: there is no byte-oriented `OsString`, so decode
676/// lossily and rewrite to backslash separators.
677#[cfg(windows)]
678pub(crate) fn git_path_from_bytes(path: &[u8]) -> PathBuf {
679    PathBuf::from(String::from_utf8_lossy(path).replace('/', "\\"))
680}
681
682fn git_command(cwd: &Path, args: &[&str]) -> Command {
683    let mut command = crate::git_env::git_command(cwd);
684    command.args(args);
685    command
686}
687
688/// Scope dead-code results to findings affected by changed files.
689///
690/// Dependency-level issues stay unfiltered because whether a dependency is
691/// unused is a graph-global fact, not a changed-file-local fact.
692#[expect(
693    clippy::implicit_hasher,
694    reason = "fallow standardizes on FxHashSet across the workspace"
695)]
696pub fn filter_results_by_changed_files(
697    results: &mut AnalysisResults,
698    changed_files: &FxHashSet<PathBuf>,
699) {
700    filter_results_by_path_scope(results, &NormalizedChangedFiles::new(changed_files));
701}
702
703/// Scope dead-code results like [`filter_results_by_changed_files`], but keep
704/// every unused file and every unused export.
705///
706/// A change can make a file or an export unused without a change to it: the
707/// change removes its last import, or a config change removes an entry point.
708/// `fallow audit --gate new-only` keeps these findings, compares them with the
709/// base, and reports only the ones that the base did not report.
710#[expect(
711    clippy::implicit_hasher,
712    reason = "fallow standardizes on FxHashSet across the workspace"
713)]
714pub fn filter_results_by_changed_files_keeping_unused_code(
715    results: &mut AnalysisResults,
716    changed_files: &FxHashSet<PathBuf>,
717) {
718    keeping_unused_code(results, |results| {
719        filter_results_by_changed_files(results, changed_files);
720    });
721}
722
723/// Run `filter` over `results`, but keep every unused file and unused export.
724pub(crate) fn keeping_unused_code(
725    results: &mut AnalysisResults,
726    filter: impl FnOnce(&mut AnalysisResults),
727) {
728    let unused_files = std::mem::take(&mut results.unused_files);
729    let unused_exports = std::mem::take(&mut results.unused_exports);
730    filter(results);
731    results.unused_files = unused_files;
732    results.unused_exports = unused_exports;
733}
734
735/// Path membership for one resolved result scope. Implementations own path
736/// normalization so source and manifest findings use the same policy.
737pub(crate) trait ChangedPathScope {
738    fn contains(&self, path: &Path) -> bool;
739    fn contains_workspace(&self, path: &Path) -> bool {
740        self.contains(path)
741    }
742}
743
744/// A changed-file set normalized the way every changed-file filter reads it.
745#[derive(Debug, Clone, Default)]
746pub(crate) struct NormalizedChangedFiles(FxHashSet<PathBuf>);
747
748impl NormalizedChangedFiles {
749    pub(crate) fn new(changed_files: &FxHashSet<PathBuf>) -> Self {
750        Self(normalize_changed_files_set(changed_files))
751    }
752}
753
754impl ChangedPathScope for NormalizedChangedFiles {
755    fn contains(&self, path: &Path) -> bool {
756        contains_normalized(&self.0, path)
757    }
758
759    fn contains_workspace(&self, path: &Path) -> bool {
760        normalized_set_contains_path(&self.0, path)
761    }
762}
763
764pub(crate) fn filter_results_by_path_scope(
765    results: &mut AnalysisResults,
766    scope: &impl ChangedPathScope,
767) {
768    if let Some(inventory) = &mut results.shared_state {
769        inventory.retain_sites(|site| scope.contains(&site.path));
770    }
771    classify_changed_file_filter_fields(results);
772    retain_basic_issue_findings_by_changed_path(results, scope);
773    retain_graph_findings_by_changed_files(results, scope);
774    retain_boundary_policy_and_suppression_findings(results, scope);
775    retain_security_and_workspace_findings(results, scope);
776    retain_framework_findings_by_changed_files(results, scope);
777}
778fn classify_changed_file_filter_fields(results: &AnalysisResults) {
779    let AnalysisResults {
780        shared_state: _,
781        unused_files: _unused_files,
782        unused_exports: _unused_exports,
783        unused_types: _unused_types,
784        private_type_leaks: _private_type_leaks,
785        deprecated_exports_in_use: _deprecated_exports_in_use,
786        unused_dependencies: _unused_dependencies,
787        unused_dev_dependencies: _unused_dev_dependencies,
788        unused_optional_dependencies: _unused_optional_dependencies,
789        unused_enum_members: _unused_enum_members,
790        unused_class_members: _unused_class_members,
791        unused_namespace_members: _unused_namespace_members,
792        unused_protected_class_members: _unused_protected_class_members,
793        unused_store_members: _unused_store_members,
794        unresolved_imports: _unresolved_imports,
795        unlisted_dependencies: _unlisted_dependencies,
796        unlisted_binaries: _unlisted_binaries,
797        duplicate_exports: _duplicate_exports,
798        duplicate_export_aliases: _duplicate_export_aliases,
799        type_only_dependencies: _type_only_dependencies,
800        test_only_dependencies: _test_only_dependencies,
801        dev_dependencies_in_production: _dev_dependencies_in_production,
802        circular_dependencies: _circular_dependencies,
803        re_export_cycles: _re_export_cycles,
804        package_cycles: _package_cycles,
805        boundary_violations: _boundary_violations,
806        boundary_coverage_violations: _boundary_coverage_violations,
807        boundary_call_violations: _boundary_call_violations,
808        policy_violations: _policy_violations,
809        stale_suppressions: _stale_suppressions,
810        unused_catalog_entries: _unused_catalog_entries,
811        empty_catalog_groups: _empty_catalog_groups,
812        unresolved_catalog_references: _unresolved_catalog_references,
813        unused_dependency_overrides: _unused_dependency_overrides,
814        misconfigured_dependency_overrides: _misconfigured_dependency_overrides,
815        invalid_client_exports: _invalid_client_exports,
816        mixed_client_server_barrels: _mixed_client_server_barrels,
817        misplaced_directives: _misplaced_directives,
818        unprovided_injects: _unprovided_injects,
819        unrendered_components: _unrendered_components,
820        route_collisions: _route_collisions,
821        dynamic_segment_name_conflicts: _dynamic_segment_name_conflicts,
822        unused_component_props: _unused_component_props,
823        absent_component_props: _absent_component_props,
824        constant_parameters: _constant_parameters,
825        unused_component_emits: _unused_component_emits,
826        unused_component_inputs: _unused_component_inputs,
827        unused_component_outputs: _unused_component_outputs,
828        unused_svelte_events: _unused_svelte_events,
829        unused_effect_layers: _unused_effect_layers,
830        unused_tagged_errors: _unused_tagged_errors,
831        unproduced_catch_tags: _unproduced_catch_tags,
832        unused_server_actions: _unused_server_actions,
833        unused_load_data_keys: _unused_load_data_keys,
834        unused_load_data_keys_global_abstain: _unused_load_data_keys_global_abstain,
835        prop_drilling_chains: _prop_drilling_chains,
836        thin_wrappers: _thin_wrappers,
837        duplicate_prop_shapes: _duplicate_prop_shapes,
838        cascade_hidden: _cascade_hidden,
839        cascade: _cascade,
840        suppression_count: _suppression_count,
841        unused_component_props_exempted: _unused_component_props_exempted,
842        active_suppressions: _active_suppressions,
843        feature_flags: _feature_flags,
844        security_findings: _security_findings,
845        suppressed_security_findings: _suppressed_security_findings,
846        security_unresolved_edge_files: _security_unresolved_edge_files,
847        security_unresolved_callee_sites: _security_unresolved_callee_sites,
848        security_unresolved_callee_diagnostics: _security_unresolved_callee_diagnostics,
849        export_usages: _export_usages,
850        entry_point_summary: _entry_point_summary,
851        render_fan_in: _render_fan_in,
852        react_component_intel: _react_component_intel,
853        semantic_reachable_files: _,
854        semantic_framework_contracts: _semantic_framework_contracts,
855        constant_parameter_candidates: _,
856    } = results;
857}
858
859fn retain_basic_issue_findings_by_changed_path(
860    results: &mut AnalysisResults,
861    scope: &impl ChangedPathScope,
862) {
863    retain_by_changed_path(&mut results.unused_files, scope, |f| &f.file.path);
864    retain_by_changed_path(&mut results.unused_exports, scope, |e| &e.export.path);
865    retain_by_changed_path(&mut results.unused_types, scope, |e| &e.export.path);
866    retain_by_changed_path(&mut results.private_type_leaks, scope, |e| &e.leak.path);
867    retain_by_changed_path(&mut results.deprecated_exports_in_use, scope, |e| {
868        &e.export.path
869    });
870    retain_by_changed_path(&mut results.unused_enum_members, scope, |m| &m.member.path);
871    retain_by_changed_path(&mut results.unused_class_members, scope, |m| &m.member.path);
872    retain_by_changed_path(&mut results.unused_namespace_members, scope, |m| {
873        &m.member.path
874    });
875    retain_by_changed_path(&mut results.unused_protected_class_members, scope, |m| {
876        &m.member.path
877    });
878    retain_by_changed_path(&mut results.unused_store_members, scope, |m| &m.member.path);
879    retain_by_changed_path(&mut results.unresolved_imports, scope, |i| &i.import.path);
880}
881
882fn retain_graph_findings_by_changed_files(
883    results: &mut AnalysisResults,
884    scope: &impl ChangedPathScope,
885) {
886    retain_unlisted_dependencies_by_import_site(&mut results.unlisted_dependencies, scope);
887    results.unlisted_binaries.retain(|binary| {
888        binary
889            .binary
890            .used_in
891            .iter()
892            .any(|site| scope.contains(&site.path))
893    });
894    retain_duplicate_exports_by_changed_locations(&mut results.duplicate_exports, scope);
895    retain_by_changed_path(&mut results.duplicate_export_aliases, scope, |a| {
896        &a.alias.path
897    });
898    retain_circular_dependencies_by_changed_file(&mut results.circular_dependencies, scope);
899    retain_re_export_cycles_by_changed_file(&mut results.re_export_cycles, scope);
900    retain_package_cycles_by_changed_file(&mut results.package_cycles, scope);
901}
902
903fn retain_boundary_policy_and_suppression_findings(
904    results: &mut AnalysisResults,
905    scope: &impl ChangedPathScope,
906) {
907    retain_by_changed_path(&mut results.boundary_violations, scope, |v| {
908        &v.violation.from_path
909    });
910    retain_by_changed_path(&mut results.boundary_coverage_violations, scope, |v| {
911        &v.violation.path
912    });
913    retain_by_changed_path(&mut results.boundary_call_violations, scope, |v| {
914        &v.violation.path
915    });
916    retain_by_changed_path(&mut results.policy_violations, scope, |v| &v.violation.path);
917    retain_by_changed_path(&mut results.stale_suppressions, scope, |s| &s.path);
918}
919
920fn retain_security_and_workspace_findings(
921    results: &mut AnalysisResults,
922    scope: &impl ChangedPathScope,
923) {
924    retain_security_findings_by_changed_path(&mut results.security_findings, scope);
925    retain_by_changed_path(
926        &mut results.security_unresolved_callee_diagnostics,
927        scope,
928        |d| &d.path,
929    );
930    retain_by_changed_path(&mut results.unresolved_catalog_references, scope, |r| {
931        &r.reference.path
932    });
933    results
934        .empty_catalog_groups
935        .retain(|g| scope.contains_workspace(&g.group.path));
936    retain_by_changed_path(&mut results.unused_dependency_overrides, scope, |o| {
937        &o.entry.path
938    });
939    retain_by_changed_path(
940        &mut results.misconfigured_dependency_overrides,
941        scope,
942        |o| &o.entry.path,
943    );
944}
945
946fn retain_framework_findings_by_changed_files(
947    results: &mut AnalysisResults,
948    scope: &impl ChangedPathScope,
949) {
950    retain_client_boundary_findings_by_changed_files(results, scope);
951    retain_component_contract_findings_by_changed_files(results, scope);
952    retain_react_health_findings_by_changed_files(results, scope);
953    retain_nextjs_findings_by_changed_files(results, scope);
954}
955
956fn retain_client_boundary_findings_by_changed_files(
957    results: &mut AnalysisResults,
958    scope: &impl ChangedPathScope,
959) {
960    let AnalysisResults {
961        shared_state: _,
962        invalid_client_exports,
963        mixed_client_server_barrels,
964        misplaced_directives,
965        ..
966    } = results;
967
968    retain_by_changed_path(invalid_client_exports, scope, |e| &e.export.path);
969    retain_by_changed_path(mixed_client_server_barrels, scope, |b| &b.barrel.path);
970    retain_by_changed_path(misplaced_directives, scope, |d| &d.directive_site.path);
971}
972
973fn retain_component_contract_findings_by_changed_files(
974    results: &mut AnalysisResults,
975    scope: &impl ChangedPathScope,
976) {
977    let AnalysisResults {
978        shared_state: _,
979        unprovided_injects,
980        unrendered_components,
981        unused_component_props,
982        absent_component_props,
983        constant_parameters,
984        unused_component_emits,
985        unused_component_inputs,
986        unused_component_outputs,
987        unused_svelte_events,
988        unused_effect_layers,
989        unused_tagged_errors,
990        unproduced_catch_tags,
991        unused_server_actions,
992        unused_load_data_keys,
993        ..
994    } = results;
995
996    retain_by_changed_path(unprovided_injects, scope, |i| &i.inject.path);
997    retain_by_changed_path(unrendered_components, scope, |c| &c.component.path);
998    retain_by_changed_path(unused_component_props, scope, |p| &p.prop.path);
999    retain_by_changed_path(absent_component_props, scope, |p| &p.prop.path);
1000    retain_by_changed_path(constant_parameters, scope, |p| &p.parameter.path);
1001    retain_by_changed_path(unused_component_emits, scope, |e| &e.emit.path);
1002    retain_by_changed_path(unused_component_inputs, scope, |i| &i.input.path);
1003    retain_by_changed_path(unused_component_outputs, scope, |o| &o.output.path);
1004    retain_by_changed_path(unused_svelte_events, scope, |e| &e.event.path);
1005    retain_by_changed_path(unused_effect_layers, scope, |e| &e.layer.path);
1006    retain_by_changed_path(unused_tagged_errors, scope, |e| &e.error.path);
1007    retain_by_changed_path(unproduced_catch_tags, scope, |e| &e.catch_tag.path);
1008    retain_by_changed_path(unused_server_actions, scope, |a| &a.action.path);
1009    retain_by_changed_path(unused_load_data_keys, scope, |k| &k.key.path);
1010}
1011
1012fn retain_react_health_findings_by_changed_files(
1013    results: &mut AnalysisResults,
1014    scope: &impl ChangedPathScope,
1015) {
1016    let AnalysisResults {
1017        shared_state: _,
1018        prop_drilling_chains,
1019        thin_wrappers,
1020        duplicate_prop_shapes,
1021        ..
1022    } = results;
1023
1024    retain_prop_drilling_chains_by_anchor(prop_drilling_chains, scope);
1025    retain_by_changed_path(thin_wrappers, scope, |w| &w.wrapper.file);
1026    retain_duplicate_prop_shapes_by_anchor(duplicate_prop_shapes, scope);
1027}
1028
1029fn retain_nextjs_findings_by_changed_files(
1030    results: &mut AnalysisResults,
1031    scope: &impl ChangedPathScope,
1032) {
1033    let AnalysisResults {
1034        shared_state: _,
1035        route_collisions,
1036        dynamic_segment_name_conflicts,
1037        ..
1038    } = results;
1039
1040    retain_by_changed_path(route_collisions, scope, |c| &c.collision.path);
1041    retain_by_changed_path(dynamic_segment_name_conflicts, scope, |c| &c.conflict.path);
1042}
1043
1044fn retain_unlisted_dependencies_by_import_site(
1045    dependencies: &mut Vec<UnlistedDependencyFinding>,
1046    scope: &impl ChangedPathScope,
1047) {
1048    dependencies.retain(|dependency| {
1049        dependency
1050            .dep
1051            .imported_from
1052            .iter()
1053            .any(|site| scope.contains(&site.path))
1054    });
1055}
1056
1057fn retain_duplicate_exports_by_changed_locations(
1058    duplicate_exports: &mut Vec<DuplicateExportFinding>,
1059    scope: &impl ChangedPathScope,
1060) {
1061    for duplicate in &mut *duplicate_exports {
1062        duplicate
1063            .export
1064            .locations
1065            .retain(|location| scope.contains(&location.path));
1066    }
1067    duplicate_exports.retain(|duplicate| duplicate.export.locations.len() >= 2);
1068}
1069
1070fn retain_circular_dependencies_by_changed_file(
1071    cycles: &mut Vec<CircularDependencyFinding>,
1072    scope: &impl ChangedPathScope,
1073) {
1074    cycles.retain(|cycle| cycle.cycle.files.iter().any(|file| scope.contains(file)));
1075}
1076
1077fn retain_re_export_cycles_by_changed_file(
1078    cycles: &mut Vec<ReExportCycleFinding>,
1079    scope: &impl ChangedPathScope,
1080) {
1081    cycles.retain(|cycle| cycle.cycle.files.iter().any(|file| scope.contains(file)));
1082}
1083
1084fn retain_package_cycles_by_changed_file(
1085    cycles: &mut Vec<PackageCycleFinding>,
1086    scope: &impl ChangedPathScope,
1087) {
1088    cycles.retain(|cycle| {
1089        cycle
1090            .cycle
1091            .edges
1092            .iter()
1093            .any(|edge| scope.contains(&edge.path))
1094    });
1095}
1096
1097fn retain_security_findings_by_changed_path(
1098    findings: &mut Vec<SecurityFinding>,
1099    scope: &impl ChangedPathScope,
1100) {
1101    findings.retain(|finding| security_finding_touches_changed_path(finding, scope));
1102}
1103
1104fn retain_prop_drilling_chains_by_anchor(
1105    chains: &mut Vec<PropDrillingChainFinding>,
1106    scope: &impl ChangedPathScope,
1107) {
1108    chains.retain(|chain| {
1109        if chain.effective_severity
1110            == Some(fallow_types::output_dead_code::EffectiveSeverity::Error)
1111        {
1112            return chain.chain.hops.is_empty()
1113                || chain.chain.hops.iter().any(|hop| scope.contains(&hop.file));
1114        }
1115        chain
1116            .chain
1117            .hops
1118            .first()
1119            .is_some_and(|hop| scope.contains(&hop.file))
1120    });
1121}
1122
1123fn retain_duplicate_prop_shapes_by_anchor(
1124    shapes: &mut Vec<DuplicatePropShapeFinding>,
1125    scope: &impl ChangedPathScope,
1126) {
1127    retain_by_changed_path(shapes, scope, |shape| &shape.shape.file);
1128}
1129
1130fn retain_by_changed_path<T>(
1131    items: &mut Vec<T>,
1132    scope: &impl ChangedPathScope,
1133    path: impl Fn(&T) -> &Path,
1134) {
1135    items.retain(|item| scope.contains(path(item)));
1136}
1137
1138fn security_finding_touches_changed_path(
1139    finding: &SecurityFinding,
1140    scope: &impl ChangedPathScope,
1141) -> bool {
1142    scope.contains(&finding.path)
1143        || finding.trace.iter().any(|hop| scope.contains(&hop.path))
1144        || finding.reachability.as_ref().is_some_and(|reachability| {
1145            reachability
1146                .untrusted_source_trace
1147                .iter()
1148                .any(|hop| scope.contains(&hop.path))
1149        })
1150}
1151
1152fn normalize_changed_files_set(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<PathBuf> {
1153    changed_files
1154        .iter()
1155        .map(|p| dunce::simplified(p).to_path_buf())
1156        .collect()
1157}
1158
1159fn contains_normalized(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
1160    normalized.contains(dunce::simplified(path))
1161}
1162
1163fn normalized_set_contains_path(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
1164    contains_normalized(normalized, path)
1165        || (path.is_relative() && normalized.iter().any(|changed| changed.ends_with(path)))
1166}
1167
1168/// Scope duplication groups to clone groups touching at least one changed file.
1169#[expect(
1170    clippy::implicit_hasher,
1171    reason = "fallow standardizes on FxHashSet across the workspace"
1172)]
1173pub fn filter_duplication_by_changed_files(
1174    report: &mut DuplicationReport,
1175    changed_files: &FxHashSet<PathBuf>,
1176    root: &Path,
1177) {
1178    filter_duplication_by_path_scope(report, &NormalizedChangedFiles::new(changed_files), root);
1179}
1180
1181pub(crate) fn filter_duplication_by_path_scope(
1182    report: &mut DuplicationReport,
1183    scope: &impl ChangedPathScope,
1184    root: &Path,
1185) {
1186    report.clone_groups.retain(|group| {
1187        group
1188            .instances
1189            .iter()
1190            .any(|instance| scope.contains(&instance.file))
1191    });
1192    report
1193        .range_marker_problems
1194        .retain(|finding| scope.contains(&finding.path));
1195    duplicates::refresh_scoped_report(report, root);
1196}
1197
1198#[cfg(test)]
1199mod tests {
1200    use super::*;
1201    use fallow_types::{
1202        duplicates::{CloneGroup, CloneInstance, DuplicationStats},
1203        output_dead_code::{
1204            EmptyCatalogGroupFinding, UnusedDependencyFinding, UnusedExportFinding,
1205            UnusedFileFinding,
1206        },
1207        results::{
1208            DependencyLocation, EmptyCatalogGroup, UnusedDependency, UnusedExport, UnusedFile,
1209        },
1210    };
1211
1212    /// One reason token per cause, because each carries a different remedy and
1213    /// a consumer branches on the token rather than on the prose.
1214    #[test]
1215    fn every_changed_files_cause_reports_its_own_reason() {
1216        let reasons = [
1217            ChangedFilesError::InvalidRef("unclosed brace".to_owned()).reason(),
1218            ChangedFilesError::GitMissing("no such file".to_owned()).reason(),
1219            ChangedFilesError::NotARepository.reason(),
1220            ChangedFilesError::GitFailed("unknown revision".to_owned()).reason(),
1221        ];
1222        assert_eq!(
1223            reasons,
1224            [
1225                "invalid-ref",
1226                "git-missing",
1227                "not-a-repository",
1228                "git-failed"
1229            ]
1230        );
1231        let unique: std::collections::BTreeSet<&str> = reasons.iter().copied().collect();
1232        assert_eq!(
1233            unique.len(),
1234            reasons.len(),
1235            "two causes must not share a token"
1236        );
1237    }
1238
1239    /// The published sentence and the stderr line are the same string, so the
1240    /// remedy cannot drift between a log a human read and a report a script
1241    /// read. It names the ref, says the report widened, and ends with a next
1242    /// step.
1243    #[test]
1244    fn the_changed_since_message_names_the_ref_the_widening_and_the_next_step() {
1245        let message = ChangedFilesError::NotARepository.changed_since_message("origin/main");
1246        assert!(
1247            message.contains("--changed-since 'origin/main'"),
1248            "{message}"
1249        );
1250        assert!(message.contains("covers the whole project"), "{message}");
1251        assert!(message.ends_with("or drop --changed-since."), "{message}");
1252    }
1253
1254    /// Git writes multi-line stderr, and the sentence travels into a CI
1255    /// annotation and a rendered comment where a newline splits one fact
1256    /// across two records.
1257    #[test]
1258    fn the_changed_since_message_folds_git_stderr_onto_one_line() {
1259        let message = ChangedFilesError::GitFailed(
1260            "fatal: ambiguous argument 'x'\nUse '--' to separate paths".to_owned(),
1261        )
1262        .changed_since_message("x");
1263        assert!(!message.contains('\n'), "{message}");
1264        assert!(
1265            message.contains("ambiguous argument 'x' Use '--'"),
1266            "{message}"
1267        );
1268    }
1269
1270    #[test]
1271    fn git_command_clears_parent_git_environment() {
1272        let command = git_command(Path::new("."), &["status"]);
1273        let envs: Vec<_> = command.get_envs().collect();
1274
1275        for var in AMBIENT_GIT_ENV_VARS {
1276            assert!(
1277                envs.iter()
1278                    .any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
1279                "{var} should be cleared from the command env",
1280            );
1281        }
1282    }
1283
1284    #[test]
1285    fn try_get_changed_files_not_a_repository() {
1286        let temp = tempfile::tempdir().expect("tempdir");
1287        let result = try_get_changed_files(temp.path(), "main");
1288        assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
1289    }
1290
1291    #[test]
1292    fn batched_refs_match_independent_changed_file_scopes() {
1293        let repo = tempfile::tempdir().expect("tempdir");
1294        for args in [
1295            &["init", "--quiet"][..],
1296            &["config", "user.email", "test@example.com"][..],
1297            &["config", "user.name", "Test User"][..],
1298            &["config", "commit.gpgsign", "false"][..],
1299        ] {
1300            run_git(repo.path(), args);
1301        }
1302        for name in ["committed.ts", "staged.ts", "unstaged.ts"] {
1303            std::fs::write(repo.path().join(name), "old\n").expect("initial file");
1304        }
1305        run_git(repo.path(), &["add", "."]);
1306        run_git(repo.path(), &["commit", "--quiet", "-m", "base"]);
1307        run_git(repo.path(), &["branch", "base"]);
1308
1309        std::fs::write(repo.path().join("committed.ts"), "new\n").expect("committed change");
1310        run_git(repo.path(), &["add", "committed.ts"]);
1311        run_git(repo.path(), &["commit", "--quiet", "-m", "change"]);
1312        std::fs::write(repo.path().join("staged.ts"), "new\n").expect("staged change");
1313        run_git(repo.path(), &["add", "staged.ts"]);
1314        std::fs::write(repo.path().join("unstaged.ts"), "new\n").expect("unstaged change");
1315        std::fs::write(repo.path().join("untracked.ts"), "new\n").expect("untracked file");
1316
1317        let mut batch = ChangedFilesBatch::new(repo.path(), "base").expect("batch");
1318        for reference in ["base", "HEAD"] {
1319            let batched = batch.changed_files(reference).expect("batched changes");
1320            let independent = changed_files(repo.path(), reference).expect("independent changes");
1321            assert_eq!(batched, independent, "{reference} scope changed");
1322        }
1323    }
1324
1325    #[cfg(unix)]
1326    #[test]
1327    fn changed_files_preserve_special_filenames() {
1328        let repo = tempfile::tempdir().expect("tempdir");
1329        for args in [
1330            &["init", "--quiet"][..],
1331            &["config", "user.email", "test@example.com"][..],
1332            &["config", "user.name", "Test User"][..],
1333            &["config", "commit.gpgsign", "false"][..],
1334            &["config", "tag.gpgsign", "false"][..],
1335        ] {
1336            run_git(repo.path(), args);
1337        }
1338        std::fs::write(repo.path().join("initial.ts"), "initial\n").expect("initial fixture");
1339        run_git(repo.path(), &["add", "."]);
1340        run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
1341        run_git(repo.path(), &["tag", "base"]);
1342
1343        let canonical_root = repo.path().canonicalize().expect("canonical repo");
1344        let special_files = [
1345            "src/line\nbreak.ts",
1346            "src/space name.ts",
1347            "src/quote\"name.ts",
1348            "src/back\\slash.ts",
1349            "src/unicode-λ.ts",
1350        ]
1351        .map(|path| canonical_root.join(path));
1352        std::fs::create_dir_all(canonical_root.join("src")).expect("source dir");
1353        for special in &special_files {
1354            std::fs::write(special, "changed\n").expect("special fixture");
1355        }
1356
1357        let changed = try_get_changed_files(repo.path(), "base").expect("changed files");
1358        for special in special_files {
1359            assert!(
1360                changed.contains(&special),
1361                "missing {special:?}: {changed:?}"
1362            );
1363        }
1364    }
1365
1366    #[cfg(windows)]
1367    #[test]
1368    fn git_path_bytes_use_windows_separators() {
1369        assert_eq!(
1370            git_path_from_bytes(b"src/nested/file.ts"),
1371            PathBuf::from(r"src\nested\file.ts")
1372        );
1373    }
1374
1375    #[test]
1376    fn changed_diff_covers_staged_unstaged_and_untracked_files() {
1377        let repo = tempfile::tempdir().expect("tempdir");
1378        for args in [
1379            &["init", "--quiet"][..],
1380            &["config", "user.email", "test@example.com"][..],
1381            &["config", "user.name", "Test User"][..],
1382            &["config", "commit.gpgsign", "false"][..],
1383            &["config", "tag.gpgsign", "false"][..],
1384        ] {
1385            run_git(repo.path(), args);
1386        }
1387        std::fs::write(repo.path().join("staged.ts"), "old\n").expect("staged fixture");
1388        std::fs::write(repo.path().join("unstaged.ts"), "old\n").expect("unstaged fixture");
1389        run_git(repo.path(), &["add", "."]);
1390        run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
1391        run_git(repo.path(), &["tag", "base"]);
1392
1393        std::fs::write(repo.path().join("committed.ts"), "committed\n").expect("committed fixture");
1394        run_git(repo.path(), &["add", "committed.ts"]);
1395        run_git(
1396            repo.path(),
1397            &["commit", "--quiet", "-m", "committed change"],
1398        );
1399
1400        std::fs::write(repo.path().join("staged.ts"), "staged\n").expect("staged edit");
1401        run_git(repo.path(), &["add", "staged.ts"]);
1402        std::fs::write(repo.path().join("unstaged.ts"), "unstaged\n").expect("unstaged edit");
1403        std::fs::write(repo.path().join("untracked.ts"), "untracked\n").expect("untracked edit");
1404
1405        for diff in [
1406            try_get_changed_diff(repo.path(), "base"),
1407            try_get_mutation_diff(repo.path(), "base"),
1408        ] {
1409            let diff = diff.expect("complete changeset diff");
1410            let index = fallow_output::DiffIndex::from_unified_diff(&diff);
1411
1412            assert!(diff.contains("b/committed.ts"), "{diff}");
1413            assert!(diff.contains("b/staged.ts"), "{diff}");
1414            assert!(diff.contains("b/unstaged.ts"), "{diff}");
1415            assert!(diff.contains("b/untracked.ts"), "{diff}");
1416            assert_eq!(index.hunk_count(), 4);
1417            assert_eq!(index.net_lines(), 2);
1418        }
1419    }
1420
1421    fn run_git(root: &Path, args: &[&str]) {
1422        let output = spawn_output(&mut git_command(root, args)).expect("git command");
1423        assert!(
1424            output.status.success(),
1425            "git {args:?} failed: {}",
1426            String::from_utf8_lossy(&output.stderr)
1427        );
1428    }
1429
1430    #[test]
1431    fn untracked_path_arg_uses_forward_slashes() {
1432        assert_eq!(
1433            super::untracked_path_arg(Path::new("src\\nested\\b.ts")),
1434            "src/nested/b.ts"
1435        );
1436        assert_eq!(super::untracked_path_arg(Path::new("src/b.ts")), "src/b.ts");
1437    }
1438
1439    #[test]
1440    fn changed_files_error_describe_matches_core_contract() {
1441        assert_eq!(
1442            ChangedFilesError::InvalidRef("bad ref".to_string()).describe(),
1443            "invalid git ref: bad ref"
1444        );
1445        assert_eq!(
1446            ChangedFilesError::GitMissing("not found".to_string()).describe(),
1447            "failed to run git: not found"
1448        );
1449        assert_eq!(
1450            ChangedFilesError::NotARepository.describe(),
1451            "not a git repository"
1452        );
1453        assert!(
1454            ChangedFilesError::GitFailed("unknown revision main".to_string())
1455                .describe()
1456                .contains("fetch-depth: 0")
1457        );
1458    }
1459
1460    #[test]
1461    fn filter_results_keeps_only_changed_file_findings() {
1462        let mut results = AnalysisResults::default();
1463        results
1464            .unused_files
1465            .push(UnusedFileFinding::with_actions(UnusedFile {
1466                path: PathBuf::from("/repo/a.ts"),
1467            }));
1468        results
1469            .unused_files
1470            .push(UnusedFileFinding::with_actions(UnusedFile {
1471                path: PathBuf::from("/repo/b.ts"),
1472            }));
1473        results
1474            .unused_exports
1475            .push(UnusedExportFinding::with_actions(UnusedExport {
1476                path: PathBuf::from("/repo/a.ts"),
1477                export_name: "foo".to_owned(),
1478                is_type_only: false,
1479                line: 1,
1480                col: 0,
1481                span_start: 0,
1482                is_re_export: false,
1483                deprecated: false,
1484                deprecated_reason: None,
1485            }));
1486
1487        let mut changed = FxHashSet::default();
1488        changed.insert(PathBuf::from("/repo/a.ts"));
1489
1490        filter_results_by_changed_files(&mut results, &changed);
1491
1492        assert_eq!(results.unused_files.len(), 1);
1493        assert_eq!(
1494            results.unused_files[0].file.path,
1495            PathBuf::from("/repo/a.ts")
1496        );
1497        assert_eq!(results.unused_exports.len(), 1);
1498    }
1499
1500    #[test]
1501    fn filter_results_preserves_graph_global_dependency_findings() {
1502        let mut results = AnalysisResults::default();
1503        results
1504            .unused_dependencies
1505            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1506                package_name: "lodash".to_owned(),
1507                location: DependencyLocation::Dependencies,
1508                path: PathBuf::from("/repo/package.json"),
1509                line: 3,
1510                used_in_workspaces: Vec::new(),
1511                declared_and_imported_in: Vec::new(),
1512            }));
1513
1514        let changed = FxHashSet::default();
1515        filter_results_by_changed_files(&mut results, &changed);
1516
1517        assert_eq!(results.unused_dependencies.len(), 1);
1518    }
1519
1520    /// Retention for `deprecated-export-in-use` keys on the file that declares
1521    /// the export. A change that only adds a consumer does not surface an old
1522    /// deprecated export (documented v1 behavior).
1523    #[test]
1524    fn filter_results_keeps_deprecated_export_only_when_its_declaring_file_changed() {
1525        let finding = |path: &str| {
1526            fallow_types::output_dead_code::DeprecatedExportInUseFinding::with_actions(
1527                fallow_types::results::DeprecatedExportInUse {
1528                    path: PathBuf::from(path),
1529                    export_name: "old".to_owned(),
1530                    is_type_only: false,
1531                    line: 2,
1532                    col: 0,
1533                    span_start: 0,
1534                    deprecated_reason: None,
1535                    consumer_count: 1,
1536                    consumers: vec![fallow_types::results::DeprecatedExportConsumer {
1537                        path: PathBuf::from("/repo/consumer.ts"),
1538                        line: 1,
1539                        col: 0,
1540                        kind: fallow_types::results::DeprecatedConsumerKind::NamedImport,
1541                    }],
1542                    public_api: false,
1543                },
1544            )
1545        };
1546        let mut results = AnalysisResults::default();
1547        results
1548            .deprecated_exports_in_use
1549            .push(finding("/repo/a.ts"));
1550        results
1551            .deprecated_exports_in_use
1552            .push(finding("/repo/b.ts"));
1553
1554        let mut changed = FxHashSet::default();
1555        changed.insert(PathBuf::from("/repo/a.ts"));
1556        changed.insert(PathBuf::from("/repo/consumer.ts"));
1557        filter_results_by_changed_files(&mut results, &changed);
1558
1559        let kept: Vec<_> = results
1560            .deprecated_exports_in_use
1561            .iter()
1562            .map(|f| f.export.path.clone())
1563            .collect();
1564        assert_eq!(kept, vec![PathBuf::from("/repo/a.ts")]);
1565    }
1566
1567    #[test]
1568    fn filter_results_keeps_relative_manifest_finding_when_manifest_changed() {
1569        let mut results = AnalysisResults::default();
1570        results
1571            .empty_catalog_groups
1572            .push(EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
1573                catalog_name: "legacy".to_owned(),
1574                path: PathBuf::from("pnpm-workspace.yaml"),
1575                line: 4,
1576            }));
1577
1578        let mut changed = FxHashSet::default();
1579        changed.insert(PathBuf::from("/repo/pnpm-workspace.yaml"));
1580
1581        filter_results_by_changed_files(&mut results, &changed);
1582
1583        assert_eq!(results.empty_catalog_groups.len(), 1);
1584    }
1585
1586    #[test]
1587    fn filter_duplication_keeps_groups_with_changed_instances_and_recomputes_stats() {
1588        let mut report = DuplicationReport {
1589            clone_groups: vec![
1590                CloneGroup {
1591                    instances: vec![
1592                        CloneInstance {
1593                            is_symlink: false,
1594                            file: PathBuf::from("/repo/a.ts"),
1595                            start_line: 1,
1596                            end_line: 5,
1597                            start_col: 0,
1598                            end_col: 10,
1599                            fragment: "code".to_owned(),
1600                        },
1601                        CloneInstance {
1602                            is_symlink: false,
1603                            file: PathBuf::from("/repo/b.ts"),
1604                            start_line: 1,
1605                            end_line: 5,
1606                            start_col: 0,
1607                            end_col: 10,
1608                            fragment: "code".to_owned(),
1609                        },
1610                    ],
1611                    token_count: 20,
1612                    line_count: 5,
1613                    similarity: None,
1614                },
1615                CloneGroup {
1616                    instances: vec![
1617                        CloneInstance {
1618                            is_symlink: false,
1619                            file: PathBuf::from("/repo/c.ts"),
1620                            start_line: 1,
1621                            end_line: 5,
1622                            start_col: 0,
1623                            end_col: 10,
1624                            fragment: "other".to_owned(),
1625                        },
1626                        CloneInstance {
1627                            is_symlink: false,
1628                            file: PathBuf::from("/repo/d.ts"),
1629                            start_line: 1,
1630                            end_line: 5,
1631                            start_col: 0,
1632                            end_col: 10,
1633                            fragment: "other".to_owned(),
1634                        },
1635                    ],
1636                    token_count: 20,
1637                    line_count: 5,
1638                    similarity: None,
1639                },
1640            ],
1641            clone_families: Vec::new(),
1642            mirrored_directories: Vec::new(),
1643            range_marker_problems: Vec::new(),
1644            stats: DuplicationStats {
1645                total_files: 4,
1646                files_with_clones: 4,
1647                total_lines: 100,
1648                duplicated_lines: 20,
1649                total_tokens: 200,
1650                duplicated_tokens: 80,
1651                clone_groups: 2,
1652                clone_families: 0,
1653                clone_instances: 4,
1654                duplication_percentage: 20.0,
1655                clone_groups_below_min_occurrences: 0,
1656                clone_groups_ignored: 0,
1657                near_candidates_skipped: 0,
1658            },
1659        };
1660
1661        let mut changed = FxHashSet::default();
1662        changed.insert(PathBuf::from("/repo/a.ts"));
1663
1664        filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1665
1666        assert_eq!(report.clone_groups.len(), 1);
1667        assert_eq!(report.stats.clone_groups, 1);
1668        assert_eq!(report.stats.clone_instances, 2);
1669    }
1670
1671    /// A changed-file scope keeps the family order of every other path: the
1672    /// file set. The larger family has the later file set, so an order by
1673    /// duplicated lines puts it first.
1674    #[test]
1675    fn changed_file_scope_orders_families_by_file_set() {
1676        let group = |files: [&str; 2], line_count: usize| CloneGroup {
1677            instances: files
1678                .iter()
1679                .map(|file| CloneInstance {
1680                    is_symlink: false,
1681                    file: PathBuf::from(file),
1682                    start_line: 1,
1683                    end_line: line_count,
1684                    start_col: 0,
1685                    end_col: 10,
1686                    fragment: String::new(),
1687                })
1688                .collect(),
1689            token_count: line_count * 10,
1690            line_count,
1691            similarity: None,
1692        };
1693        let mut report = DuplicationReport {
1694            clone_groups: vec![
1695                group(["/repo/y.ts", "/repo/z.ts"], 46),
1696                group(["/repo/a.ts", "/repo/b.ts"], 7),
1697            ],
1698            clone_families: Vec::new(),
1699            mirrored_directories: Vec::new(),
1700            range_marker_problems: Vec::new(),
1701            stats: DuplicationStats::default(),
1702        };
1703        let changed: FxHashSet<PathBuf> = ["/repo/a.ts", "/repo/y.ts"]
1704            .into_iter()
1705            .map(PathBuf::from)
1706            .collect();
1707
1708        filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1709
1710        let order: Vec<&PathBuf> = report
1711            .clone_families
1712            .iter()
1713            .map(|family| &family.files[0])
1714            .collect();
1715        assert_eq!(
1716            order,
1717            [&PathBuf::from("/repo/a.ts"), &PathBuf::from("/repo/y.ts")]
1718        );
1719    }
1720
1721    /// The combined probe gives the same two paths as the two single probes,
1722    /// from the repository root and from a subdirectory.
1723    #[test]
1724    fn one_probe_resolves_the_common_dir_and_the_toplevel() {
1725        let repo = tempfile::tempdir().expect("tempdir");
1726        run_git(repo.path(), &["init", "--quiet"]);
1727        let nested = repo.path().join("packages/app");
1728        std::fs::create_dir_all(&nested).expect("nested dir");
1729        for cwd in [repo.path(), nested.as_path()] {
1730            let (common, toplevel) =
1731                resolve_git_common_dir_and_toplevel(cwd).expect("combined probe");
1732            assert_eq!(common, resolve_git_common_dir(cwd).expect("common dir"));
1733            assert_eq!(toplevel, resolve_git_toplevel(cwd).expect("toplevel"));
1734        }
1735    }
1736
1737    /// A bare repository has a common dir but no work tree, so the combined
1738    /// probe fails and a caller falls back to the single probes.
1739    #[test]
1740    fn the_combined_probe_fails_without_a_work_tree() {
1741        let repo = tempfile::tempdir().expect("tempdir");
1742        run_git(repo.path(), &["init", "--quiet", "--bare"]);
1743        assert!(resolve_git_common_dir_and_toplevel(repo.path()).is_err());
1744        // Fallow Git commands pass safe.bareRepository=explicit, so the single
1745        // probe also refuses a bare repository that Git finds on its own.
1746        assert!(resolve_git_common_dir(repo.path()).is_err());
1747    }
1748}