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