1use std::path::{Path, PathBuf};
17
18use rustc_hash::{FxHashMap, FxHashSet};
19
20use crate::duplicates::{DuplicationReport, DuplicationStats, families};
21use crate::results::AnalysisResults;
22
23pub 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#[derive(Debug)]
62pub enum ChangedFilesError {
63 InvalidRef(String),
65 GitMissing(String),
67 NotARepository,
69 GitFailed(String),
71}
72
73impl ChangedFilesError {
74 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
87fn 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
106pub 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 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
181pub fn try_get_changed_files(
199 root: &Path,
200 git_ref: &str,
201) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
202 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
212pub 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 files.extend(collect_git_paths(
246 cwd,
247 toplevel,
248 &["ls-files", "--full-name", "--others", "--exclude-standard"],
249 )?);
250 Ok(files)
251}
252
253#[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#[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 results.unlisted_dependencies.retain(|d| {
321 d.imported_from
322 .iter()
323 .any(|s| changed_files.contains(&s.path))
324 });
325
326 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 results
335 .circular_dependencies
336 .retain(|c| c.files.iter().any(|f| changed_files.contains(f)));
337
338 results
340 .boundary_violations
341 .retain(|v| changed_files.contains(&v.from_path));
342
343 results
345 .stale_suppressions
346 .retain(|s| changed_files.contains(&s.path));
347
348 results
351 .unresolved_catalog_references
352 .retain(|r| changed_files.contains(&r.path));
353
354 results
358 .unused_dependency_overrides
359 .retain(|o| changed_files.contains(&o.path));
360 results
361 .misconfigured_dependency_overrides
362 .retain(|o| changed_files.contains(&o.path));
363}
364
365fn recompute_duplication_stats(report: &DuplicationReport) -> DuplicationStats {
371 let mut files_with_clones: FxHashSet<&Path> = FxHashSet::default();
372 let mut file_dup_lines: FxHashMap<&Path, FxHashSet<usize>> = FxHashMap::default();
373 let mut duplicated_tokens = 0_usize;
374 let mut clone_instances = 0_usize;
375
376 for group in &report.clone_groups {
377 for instance in &group.instances {
378 files_with_clones.insert(&instance.file);
379 clone_instances += 1;
380 let lines = file_dup_lines.entry(&instance.file).or_default();
381 for line in instance.start_line..=instance.end_line {
382 lines.insert(line);
383 }
384 }
385 duplicated_tokens += group.token_count * group.instances.len();
386 }
387
388 let duplicated_lines: usize = file_dup_lines.values().map(FxHashSet::len).sum();
389
390 DuplicationStats {
391 total_files: report.stats.total_files,
392 files_with_clones: files_with_clones.len(),
393 total_lines: report.stats.total_lines,
394 duplicated_lines,
395 total_tokens: report.stats.total_tokens,
396 duplicated_tokens,
397 clone_groups: report.clone_groups.len(),
398 clone_instances,
399 #[expect(
400 clippy::cast_precision_loss,
401 reason = "stat percentages are display-only; precision loss at usize::MAX line counts is acceptable"
402 )]
403 duplication_percentage: if report.stats.total_lines > 0 {
404 (duplicated_lines as f64 / report.stats.total_lines as f64) * 100.0
405 } else {
406 0.0
407 },
408 clone_groups_below_min_occurrences: report.stats.clone_groups_below_min_occurrences,
409 }
410}
411
412#[expect(
417 clippy::implicit_hasher,
418 reason = "fallow standardizes on FxHashSet across the workspace"
419)]
420pub fn filter_duplication_by_changed_files(
421 report: &mut DuplicationReport,
422 changed_files: &FxHashSet<PathBuf>,
423 root: &Path,
424) {
425 report
426 .clone_groups
427 .retain(|g| g.instances.iter().any(|i| changed_files.contains(&i.file)));
428 report.clone_families = families::group_into_families(&report.clone_groups, root);
429 report.mirrored_directories =
430 families::detect_mirrored_directories(&report.clone_families, root);
431 report.stats = recompute_duplication_stats(report);
432}
433
434#[cfg(test)]
435mod tests {
436 use super::*;
437 use crate::duplicates::{CloneGroup, CloneInstance};
438 use crate::results::{BoundaryViolation, CircularDependency, UnusedExport, UnusedFile};
439
440 #[test]
441 fn changed_files_error_describe_variants() {
442 assert!(
443 ChangedFilesError::InvalidRef("bad".to_owned())
444 .describe()
445 .contains("invalid git ref")
446 );
447 assert!(
448 ChangedFilesError::GitMissing("oops".to_owned())
449 .describe()
450 .contains("oops")
451 );
452 assert_eq!(
453 ChangedFilesError::NotARepository.describe(),
454 "not a git repository"
455 );
456 assert!(
457 ChangedFilesError::GitFailed("bad ref".to_owned())
458 .describe()
459 .contains("bad ref")
460 );
461 }
462
463 #[test]
464 fn augment_git_failed_appends_shallow_clone_hint_for_unknown_revision() {
465 let stderr = "fatal: ambiguous argument 'fallow-baseline...HEAD': unknown revision or path not in the working tree.";
466 let described = ChangedFilesError::GitFailed(stderr.to_owned()).describe();
467 assert!(described.contains(stderr), "original stderr preserved");
468 assert!(
469 described.contains("shallow clone"),
470 "hint surfaced: {described}"
471 );
472 assert!(
473 described.contains("fetch-depth: 0") || described.contains("git fetch --unshallow"),
474 "hint actionable: {described}"
475 );
476 }
477
478 #[test]
479 fn augment_git_failed_passthrough_for_other_errors() {
480 let stderr = "fatal: refusing to merge unrelated histories";
482 let described = ChangedFilesError::GitFailed(stderr.to_owned()).describe();
483 assert_eq!(described, stderr);
484 }
485
486 #[test]
487 fn validate_git_ref_rejects_leading_dash() {
488 assert!(validate_git_ref("--upload-pack=evil").is_err());
489 assert!(validate_git_ref("-flag").is_err());
490 }
491
492 #[test]
493 fn validate_git_ref_accepts_baseline_tag() {
494 assert_eq!(
495 validate_git_ref("fallow-baseline").unwrap(),
496 "fallow-baseline"
497 );
498 }
499
500 #[test]
501 fn try_get_changed_files_rejects_invalid_ref() {
502 let err = try_get_changed_files(Path::new("/"), "--evil")
504 .expect_err("leading-dash ref must be rejected");
505 assert!(matches!(err, ChangedFilesError::InvalidRef(_)));
506 assert!(err.describe().contains("cannot start with"));
507 }
508
509 #[test]
510 fn validate_git_ref_rejects_option_like_ref() {
511 assert!(validate_git_ref("--output=/tmp/fallow-proof").is_err());
512 }
513
514 #[test]
515 fn validate_git_ref_allows_reflog_relative_date() {
516 assert!(validate_git_ref("HEAD@{1 week ago}").is_ok());
517 }
518
519 #[test]
520 fn try_get_changed_files_rejects_option_like_ref_before_git() {
521 let root = tempfile::tempdir().expect("create temp dir");
522 let proof_path = root.path().join("proof");
523
524 let result = try_get_changed_files(
525 root.path(),
526 &format!("--output={}", proof_path.to_string_lossy()),
527 );
528
529 assert!(matches!(result, Err(ChangedFilesError::InvalidRef(_))));
530 assert!(
531 !proof_path.exists(),
532 "invalid changedSince ref must not be passed through to git as an option"
533 );
534 }
535
536 #[test]
537 fn git_command_clears_parent_git_environment() {
538 let command = git_command(Path::new("."), &["status", "--short"]);
539 let overrides: Vec<_> = command.get_envs().collect();
540
541 for var in crate::git_env::AMBIENT_GIT_ENV_VARS {
542 assert!(
543 overrides
544 .iter()
545 .any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
546 "git helper must clear inherited {var}",
547 );
548 }
549 }
550
551 #[test]
552 fn filter_results_keeps_only_changed_files() {
553 let mut results = AnalysisResults::default();
554 results.unused_files.push(UnusedFile {
555 path: "/a.ts".into(),
556 });
557 results.unused_files.push(UnusedFile {
558 path: "/b.ts".into(),
559 });
560 results.unused_exports.push(UnusedExport {
561 path: "/a.ts".into(),
562 export_name: "foo".into(),
563 is_type_only: false,
564 line: 1,
565 col: 0,
566 span_start: 0,
567 is_re_export: false,
568 });
569
570 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
571 changed.insert("/a.ts".into());
572
573 filter_results_by_changed_files(&mut results, &changed);
574
575 assert_eq!(results.unused_files.len(), 1);
576 assert_eq!(results.unused_files[0].path, PathBuf::from("/a.ts"));
577 assert_eq!(results.unused_exports.len(), 1);
578 }
579
580 #[test]
581 fn filter_results_preserves_dependency_level_issues() {
582 let mut results = AnalysisResults::default();
583 results
584 .unused_dependencies
585 .push(crate::results::UnusedDependency {
586 package_name: "lodash".into(),
587 location: crate::results::DependencyLocation::Dependencies,
588 path: "/pkg.json".into(),
589 line: 3,
590 used_in_workspaces: Vec::new(),
591 });
592
593 let changed: FxHashSet<PathBuf> = FxHashSet::default();
594 filter_results_by_changed_files(&mut results, &changed);
595
596 assert_eq!(results.unused_dependencies.len(), 1);
598 }
599
600 #[test]
601 fn filter_results_keeps_circular_dep_when_any_file_changed() {
602 let mut results = AnalysisResults::default();
603 results.circular_dependencies.push(CircularDependency {
604 files: vec!["/a.ts".into(), "/b.ts".into()],
605 length: 2,
606 line: 1,
607 col: 0,
608 is_cross_package: false,
609 });
610
611 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
612 changed.insert("/b.ts".into());
613
614 filter_results_by_changed_files(&mut results, &changed);
615 assert_eq!(results.circular_dependencies.len(), 1);
616 }
617
618 #[test]
619 fn filter_results_drops_circular_dep_when_no_file_changed() {
620 let mut results = AnalysisResults::default();
621 results.circular_dependencies.push(CircularDependency {
622 files: vec!["/a.ts".into(), "/b.ts".into()],
623 length: 2,
624 line: 1,
625 col: 0,
626 is_cross_package: false,
627 });
628
629 let changed: FxHashSet<PathBuf> = FxHashSet::default();
630 filter_results_by_changed_files(&mut results, &changed);
631 assert!(results.circular_dependencies.is_empty());
632 }
633
634 #[test]
635 fn filter_results_drops_boundary_violation_when_importer_unchanged() {
636 let mut results = AnalysisResults::default();
637 results.boundary_violations.push(BoundaryViolation {
638 from_path: "/a.ts".into(),
639 to_path: "/b.ts".into(),
640 from_zone: "ui".into(),
641 to_zone: "data".into(),
642 import_specifier: "../data/db".into(),
643 line: 1,
644 col: 0,
645 });
646
647 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
648 changed.insert("/b.ts".into());
650
651 filter_results_by_changed_files(&mut results, &changed);
652 assert!(results.boundary_violations.is_empty());
653 }
654
655 #[test]
656 fn filter_duplication_keeps_groups_with_at_least_one_changed_instance() {
657 let mut report = DuplicationReport {
658 clone_groups: vec![CloneGroup {
659 instances: vec![
660 CloneInstance {
661 file: "/a.ts".into(),
662 start_line: 1,
663 end_line: 5,
664 start_col: 0,
665 end_col: 10,
666 fragment: "code".into(),
667 },
668 CloneInstance {
669 file: "/b.ts".into(),
670 start_line: 1,
671 end_line: 5,
672 start_col: 0,
673 end_col: 10,
674 fragment: "code".into(),
675 },
676 ],
677 token_count: 20,
678 line_count: 5,
679 }],
680 clone_families: vec![],
681 mirrored_directories: vec![],
682 stats: DuplicationStats {
683 total_files: 2,
684 files_with_clones: 2,
685 total_lines: 100,
686 duplicated_lines: 10,
687 total_tokens: 200,
688 duplicated_tokens: 40,
689 clone_groups: 1,
690 clone_instances: 2,
691 duplication_percentage: 10.0,
692 clone_groups_below_min_occurrences: 0,
693 },
694 };
695
696 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
697 changed.insert("/a.ts".into());
698
699 filter_duplication_by_changed_files(&mut report, &changed, Path::new(""));
700 assert_eq!(report.clone_groups.len(), 1);
701 assert_eq!(report.stats.clone_groups, 1);
703 assert_eq!(report.stats.clone_instances, 2);
704 }
705
706 fn init_repo(repo: &Path) -> PathBuf {
718 run_git(repo, &["init", "--quiet", "--initial-branch=main"]);
719 run_git(repo, &["config", "user.email", "test@example.com"]);
720 run_git(repo, &["config", "user.name", "test"]);
721 run_git(repo, &["config", "commit.gpgsign", "false"]);
722 std::fs::write(repo.join("seed.txt"), "seed\n").unwrap();
723 run_git(repo, &["add", "seed.txt"]);
724 run_git(repo, &["commit", "--quiet", "-m", "initial"]);
725 run_git(repo, &["tag", "fallow-baseline"]);
726 repo.canonicalize().unwrap()
727 }
728
729 fn run_git(cwd: &Path, args: &[&str]) {
730 let output = std::process::Command::new("git")
731 .args(args)
732 .current_dir(cwd)
733 .output()
734 .expect("git available");
735 assert!(
736 output.status.success(),
737 "git {args:?} failed: {}",
738 String::from_utf8_lossy(&output.stderr)
739 );
740 }
741
742 #[test]
745 fn try_get_changed_files_workspace_at_repo_root() {
746 let tmp = tempfile::tempdir().unwrap();
747 let repo = init_repo(tmp.path());
748 std::fs::create_dir_all(repo.join("src")).unwrap();
749 std::fs::write(repo.join("src/new.ts"), "export const x = 1;\n").unwrap();
750
751 let changed = try_get_changed_files(&repo, "fallow-baseline").unwrap();
752
753 let expected = repo.join("src/new.ts");
754 assert!(
755 changed.contains(&expected),
756 "changed set should contain {expected:?}; actual: {changed:?}"
757 );
758 }
759
760 #[test]
768 fn try_get_changed_files_workspace_in_subdirectory() {
769 let tmp = tempfile::tempdir().unwrap();
770 let repo = init_repo(tmp.path());
771 let frontend = repo.join("frontend");
772 std::fs::create_dir_all(frontend.join("src")).unwrap();
773 std::fs::write(frontend.join("src/new.ts"), "export const x = 1;\n").unwrap();
774
775 let changed = try_get_changed_files(&frontend, "fallow-baseline").unwrap();
776
777 let expected = repo.join("frontend/src/new.ts");
778 assert!(
779 changed.contains(&expected),
780 "changed set should contain canonical {expected:?}; actual: {changed:?}"
781 );
782 let bogus = frontend.join("frontend/src/new.ts");
784 assert!(
785 !changed.contains(&bogus),
786 "changed set must not contain double-frontend path {bogus:?}"
787 );
788 }
789
790 #[test]
805 fn try_get_changed_files_includes_committed_sibling_changes() {
806 let tmp = tempfile::tempdir().unwrap();
807 let repo = init_repo(tmp.path());
808 let backend = repo.join("backend");
809 std::fs::create_dir_all(&backend).unwrap();
810 std::fs::write(backend.join("server.py"), "print('hi')\n").unwrap();
811 run_git(&repo, &["add", "."]);
812 run_git(&repo, &["commit", "--quiet", "-m", "add backend"]);
813
814 let frontend = repo.join("frontend");
815 std::fs::create_dir_all(&frontend).unwrap();
816
817 let changed = try_get_changed_files(&frontend, "fallow-baseline").unwrap();
818
819 let expected = repo.join("backend/server.py");
820 assert!(
821 changed.contains(&expected),
822 "committed sibling backend/server.py should be in the set: {changed:?}"
823 );
824 }
825
826 #[test]
830 fn try_get_changed_files_includes_modified_tracked_file() {
831 let tmp = tempfile::tempdir().unwrap();
832 let repo = init_repo(tmp.path());
833 let frontend = repo.join("frontend");
834 std::fs::create_dir_all(frontend.join("src")).unwrap();
835 std::fs::write(frontend.join("src/old.ts"), "export const x = 1;\n").unwrap();
836 run_git(&repo, &["add", "."]);
837 run_git(&repo, &["commit", "--quiet", "-m", "add old"]);
838 run_git(&repo, &["tag", "fallow-baseline-v2"]);
839 std::fs::write(frontend.join("src/old.ts"), "export const x = 2;\n").unwrap();
841
842 let changed = try_get_changed_files(&frontend, "fallow-baseline-v2").unwrap();
843
844 let expected = repo.join("frontend/src/old.ts");
845 assert!(
846 changed.contains(&expected),
847 "modified tracked file {expected:?} missing from set: {changed:?}"
848 );
849 }
850
851 #[test]
857 fn resolve_git_toplevel_returns_canonical_path() {
858 let tmp = tempfile::tempdir().unwrap();
859 let repo = init_repo(tmp.path());
860 let frontend = repo.join("frontend");
861 std::fs::create_dir_all(&frontend).unwrap();
862
863 let toplevel = resolve_git_toplevel(&frontend).unwrap();
864 assert_eq!(toplevel, repo, "toplevel should equal canonical repo root");
865 assert_eq!(
866 toplevel,
867 toplevel.canonicalize().unwrap(),
868 "resolved toplevel should already be canonical"
869 );
870 }
871
872 #[test]
876 fn resolve_git_toplevel_not_a_repository() {
877 let tmp = tempfile::tempdir().unwrap();
878 let result = resolve_git_toplevel(tmp.path());
879 assert!(
880 matches!(result, Err(ChangedFilesError::NotARepository)),
881 "expected NotARepository, got {result:?}"
882 );
883 }
884
885 #[test]
888 fn try_get_changed_files_not_a_repository() {
889 let tmp = tempfile::tempdir().unwrap();
890 let result = try_get_changed_files(tmp.path(), "main");
891 assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
892 }
893
894 #[test]
895 fn filter_duplication_drops_groups_with_no_changed_instance() {
896 let mut report = DuplicationReport {
897 clone_groups: vec![CloneGroup {
898 instances: vec![CloneInstance {
899 file: "/a.ts".into(),
900 start_line: 1,
901 end_line: 5,
902 start_col: 0,
903 end_col: 10,
904 fragment: "code".into(),
905 }],
906 token_count: 20,
907 line_count: 5,
908 }],
909 clone_families: vec![],
910 mirrored_directories: vec![],
911 stats: DuplicationStats {
912 total_files: 1,
913 files_with_clones: 1,
914 total_lines: 100,
915 duplicated_lines: 5,
916 total_tokens: 100,
917 duplicated_tokens: 20,
918 clone_groups: 1,
919 clone_instances: 1,
920 duplication_percentage: 5.0,
921 clone_groups_below_min_occurrences: 0,
922 },
923 };
924
925 let changed: FxHashSet<PathBuf> = FxHashSet::default();
926 filter_duplication_by_changed_files(&mut report, &changed, Path::new(""));
927 assert!(report.clone_groups.is_empty());
928 assert_eq!(report.stats.clone_groups, 0);
929 assert_eq!(report.stats.clone_instances, 0);
930 assert!((report.stats.duplication_percentage - 0.0).abs() < f64::EPSILON);
931 }
932}