Skip to main content

fallow_engine/
changed_files.rs

1//! Changed-file helpers owned by the engine boundary.
2
3use std::path::{Path, PathBuf};
4use std::process::{Command, Output};
5use std::sync::OnceLock;
6
7use fallow_types::{
8    output_dead_code::{
9        CircularDependencyFinding, DuplicateExportFinding, DuplicatePropShapeFinding,
10        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    command.args(args).current_dir(cwd);
500    command
501}
502
503/// Scope dead-code results to findings affected by changed files.
504///
505/// Dependency-level issues stay unfiltered because whether a dependency is
506/// unused is a graph-global fact, not a changed-file-local fact.
507#[expect(
508    clippy::implicit_hasher,
509    reason = "fallow standardizes on FxHashSet across the workspace"
510)]
511pub fn filter_results_by_changed_files(
512    results: &mut AnalysisResults,
513    changed_files: &FxHashSet<PathBuf>,
514) {
515    let cf = normalize_changed_files_set(changed_files);
516    classify_changed_file_filter_fields(results);
517    retain_basic_issue_findings_by_changed_path(results, &cf);
518    retain_graph_findings_by_changed_files(results, &cf);
519    retain_boundary_policy_and_suppression_findings(results, &cf);
520    retain_security_and_workspace_findings(results, &cf);
521    retain_framework_findings_by_changed_files(results, &cf);
522}
523
524fn classify_changed_file_filter_fields(results: &AnalysisResults) {
525    let AnalysisResults {
526        unused_files: _unused_files,
527        unused_exports: _unused_exports,
528        unused_types: _unused_types,
529        private_type_leaks: _private_type_leaks,
530        unused_dependencies: _unused_dependencies,
531        unused_dev_dependencies: _unused_dev_dependencies,
532        unused_optional_dependencies: _unused_optional_dependencies,
533        unused_enum_members: _unused_enum_members,
534        unused_class_members: _unused_class_members,
535        unused_store_members: _unused_store_members,
536        unresolved_imports: _unresolved_imports,
537        unlisted_dependencies: _unlisted_dependencies,
538        duplicate_exports: _duplicate_exports,
539        type_only_dependencies: _type_only_dependencies,
540        test_only_dependencies: _test_only_dependencies,
541        dev_dependencies_in_production: _dev_dependencies_in_production,
542        circular_dependencies: _circular_dependencies,
543        re_export_cycles: _re_export_cycles,
544        boundary_violations: _boundary_violations,
545        boundary_coverage_violations: _boundary_coverage_violations,
546        boundary_call_violations: _boundary_call_violations,
547        policy_violations: _policy_violations,
548        stale_suppressions: _stale_suppressions,
549        unused_catalog_entries: _unused_catalog_entries,
550        empty_catalog_groups: _empty_catalog_groups,
551        unresolved_catalog_references: _unresolved_catalog_references,
552        unused_dependency_overrides: _unused_dependency_overrides,
553        misconfigured_dependency_overrides: _misconfigured_dependency_overrides,
554        invalid_client_exports: _invalid_client_exports,
555        mixed_client_server_barrels: _mixed_client_server_barrels,
556        misplaced_directives: _misplaced_directives,
557        unprovided_injects: _unprovided_injects,
558        unrendered_components: _unrendered_components,
559        route_collisions: _route_collisions,
560        dynamic_segment_name_conflicts: _dynamic_segment_name_conflicts,
561        unused_component_props: _unused_component_props,
562        unused_component_emits: _unused_component_emits,
563        unused_component_inputs: _unused_component_inputs,
564        unused_component_outputs: _unused_component_outputs,
565        unused_svelte_events: _unused_svelte_events,
566        unused_server_actions: _unused_server_actions,
567        unused_load_data_keys: _unused_load_data_keys,
568        unused_load_data_keys_global_abstain: _unused_load_data_keys_global_abstain,
569        prop_drilling_chains: _prop_drilling_chains,
570        thin_wrappers: _thin_wrappers,
571        duplicate_prop_shapes: _duplicate_prop_shapes,
572        suppression_count: _suppression_count,
573        unused_component_props_exempted: _unused_component_props_exempted,
574        active_suppressions: _active_suppressions,
575        feature_flags: _feature_flags,
576        security_findings: _security_findings,
577        security_unresolved_edge_files: _security_unresolved_edge_files,
578        security_unresolved_callee_sites: _security_unresolved_callee_sites,
579        security_unresolved_callee_diagnostics: _security_unresolved_callee_diagnostics,
580        export_usages: _export_usages,
581        entry_point_summary: _entry_point_summary,
582        render_fan_in: _render_fan_in,
583        react_component_intel: _react_component_intel,
584        semantic_framework_contracts: _semantic_framework_contracts,
585    } = results;
586}
587
588fn retain_basic_issue_findings_by_changed_path(
589    results: &mut AnalysisResults,
590    changed_files: &FxHashSet<PathBuf>,
591) {
592    retain_by_changed_path(&mut results.unused_files, changed_files, |f| &f.file.path);
593    retain_by_changed_path(&mut results.unused_exports, changed_files, |e| {
594        &e.export.path
595    });
596    retain_by_changed_path(&mut results.unused_types, changed_files, |e| &e.export.path);
597    retain_by_changed_path(&mut results.private_type_leaks, changed_files, |e| {
598        &e.leak.path
599    });
600    retain_by_changed_path(&mut results.unused_enum_members, changed_files, |m| {
601        &m.member.path
602    });
603    retain_by_changed_path(&mut results.unused_class_members, changed_files, |m| {
604        &m.member.path
605    });
606    retain_by_changed_path(&mut results.unused_store_members, changed_files, |m| {
607        &m.member.path
608    });
609    retain_by_changed_path(&mut results.unresolved_imports, changed_files, |i| {
610        &i.import.path
611    });
612}
613
614fn retain_graph_findings_by_changed_files(
615    results: &mut AnalysisResults,
616    changed_files: &FxHashSet<PathBuf>,
617) {
618    retain_unlisted_dependencies_by_import_site(&mut results.unlisted_dependencies, changed_files);
619    retain_duplicate_exports_by_changed_locations(&mut results.duplicate_exports, changed_files);
620    retain_circular_dependencies_by_changed_file(&mut results.circular_dependencies, changed_files);
621    retain_re_export_cycles_by_changed_file(&mut results.re_export_cycles, changed_files);
622}
623
624fn retain_boundary_policy_and_suppression_findings(
625    results: &mut AnalysisResults,
626    changed_files: &FxHashSet<PathBuf>,
627) {
628    retain_by_changed_path(&mut results.boundary_violations, changed_files, |v| {
629        &v.violation.from_path
630    });
631    retain_by_changed_path(
632        &mut results.boundary_coverage_violations,
633        changed_files,
634        |v| &v.violation.path,
635    );
636    retain_by_changed_path(&mut results.boundary_call_violations, changed_files, |v| {
637        &v.violation.path
638    });
639    retain_by_changed_path(&mut results.policy_violations, changed_files, |v| {
640        &v.violation.path
641    });
642    retain_by_changed_path(&mut results.stale_suppressions, changed_files, |s| &s.path);
643}
644
645fn retain_security_and_workspace_findings(
646    results: &mut AnalysisResults,
647    changed_files: &FxHashSet<PathBuf>,
648) {
649    retain_security_findings_by_changed_path(&mut results.security_findings, changed_files);
650    retain_by_changed_path(
651        &mut results.security_unresolved_callee_diagnostics,
652        changed_files,
653        |d| &d.path,
654    );
655    retain_by_changed_path(
656        &mut results.unresolved_catalog_references,
657        changed_files,
658        |r| &r.reference.path,
659    );
660    results
661        .empty_catalog_groups
662        .retain(|g| normalized_set_contains_path(changed_files, &g.group.path));
663    retain_by_changed_path(
664        &mut results.unused_dependency_overrides,
665        changed_files,
666        |o| &o.entry.path,
667    );
668    retain_by_changed_path(
669        &mut results.misconfigured_dependency_overrides,
670        changed_files,
671        |o| &o.entry.path,
672    );
673}
674
675fn retain_framework_findings_by_changed_files(
676    results: &mut AnalysisResults,
677    changed_files: &FxHashSet<PathBuf>,
678) {
679    retain_client_boundary_findings_by_changed_files(results, changed_files);
680    retain_component_contract_findings_by_changed_files(results, changed_files);
681    retain_react_health_findings_by_changed_files(results, changed_files);
682    retain_nextjs_findings_by_changed_files(results, changed_files);
683}
684
685fn retain_client_boundary_findings_by_changed_files(
686    results: &mut AnalysisResults,
687    changed_files: &FxHashSet<PathBuf>,
688) {
689    let AnalysisResults {
690        invalid_client_exports,
691        mixed_client_server_barrels,
692        misplaced_directives,
693        ..
694    } = results;
695
696    retain_by_changed_path(invalid_client_exports, changed_files, |e| &e.export.path);
697    retain_by_changed_path(mixed_client_server_barrels, changed_files, |b| {
698        &b.barrel.path
699    });
700    retain_by_changed_path(misplaced_directives, changed_files, |d| {
701        &d.directive_site.path
702    });
703}
704
705fn retain_component_contract_findings_by_changed_files(
706    results: &mut AnalysisResults,
707    changed_files: &FxHashSet<PathBuf>,
708) {
709    let AnalysisResults {
710        unprovided_injects,
711        unrendered_components,
712        unused_component_props,
713        unused_component_emits,
714        unused_component_inputs,
715        unused_component_outputs,
716        unused_svelte_events,
717        unused_server_actions,
718        unused_load_data_keys,
719        ..
720    } = results;
721
722    retain_by_changed_path(unprovided_injects, changed_files, |i| &i.inject.path);
723    retain_by_changed_path(unrendered_components, changed_files, |c| &c.component.path);
724    retain_by_changed_path(unused_component_props, changed_files, |p| &p.prop.path);
725    retain_by_changed_path(unused_component_emits, changed_files, |e| &e.emit.path);
726    retain_by_changed_path(unused_component_inputs, changed_files, |i| &i.input.path);
727    retain_by_changed_path(unused_component_outputs, changed_files, |o| &o.output.path);
728    retain_by_changed_path(unused_svelte_events, changed_files, |e| &e.event.path);
729    retain_by_changed_path(unused_server_actions, changed_files, |a| &a.action.path);
730    retain_by_changed_path(unused_load_data_keys, changed_files, |k| &k.key.path);
731}
732
733fn retain_react_health_findings_by_changed_files(
734    results: &mut AnalysisResults,
735    changed_files: &FxHashSet<PathBuf>,
736) {
737    let AnalysisResults {
738        prop_drilling_chains,
739        thin_wrappers,
740        duplicate_prop_shapes,
741        ..
742    } = results;
743
744    retain_prop_drilling_chains_by_anchor(prop_drilling_chains, changed_files);
745    retain_by_changed_path(thin_wrappers, changed_files, |w| &w.wrapper.file);
746    retain_duplicate_prop_shapes_by_anchor(duplicate_prop_shapes, changed_files);
747}
748
749fn retain_nextjs_findings_by_changed_files(
750    results: &mut AnalysisResults,
751    changed_files: &FxHashSet<PathBuf>,
752) {
753    let AnalysisResults {
754        route_collisions,
755        dynamic_segment_name_conflicts,
756        ..
757    } = results;
758
759    retain_by_changed_path(route_collisions, changed_files, |c| &c.collision.path);
760    retain_by_changed_path(dynamic_segment_name_conflicts, changed_files, |c| {
761        &c.conflict.path
762    });
763}
764
765fn retain_unlisted_dependencies_by_import_site(
766    dependencies: &mut Vec<UnlistedDependencyFinding>,
767    changed_files: &FxHashSet<PathBuf>,
768) {
769    dependencies.retain(|dependency| {
770        dependency
771            .dep
772            .imported_from
773            .iter()
774            .any(|site| contains_normalized(changed_files, &site.path))
775    });
776}
777
778fn retain_duplicate_exports_by_changed_locations(
779    duplicate_exports: &mut Vec<DuplicateExportFinding>,
780    changed_files: &FxHashSet<PathBuf>,
781) {
782    for duplicate in &mut *duplicate_exports {
783        duplicate
784            .export
785            .locations
786            .retain(|location| contains_normalized(changed_files, &location.path));
787    }
788    duplicate_exports.retain(|duplicate| duplicate.export.locations.len() >= 2);
789}
790
791fn retain_circular_dependencies_by_changed_file(
792    cycles: &mut Vec<CircularDependencyFinding>,
793    changed_files: &FxHashSet<PathBuf>,
794) {
795    cycles.retain(|cycle| {
796        cycle
797            .cycle
798            .files
799            .iter()
800            .any(|file| contains_normalized(changed_files, file))
801    });
802}
803
804fn retain_re_export_cycles_by_changed_file(
805    cycles: &mut Vec<ReExportCycleFinding>,
806    changed_files: &FxHashSet<PathBuf>,
807) {
808    cycles.retain(|cycle| {
809        cycle
810            .cycle
811            .files
812            .iter()
813            .any(|file| contains_normalized(changed_files, file))
814    });
815}
816
817fn retain_security_findings_by_changed_path(
818    findings: &mut Vec<SecurityFinding>,
819    changed_files: &FxHashSet<PathBuf>,
820) {
821    findings.retain(|finding| security_finding_touches_changed_path(finding, changed_files));
822}
823
824fn retain_prop_drilling_chains_by_anchor(
825    chains: &mut Vec<PropDrillingChainFinding>,
826    changed_files: &FxHashSet<PathBuf>,
827) {
828    chains.retain(|chain| {
829        chain
830            .chain
831            .hops
832            .first()
833            .is_some_and(|hop| contains_normalized(changed_files, &hop.file))
834    });
835}
836
837fn retain_duplicate_prop_shapes_by_anchor(
838    shapes: &mut Vec<DuplicatePropShapeFinding>,
839    changed_files: &FxHashSet<PathBuf>,
840) {
841    retain_by_changed_path(shapes, changed_files, |shape| &shape.shape.file);
842}
843
844fn retain_by_changed_path<T>(
845    items: &mut Vec<T>,
846    changed_files: &FxHashSet<PathBuf>,
847    path: impl Fn(&T) -> &Path,
848) {
849    items.retain(|item| contains_normalized(changed_files, path(item)));
850}
851
852fn security_finding_touches_changed_path(
853    finding: &SecurityFinding,
854    changed_files: &FxHashSet<PathBuf>,
855) -> bool {
856    contains_normalized(changed_files, &finding.path)
857        || finding
858            .trace
859            .iter()
860            .any(|hop| contains_normalized(changed_files, &hop.path))
861        || finding.reachability.as_ref().is_some_and(|reachability| {
862            reachability
863                .untrusted_source_trace
864                .iter()
865                .any(|hop| contains_normalized(changed_files, &hop.path))
866        })
867}
868
869fn normalize_changed_files_set(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<PathBuf> {
870    changed_files
871        .iter()
872        .map(|p| dunce::simplified(p).to_path_buf())
873        .collect()
874}
875
876fn contains_normalized(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
877    normalized.contains(dunce::simplified(path))
878}
879
880fn normalized_set_contains_path(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
881    contains_normalized(normalized, path)
882        || (path.is_relative() && normalized.iter().any(|changed| changed.ends_with(path)))
883}
884
885/// Scope duplication groups to clone groups touching at least one changed file.
886#[expect(
887    clippy::implicit_hasher,
888    reason = "fallow standardizes on FxHashSet across the workspace"
889)]
890pub fn filter_duplication_by_changed_files(
891    report: &mut DuplicationReport,
892    changed_files: &FxHashSet<PathBuf>,
893    root: &Path,
894) {
895    let cf = normalize_changed_files_set(changed_files);
896    report.clone_groups.retain(|group| {
897        group
898            .instances
899            .iter()
900            .any(|instance| contains_normalized(&cf, &instance.file))
901    });
902    duplicates::refresh_clone_families(report, root);
903    report.stats = duplicates::recompute_stats(report);
904}
905
906#[cfg(test)]
907mod tests {
908    use super::*;
909    use fallow_types::{
910        duplicates::{CloneGroup, CloneInstance, DuplicationStats},
911        output_dead_code::{
912            EmptyCatalogGroupFinding, UnusedDependencyFinding, UnusedExportFinding,
913            UnusedFileFinding,
914        },
915        results::{
916            DependencyLocation, EmptyCatalogGroup, UnusedDependency, UnusedExport, UnusedFile,
917        },
918    };
919
920    #[test]
921    fn validate_git_ref_rejects_option_like_ref() {
922        assert!(validate_git_ref("--upload-pack=evil").is_err());
923        assert!(validate_git_ref("-flag").is_err());
924    }
925
926    #[test]
927    fn validate_git_ref_allows_reflog_relative_date() {
928        assert!(validate_git_ref("HEAD@{1 week ago}").is_ok());
929    }
930
931    #[test]
932    fn git_command_clears_parent_git_environment() {
933        let command = git_command(Path::new("."), &["status"]);
934        let envs: Vec<_> = command.get_envs().collect();
935
936        for var in AMBIENT_GIT_ENV_VARS {
937            assert!(
938                envs.iter()
939                    .any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
940                "{var} should be cleared from the command env",
941            );
942        }
943    }
944
945    #[test]
946    fn try_get_changed_files_not_a_repository() {
947        let temp = tempfile::tempdir().expect("tempdir");
948        let result = try_get_changed_files(temp.path(), "main");
949        assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
950    }
951
952    #[cfg(unix)]
953    #[test]
954    fn changed_files_preserve_special_filenames() {
955        let repo = tempfile::tempdir().expect("tempdir");
956        for args in [
957            &["init", "--quiet"][..],
958            &["config", "user.email", "test@example.com"][..],
959            &["config", "user.name", "Test User"][..],
960            &["config", "commit.gpgsign", "false"][..],
961        ] {
962            run_git(repo.path(), args);
963        }
964        std::fs::write(repo.path().join("initial.ts"), "initial\n").expect("initial fixture");
965        run_git(repo.path(), &["add", "."]);
966        run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
967        run_git(repo.path(), &["tag", "base"]);
968
969        let canonical_root = repo.path().canonicalize().expect("canonical repo");
970        let special_files = [
971            "src/line\nbreak.ts",
972            "src/space name.ts",
973            "src/quote\"name.ts",
974            "src/back\\slash.ts",
975            "src/unicode-λ.ts",
976        ]
977        .map(|path| canonical_root.join(path));
978        std::fs::create_dir_all(canonical_root.join("src")).expect("source dir");
979        for special in &special_files {
980            std::fs::write(special, "changed\n").expect("special fixture");
981        }
982
983        let changed = try_get_changed_files(repo.path(), "base").expect("changed files");
984        for special in special_files {
985            assert!(
986                changed.contains(&special),
987                "missing {special:?}: {changed:?}"
988            );
989        }
990    }
991
992    #[cfg(windows)]
993    #[test]
994    fn git_path_bytes_use_windows_separators() {
995        assert_eq!(
996            git_path_from_bytes(b"src/nested/file.ts"),
997            PathBuf::from(r"src\nested\file.ts")
998        );
999    }
1000
1001    #[test]
1002    fn changed_diff_covers_staged_unstaged_and_untracked_files() {
1003        let repo = tempfile::tempdir().expect("tempdir");
1004        for args in [
1005            &["init", "--quiet"][..],
1006            &["config", "user.email", "test@example.com"][..],
1007            &["config", "user.name", "Test User"][..],
1008            &["config", "commit.gpgsign", "false"][..],
1009        ] {
1010            run_git(repo.path(), args);
1011        }
1012        std::fs::write(repo.path().join("staged.ts"), "old\n").expect("staged fixture");
1013        std::fs::write(repo.path().join("unstaged.ts"), "old\n").expect("unstaged fixture");
1014        run_git(repo.path(), &["add", "."]);
1015        run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
1016        run_git(repo.path(), &["tag", "base"]);
1017
1018        std::fs::write(repo.path().join("committed.ts"), "committed\n").expect("committed fixture");
1019        run_git(repo.path(), &["add", "committed.ts"]);
1020        run_git(
1021            repo.path(),
1022            &["commit", "--quiet", "-m", "committed change"],
1023        );
1024
1025        std::fs::write(repo.path().join("staged.ts"), "staged\n").expect("staged edit");
1026        run_git(repo.path(), &["add", "staged.ts"]);
1027        std::fs::write(repo.path().join("unstaged.ts"), "unstaged\n").expect("unstaged edit");
1028        std::fs::write(repo.path().join("untracked.ts"), "untracked\n").expect("untracked edit");
1029
1030        let diff = try_get_changed_diff(repo.path(), "base").expect("complete changeset diff");
1031        let index = fallow_output::DiffIndex::from_unified_diff(&diff);
1032
1033        assert!(diff.contains("b/committed.ts"), "{diff}");
1034        assert!(diff.contains("b/staged.ts"), "{diff}");
1035        assert!(diff.contains("b/unstaged.ts"), "{diff}");
1036        assert!(diff.contains("b/untracked.ts"), "{diff}");
1037        assert_eq!(index.hunk_count(), 4);
1038        assert_eq!(index.net_lines(), 2);
1039    }
1040
1041    fn run_git(root: &Path, args: &[&str]) {
1042        let output = spawn_output(&mut git_command(root, args)).expect("git command");
1043        assert!(
1044            output.status.success(),
1045            "git {args:?} failed: {}",
1046            String::from_utf8_lossy(&output.stderr)
1047        );
1048    }
1049
1050    #[test]
1051    fn untracked_path_arg_uses_forward_slashes() {
1052        assert_eq!(
1053            super::untracked_path_arg(Path::new("src\\nested\\b.ts")),
1054            "src/nested/b.ts"
1055        );
1056        assert_eq!(super::untracked_path_arg(Path::new("src/b.ts")), "src/b.ts");
1057    }
1058
1059    #[test]
1060    fn changed_files_error_describe_matches_core_contract() {
1061        assert_eq!(
1062            ChangedFilesError::InvalidRef("bad ref".to_string()).describe(),
1063            "invalid git ref: bad ref"
1064        );
1065        assert_eq!(
1066            ChangedFilesError::GitMissing("not found".to_string()).describe(),
1067            "failed to run git: not found"
1068        );
1069        assert_eq!(
1070            ChangedFilesError::NotARepository.describe(),
1071            "not a git repository"
1072        );
1073        assert!(
1074            ChangedFilesError::GitFailed("unknown revision main".to_string())
1075                .describe()
1076                .contains("fetch-depth: 0")
1077        );
1078    }
1079
1080    #[test]
1081    fn filter_results_keeps_only_changed_file_findings() {
1082        let mut results = AnalysisResults::default();
1083        results
1084            .unused_files
1085            .push(UnusedFileFinding::with_actions(UnusedFile {
1086                path: PathBuf::from("/repo/a.ts"),
1087            }));
1088        results
1089            .unused_files
1090            .push(UnusedFileFinding::with_actions(UnusedFile {
1091                path: PathBuf::from("/repo/b.ts"),
1092            }));
1093        results
1094            .unused_exports
1095            .push(UnusedExportFinding::with_actions(UnusedExport {
1096                path: PathBuf::from("/repo/a.ts"),
1097                export_name: "foo".to_owned(),
1098                is_type_only: false,
1099                line: 1,
1100                col: 0,
1101                span_start: 0,
1102                is_re_export: false,
1103            }));
1104
1105        let mut changed = FxHashSet::default();
1106        changed.insert(PathBuf::from("/repo/a.ts"));
1107
1108        filter_results_by_changed_files(&mut results, &changed);
1109
1110        assert_eq!(results.unused_files.len(), 1);
1111        assert_eq!(
1112            results.unused_files[0].file.path,
1113            PathBuf::from("/repo/a.ts")
1114        );
1115        assert_eq!(results.unused_exports.len(), 1);
1116    }
1117
1118    #[test]
1119    fn filter_results_preserves_graph_global_dependency_findings() {
1120        let mut results = AnalysisResults::default();
1121        results
1122            .unused_dependencies
1123            .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1124                package_name: "lodash".to_owned(),
1125                location: DependencyLocation::Dependencies,
1126                path: PathBuf::from("/repo/package.json"),
1127                line: 3,
1128                used_in_workspaces: Vec::new(),
1129            }));
1130
1131        let changed = FxHashSet::default();
1132        filter_results_by_changed_files(&mut results, &changed);
1133
1134        assert_eq!(results.unused_dependencies.len(), 1);
1135    }
1136
1137    #[test]
1138    fn filter_results_keeps_relative_manifest_finding_when_manifest_changed() {
1139        let mut results = AnalysisResults::default();
1140        results
1141            .empty_catalog_groups
1142            .push(EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
1143                catalog_name: "legacy".to_owned(),
1144                path: PathBuf::from("pnpm-workspace.yaml"),
1145                line: 4,
1146            }));
1147
1148        let mut changed = FxHashSet::default();
1149        changed.insert(PathBuf::from("/repo/pnpm-workspace.yaml"));
1150
1151        filter_results_by_changed_files(&mut results, &changed);
1152
1153        assert_eq!(results.empty_catalog_groups.len(), 1);
1154    }
1155
1156    #[test]
1157    fn filter_duplication_keeps_groups_with_changed_instances_and_recomputes_stats() {
1158        let mut report = DuplicationReport {
1159            clone_groups: vec![
1160                CloneGroup {
1161                    instances: vec![
1162                        CloneInstance {
1163                            file: PathBuf::from("/repo/a.ts"),
1164                            start_line: 1,
1165                            end_line: 5,
1166                            start_col: 0,
1167                            end_col: 10,
1168                            fragment: "code".to_owned(),
1169                        },
1170                        CloneInstance {
1171                            file: PathBuf::from("/repo/b.ts"),
1172                            start_line: 1,
1173                            end_line: 5,
1174                            start_col: 0,
1175                            end_col: 10,
1176                            fragment: "code".to_owned(),
1177                        },
1178                    ],
1179                    token_count: 20,
1180                    line_count: 5,
1181                    similarity: None,
1182                },
1183                CloneGroup {
1184                    instances: vec![
1185                        CloneInstance {
1186                            file: PathBuf::from("/repo/c.ts"),
1187                            start_line: 1,
1188                            end_line: 5,
1189                            start_col: 0,
1190                            end_col: 10,
1191                            fragment: "other".to_owned(),
1192                        },
1193                        CloneInstance {
1194                            file: PathBuf::from("/repo/d.ts"),
1195                            start_line: 1,
1196                            end_line: 5,
1197                            start_col: 0,
1198                            end_col: 10,
1199                            fragment: "other".to_owned(),
1200                        },
1201                    ],
1202                    token_count: 20,
1203                    line_count: 5,
1204                    similarity: None,
1205                },
1206            ],
1207            clone_families: Vec::new(),
1208            mirrored_directories: Vec::new(),
1209            stats: DuplicationStats {
1210                total_files: 4,
1211                files_with_clones: 4,
1212                total_lines: 100,
1213                duplicated_lines: 20,
1214                total_tokens: 200,
1215                duplicated_tokens: 80,
1216                clone_groups: 2,
1217                clone_instances: 4,
1218                duplication_percentage: 20.0,
1219                clone_groups_below_min_occurrences: 0,
1220                clone_groups_ignored: 0,
1221                near_candidates_skipped: 0,
1222            },
1223        };
1224
1225        let mut changed = FxHashSet::default();
1226        changed.insert(PathBuf::from("/repo/a.ts"));
1227
1228        filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1229
1230        assert_eq!(report.clone_groups.len(), 1);
1231        assert_eq!(report.stats.clone_groups, 1);
1232        assert_eq!(report.stats.clone_instances, 2);
1233    }
1234}