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