Skip to main content

fallow_core/
changed_files.rs

1//! Git-aware "changed files" filtering shared between fallow-cli and fallow-lsp.
2//!
3//! Provides:
4//! - [`validate_git_ref`] for input validation at trust boundaries.
5//! - [`ChangedFilesError`] / [`try_get_changed_files`] / [`get_changed_files`]
6//!   for resolving a git ref into the set of changed files.
7//! - [`filter_results_by_changed_files`] for narrowing an [`AnalysisResults`]
8//!   to issues in those files.
9//! - [`filter_duplication_by_changed_files`] for narrowing a
10//!   [`DuplicationReport`] to clone groups touching at least one changed file.
11//!
12//! Both filters intentionally exclude dependency-level issues (unused deps,
13//! type-only deps, test-only deps) since "unused dependency" is a function of
14//! the entire import graph and can't be attributed to individual changed files.
15
16use std::path::{Path, PathBuf};
17
18use rustc_hash::{FxHashMap, FxHashSet};
19
20use crate::duplicates::{DuplicationReport, DuplicationStats, families};
21use crate::results::AnalysisResults;
22
23/// Validate a user-supplied git ref before passing it to `git diff`.
24///
25/// Rejects empty strings, refs starting with `-` (which `git` would interpret
26/// as an option flag), and characters outside the safe allowlist for branch
27/// names, tags, SHAs, and reflog expressions (`HEAD~N`, `HEAD@{...}`).
28///
29/// Inside `@{...}` braces, colons and spaces are allowed so reflog timestamps
30/// like `HEAD@{2025-01-01}` and `HEAD@{1 week ago}` round-trip.
31///
32/// Used by both the CLI (clap value parser) and the LSP (initializationOptions
33/// trust boundary) to fail fast with a readable error rather than handing a
34/// malformed ref to git.
35pub fn validate_git_ref(s: &str) -> Result<&str, String> {
36    if s.is_empty() {
37        return Err("git ref cannot be empty".to_string());
38    }
39    if s.starts_with('-') {
40        return Err("git ref cannot start with '-'".to_string());
41    }
42    let mut in_braces = false;
43    for c in s.chars() {
44        match c {
45            '{' => in_braces = true,
46            '}' => in_braces = false,
47            ':' | ' ' if in_braces => {}
48            c if c.is_ascii_alphanumeric()
49                || matches!(c, '.' | '_' | '-' | '/' | '~' | '^' | '@' | '{' | '}') => {}
50            _ => return Err(format!("git ref contains disallowed character: '{c}'")),
51        }
52    }
53    if in_braces {
54        return Err("git ref has unclosed '{'".to_string());
55    }
56    Ok(s)
57}
58
59/// Classification of a `git diff` failure, so callers can pick their own
60/// wording (soft warning vs hard error) without re-parsing stderr.
61#[derive(Debug)]
62pub enum ChangedFilesError {
63    /// Git ref failed validation before invoking `git`.
64    InvalidRef(String),
65    /// `git` binary not found / not executable.
66    GitMissing(String),
67    /// Command ran but the directory isn't a git repository.
68    NotARepository,
69    /// Command ran but the ref is invalid / another git error.
70    GitFailed(String),
71}
72
73impl ChangedFilesError {
74    /// Human-readable clause suitable for embedding in an error message.
75    /// Does not include the flag name (e.g. "--changed-since") so callers can
76    /// prepend their own context.
77    pub fn describe(&self) -> String {
78        match self {
79            Self::InvalidRef(e) => format!("invalid git ref: {e}"),
80            Self::GitMissing(e) => format!("failed to run git: {e}"),
81            Self::NotARepository => "not a git repository".to_owned(),
82            Self::GitFailed(stderr) => augment_git_failed(stderr),
83        }
84    }
85}
86
87/// Enrich a raw `git diff` stderr with actionable hints when the failure mode
88/// is recognizable. Today: shallow-clone misses (`actions/checkout@v4` defaults
89/// to `fetch-depth: 1`, GitLab CI to `GIT_DEPTH: 50`), where the baseline ref
90/// predates the fetch boundary. Bare git stderr is famously cryptic; a hint
91/// here is much more useful than a docs link the reader has to chase.
92fn augment_git_failed(stderr: &str) -> String {
93    let lower = stderr.to_ascii_lowercase();
94    if lower.contains("not a valid object name")
95        || lower.contains("unknown revision")
96        || lower.contains("ambiguous argument")
97    {
98        format!(
99            "{stderr} (shallow clone? try `git fetch --unshallow`, or set `fetch-depth: 0` on actions/checkout / `GIT_DEPTH: 0` in GitLab CI)"
100        )
101    } else {
102        stderr.to_owned()
103    }
104}
105
106/// Resolve the canonical git toplevel for `cwd`.
107///
108/// Runs `git rev-parse --show-toplevel`, which is git's own answer to "where
109/// does this repository live?". The returned path is canonicalized so it
110/// agrees with paths produced by `fs::canonicalize` elsewhere on macOS
111/// (`/tmp` -> `/private/tmp`) and Windows (8.3 short paths).
112///
113/// Used by `try_get_changed_files` to produce changed-file paths whose
114/// absolute form matches what the analysis pipeline emits, regardless of
115/// whether the caller's `cwd` is the repo root or a subdirectory of it.
116pub fn resolve_git_toplevel(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
117    let output = git_command(cwd, &["rev-parse", "--show-toplevel"])
118        .output()
119        .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
120
121    if !output.status.success() {
122        let stderr = String::from_utf8_lossy(&output.stderr);
123        return Err(if stderr.contains("not a git repository") {
124            ChangedFilesError::NotARepository
125        } else {
126            ChangedFilesError::GitFailed(stderr.trim().to_owned())
127        });
128    }
129
130    let raw = String::from_utf8_lossy(&output.stdout);
131    let trimmed = raw.trim();
132    if trimmed.is_empty() {
133        return Err(ChangedFilesError::GitFailed(
134            "git rev-parse --show-toplevel returned empty output".to_owned(),
135        ));
136    }
137
138    let path = PathBuf::from(trimmed);
139    Ok(path.canonicalize().unwrap_or(path))
140}
141
142fn collect_git_paths(
143    cwd: &Path,
144    toplevel: &Path,
145    args: &[&str],
146) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
147    let output = git_command(cwd, args)
148        .output()
149        .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
150
151    if !output.status.success() {
152        let stderr = String::from_utf8_lossy(&output.stderr);
153        return Err(if stderr.contains("not a git repository") {
154            ChangedFilesError::NotARepository
155        } else {
156            ChangedFilesError::GitFailed(stderr.trim().to_owned())
157        });
158    }
159
160    // All callers use modes whose output is repository-root-relative
161    // (`git diff --name-only`, `git ls-files --full-name --others`). Joining
162    // against `toplevel` yields absolute paths that line up with what
163    // `analyze_project` emits when given a canonical workspace root, even if
164    // the LSP / CLI was invoked from a subdirectory.
165    let files: FxHashSet<PathBuf> = String::from_utf8_lossy(&output.stdout)
166        .lines()
167        .filter(|line| !line.is_empty())
168        .map(|line| toplevel.join(line))
169        .collect();
170
171    Ok(files)
172}
173
174fn git_command(cwd: &Path, args: &[&str]) -> std::process::Command {
175    let mut command = std::process::Command::new("git");
176    command.args(args).current_dir(cwd);
177    crate::git_env::clear_ambient_git_env(&mut command);
178    command
179}
180
181/// Get files changed since a git ref. Returns `Err` (with details) when the
182/// git invocation itself failed, so callers can choose between warn-and-ignore
183/// and hard-error behavior.
184///
185/// Includes both:
186/// - committed changes from the merge-base range `git_ref...HEAD`
187/// - tracked staged/unstaged changes from `HEAD` to the current worktree
188/// - untracked files not ignored by Git
189///
190/// This keeps `--changed-since` useful for local validation instead of only
191/// reflecting the last committed `HEAD`.
192///
193/// All paths in the returned set are absolute and rooted at the canonical
194/// git toplevel, not at `root`. This matters when the LSP / CLI is invoked
195/// from a subdirectory of the repository (e.g., a Turborepo workspace at
196/// `apps/web`): `git diff` emits root-relative paths, and we need to join
197/// them against the actual repo root rather than the caller's cwd.
198pub fn try_get_changed_files(
199    root: &Path,
200    git_ref: &str,
201) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
202    // Validate the ref BEFORE resolving the toplevel so the security-relevant
203    // boundary check (rejects refs starting with `-`, etc.) runs even when
204    // `cwd` happens to not be a git repo. Otherwise an attacker-controlled
205    // `--changed-since=--upload-pack=evil` would leak through to
206    // `git rev-parse` instead of being rejected at validation.
207    validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
208    let toplevel = resolve_git_toplevel(root)?;
209    try_get_changed_files_with_toplevel(root, &toplevel, git_ref)
210}
211
212/// Like [`try_get_changed_files`], but takes a pre-resolved canonical
213/// `toplevel` so callers (the LSP) can cache it across runs and avoid the
214/// extra `git rev-parse --show-toplevel` subprocess on every save.
215///
216/// `toplevel` MUST be the canonical git toplevel for `cwd`; passing anything
217/// else produces incorrect changed-file paths. The CLI does not call this
218/// directly: it uses [`try_get_changed_files`] which resolves on each call.
219pub fn try_get_changed_files_with_toplevel(
220    cwd: &Path,
221    toplevel: &Path,
222    git_ref: &str,
223) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
224    validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
225
226    let mut files = collect_git_paths(
227        cwd,
228        toplevel,
229        &[
230            "diff",
231            "--name-only",
232            "--end-of-options",
233            &format!("{git_ref}...HEAD"),
234        ],
235    )?;
236    files.extend(collect_git_paths(
237        cwd,
238        toplevel,
239        &["diff", "--name-only", "HEAD"],
240    )?);
241    // `--full-name` forces `ls-files` to emit repository-root-relative paths,
242    // matching `git diff`'s default. Without it, `ls-files` emits paths
243    // relative to cwd, which silently produces wrong joins when the caller
244    // invokes from a subdirectory.
245    files.extend(collect_git_paths(
246        cwd,
247        toplevel,
248        &["ls-files", "--full-name", "--others", "--exclude-standard"],
249    )?);
250    Ok(files)
251}
252
253/// Get files changed since a git ref. Returns `None` on git failure after
254/// printing a warning to stderr. Used by `--changed-since` and `--file`, where
255/// a failure falls back to full-scope analysis.
256#[expect(
257    clippy::print_stderr,
258    reason = "intentional user-facing warning for the CLI's --changed-since fallback path; LSP callers use try_get_changed_files instead"
259)]
260pub fn get_changed_files(root: &Path, git_ref: &str) -> Option<FxHashSet<PathBuf>> {
261    match try_get_changed_files(root, git_ref) {
262        Ok(files) => Some(files),
263        Err(ChangedFilesError::InvalidRef(e)) => {
264            eprintln!("Warning: --changed-since ignored: invalid git ref: {e}");
265            None
266        }
267        Err(ChangedFilesError::GitMissing(e)) => {
268            eprintln!("Warning: --changed-since ignored: failed to run git: {e}");
269            None
270        }
271        Err(ChangedFilesError::NotARepository) => {
272            eprintln!("Warning: --changed-since ignored: not a git repository");
273            None
274        }
275        Err(ChangedFilesError::GitFailed(stderr)) => {
276            eprintln!("Warning: --changed-since failed for ref '{git_ref}': {stderr}");
277            None
278        }
279    }
280}
281
282/// Filter `results` to only include issues whose source file is in
283/// `changed_files`.
284///
285/// Dependency-level issues (unused deps, dev deps, optional deps, type-only
286/// deps, test-only deps) are intentionally NOT filtered here. Unlike
287/// file-level issues, a dependency being "unused" is a function of the entire
288/// import graph and can't be attributed to individual changed source files.
289#[expect(
290    clippy::implicit_hasher,
291    reason = "fallow standardizes on FxHashSet across the workspace"
292)]
293pub fn filter_results_by_changed_files(
294    results: &mut AnalysisResults,
295    changed_files: &FxHashSet<PathBuf>,
296) {
297    results
298        .unused_files
299        .retain(|f| changed_files.contains(&f.path));
300    results
301        .unused_exports
302        .retain(|e| changed_files.contains(&e.path));
303    results
304        .unused_types
305        .retain(|e| changed_files.contains(&e.path));
306    results
307        .private_type_leaks
308        .retain(|e| changed_files.contains(&e.path));
309    results
310        .unused_enum_members
311        .retain(|m| changed_files.contains(&m.path));
312    results
313        .unused_class_members
314        .retain(|m| changed_files.contains(&m.path));
315    results
316        .unresolved_imports
317        .retain(|i| changed_files.contains(&i.path));
318
319    // Unlisted deps: keep only if any importing file is changed
320    results.unlisted_dependencies.retain(|d| {
321        d.imported_from
322            .iter()
323            .any(|s| changed_files.contains(&s.path))
324    });
325
326    // Duplicate exports: filter locations to changed files, drop groups with < 2
327    for dup in &mut results.duplicate_exports {
328        dup.locations
329            .retain(|loc| changed_files.contains(&loc.path));
330    }
331    results.duplicate_exports.retain(|d| d.locations.len() >= 2);
332
333    // Circular deps: keep cycles where at least one file is changed
334    results
335        .circular_dependencies
336        .retain(|c| c.files.iter().any(|f| changed_files.contains(f)));
337
338    // Boundary violations: keep if the importing file changed
339    results
340        .boundary_violations
341        .retain(|v| changed_files.contains(&v.from_path));
342
343    // Stale suppressions: keep if the file changed
344    results
345        .stale_suppressions
346        .retain(|s| changed_files.contains(&s.path));
347
348    // Unresolved catalog references: anchored at the consumer package.json,
349    // so keep only findings whose path is in the changed set.
350    results
351        .unresolved_catalog_references
352        .retain(|r| changed_files.contains(&r.path));
353}
354
355/// Recompute duplication statistics after filtering.
356///
357/// Uses per-file line deduplication (matching `compute_stats` in
358/// `duplicates/detect.rs`) so overlapping clone instances don't inflate the
359/// duplicated line count.
360fn recompute_duplication_stats(report: &DuplicationReport) -> DuplicationStats {
361    let mut files_with_clones: FxHashSet<&Path> = FxHashSet::default();
362    let mut file_dup_lines: FxHashMap<&Path, FxHashSet<usize>> = FxHashMap::default();
363    let mut duplicated_tokens = 0_usize;
364    let mut clone_instances = 0_usize;
365
366    for group in &report.clone_groups {
367        for instance in &group.instances {
368            files_with_clones.insert(&instance.file);
369            clone_instances += 1;
370            let lines = file_dup_lines.entry(&instance.file).or_default();
371            for line in instance.start_line..=instance.end_line {
372                lines.insert(line);
373            }
374        }
375        duplicated_tokens += group.token_count * group.instances.len();
376    }
377
378    let duplicated_lines: usize = file_dup_lines.values().map(FxHashSet::len).sum();
379
380    DuplicationStats {
381        total_files: report.stats.total_files,
382        files_with_clones: files_with_clones.len(),
383        total_lines: report.stats.total_lines,
384        duplicated_lines,
385        total_tokens: report.stats.total_tokens,
386        duplicated_tokens,
387        clone_groups: report.clone_groups.len(),
388        clone_instances,
389        #[expect(
390            clippy::cast_precision_loss,
391            reason = "stat percentages are display-only; precision loss at usize::MAX line counts is acceptable"
392        )]
393        duplication_percentage: if report.stats.total_lines > 0 {
394            (duplicated_lines as f64 / report.stats.total_lines as f64) * 100.0
395        } else {
396            0.0
397        },
398    }
399}
400
401/// Filter a duplication report to only retain clone groups where at least one
402/// instance belongs to a changed file. Families, mirrored directories, and
403/// stats are rebuilt from the surviving groups so consumers see consistent,
404/// correctly-scoped numbers.
405#[expect(
406    clippy::implicit_hasher,
407    reason = "fallow standardizes on FxHashSet across the workspace"
408)]
409pub fn filter_duplication_by_changed_files(
410    report: &mut DuplicationReport,
411    changed_files: &FxHashSet<PathBuf>,
412    root: &Path,
413) {
414    report
415        .clone_groups
416        .retain(|g| g.instances.iter().any(|i| changed_files.contains(&i.file)));
417    report.clone_families = families::group_into_families(&report.clone_groups, root);
418    report.mirrored_directories =
419        families::detect_mirrored_directories(&report.clone_families, root);
420    report.stats = recompute_duplication_stats(report);
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426    use crate::duplicates::{CloneGroup, CloneInstance};
427    use crate::results::{BoundaryViolation, CircularDependency, UnusedExport, UnusedFile};
428
429    #[test]
430    fn changed_files_error_describe_variants() {
431        assert!(
432            ChangedFilesError::InvalidRef("bad".to_owned())
433                .describe()
434                .contains("invalid git ref")
435        );
436        assert!(
437            ChangedFilesError::GitMissing("oops".to_owned())
438                .describe()
439                .contains("oops")
440        );
441        assert_eq!(
442            ChangedFilesError::NotARepository.describe(),
443            "not a git repository"
444        );
445        assert!(
446            ChangedFilesError::GitFailed("bad ref".to_owned())
447                .describe()
448                .contains("bad ref")
449        );
450    }
451
452    #[test]
453    fn augment_git_failed_appends_shallow_clone_hint_for_unknown_revision() {
454        let stderr = "fatal: ambiguous argument 'fallow-baseline...HEAD': unknown revision or path not in the working tree.";
455        let described = ChangedFilesError::GitFailed(stderr.to_owned()).describe();
456        assert!(described.contains(stderr), "original stderr preserved");
457        assert!(
458            described.contains("shallow clone"),
459            "hint surfaced: {described}"
460        );
461        assert!(
462            described.contains("fetch-depth: 0") || described.contains("git fetch --unshallow"),
463            "hint actionable: {described}"
464        );
465    }
466
467    #[test]
468    fn augment_git_failed_passthrough_for_other_errors() {
469        // Errors that aren't shallow-clone-related stay verbatim
470        let stderr = "fatal: refusing to merge unrelated histories";
471        let described = ChangedFilesError::GitFailed(stderr.to_owned()).describe();
472        assert_eq!(described, stderr);
473    }
474
475    #[test]
476    fn validate_git_ref_rejects_leading_dash() {
477        assert!(validate_git_ref("--upload-pack=evil").is_err());
478        assert!(validate_git_ref("-flag").is_err());
479    }
480
481    #[test]
482    fn validate_git_ref_accepts_baseline_tag() {
483        assert_eq!(
484            validate_git_ref("fallow-baseline").unwrap(),
485            "fallow-baseline"
486        );
487    }
488
489    #[test]
490    fn try_get_changed_files_rejects_invalid_ref() {
491        // Validation runs before git invocation, so any path will do
492        let err = try_get_changed_files(Path::new("/"), "--evil")
493            .expect_err("leading-dash ref must be rejected");
494        assert!(matches!(err, ChangedFilesError::InvalidRef(_)));
495        assert!(err.describe().contains("cannot start with"));
496    }
497
498    #[test]
499    fn validate_git_ref_rejects_option_like_ref() {
500        assert!(validate_git_ref("--output=/tmp/fallow-proof").is_err());
501    }
502
503    #[test]
504    fn validate_git_ref_allows_reflog_relative_date() {
505        assert!(validate_git_ref("HEAD@{1 week ago}").is_ok());
506    }
507
508    #[test]
509    fn try_get_changed_files_rejects_option_like_ref_before_git() {
510        let root = tempfile::tempdir().expect("create temp dir");
511        let proof_path = root.path().join("proof");
512
513        let result = try_get_changed_files(
514            root.path(),
515            &format!("--output={}", proof_path.to_string_lossy()),
516        );
517
518        assert!(matches!(result, Err(ChangedFilesError::InvalidRef(_))));
519        assert!(
520            !proof_path.exists(),
521            "invalid changedSince ref must not be passed through to git as an option"
522        );
523    }
524
525    #[test]
526    fn git_command_clears_parent_git_environment() {
527        let command = git_command(Path::new("."), &["status", "--short"]);
528        let overrides: Vec<_> = command.get_envs().collect();
529
530        for var in crate::git_env::AMBIENT_GIT_ENV_VARS {
531            assert!(
532                overrides
533                    .iter()
534                    .any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
535                "git helper must clear inherited {var}",
536            );
537        }
538    }
539
540    #[test]
541    fn filter_results_keeps_only_changed_files() {
542        let mut results = AnalysisResults::default();
543        results.unused_files.push(UnusedFile {
544            path: "/a.ts".into(),
545        });
546        results.unused_files.push(UnusedFile {
547            path: "/b.ts".into(),
548        });
549        results.unused_exports.push(UnusedExport {
550            path: "/a.ts".into(),
551            export_name: "foo".into(),
552            is_type_only: false,
553            line: 1,
554            col: 0,
555            span_start: 0,
556            is_re_export: false,
557        });
558
559        let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
560        changed.insert("/a.ts".into());
561
562        filter_results_by_changed_files(&mut results, &changed);
563
564        assert_eq!(results.unused_files.len(), 1);
565        assert_eq!(results.unused_files[0].path, PathBuf::from("/a.ts"));
566        assert_eq!(results.unused_exports.len(), 1);
567    }
568
569    #[test]
570    fn filter_results_preserves_dependency_level_issues() {
571        let mut results = AnalysisResults::default();
572        results
573            .unused_dependencies
574            .push(crate::results::UnusedDependency {
575                package_name: "lodash".into(),
576                location: crate::results::DependencyLocation::Dependencies,
577                path: "/pkg.json".into(),
578                line: 3,
579                used_in_workspaces: Vec::new(),
580            });
581
582        let changed: FxHashSet<PathBuf> = FxHashSet::default();
583        filter_results_by_changed_files(&mut results, &changed);
584
585        // Dependency-level issues survive even when no source files changed
586        assert_eq!(results.unused_dependencies.len(), 1);
587    }
588
589    #[test]
590    fn filter_results_keeps_circular_dep_when_any_file_changed() {
591        let mut results = AnalysisResults::default();
592        results.circular_dependencies.push(CircularDependency {
593            files: vec!["/a.ts".into(), "/b.ts".into()],
594            length: 2,
595            line: 1,
596            col: 0,
597            is_cross_package: false,
598        });
599
600        let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
601        changed.insert("/b.ts".into());
602
603        filter_results_by_changed_files(&mut results, &changed);
604        assert_eq!(results.circular_dependencies.len(), 1);
605    }
606
607    #[test]
608    fn filter_results_drops_circular_dep_when_no_file_changed() {
609        let mut results = AnalysisResults::default();
610        results.circular_dependencies.push(CircularDependency {
611            files: vec!["/a.ts".into(), "/b.ts".into()],
612            length: 2,
613            line: 1,
614            col: 0,
615            is_cross_package: false,
616        });
617
618        let changed: FxHashSet<PathBuf> = FxHashSet::default();
619        filter_results_by_changed_files(&mut results, &changed);
620        assert!(results.circular_dependencies.is_empty());
621    }
622
623    #[test]
624    fn filter_results_drops_boundary_violation_when_importer_unchanged() {
625        let mut results = AnalysisResults::default();
626        results.boundary_violations.push(BoundaryViolation {
627            from_path: "/a.ts".into(),
628            to_path: "/b.ts".into(),
629            from_zone: "ui".into(),
630            to_zone: "data".into(),
631            import_specifier: "../data/db".into(),
632            line: 1,
633            col: 0,
634        });
635
636        let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
637        // only the imported file changed, not the importer
638        changed.insert("/b.ts".into());
639
640        filter_results_by_changed_files(&mut results, &changed);
641        assert!(results.boundary_violations.is_empty());
642    }
643
644    #[test]
645    fn filter_duplication_keeps_groups_with_at_least_one_changed_instance() {
646        let mut report = DuplicationReport {
647            clone_groups: vec![CloneGroup {
648                instances: vec![
649                    CloneInstance {
650                        file: "/a.ts".into(),
651                        start_line: 1,
652                        end_line: 5,
653                        start_col: 0,
654                        end_col: 10,
655                        fragment: "code".into(),
656                    },
657                    CloneInstance {
658                        file: "/b.ts".into(),
659                        start_line: 1,
660                        end_line: 5,
661                        start_col: 0,
662                        end_col: 10,
663                        fragment: "code".into(),
664                    },
665                ],
666                token_count: 20,
667                line_count: 5,
668            }],
669            clone_families: vec![],
670            mirrored_directories: vec![],
671            stats: DuplicationStats {
672                total_files: 2,
673                files_with_clones: 2,
674                total_lines: 100,
675                duplicated_lines: 10,
676                total_tokens: 200,
677                duplicated_tokens: 40,
678                clone_groups: 1,
679                clone_instances: 2,
680                duplication_percentage: 10.0,
681            },
682        };
683
684        let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
685        changed.insert("/a.ts".into());
686
687        filter_duplication_by_changed_files(&mut report, &changed, Path::new(""));
688        assert_eq!(report.clone_groups.len(), 1);
689        // stats recomputed from surviving groups
690        assert_eq!(report.stats.clone_groups, 1);
691        assert_eq!(report.stats.clone_instances, 2);
692    }
693
694    // -----------------------------------------------------------------------
695    // Real git interactions (tempdir + git init). These exercise the
696    // path-resolution boundary between `git rev-parse --show-toplevel`,
697    // `git diff --name-only`, and `git ls-files --full-name --others` to
698    // catch regressions like issue #190 where the LSP workspace was a
699    // subdirectory of the git repo and changed-file paths were joined
700    // against the wrong base.
701    // -----------------------------------------------------------------------
702
703    /// Initialize a temp git repo with a single committed file plus a tag
704    /// at HEAD. Returns the canonical repo root.
705    fn init_repo(repo: &Path) -> PathBuf {
706        run_git(repo, &["init", "--quiet", "--initial-branch=main"]);
707        run_git(repo, &["config", "user.email", "test@example.com"]);
708        run_git(repo, &["config", "user.name", "test"]);
709        run_git(repo, &["config", "commit.gpgsign", "false"]);
710        std::fs::write(repo.join("seed.txt"), "seed\n").unwrap();
711        run_git(repo, &["add", "seed.txt"]);
712        run_git(repo, &["commit", "--quiet", "-m", "initial"]);
713        run_git(repo, &["tag", "fallow-baseline"]);
714        repo.canonicalize().unwrap()
715    }
716
717    fn run_git(cwd: &Path, args: &[&str]) {
718        let output = std::process::Command::new("git")
719            .args(args)
720            .current_dir(cwd)
721            .output()
722            .expect("git available");
723        assert!(
724            output.status.success(),
725            "git {args:?} failed: {}",
726            String::from_utf8_lossy(&output.stderr)
727        );
728    }
729
730    /// Workspace at git root, an untracked file is included in the
731    /// changed-files set with an absolute path joined from the repo root.
732    #[test]
733    fn try_get_changed_files_workspace_at_repo_root() {
734        let tmp = tempfile::tempdir().unwrap();
735        let repo = init_repo(tmp.path());
736        std::fs::create_dir_all(repo.join("src")).unwrap();
737        std::fs::write(repo.join("src/new.ts"), "export const x = 1;\n").unwrap();
738
739        let changed = try_get_changed_files(&repo, "fallow-baseline").unwrap();
740
741        let expected = repo.join("src/new.ts");
742        assert!(
743            changed.contains(&expected),
744            "changed set should contain {expected:?}; actual: {changed:?}"
745        );
746    }
747
748    /// Regression test for #190. When the workspace is a subdirectory of
749    /// the git repository, `git diff --name-only` emits paths relative to
750    /// the repo root (e.g., `frontend/src/new.ts`). Without the
751    /// rev-parse-based toplevel resolution the function joined those
752    /// against the workspace root, producing bogus paths like
753    /// `<repo>/frontend/frontend/src/new.ts` that never matched
754    /// `analyze_project` output and silently dropped the filter.
755    #[test]
756    fn try_get_changed_files_workspace_in_subdirectory() {
757        let tmp = tempfile::tempdir().unwrap();
758        let repo = init_repo(tmp.path());
759        let frontend = repo.join("frontend");
760        std::fs::create_dir_all(frontend.join("src")).unwrap();
761        std::fs::write(frontend.join("src/new.ts"), "export const x = 1;\n").unwrap();
762
763        let changed = try_get_changed_files(&frontend, "fallow-baseline").unwrap();
764
765        let expected = repo.join("frontend/src/new.ts");
766        assert!(
767            changed.contains(&expected),
768            "changed set should contain canonical {expected:?}; actual: {changed:?}"
769        );
770        // Verify the bogus double-frontend path is NOT in the set
771        let bogus = frontend.join("frontend/src/new.ts");
772        assert!(
773            !changed.contains(&bogus),
774            "changed set must not contain double-frontend path {bogus:?}"
775        );
776    }
777
778    /// A *committed* change in a sibling subdirectory (outside the
779    /// workspace) appears in the changed-files set because `git diff`
780    /// is repo-wide regardless of cwd. The downstream
781    /// `filter_results_by_changed_files` retains it only if
782    /// `analyze_project` saw it; for a workspace scoped to one subdir,
783    /// the sibling file is not in the analysis paths and falls away at
784    /// the result-merge boundary, not here. This test pins the contract:
785    /// for committed changes, the set is repo-wide.
786    ///
787    /// Note: `git ls-files --others --exclude-standard` only lists
788    /// untracked files in cwd's subtree, so untracked siblings are NOT
789    /// in the set when invoked from a subdirectory. That's harmless for
790    /// the LSP because `analyze_project` only walks files under the
791    /// workspace root either way.
792    #[test]
793    fn try_get_changed_files_includes_committed_sibling_changes() {
794        let tmp = tempfile::tempdir().unwrap();
795        let repo = init_repo(tmp.path());
796        let backend = repo.join("backend");
797        std::fs::create_dir_all(&backend).unwrap();
798        std::fs::write(backend.join("server.py"), "print('hi')\n").unwrap();
799        run_git(&repo, &["add", "."]);
800        run_git(&repo, &["commit", "--quiet", "-m", "add backend"]);
801
802        let frontend = repo.join("frontend");
803        std::fs::create_dir_all(&frontend).unwrap();
804
805        let changed = try_get_changed_files(&frontend, "fallow-baseline").unwrap();
806
807        let expected = repo.join("backend/server.py");
808        assert!(
809            changed.contains(&expected),
810            "committed sibling backend/server.py should be in the set: {changed:?}"
811        );
812    }
813
814    /// Modifying a tracked file shows up via `git diff --name-only HEAD`,
815    /// not just via `ls-files --others`. Confirm the path-join fix
816    /// applies to that codepath too.
817    #[test]
818    fn try_get_changed_files_includes_modified_tracked_file() {
819        let tmp = tempfile::tempdir().unwrap();
820        let repo = init_repo(tmp.path());
821        let frontend = repo.join("frontend");
822        std::fs::create_dir_all(frontend.join("src")).unwrap();
823        std::fs::write(frontend.join("src/old.ts"), "export const x = 1;\n").unwrap();
824        run_git(&repo, &["add", "."]);
825        run_git(&repo, &["commit", "--quiet", "-m", "add old"]);
826        run_git(&repo, &["tag", "fallow-baseline-v2"]);
827        // Modify the tracked file (no commit, so diff-HEAD picks it up)
828        std::fs::write(frontend.join("src/old.ts"), "export const x = 2;\n").unwrap();
829
830        let changed = try_get_changed_files(&frontend, "fallow-baseline-v2").unwrap();
831
832        let expected = repo.join("frontend/src/old.ts");
833        assert!(
834            changed.contains(&expected),
835            "modified tracked file {expected:?} missing from set: {changed:?}"
836        );
837    }
838
839    /// `resolve_git_toplevel` returns the canonical repo path even when
840    /// invoked from inside a subdirectory and via a symlinked input path.
841    /// On macOS this guards against the `/tmp` -> `/private/tmp`
842    /// canonicalization gap that would otherwise make the LSP filter set
843    /// disagree with `analyze_project` paths.
844    #[test]
845    fn resolve_git_toplevel_returns_canonical_path() {
846        let tmp = tempfile::tempdir().unwrap();
847        let repo = init_repo(tmp.path());
848        let frontend = repo.join("frontend");
849        std::fs::create_dir_all(&frontend).unwrap();
850
851        let toplevel = resolve_git_toplevel(&frontend).unwrap();
852        assert_eq!(toplevel, repo, "toplevel should equal canonical repo root");
853        assert_eq!(
854            toplevel,
855            toplevel.canonicalize().unwrap(),
856            "resolved toplevel should already be canonical"
857        );
858    }
859
860    /// Outside any git repo, `resolve_git_toplevel` returns
861    /// `NotARepository` rather than panicking or returning a wrong path.
862    /// The LSP relies on this to fall back to the workspace root cleanly.
863    #[test]
864    fn resolve_git_toplevel_not_a_repository() {
865        let tmp = tempfile::tempdir().unwrap();
866        let result = resolve_git_toplevel(tmp.path());
867        assert!(
868            matches!(result, Err(ChangedFilesError::NotARepository)),
869            "expected NotARepository, got {result:?}"
870        );
871    }
872
873    /// `try_get_changed_files` propagates the not-a-repo error so the
874    /// LSP can warn and fall back to full-scope results.
875    #[test]
876    fn try_get_changed_files_not_a_repository() {
877        let tmp = tempfile::tempdir().unwrap();
878        let result = try_get_changed_files(tmp.path(), "main");
879        assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
880    }
881
882    #[test]
883    fn filter_duplication_drops_groups_with_no_changed_instance() {
884        let mut report = DuplicationReport {
885            clone_groups: vec![CloneGroup {
886                instances: vec![CloneInstance {
887                    file: "/a.ts".into(),
888                    start_line: 1,
889                    end_line: 5,
890                    start_col: 0,
891                    end_col: 10,
892                    fragment: "code".into(),
893                }],
894                token_count: 20,
895                line_count: 5,
896            }],
897            clone_families: vec![],
898            mirrored_directories: vec![],
899            stats: DuplicationStats {
900                total_files: 1,
901                files_with_clones: 1,
902                total_lines: 100,
903                duplicated_lines: 5,
904                total_tokens: 100,
905                duplicated_tokens: 20,
906                clone_groups: 1,
907                clone_instances: 1,
908                duplication_percentage: 5.0,
909            },
910        };
911
912        let changed: FxHashSet<PathBuf> = FxHashSet::default();
913        filter_duplication_by_changed_files(&mut report, &changed, Path::new(""));
914        assert!(report.clone_groups.is_empty());
915        assert_eq!(report.stats.clone_groups, 0);
916        assert_eq!(report.stats.clone_instances, 0);
917        assert!((report.stats.duplication_percentage - 0.0).abs() < f64::EPSILON);
918    }
919}