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, Stdio};
5use std::sync::OnceLock;
6
7use fallow_types::{
8    output_dead_code::{
9        CircularDependencyFinding, DuplicateExportFinding, DuplicatePropShapeFinding,
10        PropDrillingChainFinding, ReExportCycleFinding, UnlistedDependencyFinding,
11    },
12    results::{AnalysisResults, SecurityFinding},
13};
14use rustc_hash::FxHashSet;
15
16use crate::duplicates::{self, DuplicationReport};
17
18pub use crate::git_env::{AMBIENT_GIT_ENV_VARS, clear_ambient_git_env};
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
52fn augment_git_failed(stderr: &str) -> String {
53    let lower = stderr.to_ascii_lowercase();
54    if lower.contains("not a valid object name")
55        || lower.contains("unknown revision")
56        || lower.contains("ambiguous argument")
57    {
58        format!(
59            "{stderr} (shallow clone? try `git fetch --unshallow`, or set `fetch-depth: 0` on actions/checkout / `GIT_DEPTH: 0` in GitLab CI)"
60        )
61    } else {
62        stderr.to_owned()
63    }
64}
65
66/// Install a spawn-hook for changed-file git subprocesses.
67pub fn set_spawn_hook(hook: ChangedFilesSpawnHook) {
68    let _ = SPAWN_HOOK.set(hook);
69}
70
71/// Validate a user-supplied git ref before passing it to git.
72pub(crate) fn validate_git_ref(s: &str) -> Result<&str, String> {
73    if s.is_empty() {
74        return Err("git ref cannot be empty".to_string());
75    }
76    if s.starts_with('-') {
77        return Err("git ref cannot start with '-'".to_string());
78    }
79    let mut in_braces = false;
80    for c in s.chars() {
81        match c {
82            '{' => in_braces = true,
83            '}' => in_braces = false,
84            ':' | ' ' if in_braces => {}
85            c if c.is_ascii_alphanumeric()
86                || matches!(c, '.' | '_' | '-' | '/' | '~' | '^' | '@' | '{' | '}') => {}
87            _ => return Err(format!("git ref contains disallowed character: '{c}'")),
88        }
89    }
90    if in_braces {
91        return Err("git ref has unclosed '{'".to_string());
92    }
93    Ok(s)
94}
95
96/// Resolve the canonical git toplevel for `cwd`.
97pub fn resolve_git_toplevel(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
98    let output = spawn_output(&mut git_command(cwd, &["rev-parse", "--show-toplevel"]))
99        .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
100
101    if !output.status.success() {
102        let stderr = String::from_utf8_lossy(&output.stderr);
103        return Err(if stderr.contains("not a git repository") {
104            ChangedFilesError::NotARepository
105        } else {
106            ChangedFilesError::GitFailed(stderr.trim().to_owned())
107        });
108    }
109
110    let raw = String::from_utf8_lossy(&output.stdout);
111    let trimmed = raw.trim();
112    if trimmed.is_empty() {
113        return Err(ChangedFilesError::GitFailed(
114            "git rev-parse --show-toplevel returned empty output".to_owned(),
115        ));
116    }
117
118    let path = PathBuf::from(trimmed);
119    Ok(dunce::canonicalize(&path).unwrap_or(path))
120}
121
122/// Resolve the canonical git common directory for `cwd`.
123pub fn resolve_git_common_dir(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
124    let output = spawn_output(&mut git_command(
125        cwd,
126        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
127    ))
128    .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
129
130    if !output.status.success() {
131        let stderr = String::from_utf8_lossy(&output.stderr);
132        return Err(if stderr.contains("not a git repository") {
133            ChangedFilesError::NotARepository
134        } else {
135            ChangedFilesError::GitFailed(stderr.trim().to_owned())
136        });
137    }
138
139    let raw = String::from_utf8_lossy(&output.stdout);
140    let trimmed = raw.trim();
141    if trimmed.is_empty() {
142        return Err(ChangedFilesError::GitFailed(
143            "git rev-parse --git-common-dir returned empty output".to_owned(),
144        ));
145    }
146
147    let path = PathBuf::from(trimmed);
148    Ok(dunce::canonicalize(&path).unwrap_or(path))
149}
150
151/// Get files changed since a git ref.
152fn try_get_changed_files(
153    root: &Path,
154    git_ref: &str,
155) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
156    validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
157    let toplevel = resolve_git_toplevel(root)?;
158    try_get_changed_files_with_toplevel(root, &toplevel, git_ref)
159}
160
161/// Resolve changed files for a git ref relative to a project root.
162///
163/// # Errors
164///
165/// Returns an error when git cannot resolve the ref or repository state.
166pub fn changed_files(root: &Path, git_ref: &str) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
167    try_get_changed_files(root, git_ref)
168}
169
170/// Get changed files and the git toplevel used to resolve them.
171pub fn try_get_changed_files_with_toplevel(
172    cwd: &Path,
173    toplevel: &Path,
174    git_ref: &str,
175) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
176    validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
177
178    let mut files = collect_git_paths(
179        cwd,
180        toplevel,
181        &[
182            "diff",
183            "--name-only",
184            "-z",
185            "--end-of-options",
186            &format!("{git_ref}...HEAD"),
187        ],
188    )?;
189    files.extend(collect_git_paths(
190        cwd,
191        toplevel,
192        &["diff", "--name-only", "-z", "HEAD"],
193    )?);
194    files.extend(collect_git_paths(
195        cwd,
196        toplevel,
197        &[
198            "ls-files",
199            "--full-name",
200            "--others",
201            "--exclude-standard",
202            "-z",
203        ],
204    )?);
205    Ok(files)
206}
207
208/// A file rename detected between a git ref's merge base and the working
209/// tree, with absolute paths joined onto the git toplevel.
210#[derive(Debug, Clone, PartialEq, Eq)]
211pub struct RenamedFile {
212    /// Absolute pre-rename path (exists in the base tree).
213    pub from: PathBuf,
214    /// Absolute post-rename path (exists in the current tree).
215    pub to: PathBuf,
216}
217
218/// Detect renamed files between a git ref's merge base and the current tree.
219///
220/// Covers the committed range (`<ref>...HEAD`) plus renames staged against
221/// `HEAD`, mirroring the tracked scope of [`try_get_changed_files_with_toplevel`].
222/// A rename committed as `a -> b` and then staged as `b -> c` is composed into
223/// one `a -> c` entry. Copies are intentionally not reported: a copy leaves
224/// the original in place, so findings on the copy are genuinely new.
225///
226/// # Errors
227///
228/// Returns an error when git cannot resolve the ref or repository state.
229pub fn try_get_renamed_files(
230    root: &Path,
231    git_ref: &str,
232) -> Result<Vec<RenamedFile>, ChangedFilesError> {
233    validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
234    let toplevel = resolve_git_toplevel(root)?;
235    let mut renames = collect_git_rename_pairs(
236        root,
237        &toplevel,
238        &[
239            "diff",
240            "--name-status",
241            "-z",
242            "--find-renames",
243            "--end-of-options",
244            &format!("{git_ref}...HEAD"),
245        ],
246    )?;
247    let staged = collect_git_rename_pairs(
248        root,
249        &toplevel,
250        &["diff", "--name-status", "-z", "--find-renames", "HEAD"],
251    )?;
252    for pair in staged {
253        if let Some(chained) = renames.iter_mut().find(|rename| rename.to == pair.from) {
254            chained.to = pair.to;
255        } else {
256            renames.push(pair);
257        }
258    }
259    Ok(renames)
260}
261
262/// Run a `--name-status -z` diff and collect its `R` (rename) pairs.
263///
264/// The `-z` stream alternates status and path fields separated by NUL; rename
265/// and copy statuses (`R<score>` / `C<score>`) carry two path fields (old then
266/// new), every other status carries one.
267fn collect_git_rename_pairs(
268    cwd: &Path,
269    toplevel: &Path,
270    args: &[&str],
271) -> Result<Vec<RenamedFile>, ChangedFilesError> {
272    let output = spawn_output(&mut git_command(cwd, args))
273        .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
274
275    if !output.status.success() {
276        return Err(changed_files_error_from_output(&output));
277    }
278
279    let mut fields = output
280        .stdout
281        .split(|byte| *byte == 0)
282        .filter(|field| !field.is_empty());
283    let mut renames = Vec::new();
284    while let Some(status) = fields.next() {
285        let Some(first_path) = fields.next() else {
286            break;
287        };
288        match status.first() {
289            Some(b'R') => {
290                let Some(second_path) = fields.next() else {
291                    break;
292                };
293                renames.push(RenamedFile {
294                    from: toplevel.join(git_path_from_bytes(first_path)),
295                    to: toplevel.join(git_path_from_bytes(second_path)),
296                });
297            }
298            // Copies also carry two path fields but are conservatively treated
299            // as new files, so only the extra field is consumed.
300            Some(b'C') => {
301                let _ = fields.next();
302            }
303            _ => {}
304        }
305    }
306    Ok(renames)
307}
308
309/// Return the raw git diff from a ref's merge base through the working tree.
310///
311/// The result includes committed, staged, unstaged, and untracked changes so it
312/// covers the same scope as `try_get_changed_files`.
313pub fn try_get_changed_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
314    validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
315    let toplevel = resolve_git_toplevel(root)?;
316    let merge_base_output = spawn_output(&mut git_command(root, &["merge-base", git_ref, "HEAD"]))
317        .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
318    if !merge_base_output.status.success() {
319        return Err(changed_files_error_from_output(&merge_base_output));
320    }
321    let merge_base = String::from_utf8_lossy(&merge_base_output.stdout)
322        .trim()
323        .to_owned();
324    if merge_base.is_empty() {
325        return Err(ChangedFilesError::GitFailed(
326            "git merge-base returned empty output".to_owned(),
327        ));
328    }
329
330    let output = spawn_output(&mut git_command(
331        root,
332        &[
333            "diff",
334            "--relative",
335            "--unified=0",
336            "--end-of-options",
337            &merge_base,
338        ],
339    ))
340    .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
341
342    if !output.status.success() {
343        return Err(changed_files_error_from_output(&output));
344    }
345
346    let mut diff = String::from_utf8_lossy(&output.stdout).into_owned();
347    append_untracked_diffs(root, &toplevel, &mut diff)?;
348    Ok(diff)
349}
350
351fn append_untracked_diffs(
352    root: &Path,
353    toplevel: &Path,
354    diff: &mut String,
355) -> Result<(), ChangedFilesError> {
356    let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
357    let mut untracked: Vec<PathBuf> = collect_git_paths(
358        root,
359        toplevel,
360        &[
361            "ls-files",
362            "--full-name",
363            "--others",
364            "--exclude-standard",
365            "-z",
366        ],
367    )?
368    .into_iter()
369    .filter_map(|path| {
370        path.strip_prefix(&canonical_root)
371            .ok()
372            .map(Path::to_path_buf)
373    })
374    .collect();
375    untracked.sort_unstable();
376
377    #[cfg(windows)]
378    let empty_file = "NUL";
379    #[cfg(not(windows))]
380    let empty_file = "/dev/null";
381
382    for path in untracked {
383        let mut command = git_command(root, &["diff", "--no-index", "--unified=0", "--"]);
384        command.arg(empty_file).arg(untracked_path_arg(&path));
385        let output =
386            spawn_output(&mut command).map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
387        if !output.status.success() && output.status.code() != Some(1) {
388            return Err(changed_files_error_from_output(&output));
389        }
390        if !diff.is_empty() && !diff.ends_with('\n') {
391            diff.push('\n');
392        }
393        diff.push_str(&String::from_utf8_lossy(&output.stdout));
394    }
395    Ok(())
396}
397
398/// Forward-slashed relative path for the `git diff --no-index` argument.
399/// Passing the native form on Windows makes git echo backslashes into the
400/// `+++ b/` header, so every consumer keyed on forward-slashed diff paths
401/// (added-line lookups included) silently misses the file.
402fn untracked_path_arg(path: &Path) -> String {
403    path.to_string_lossy().replace('\\', "/")
404}
405
406fn changed_files_error_from_output(output: &Output) -> ChangedFilesError {
407    let stderr = String::from_utf8_lossy(&output.stderr);
408    if stderr.contains("not a git repository") {
409        ChangedFilesError::NotARepository
410    } else {
411        ChangedFilesError::GitFailed(stderr.trim().to_owned())
412    }
413}
414
415/// Get changed files if git can resolve them, otherwise return `None`.
416#[must_use]
417#[expect(
418    clippy::print_stderr,
419    reason = "intentional user-facing warning for the CLI's --changed-since fallback path; typed callers use try_get_changed_files instead"
420)]
421pub fn get_changed_files(root: &Path, git_ref: &str) -> Option<FxHashSet<PathBuf>> {
422    match try_get_changed_files(root, git_ref) {
423        Ok(files) => Some(files),
424        Err(ChangedFilesError::InvalidRef(e)) => {
425            eprintln!("Warning: --changed-since ignored: invalid git ref: {e}");
426            None
427        }
428        Err(ChangedFilesError::GitMissing(e)) => {
429            eprintln!("Warning: --changed-since ignored: failed to run git: {e}");
430            None
431        }
432        Err(ChangedFilesError::NotARepository) => {
433            eprintln!("Warning: --changed-since ignored: not a git repository");
434            None
435        }
436        Err(ChangedFilesError::GitFailed(stderr)) => {
437            eprintln!("Warning: --changed-since failed for ref '{git_ref}': {stderr}");
438            None
439        }
440    }
441}
442
443fn spawn_output(command: &mut Command) -> std::io::Result<Output> {
444    if let Some(hook) = SPAWN_HOOK.get() {
445        hook(command)
446    } else {
447        command.output()
448    }
449}
450
451fn collect_git_paths(
452    cwd: &Path,
453    toplevel: &Path,
454    args: &[&str],
455) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
456    let output = spawn_output(&mut git_command(cwd, args))
457        .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
458
459    if !output.status.success() {
460        let stderr = String::from_utf8_lossy(&output.stderr);
461        return Err(if stderr.contains("not a git repository") {
462            ChangedFilesError::NotARepository
463        } else {
464            ChangedFilesError::GitFailed(stderr.trim().to_owned())
465        });
466    }
467
468    let files = output
469        .stdout
470        .split(|byte| *byte == 0)
471        .filter(|path| !path.is_empty())
472        .map(git_path_from_bytes)
473        .map(|path| toplevel.join(path))
474        .collect();
475
476    Ok(files)
477}
478
479#[cfg(unix)]
480fn git_path_from_bytes(path: &[u8]) -> PathBuf {
481    use std::ffi::OsString;
482    use std::os::unix::ffi::OsStringExt;
483
484    PathBuf::from(OsString::from_vec(path.to_vec()))
485}
486
487#[cfg(windows)]
488fn git_path_from_bytes(path: &[u8]) -> PathBuf {
489    PathBuf::from(String::from_utf8_lossy(path).replace('/', "\\"))
490}
491
492#[expect(
493    clippy::disallowed_methods,
494    reason = "canonical engine-owned git spawn wrapper for changed-file orchestration"
495)]
496fn git_command(cwd: &Path, args: &[&str]) -> Command {
497    let mut command = Command::new("git");
498    clear_ambient_git_env(&mut command);
499    // Changed-file probes are non-interactive and must not inherit protocol stdin.
500    command.stdin(Stdio::null()).args(args).current_dir(cwd);
501    command
502}
503
504/// Scope dead-code results to findings affected by changed files.
505///
506/// Dependency-level issues stay unfiltered because whether a dependency is
507/// unused is a graph-global fact, not a changed-file-local fact.
508#[expect(
509    clippy::implicit_hasher,
510    reason = "fallow standardizes on FxHashSet across the workspace"
511)]
512pub fn filter_results_by_changed_files(
513    results: &mut AnalysisResults,
514    changed_files: &FxHashSet<PathBuf>,
515) {
516    let cf = normalize_changed_files_set(changed_files);
517    classify_changed_file_filter_fields(results);
518    retain_basic_issue_findings_by_changed_path(results, &cf);
519    retain_graph_findings_by_changed_files(results, &cf);
520    retain_boundary_policy_and_suppression_findings(results, &cf);
521    retain_security_and_workspace_findings(results, &cf);
522    retain_framework_findings_by_changed_files(results, &cf);
523}
524
525fn classify_changed_file_filter_fields(results: &AnalysisResults) {
526    let AnalysisResults {
527        unused_files: _unused_files,
528        unused_exports: _unused_exports,
529        unused_types: _unused_types,
530        private_type_leaks: _private_type_leaks,
531        unused_dependencies: _unused_dependencies,
532        unused_dev_dependencies: _unused_dev_dependencies,
533        unused_optional_dependencies: _unused_optional_dependencies,
534        unused_enum_members: _unused_enum_members,
535        unused_class_members: _unused_class_members,
536        unused_store_members: _unused_store_members,
537        unresolved_imports: _unresolved_imports,
538        unlisted_dependencies: _unlisted_dependencies,
539        duplicate_exports: _duplicate_exports,
540        type_only_dependencies: _type_only_dependencies,
541        test_only_dependencies: _test_only_dependencies,
542        dev_dependencies_in_production: _dev_dependencies_in_production,
543        circular_dependencies: _circular_dependencies,
544        re_export_cycles: _re_export_cycles,
545        boundary_violations: _boundary_violations,
546        boundary_coverage_violations: _boundary_coverage_violations,
547        boundary_call_violations: _boundary_call_violations,
548        policy_violations: _policy_violations,
549        stale_suppressions: _stale_suppressions,
550        unused_catalog_entries: _unused_catalog_entries,
551        empty_catalog_groups: _empty_catalog_groups,
552        unresolved_catalog_references: _unresolved_catalog_references,
553        unused_dependency_overrides: _unused_dependency_overrides,
554        misconfigured_dependency_overrides: _misconfigured_dependency_overrides,
555        invalid_client_exports: _invalid_client_exports,
556        mixed_client_server_barrels: _mixed_client_server_barrels,
557        misplaced_directives: _misplaced_directives,
558        unprovided_injects: _unprovided_injects,
559        unrendered_components: _unrendered_components,
560        route_collisions: _route_collisions,
561        dynamic_segment_name_conflicts: _dynamic_segment_name_conflicts,
562        unused_component_props: _unused_component_props,
563        unused_component_emits: _unused_component_emits,
564        unused_component_inputs: _unused_component_inputs,
565        unused_component_outputs: _unused_component_outputs,
566        unused_svelte_events: _unused_svelte_events,
567        unused_server_actions: _unused_server_actions,
568        unused_load_data_keys: _unused_load_data_keys,
569        unused_load_data_keys_global_abstain: _unused_load_data_keys_global_abstain,
570        prop_drilling_chains: _prop_drilling_chains,
571        thin_wrappers: _thin_wrappers,
572        duplicate_prop_shapes: _duplicate_prop_shapes,
573        suppression_count: _suppression_count,
574        unused_component_props_exempted: _unused_component_props_exempted,
575        active_suppressions: _active_suppressions,
576        feature_flags: _feature_flags,
577        security_findings: _security_findings,
578        security_unresolved_edge_files: _security_unresolved_edge_files,
579        security_unresolved_callee_sites: _security_unresolved_callee_sites,
580        security_unresolved_callee_diagnostics: _security_unresolved_callee_diagnostics,
581        export_usages: _export_usages,
582        entry_point_summary: _entry_point_summary,
583        render_fan_in: _render_fan_in,
584        react_component_intel: _react_component_intel,
585        semantic_framework_contracts: _semantic_framework_contracts,
586    } = results;
587}
588
589fn retain_basic_issue_findings_by_changed_path(
590    results: &mut AnalysisResults,
591    changed_files: &FxHashSet<PathBuf>,
592) {
593    retain_by_changed_path(&mut results.unused_files, changed_files, |f| &f.file.path);
594    retain_by_changed_path(&mut results.unused_exports, changed_files, |e| {
595        &e.export.path
596    });
597    retain_by_changed_path(&mut results.unused_types, changed_files, |e| &e.export.path);
598    retain_by_changed_path(&mut results.private_type_leaks, changed_files, |e| {
599        &e.leak.path
600    });
601    retain_by_changed_path(&mut results.unused_enum_members, changed_files, |m| {
602        &m.member.path
603    });
604    retain_by_changed_path(&mut results.unused_class_members, changed_files, |m| {
605        &m.member.path
606    });
607    retain_by_changed_path(&mut results.unused_store_members, changed_files, |m| {
608        &m.member.path
609    });
610    retain_by_changed_path(&mut results.unresolved_imports, changed_files, |i| {
611        &i.import.path
612    });
613}
614
615fn retain_graph_findings_by_changed_files(
616    results: &mut AnalysisResults,
617    changed_files: &FxHashSet<PathBuf>,
618) {
619    retain_unlisted_dependencies_by_import_site(&mut results.unlisted_dependencies, changed_files);
620    retain_duplicate_exports_by_changed_locations(&mut results.duplicate_exports, changed_files);
621    retain_circular_dependencies_by_changed_file(&mut results.circular_dependencies, changed_files);
622    retain_re_export_cycles_by_changed_file(&mut results.re_export_cycles, changed_files);
623}
624
625fn retain_boundary_policy_and_suppression_findings(
626    results: &mut AnalysisResults,
627    changed_files: &FxHashSet<PathBuf>,
628) {
629    retain_by_changed_path(&mut results.boundary_violations, changed_files, |v| {
630        &v.violation.from_path
631    });
632    retain_by_changed_path(
633        &mut results.boundary_coverage_violations,
634        changed_files,
635        |v| &v.violation.path,
636    );
637    retain_by_changed_path(&mut results.boundary_call_violations, changed_files, |v| {
638        &v.violation.path
639    });
640    retain_by_changed_path(&mut results.policy_violations, changed_files, |v| {
641        &v.violation.path
642    });
643    retain_by_changed_path(&mut results.stale_suppressions, changed_files, |s| &s.path);
644}
645
646fn retain_security_and_workspace_findings(
647    results: &mut AnalysisResults,
648    changed_files: &FxHashSet<PathBuf>,
649) {
650    retain_security_findings_by_changed_path(&mut results.security_findings, changed_files);
651    retain_by_changed_path(
652        &mut results.security_unresolved_callee_diagnostics,
653        changed_files,
654        |d| &d.path,
655    );
656    retain_by_changed_path(
657        &mut results.unresolved_catalog_references,
658        changed_files,
659        |r| &r.reference.path,
660    );
661    results
662        .empty_catalog_groups
663        .retain(|g| normalized_set_contains_path(changed_files, &g.group.path));
664    retain_by_changed_path(
665        &mut results.unused_dependency_overrides,
666        changed_files,
667        |o| &o.entry.path,
668    );
669    retain_by_changed_path(
670        &mut results.misconfigured_dependency_overrides,
671        changed_files,
672        |o| &o.entry.path,
673    );
674}
675
676fn retain_framework_findings_by_changed_files(
677    results: &mut AnalysisResults,
678    changed_files: &FxHashSet<PathBuf>,
679) {
680    retain_client_boundary_findings_by_changed_files(results, changed_files);
681    retain_component_contract_findings_by_changed_files(results, changed_files);
682    retain_react_health_findings_by_changed_files(results, changed_files);
683    retain_nextjs_findings_by_changed_files(results, changed_files);
684}
685
686fn retain_client_boundary_findings_by_changed_files(
687    results: &mut AnalysisResults,
688    changed_files: &FxHashSet<PathBuf>,
689) {
690    let AnalysisResults {
691        invalid_client_exports,
692        mixed_client_server_barrels,
693        misplaced_directives,
694        ..
695    } = results;
696
697    retain_by_changed_path(invalid_client_exports, changed_files, |e| &e.export.path);
698    retain_by_changed_path(mixed_client_server_barrels, changed_files, |b| {
699        &b.barrel.path
700    });
701    retain_by_changed_path(misplaced_directives, changed_files, |d| {
702        &d.directive_site.path
703    });
704}
705
706fn retain_component_contract_findings_by_changed_files(
707    results: &mut AnalysisResults,
708    changed_files: &FxHashSet<PathBuf>,
709) {
710    let AnalysisResults {
711        unprovided_injects,
712        unrendered_components,
713        unused_component_props,
714        unused_component_emits,
715        unused_component_inputs,
716        unused_component_outputs,
717        unused_svelte_events,
718        unused_server_actions,
719        unused_load_data_keys,
720        ..
721    } = results;
722
723    retain_by_changed_path(unprovided_injects, changed_files, |i| &i.inject.path);
724    retain_by_changed_path(unrendered_components, changed_files, |c| &c.component.path);
725    retain_by_changed_path(unused_component_props, changed_files, |p| &p.prop.path);
726    retain_by_changed_path(unused_component_emits, changed_files, |e| &e.emit.path);
727    retain_by_changed_path(unused_component_inputs, changed_files, |i| &i.input.path);
728    retain_by_changed_path(unused_component_outputs, changed_files, |o| &o.output.path);
729    retain_by_changed_path(unused_svelte_events, changed_files, |e| &e.event.path);
730    retain_by_changed_path(unused_server_actions, changed_files, |a| &a.action.path);
731    retain_by_changed_path(unused_load_data_keys, changed_files, |k| &k.key.path);
732}
733
734fn retain_react_health_findings_by_changed_files(
735    results: &mut AnalysisResults,
736    changed_files: &FxHashSet<PathBuf>,
737) {
738    let AnalysisResults {
739        prop_drilling_chains,
740        thin_wrappers,
741        duplicate_prop_shapes,
742        ..
743    } = results;
744
745    retain_prop_drilling_chains_by_anchor(prop_drilling_chains, changed_files);
746    retain_by_changed_path(thin_wrappers, changed_files, |w| &w.wrapper.file);
747    retain_duplicate_prop_shapes_by_anchor(duplicate_prop_shapes, changed_files);
748}
749
750fn retain_nextjs_findings_by_changed_files(
751    results: &mut AnalysisResults,
752    changed_files: &FxHashSet<PathBuf>,
753) {
754    let AnalysisResults {
755        route_collisions,
756        dynamic_segment_name_conflicts,
757        ..
758    } = results;
759
760    retain_by_changed_path(route_collisions, changed_files, |c| &c.collision.path);
761    retain_by_changed_path(dynamic_segment_name_conflicts, changed_files, |c| {
762        &c.conflict.path
763    });
764}
765
766fn retain_unlisted_dependencies_by_import_site(
767    dependencies: &mut Vec<UnlistedDependencyFinding>,
768    changed_files: &FxHashSet<PathBuf>,
769) {
770    dependencies.retain(|dependency| {
771        dependency
772            .dep
773            .imported_from
774            .iter()
775            .any(|site| contains_normalized(changed_files, &site.path))
776    });
777}
778
779fn retain_duplicate_exports_by_changed_locations(
780    duplicate_exports: &mut Vec<DuplicateExportFinding>,
781    changed_files: &FxHashSet<PathBuf>,
782) {
783    for duplicate in &mut *duplicate_exports {
784        duplicate
785            .export
786            .locations
787            .retain(|location| contains_normalized(changed_files, &location.path));
788    }
789    duplicate_exports.retain(|duplicate| duplicate.export.locations.len() >= 2);
790}
791
792fn retain_circular_dependencies_by_changed_file(
793    cycles: &mut Vec<CircularDependencyFinding>,
794    changed_files: &FxHashSet<PathBuf>,
795) {
796    cycles.retain(|cycle| {
797        cycle
798            .cycle
799            .files
800            .iter()
801            .any(|file| contains_normalized(changed_files, file))
802    });
803}
804
805fn retain_re_export_cycles_by_changed_file(
806    cycles: &mut Vec<ReExportCycleFinding>,
807    changed_files: &FxHashSet<PathBuf>,
808) {
809    cycles.retain(|cycle| {
810        cycle
811            .cycle
812            .files
813            .iter()
814            .any(|file| contains_normalized(changed_files, file))
815    });
816}
817
818fn retain_security_findings_by_changed_path(
819    findings: &mut Vec<SecurityFinding>,
820    changed_files: &FxHashSet<PathBuf>,
821) {
822    findings.retain(|finding| security_finding_touches_changed_path(finding, changed_files));
823}
824
825fn retain_prop_drilling_chains_by_anchor(
826    chains: &mut Vec<PropDrillingChainFinding>,
827    changed_files: &FxHashSet<PathBuf>,
828) {
829    chains.retain(|chain| {
830        chain
831            .chain
832            .hops
833            .first()
834            .is_some_and(|hop| contains_normalized(changed_files, &hop.file))
835    });
836}
837
838fn retain_duplicate_prop_shapes_by_anchor(
839    shapes: &mut Vec<DuplicatePropShapeFinding>,
840    changed_files: &FxHashSet<PathBuf>,
841) {
842    retain_by_changed_path(shapes, changed_files, |shape| &shape.shape.file);
843}
844
845fn retain_by_changed_path<T>(
846    items: &mut Vec<T>,
847    changed_files: &FxHashSet<PathBuf>,
848    path: impl Fn(&T) -> &Path,
849) {
850    items.retain(|item| contains_normalized(changed_files, path(item)));
851}
852
853fn security_finding_touches_changed_path(
854    finding: &SecurityFinding,
855    changed_files: &FxHashSet<PathBuf>,
856) -> bool {
857    contains_normalized(changed_files, &finding.path)
858        || finding
859            .trace
860            .iter()
861            .any(|hop| contains_normalized(changed_files, &hop.path))
862        || finding.reachability.as_ref().is_some_and(|reachability| {
863            reachability
864                .untrusted_source_trace
865                .iter()
866                .any(|hop| contains_normalized(changed_files, &hop.path))
867        })
868}
869
870fn normalize_changed_files_set(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<PathBuf> {
871    changed_files
872        .iter()
873        .map(|p| dunce::simplified(p).to_path_buf())
874        .collect()
875}
876
877fn contains_normalized(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
878    normalized.contains(dunce::simplified(path))
879}
880
881fn normalized_set_contains_path(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
882    contains_normalized(normalized, path)
883        || (path.is_relative() && normalized.iter().any(|changed| changed.ends_with(path)))
884}
885
886/// Scope duplication groups to clone groups touching at least one changed file.
887#[expect(
888    clippy::implicit_hasher,
889    reason = "fallow standardizes on FxHashSet across the workspace"
890)]
891pub fn filter_duplication_by_changed_files(
892    report: &mut DuplicationReport,
893    changed_files: &FxHashSet<PathBuf>,
894    root: &Path,
895) {
896    let cf = normalize_changed_files_set(changed_files);
897    report.clone_groups.retain(|group| {
898        group
899            .instances
900            .iter()
901            .any(|instance| contains_normalized(&cf, &instance.file))
902    });
903    duplicates::refresh_clone_families(report, root);
904    report.stats = duplicates::recompute_stats(report);
905}
906
907#[cfg(test)]
908mod tests {
909    use super::*;
910    use fallow_types::{
911        duplicates::{CloneGroup, CloneInstance, DuplicationStats},
912        output_dead_code::{
913            EmptyCatalogGroupFinding, UnusedDependencyFinding, UnusedExportFinding,
914            UnusedFileFinding,
915        },
916        results::{
917            DependencyLocation, EmptyCatalogGroup, UnusedDependency, UnusedExport, UnusedFile,
918        },
919    };
920
921    #[test]
922    fn validate_git_ref_rejects_option_like_ref() {
923        assert!(validate_git_ref("--upload-pack=evil").is_err());
924        assert!(validate_git_ref("-flag").is_err());
925    }
926
927    #[test]
928    fn validate_git_ref_allows_reflog_relative_date() {
929        assert!(validate_git_ref("HEAD@{1 week ago}").is_ok());
930    }
931
932    #[test]
933    fn git_command_clears_parent_git_environment() {
934        let command = git_command(Path::new("."), &["status"]);
935        let envs: Vec<_> = command.get_envs().collect();
936
937        for var in AMBIENT_GIT_ENV_VARS {
938            assert!(
939                envs.iter()
940                    .any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
941                "{var} should be cleared from the command env",
942            );
943        }
944    }
945
946    #[test]
947    fn try_get_changed_files_not_a_repository() {
948        let temp = tempfile::tempdir().expect("tempdir");
949        let result = try_get_changed_files(temp.path(), "main");
950        assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
951    }
952
953    #[cfg(unix)]
954    #[test]
955    fn changed_files_preserve_special_filenames() {
956        let repo = tempfile::tempdir().expect("tempdir");
957        for args in [
958            &["init", "--quiet"][..],
959            &["config", "user.email", "test@example.com"][..],
960            &["config", "user.name", "Test User"][..],
961            &["config", "commit.gpgsign", "false"][..],
962        ] {
963            run_git(repo.path(), args);
964        }
965        std::fs::write(repo.path().join("initial.ts"), "initial\n").expect("initial fixture");
966        run_git(repo.path(), &["add", "."]);
967        run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
968        run_git(repo.path(), &["tag", "base"]);
969
970        let canonical_root = repo.path().canonicalize().expect("canonical repo");
971        let special_files = [
972            "src/line\nbreak.ts",
973            "src/space name.ts",
974            "src/quote\"name.ts",
975            "src/back\\slash.ts",
976            "src/unicode-λ.ts",
977        ]
978        .map(|path| canonical_root.join(path));
979        std::fs::create_dir_all(canonical_root.join("src")).expect("source dir");
980        for special in &special_files {
981            std::fs::write(special, "changed\n").expect("special fixture");
982        }
983
984        let changed = try_get_changed_files(repo.path(), "base").expect("changed files");
985        for special in special_files {
986            assert!(
987                changed.contains(&special),
988                "missing {special:?}: {changed:?}"
989            );
990        }
991    }
992
993    #[cfg(windows)]
994    #[test]
995    fn git_path_bytes_use_windows_separators() {
996        assert_eq!(
997            git_path_from_bytes(b"src/nested/file.ts"),
998            PathBuf::from(r"src\nested\file.ts")
999        );
1000    }
1001
1002    #[test]
1003    fn changed_diff_covers_staged_unstaged_and_untracked_files() {
1004        let repo = tempfile::tempdir().expect("tempdir");
1005        for args in [
1006            &["init", "--quiet"][..],
1007            &["config", "user.email", "test@example.com"][..],
1008            &["config", "user.name", "Test User"][..],
1009            &["config", "commit.gpgsign", "false"][..],
1010        ] {
1011            run_git(repo.path(), args);
1012        }
1013        std::fs::write(repo.path().join("staged.ts"), "old\n").expect("staged fixture");
1014        std::fs::write(repo.path().join("unstaged.ts"), "old\n").expect("unstaged fixture");
1015        run_git(repo.path(), &["add", "."]);
1016        run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
1017        run_git(repo.path(), &["tag", "base"]);
1018
1019        std::fs::write(repo.path().join("committed.ts"), "committed\n").expect("committed fixture");
1020        run_git(repo.path(), &["add", "committed.ts"]);
1021        run_git(
1022            repo.path(),
1023            &["commit", "--quiet", "-m", "committed change"],
1024        );
1025
1026        std::fs::write(repo.path().join("staged.ts"), "staged\n").expect("staged edit");
1027        run_git(repo.path(), &["add", "staged.ts"]);
1028        std::fs::write(repo.path().join("unstaged.ts"), "unstaged\n").expect("unstaged edit");
1029        std::fs::write(repo.path().join("untracked.ts"), "untracked\n").expect("untracked edit");
1030
1031        let diff = try_get_changed_diff(repo.path(), "base").expect("complete changeset diff");
1032        let index = fallow_output::DiffIndex::from_unified_diff(&diff);
1033
1034        assert!(diff.contains("b/committed.ts"), "{diff}");
1035        assert!(diff.contains("b/staged.ts"), "{diff}");
1036        assert!(diff.contains("b/unstaged.ts"), "{diff}");
1037        assert!(diff.contains("b/untracked.ts"), "{diff}");
1038        assert_eq!(index.hunk_count(), 4);
1039        assert_eq!(index.net_lines(), 2);
1040    }
1041
1042    fn run_git(root: &Path, args: &[&str]) {
1043        let output = spawn_output(&mut git_command(root, args)).expect("git command");
1044        assert!(
1045            output.status.success(),
1046            "git {args:?} failed: {}",
1047            String::from_utf8_lossy(&output.stderr)
1048        );
1049    }
1050
1051    #[test]
1052    fn untracked_path_arg_uses_forward_slashes() {
1053        assert_eq!(
1054            super::untracked_path_arg(Path::new("src\\nested\\b.ts")),
1055            "src/nested/b.ts"
1056        );
1057        assert_eq!(super::untracked_path_arg(Path::new("src/b.ts")), "src/b.ts");
1058    }
1059
1060    #[test]
1061    fn changed_files_error_describe_matches_core_contract() {
1062        assert_eq!(
1063            ChangedFilesError::InvalidRef("bad ref".to_string()).describe(),
1064            "invalid git ref: bad ref"
1065        );
1066        assert_eq!(
1067            ChangedFilesError::GitMissing("not found".to_string()).describe(),
1068            "failed to run git: not found"
1069        );
1070        assert_eq!(
1071            ChangedFilesError::NotARepository.describe(),
1072            "not a git repository"
1073        );
1074        assert!(
1075            ChangedFilesError::GitFailed("unknown revision main".to_string())
1076                .describe()
1077                .contains("fetch-depth: 0")
1078        );
1079    }
1080
1081    #[test]
1082    fn filter_results_keeps_only_changed_file_findings() {
1083        let mut results = AnalysisResults::default();
1084        results
1085            .unused_files
1086            .push(UnusedFileFinding::with_actions(UnusedFile {
1087                path: PathBuf::from("/repo/a.ts"),
1088            }));
1089        results
1090            .unused_files
1091            .push(UnusedFileFinding::with_actions(UnusedFile {
1092                path: PathBuf::from("/repo/b.ts"),
1093            }));
1094        results
1095            .unused_exports
1096            .push(UnusedExportFinding::with_actions(UnusedExport {
1097                path: PathBuf::from("/repo/a.ts"),
1098                export_name: "foo".to_owned(),
1099                is_type_only: false,
1100                line: 1,
1101                col: 0,
1102                span_start: 0,
1103                is_re_export: false,
1104            }));
1105
1106        let mut changed = FxHashSet::default();
1107        changed.insert(PathBuf::from("/repo/a.ts"));
1108
1109        filter_results_by_changed_files(&mut results, &changed);
1110
1111        assert_eq!(results.unused_files.len(), 1);
1112        assert_eq!(
1113            results.unused_files[0].file.path,
1114            PathBuf::from("/repo/a.ts")
1115        );
1116        assert_eq!(results.unused_exports.len(), 1);
1117    }
1118
1119    #[test]
1120    fn filter_results_preserves_graph_global_dependency_findings() {
1121        let mut results = AnalysisResults::default();
1122        results
1123            .unused_dependencies
1124            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1125                package_name: "lodash".to_owned(),
1126                location: DependencyLocation::Dependencies,
1127                path: PathBuf::from("/repo/package.json"),
1128                line: 3,
1129                used_in_workspaces: Vec::new(),
1130            }));
1131
1132        let changed = FxHashSet::default();
1133        filter_results_by_changed_files(&mut results, &changed);
1134
1135        assert_eq!(results.unused_dependencies.len(), 1);
1136    }
1137
1138    #[test]
1139    fn filter_results_keeps_relative_manifest_finding_when_manifest_changed() {
1140        let mut results = AnalysisResults::default();
1141        results
1142            .empty_catalog_groups
1143            .push(EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
1144                catalog_name: "legacy".to_owned(),
1145                path: PathBuf::from("pnpm-workspace.yaml"),
1146                line: 4,
1147            }));
1148
1149        let mut changed = FxHashSet::default();
1150        changed.insert(PathBuf::from("/repo/pnpm-workspace.yaml"));
1151
1152        filter_results_by_changed_files(&mut results, &changed);
1153
1154        assert_eq!(results.empty_catalog_groups.len(), 1);
1155    }
1156
1157    #[test]
1158    fn filter_duplication_keeps_groups_with_changed_instances_and_recomputes_stats() {
1159        let mut report = DuplicationReport {
1160            clone_groups: vec![
1161                CloneGroup {
1162                    instances: vec![
1163                        CloneInstance {
1164                            file: PathBuf::from("/repo/a.ts"),
1165                            start_line: 1,
1166                            end_line: 5,
1167                            start_col: 0,
1168                            end_col: 10,
1169                            fragment: "code".to_owned(),
1170                        },
1171                        CloneInstance {
1172                            file: PathBuf::from("/repo/b.ts"),
1173                            start_line: 1,
1174                            end_line: 5,
1175                            start_col: 0,
1176                            end_col: 10,
1177                            fragment: "code".to_owned(),
1178                        },
1179                    ],
1180                    token_count: 20,
1181                    line_count: 5,
1182                    similarity: None,
1183                },
1184                CloneGroup {
1185                    instances: vec![
1186                        CloneInstance {
1187                            file: PathBuf::from("/repo/c.ts"),
1188                            start_line: 1,
1189                            end_line: 5,
1190                            start_col: 0,
1191                            end_col: 10,
1192                            fragment: "other".to_owned(),
1193                        },
1194                        CloneInstance {
1195                            file: PathBuf::from("/repo/d.ts"),
1196                            start_line: 1,
1197                            end_line: 5,
1198                            start_col: 0,
1199                            end_col: 10,
1200                            fragment: "other".to_owned(),
1201                        },
1202                    ],
1203                    token_count: 20,
1204                    line_count: 5,
1205                    similarity: None,
1206                },
1207            ],
1208            clone_families: Vec::new(),
1209            mirrored_directories: Vec::new(),
1210            stats: DuplicationStats {
1211                total_files: 4,
1212                files_with_clones: 4,
1213                total_lines: 100,
1214                duplicated_lines: 20,
1215                total_tokens: 200,
1216                duplicated_tokens: 80,
1217                clone_groups: 2,
1218                clone_instances: 4,
1219                duplication_percentage: 20.0,
1220                clone_groups_below_min_occurrences: 0,
1221                clone_groups_ignored: 0,
1222                near_candidates_skipped: 0,
1223            },
1224        };
1225
1226        let mut changed = FxHashSet::default();
1227        changed.insert(PathBuf::from("/repo/a.ts"));
1228
1229        filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1230
1231        assert_eq!(report.clone_groups.len(), 1);
1232        assert_eq!(report.stats.clone_groups, 1);
1233        assert_eq!(report.stats.clone_instances, 2);
1234    }
1235}