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
355fn 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 clone_groups_below_min_occurrences: report.stats.clone_groups_below_min_occurrences,
399 }
400}
401
402#[expect(
407 clippy::implicit_hasher,
408 reason = "fallow standardizes on FxHashSet across the workspace"
409)]
410pub fn filter_duplication_by_changed_files(
411 report: &mut DuplicationReport,
412 changed_files: &FxHashSet<PathBuf>,
413 root: &Path,
414) {
415 report
416 .clone_groups
417 .retain(|g| g.instances.iter().any(|i| changed_files.contains(&i.file)));
418 report.clone_families = families::group_into_families(&report.clone_groups, root);
419 report.mirrored_directories =
420 families::detect_mirrored_directories(&report.clone_families, root);
421 report.stats = recompute_duplication_stats(report);
422}
423
424#[cfg(test)]
425mod tests {
426 use super::*;
427 use crate::duplicates::{CloneGroup, CloneInstance};
428 use crate::results::{BoundaryViolation, CircularDependency, UnusedExport, UnusedFile};
429
430 #[test]
431 fn changed_files_error_describe_variants() {
432 assert!(
433 ChangedFilesError::InvalidRef("bad".to_owned())
434 .describe()
435 .contains("invalid git ref")
436 );
437 assert!(
438 ChangedFilesError::GitMissing("oops".to_owned())
439 .describe()
440 .contains("oops")
441 );
442 assert_eq!(
443 ChangedFilesError::NotARepository.describe(),
444 "not a git repository"
445 );
446 assert!(
447 ChangedFilesError::GitFailed("bad ref".to_owned())
448 .describe()
449 .contains("bad ref")
450 );
451 }
452
453 #[test]
454 fn augment_git_failed_appends_shallow_clone_hint_for_unknown_revision() {
455 let stderr = "fatal: ambiguous argument 'fallow-baseline...HEAD': unknown revision or path not in the working tree.";
456 let described = ChangedFilesError::GitFailed(stderr.to_owned()).describe();
457 assert!(described.contains(stderr), "original stderr preserved");
458 assert!(
459 described.contains("shallow clone"),
460 "hint surfaced: {described}"
461 );
462 assert!(
463 described.contains("fetch-depth: 0") || described.contains("git fetch --unshallow"),
464 "hint actionable: {described}"
465 );
466 }
467
468 #[test]
469 fn augment_git_failed_passthrough_for_other_errors() {
470 let stderr = "fatal: refusing to merge unrelated histories";
472 let described = ChangedFilesError::GitFailed(stderr.to_owned()).describe();
473 assert_eq!(described, stderr);
474 }
475
476 #[test]
477 fn validate_git_ref_rejects_leading_dash() {
478 assert!(validate_git_ref("--upload-pack=evil").is_err());
479 assert!(validate_git_ref("-flag").is_err());
480 }
481
482 #[test]
483 fn validate_git_ref_accepts_baseline_tag() {
484 assert_eq!(
485 validate_git_ref("fallow-baseline").unwrap(),
486 "fallow-baseline"
487 );
488 }
489
490 #[test]
491 fn try_get_changed_files_rejects_invalid_ref() {
492 let err = try_get_changed_files(Path::new("/"), "--evil")
494 .expect_err("leading-dash ref must be rejected");
495 assert!(matches!(err, ChangedFilesError::InvalidRef(_)));
496 assert!(err.describe().contains("cannot start with"));
497 }
498
499 #[test]
500 fn validate_git_ref_rejects_option_like_ref() {
501 assert!(validate_git_ref("--output=/tmp/fallow-proof").is_err());
502 }
503
504 #[test]
505 fn validate_git_ref_allows_reflog_relative_date() {
506 assert!(validate_git_ref("HEAD@{1 week ago}").is_ok());
507 }
508
509 #[test]
510 fn try_get_changed_files_rejects_option_like_ref_before_git() {
511 let root = tempfile::tempdir().expect("create temp dir");
512 let proof_path = root.path().join("proof");
513
514 let result = try_get_changed_files(
515 root.path(),
516 &format!("--output={}", proof_path.to_string_lossy()),
517 );
518
519 assert!(matches!(result, Err(ChangedFilesError::InvalidRef(_))));
520 assert!(
521 !proof_path.exists(),
522 "invalid changedSince ref must not be passed through to git as an option"
523 );
524 }
525
526 #[test]
527 fn git_command_clears_parent_git_environment() {
528 let command = git_command(Path::new("."), &["status", "--short"]);
529 let overrides: Vec<_> = command.get_envs().collect();
530
531 for var in crate::git_env::AMBIENT_GIT_ENV_VARS {
532 assert!(
533 overrides
534 .iter()
535 .any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
536 "git helper must clear inherited {var}",
537 );
538 }
539 }
540
541 #[test]
542 fn filter_results_keeps_only_changed_files() {
543 let mut results = AnalysisResults::default();
544 results.unused_files.push(UnusedFile {
545 path: "/a.ts".into(),
546 });
547 results.unused_files.push(UnusedFile {
548 path: "/b.ts".into(),
549 });
550 results.unused_exports.push(UnusedExport {
551 path: "/a.ts".into(),
552 export_name: "foo".into(),
553 is_type_only: false,
554 line: 1,
555 col: 0,
556 span_start: 0,
557 is_re_export: false,
558 });
559
560 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
561 changed.insert("/a.ts".into());
562
563 filter_results_by_changed_files(&mut results, &changed);
564
565 assert_eq!(results.unused_files.len(), 1);
566 assert_eq!(results.unused_files[0].path, PathBuf::from("/a.ts"));
567 assert_eq!(results.unused_exports.len(), 1);
568 }
569
570 #[test]
571 fn filter_results_preserves_dependency_level_issues() {
572 let mut results = AnalysisResults::default();
573 results
574 .unused_dependencies
575 .push(crate::results::UnusedDependency {
576 package_name: "lodash".into(),
577 location: crate::results::DependencyLocation::Dependencies,
578 path: "/pkg.json".into(),
579 line: 3,
580 used_in_workspaces: Vec::new(),
581 });
582
583 let changed: FxHashSet<PathBuf> = FxHashSet::default();
584 filter_results_by_changed_files(&mut results, &changed);
585
586 assert_eq!(results.unused_dependencies.len(), 1);
588 }
589
590 #[test]
591 fn filter_results_keeps_circular_dep_when_any_file_changed() {
592 let mut results = AnalysisResults::default();
593 results.circular_dependencies.push(CircularDependency {
594 files: vec!["/a.ts".into(), "/b.ts".into()],
595 length: 2,
596 line: 1,
597 col: 0,
598 is_cross_package: false,
599 });
600
601 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
602 changed.insert("/b.ts".into());
603
604 filter_results_by_changed_files(&mut results, &changed);
605 assert_eq!(results.circular_dependencies.len(), 1);
606 }
607
608 #[test]
609 fn filter_results_drops_circular_dep_when_no_file_changed() {
610 let mut results = AnalysisResults::default();
611 results.circular_dependencies.push(CircularDependency {
612 files: vec!["/a.ts".into(), "/b.ts".into()],
613 length: 2,
614 line: 1,
615 col: 0,
616 is_cross_package: false,
617 });
618
619 let changed: FxHashSet<PathBuf> = FxHashSet::default();
620 filter_results_by_changed_files(&mut results, &changed);
621 assert!(results.circular_dependencies.is_empty());
622 }
623
624 #[test]
625 fn filter_results_drops_boundary_violation_when_importer_unchanged() {
626 let mut results = AnalysisResults::default();
627 results.boundary_violations.push(BoundaryViolation {
628 from_path: "/a.ts".into(),
629 to_path: "/b.ts".into(),
630 from_zone: "ui".into(),
631 to_zone: "data".into(),
632 import_specifier: "../data/db".into(),
633 line: 1,
634 col: 0,
635 });
636
637 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
638 changed.insert("/b.ts".into());
640
641 filter_results_by_changed_files(&mut results, &changed);
642 assert!(results.boundary_violations.is_empty());
643 }
644
645 #[test]
646 fn filter_duplication_keeps_groups_with_at_least_one_changed_instance() {
647 let mut report = DuplicationReport {
648 clone_groups: vec![CloneGroup {
649 instances: vec![
650 CloneInstance {
651 file: "/a.ts".into(),
652 start_line: 1,
653 end_line: 5,
654 start_col: 0,
655 end_col: 10,
656 fragment: "code".into(),
657 },
658 CloneInstance {
659 file: "/b.ts".into(),
660 start_line: 1,
661 end_line: 5,
662 start_col: 0,
663 end_col: 10,
664 fragment: "code".into(),
665 },
666 ],
667 token_count: 20,
668 line_count: 5,
669 }],
670 clone_families: vec![],
671 mirrored_directories: vec![],
672 stats: DuplicationStats {
673 total_files: 2,
674 files_with_clones: 2,
675 total_lines: 100,
676 duplicated_lines: 10,
677 total_tokens: 200,
678 duplicated_tokens: 40,
679 clone_groups: 1,
680 clone_instances: 2,
681 duplication_percentage: 10.0,
682 clone_groups_below_min_occurrences: 0,
683 },
684 };
685
686 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
687 changed.insert("/a.ts".into());
688
689 filter_duplication_by_changed_files(&mut report, &changed, Path::new(""));
690 assert_eq!(report.clone_groups.len(), 1);
691 assert_eq!(report.stats.clone_groups, 1);
693 assert_eq!(report.stats.clone_instances, 2);
694 }
695
696 fn init_repo(repo: &Path) -> PathBuf {
708 run_git(repo, &["init", "--quiet", "--initial-branch=main"]);
709 run_git(repo, &["config", "user.email", "test@example.com"]);
710 run_git(repo, &["config", "user.name", "test"]);
711 run_git(repo, &["config", "commit.gpgsign", "false"]);
712 std::fs::write(repo.join("seed.txt"), "seed\n").unwrap();
713 run_git(repo, &["add", "seed.txt"]);
714 run_git(repo, &["commit", "--quiet", "-m", "initial"]);
715 run_git(repo, &["tag", "fallow-baseline"]);
716 repo.canonicalize().unwrap()
717 }
718
719 fn run_git(cwd: &Path, args: &[&str]) {
720 let output = std::process::Command::new("git")
721 .args(args)
722 .current_dir(cwd)
723 .output()
724 .expect("git available");
725 assert!(
726 output.status.success(),
727 "git {args:?} failed: {}",
728 String::from_utf8_lossy(&output.stderr)
729 );
730 }
731
732 #[test]
735 fn try_get_changed_files_workspace_at_repo_root() {
736 let tmp = tempfile::tempdir().unwrap();
737 let repo = init_repo(tmp.path());
738 std::fs::create_dir_all(repo.join("src")).unwrap();
739 std::fs::write(repo.join("src/new.ts"), "export const x = 1;\n").unwrap();
740
741 let changed = try_get_changed_files(&repo, "fallow-baseline").unwrap();
742
743 let expected = repo.join("src/new.ts");
744 assert!(
745 changed.contains(&expected),
746 "changed set should contain {expected:?}; actual: {changed:?}"
747 );
748 }
749
750 #[test]
758 fn try_get_changed_files_workspace_in_subdirectory() {
759 let tmp = tempfile::tempdir().unwrap();
760 let repo = init_repo(tmp.path());
761 let frontend = repo.join("frontend");
762 std::fs::create_dir_all(frontend.join("src")).unwrap();
763 std::fs::write(frontend.join("src/new.ts"), "export const x = 1;\n").unwrap();
764
765 let changed = try_get_changed_files(&frontend, "fallow-baseline").unwrap();
766
767 let expected = repo.join("frontend/src/new.ts");
768 assert!(
769 changed.contains(&expected),
770 "changed set should contain canonical {expected:?}; actual: {changed:?}"
771 );
772 let bogus = frontend.join("frontend/src/new.ts");
774 assert!(
775 !changed.contains(&bogus),
776 "changed set must not contain double-frontend path {bogus:?}"
777 );
778 }
779
780 #[test]
795 fn try_get_changed_files_includes_committed_sibling_changes() {
796 let tmp = tempfile::tempdir().unwrap();
797 let repo = init_repo(tmp.path());
798 let backend = repo.join("backend");
799 std::fs::create_dir_all(&backend).unwrap();
800 std::fs::write(backend.join("server.py"), "print('hi')\n").unwrap();
801 run_git(&repo, &["add", "."]);
802 run_git(&repo, &["commit", "--quiet", "-m", "add backend"]);
803
804 let frontend = repo.join("frontend");
805 std::fs::create_dir_all(&frontend).unwrap();
806
807 let changed = try_get_changed_files(&frontend, "fallow-baseline").unwrap();
808
809 let expected = repo.join("backend/server.py");
810 assert!(
811 changed.contains(&expected),
812 "committed sibling backend/server.py should be in the set: {changed:?}"
813 );
814 }
815
816 #[test]
820 fn try_get_changed_files_includes_modified_tracked_file() {
821 let tmp = tempfile::tempdir().unwrap();
822 let repo = init_repo(tmp.path());
823 let frontend = repo.join("frontend");
824 std::fs::create_dir_all(frontend.join("src")).unwrap();
825 std::fs::write(frontend.join("src/old.ts"), "export const x = 1;\n").unwrap();
826 run_git(&repo, &["add", "."]);
827 run_git(&repo, &["commit", "--quiet", "-m", "add old"]);
828 run_git(&repo, &["tag", "fallow-baseline-v2"]);
829 std::fs::write(frontend.join("src/old.ts"), "export const x = 2;\n").unwrap();
831
832 let changed = try_get_changed_files(&frontend, "fallow-baseline-v2").unwrap();
833
834 let expected = repo.join("frontend/src/old.ts");
835 assert!(
836 changed.contains(&expected),
837 "modified tracked file {expected:?} missing from set: {changed:?}"
838 );
839 }
840
841 #[test]
847 fn resolve_git_toplevel_returns_canonical_path() {
848 let tmp = tempfile::tempdir().unwrap();
849 let repo = init_repo(tmp.path());
850 let frontend = repo.join("frontend");
851 std::fs::create_dir_all(&frontend).unwrap();
852
853 let toplevel = resolve_git_toplevel(&frontend).unwrap();
854 assert_eq!(toplevel, repo, "toplevel should equal canonical repo root");
855 assert_eq!(
856 toplevel,
857 toplevel.canonicalize().unwrap(),
858 "resolved toplevel should already be canonical"
859 );
860 }
861
862 #[test]
866 fn resolve_git_toplevel_not_a_repository() {
867 let tmp = tempfile::tempdir().unwrap();
868 let result = resolve_git_toplevel(tmp.path());
869 assert!(
870 matches!(result, Err(ChangedFilesError::NotARepository)),
871 "expected NotARepository, got {result:?}"
872 );
873 }
874
875 #[test]
878 fn try_get_changed_files_not_a_repository() {
879 let tmp = tempfile::tempdir().unwrap();
880 let result = try_get_changed_files(tmp.path(), "main");
881 assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
882 }
883
884 #[test]
885 fn filter_duplication_drops_groups_with_no_changed_instance() {
886 let mut report = DuplicationReport {
887 clone_groups: vec![CloneGroup {
888 instances: vec![CloneInstance {
889 file: "/a.ts".into(),
890 start_line: 1,
891 end_line: 5,
892 start_col: 0,
893 end_col: 10,
894 fragment: "code".into(),
895 }],
896 token_count: 20,
897 line_count: 5,
898 }],
899 clone_families: vec![],
900 mirrored_directories: vec![],
901 stats: DuplicationStats {
902 total_files: 1,
903 files_with_clones: 1,
904 total_lines: 100,
905 duplicated_lines: 5,
906 total_tokens: 100,
907 duplicated_tokens: 20,
908 clone_groups: 1,
909 clone_instances: 1,
910 duplication_percentage: 5.0,
911 clone_groups_below_min_occurrences: 0,
912 },
913 };
914
915 let changed: FxHashSet<PathBuf> = FxHashSet::default();
916 filter_duplication_by_changed_files(&mut report, &changed, Path::new(""));
917 assert!(report.clone_groups.is_empty());
918 assert_eq!(report.stats.clone_groups, 0);
919 assert_eq!(report.stats.clone_instances, 0);
920 assert!((report.stats.duplication_percentage - 0.0).abs() < f64::EPSILON);
921 }
922}