1use std::path::{Path, PathBuf};
17use std::process::Output;
18use std::sync::OnceLock;
19
20use rustc_hash::{FxHashMap, FxHashSet};
21
22use crate::duplicates::{DuplicationReport, DuplicationStats, families};
23use crate::results::{
24 AnalysisResults, CircularDependencyFinding, DuplicateExportFinding, DuplicatePropShapeFinding,
25 ReExportCycleFinding, SecurityFinding, UnlistedDependencyFinding,
26};
27use fallow_types::output_dead_code::PropDrillingChainFinding;
28
29pub type ChangedFilesSpawnHook = fn(&mut std::process::Command) -> std::io::Result<Output>;
36
37static SPAWN_HOOK: OnceLock<ChangedFilesSpawnHook> = OnceLock::new();
38
39pub fn set_spawn_hook(hook: ChangedFilesSpawnHook) {
46 let _ = SPAWN_HOOK.set(hook);
47}
48
49fn spawn_output(command: &mut std::process::Command) -> std::io::Result<Output> {
50 if let Some(hook) = SPAWN_HOOK.get() {
51 hook(command)
52 } else {
53 command.output()
54 }
55}
56
57pub fn validate_git_ref(s: &str) -> Result<&str, String> {
70 if s.is_empty() {
71 return Err("git ref cannot be empty".to_string());
72 }
73 if s.starts_with('-') {
74 return Err("git ref cannot start with '-'".to_string());
75 }
76 let mut in_braces = false;
77 for c in s.chars() {
78 match c {
79 '{' => in_braces = true,
80 '}' => in_braces = false,
81 ':' | ' ' if in_braces => {}
82 c if c.is_ascii_alphanumeric()
83 || matches!(c, '.' | '_' | '-' | '/' | '~' | '^' | '@' | '{' | '}') => {}
84 _ => return Err(format!("git ref contains disallowed character: '{c}'")),
85 }
86 }
87 if in_braces {
88 return Err("git ref has unclosed '{'".to_string());
89 }
90 Ok(s)
91}
92
93#[derive(Debug)]
96pub enum ChangedFilesError {
97 InvalidRef(String),
99 GitMissing(String),
101 NotARepository,
103 GitFailed(String),
105}
106
107impl ChangedFilesError {
108 pub fn describe(&self) -> String {
112 match self {
113 Self::InvalidRef(e) => format!("invalid git ref: {e}"),
114 Self::GitMissing(e) => format!("failed to run git: {e}"),
115 Self::NotARepository => "not a git repository".to_owned(),
116 Self::GitFailed(stderr) => augment_git_failed(stderr),
117 }
118 }
119}
120
121fn augment_git_failed(stderr: &str) -> String {
127 let lower = stderr.to_ascii_lowercase();
128 if lower.contains("not a valid object name")
129 || lower.contains("unknown revision")
130 || lower.contains("ambiguous argument")
131 {
132 format!(
133 "{stderr} (shallow clone? try `git fetch --unshallow`, or set `fetch-depth: 0` on actions/checkout / `GIT_DEPTH: 0` in GitLab CI)"
134 )
135 } else {
136 stderr.to_owned()
137 }
138}
139
140pub fn resolve_git_toplevel(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
151 let output = spawn_output(&mut git_command(cwd, &["rev-parse", "--show-toplevel"]))
152 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
153
154 if !output.status.success() {
155 let stderr = String::from_utf8_lossy(&output.stderr);
156 return Err(if stderr.contains("not a git repository") {
157 ChangedFilesError::NotARepository
158 } else {
159 ChangedFilesError::GitFailed(stderr.trim().to_owned())
160 });
161 }
162
163 let raw = String::from_utf8_lossy(&output.stdout);
164 let trimmed = raw.trim();
165 if trimmed.is_empty() {
166 return Err(ChangedFilesError::GitFailed(
167 "git rev-parse --show-toplevel returned empty output".to_owned(),
168 ));
169 }
170
171 let path = PathBuf::from(trimmed);
172 Ok(dunce::canonicalize(&path).unwrap_or(path))
173}
174
175pub fn resolve_git_common_dir(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
189 let output = spawn_output(&mut git_command(
190 cwd,
191 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
192 ))
193 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
194
195 if !output.status.success() {
196 let stderr = String::from_utf8_lossy(&output.stderr);
197 return Err(if stderr.contains("not a git repository") {
198 ChangedFilesError::NotARepository
199 } else {
200 ChangedFilesError::GitFailed(stderr.trim().to_owned())
201 });
202 }
203
204 let raw = String::from_utf8_lossy(&output.stdout);
205 let trimmed = raw.trim();
206 if trimmed.is_empty() {
207 return Err(ChangedFilesError::GitFailed(
208 "git rev-parse --git-common-dir returned empty output".to_owned(),
209 ));
210 }
211
212 let path = PathBuf::from(trimmed);
213 Ok(dunce::canonicalize(&path).unwrap_or(path))
214}
215
216fn collect_git_paths(
217 cwd: &Path,
218 toplevel: &Path,
219 args: &[&str],
220) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
221 let output = spawn_output(&mut git_command(cwd, args))
222 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
223
224 if !output.status.success() {
225 let stderr = String::from_utf8_lossy(&output.stderr);
226 return Err(if stderr.contains("not a git repository") {
227 ChangedFilesError::NotARepository
228 } else {
229 ChangedFilesError::GitFailed(stderr.trim().to_owned())
230 });
231 }
232
233 #[cfg(windows)]
234 let normalise_segment = |line: &str| line.replace('/', "\\");
235 #[cfg(not(windows))]
236 let normalise_segment = |line: &str| line.to_owned();
237
238 let files: FxHashSet<PathBuf> = String::from_utf8_lossy(&output.stdout)
239 .lines()
240 .filter(|line| !line.is_empty())
241 .map(|line| toplevel.join(normalise_segment(line)))
242 .collect();
243
244 Ok(files)
245}
246
247fn git_command(cwd: &Path, args: &[&str]) -> std::process::Command {
248 let mut command = crate::spawn::git();
249 command.args(args).current_dir(cwd);
250 command
251}
252
253pub fn try_get_changed_files(
271 root: &Path,
272 git_ref: &str,
273) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
274 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
275 let toplevel = resolve_git_toplevel(root)?;
276 try_get_changed_files_with_toplevel(root, &toplevel, git_ref)
277}
278
279pub fn try_get_changed_files_with_toplevel(
287 cwd: &Path,
288 toplevel: &Path,
289 git_ref: &str,
290) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
291 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
292
293 let mut files = collect_git_paths(
294 cwd,
295 toplevel,
296 &[
297 "diff",
298 "--name-only",
299 "--end-of-options",
300 &format!("{git_ref}...HEAD"),
301 ],
302 )?;
303 files.extend(collect_git_paths(
304 cwd,
305 toplevel,
306 &["diff", "--name-only", "HEAD"],
307 )?);
308 files.extend(collect_git_paths(
309 cwd,
310 toplevel,
311 &["ls-files", "--full-name", "--others", "--exclude-standard"],
312 )?);
313 Ok(files)
314}
315
316pub fn try_get_changed_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
332 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
333 let output = spawn_output(&mut git_command(
334 root,
335 &[
336 "diff",
337 "--relative",
338 "--unified=0",
339 "--end-of-options",
340 &format!("{git_ref}...HEAD"),
341 ],
342 ))
343 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
344
345 if !output.status.success() {
346 let stderr = String::from_utf8_lossy(&output.stderr);
347 return Err(if stderr.contains("not a git repository") {
348 ChangedFilesError::NotARepository
349 } else {
350 ChangedFilesError::GitFailed(stderr.trim().to_owned())
351 });
352 }
353
354 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
355}
356
357#[expect(
361 clippy::print_stderr,
362 reason = "intentional user-facing warning for the CLI's --changed-since fallback path; LSP callers use try_get_changed_files instead"
363)]
364pub fn get_changed_files(root: &Path, git_ref: &str) -> Option<FxHashSet<PathBuf>> {
365 match try_get_changed_files(root, git_ref) {
366 Ok(files) => Some(files),
367 Err(ChangedFilesError::InvalidRef(e)) => {
368 eprintln!("Warning: --changed-since ignored: invalid git ref: {e}");
369 None
370 }
371 Err(ChangedFilesError::GitMissing(e)) => {
372 eprintln!("Warning: --changed-since ignored: failed to run git: {e}");
373 None
374 }
375 Err(ChangedFilesError::NotARepository) => {
376 eprintln!("Warning: --changed-since ignored: not a git repository");
377 None
378 }
379 Err(ChangedFilesError::GitFailed(stderr)) => {
380 eprintln!("Warning: --changed-since failed for ref '{git_ref}': {stderr}");
381 None
382 }
383 }
384}
385
386#[expect(
399 clippy::implicit_hasher,
400 reason = "fallow standardizes on FxHashSet across the workspace"
401)]
402pub fn filter_results_by_changed_files(
403 results: &mut AnalysisResults,
404 changed_files: &FxHashSet<PathBuf>,
405) {
406 let cf = normalize_changed_files_set(changed_files);
407 classify_changed_file_filter_fields(results);
408 retain_basic_issue_findings_by_changed_path(results, &cf);
409 retain_graph_findings_by_changed_files(results, &cf);
410 retain_boundary_policy_and_suppression_findings(results, &cf);
411 retain_security_and_workspace_findings(results, &cf);
412 retain_framework_findings_by_changed_files(results, &cf);
413}
414
415fn classify_changed_file_filter_fields(results: &AnalysisResults) {
416 let AnalysisResults {
417 unused_files: _unused_files,
418 unused_exports: _unused_exports,
419 unused_types: _unused_types,
420 private_type_leaks: _private_type_leaks,
421 unused_dependencies: _unused_dependencies,
425 unused_dev_dependencies: _unused_dev_dependencies,
426 unused_optional_dependencies: _unused_optional_dependencies,
427 unused_enum_members: _unused_enum_members,
428 unused_class_members: _unused_class_members,
429 unused_store_members: _unused_store_members,
430 unresolved_imports: _unresolved_imports,
431 unlisted_dependencies: _unlisted_dependencies,
432 duplicate_exports: _duplicate_exports,
433 type_only_dependencies: _type_only_dependencies,
436 test_only_dependencies: _test_only_dependencies,
437 circular_dependencies: _circular_dependencies,
438 re_export_cycles: _re_export_cycles,
439 boundary_violations: _boundary_violations,
440 boundary_coverage_violations: _boundary_coverage_violations,
441 boundary_call_violations: _boundary_call_violations,
442 policy_violations: _policy_violations,
443 stale_suppressions: _stale_suppressions,
444 unused_catalog_entries: _unused_catalog_entries,
448 empty_catalog_groups: _empty_catalog_groups,
449 unresolved_catalog_references: _unresolved_catalog_references,
450 unused_dependency_overrides: _unused_dependency_overrides,
451 misconfigured_dependency_overrides: _misconfigured_dependency_overrides,
452 invalid_client_exports: _invalid_client_exports,
453 mixed_client_server_barrels: _mixed_client_server_barrels,
454 misplaced_directives: _misplaced_directives,
455 unprovided_injects: _unprovided_injects,
456 unrendered_components: _unrendered_components,
457 route_collisions: _route_collisions,
458 dynamic_segment_name_conflicts: _dynamic_segment_name_conflicts,
459 unused_component_props: _unused_component_props,
460 unused_component_emits: _unused_component_emits,
461 unused_component_inputs: _unused_component_inputs,
462 unused_component_outputs: _unused_component_outputs,
463 unused_svelte_events: _unused_svelte_events,
464 unused_server_actions: _unused_server_actions,
465 unused_load_data_keys: _unused_load_data_keys,
466 unused_load_data_keys_global_abstain: _unused_load_data_keys_global_abstain,
468 prop_drilling_chains: _prop_drilling_chains,
469 thin_wrappers: _thin_wrappers,
470 duplicate_prop_shapes: _duplicate_prop_shapes,
471 suppression_count: _suppression_count,
473 active_suppressions: _active_suppressions,
474 feature_flags: _feature_flags,
475 security_findings: _security_findings,
476 security_unresolved_edge_files: _security_unresolved_edge_files,
477 security_unresolved_callee_sites: _security_unresolved_callee_sites,
478 security_unresolved_callee_diagnostics: _security_unresolved_callee_diagnostics,
479 export_usages: _export_usages,
482 entry_point_summary: _entry_point_summary,
483 render_fan_in: _render_fan_in,
487 react_component_intel: _react_component_intel,
490 } = results;
491}
492
493fn retain_basic_issue_findings_by_changed_path(
494 results: &mut AnalysisResults,
495 changed_files: &FxHashSet<PathBuf>,
496) {
497 retain_by_changed_path(&mut results.unused_files, changed_files, |f| &f.file.path);
498 retain_by_changed_path(&mut results.unused_exports, changed_files, |e| {
499 &e.export.path
500 });
501 retain_by_changed_path(&mut results.unused_types, changed_files, |e| &e.export.path);
502 retain_by_changed_path(&mut results.private_type_leaks, changed_files, |e| {
503 &e.leak.path
504 });
505 retain_by_changed_path(&mut results.unused_enum_members, changed_files, |m| {
506 &m.member.path
507 });
508 retain_by_changed_path(&mut results.unused_class_members, changed_files, |m| {
509 &m.member.path
510 });
511 retain_by_changed_path(&mut results.unused_store_members, changed_files, |m| {
512 &m.member.path
513 });
514 retain_by_changed_path(&mut results.unresolved_imports, changed_files, |i| {
515 &i.import.path
516 });
517}
518
519fn retain_graph_findings_by_changed_files(
520 results: &mut AnalysisResults,
521 changed_files: &FxHashSet<PathBuf>,
522) {
523 retain_unlisted_dependencies_by_import_site(&mut results.unlisted_dependencies, changed_files);
524 retain_duplicate_exports_by_changed_locations(&mut results.duplicate_exports, changed_files);
525 retain_circular_dependencies_by_changed_file(&mut results.circular_dependencies, changed_files);
526 retain_re_export_cycles_by_changed_file(&mut results.re_export_cycles, changed_files);
527}
528
529fn retain_boundary_policy_and_suppression_findings(
530 results: &mut AnalysisResults,
531 changed_files: &FxHashSet<PathBuf>,
532) {
533 retain_by_changed_path(&mut results.boundary_violations, changed_files, |v| {
534 &v.violation.from_path
535 });
536 retain_by_changed_path(
537 &mut results.boundary_coverage_violations,
538 changed_files,
539 |v| &v.violation.path,
540 );
541 retain_by_changed_path(&mut results.boundary_call_violations, changed_files, |v| {
542 &v.violation.path
543 });
544 retain_by_changed_path(&mut results.policy_violations, changed_files, |v| {
545 &v.violation.path
546 });
547 retain_by_changed_path(&mut results.stale_suppressions, changed_files, |s| &s.path);
548}
549
550fn retain_security_and_workspace_findings(
551 results: &mut AnalysisResults,
552 changed_files: &FxHashSet<PathBuf>,
553) {
554 retain_security_findings_by_changed_path(&mut results.security_findings, changed_files);
555 retain_by_changed_path(
556 &mut results.security_unresolved_callee_diagnostics,
557 changed_files,
558 |d| &d.path,
559 );
560 retain_by_changed_path(
561 &mut results.unresolved_catalog_references,
562 changed_files,
563 |r| &r.reference.path,
564 );
565 results
566 .empty_catalog_groups
567 .retain(|g| normalized_set_contains_path(changed_files, &g.group.path));
568 retain_by_changed_path(
569 &mut results.unused_dependency_overrides,
570 changed_files,
571 |o| &o.entry.path,
572 );
573 retain_by_changed_path(
574 &mut results.misconfigured_dependency_overrides,
575 changed_files,
576 |o| &o.entry.path,
577 );
578}
579
580fn retain_framework_findings_by_changed_files(
581 results: &mut AnalysisResults,
582 changed_files: &FxHashSet<PathBuf>,
583) {
584 retain_client_boundary_findings_by_changed_files(results, changed_files);
585 retain_component_contract_findings_by_changed_files(results, changed_files);
586 retain_react_health_findings_by_changed_files(results, changed_files);
587 retain_nextjs_findings_by_changed_files(results, changed_files);
588}
589
590fn retain_client_boundary_findings_by_changed_files(
591 results: &mut AnalysisResults,
592 changed_files: &FxHashSet<PathBuf>,
593) {
594 let AnalysisResults {
595 invalid_client_exports,
596 mixed_client_server_barrels,
597 misplaced_directives,
598 ..
599 } = results;
600
601 retain_by_changed_path(invalid_client_exports, changed_files, |e| &e.export.path);
602 retain_by_changed_path(mixed_client_server_barrels, changed_files, |b| {
603 &b.barrel.path
604 });
605 retain_by_changed_path(misplaced_directives, changed_files, |d| {
606 &d.directive_site.path
607 });
608}
609
610fn retain_component_contract_findings_by_changed_files(
611 results: &mut AnalysisResults,
612 changed_files: &FxHashSet<PathBuf>,
613) {
614 let AnalysisResults {
615 unprovided_injects,
616 unrendered_components,
617 unused_component_props,
618 unused_component_emits,
619 unused_component_inputs,
620 unused_component_outputs,
621 unused_svelte_events,
622 unused_server_actions,
623 unused_load_data_keys,
624 ..
625 } = results;
626
627 retain_by_changed_path(unprovided_injects, changed_files, |i| &i.inject.path);
628 retain_by_changed_path(unrendered_components, changed_files, |c| &c.component.path);
629 retain_by_changed_path(unused_component_props, changed_files, |p| &p.prop.path);
630 retain_by_changed_path(unused_component_emits, changed_files, |e| &e.emit.path);
631 retain_by_changed_path(unused_component_inputs, changed_files, |i| &i.input.path);
632 retain_by_changed_path(unused_component_outputs, changed_files, |o| &o.output.path);
633 retain_by_changed_path(unused_svelte_events, changed_files, |e| &e.event.path);
634 retain_by_changed_path(unused_server_actions, changed_files, |a| &a.action.path);
635 retain_by_changed_path(unused_load_data_keys, changed_files, |k| &k.key.path);
636}
637
638fn retain_react_health_findings_by_changed_files(
639 results: &mut AnalysisResults,
640 changed_files: &FxHashSet<PathBuf>,
641) {
642 let AnalysisResults {
643 prop_drilling_chains,
644 thin_wrappers,
645 duplicate_prop_shapes,
646 ..
647 } = results;
648
649 retain_prop_drilling_chains_by_anchor(prop_drilling_chains, changed_files);
650 retain_by_changed_path(thin_wrappers, changed_files, |w| &w.wrapper.file);
651 retain_duplicate_prop_shapes_by_anchor(duplicate_prop_shapes, changed_files);
652}
653
654fn retain_nextjs_findings_by_changed_files(
655 results: &mut AnalysisResults,
656 changed_files: &FxHashSet<PathBuf>,
657) {
658 let AnalysisResults {
659 route_collisions,
660 dynamic_segment_name_conflicts,
661 ..
662 } = results;
663
664 retain_by_changed_path(route_collisions, changed_files, |c| &c.collision.path);
665 retain_by_changed_path(dynamic_segment_name_conflicts, changed_files, |c| {
666 &c.conflict.path
667 });
668}
669
670fn retain_unlisted_dependencies_by_import_site(
671 dependencies: &mut Vec<UnlistedDependencyFinding>,
672 changed_files: &FxHashSet<PathBuf>,
673) {
674 dependencies.retain(|dependency| {
675 dependency
676 .dep
677 .imported_from
678 .iter()
679 .any(|site| contains_normalized(changed_files, &site.path))
680 });
681}
682
683fn retain_duplicate_exports_by_changed_locations(
684 duplicate_exports: &mut Vec<DuplicateExportFinding>,
685 changed_files: &FxHashSet<PathBuf>,
686) {
687 for duplicate in &mut *duplicate_exports {
688 duplicate
689 .export
690 .locations
691 .retain(|location| contains_normalized(changed_files, &location.path));
692 }
693 duplicate_exports.retain(|duplicate| duplicate.export.locations.len() >= 2);
694}
695
696fn retain_circular_dependencies_by_changed_file(
697 cycles: &mut Vec<CircularDependencyFinding>,
698 changed_files: &FxHashSet<PathBuf>,
699) {
700 cycles.retain(|cycle| {
701 cycle
702 .cycle
703 .files
704 .iter()
705 .any(|file| contains_normalized(changed_files, file))
706 });
707}
708
709fn retain_re_export_cycles_by_changed_file(
710 cycles: &mut Vec<ReExportCycleFinding>,
711 changed_files: &FxHashSet<PathBuf>,
712) {
713 cycles.retain(|cycle| {
714 cycle
715 .cycle
716 .files
717 .iter()
718 .any(|file| contains_normalized(changed_files, file))
719 });
720}
721
722fn retain_security_findings_by_changed_path(
723 findings: &mut Vec<SecurityFinding>,
724 changed_files: &FxHashSet<PathBuf>,
725) {
726 findings.retain(|finding| security_finding_touches_changed_path(finding, changed_files));
727}
728
729fn retain_prop_drilling_chains_by_anchor(
730 chains: &mut Vec<PropDrillingChainFinding>,
731 changed_files: &FxHashSet<PathBuf>,
732) {
733 chains.retain(|chain| {
735 chain
736 .chain
737 .hops
738 .first()
739 .is_some_and(|hop| contains_normalized(changed_files, &hop.file))
740 });
741}
742
743fn retain_duplicate_prop_shapes_by_anchor(
744 shapes: &mut Vec<DuplicatePropShapeFinding>,
745 changed_files: &FxHashSet<PathBuf>,
746) {
747 retain_by_changed_path(shapes, changed_files, |shape| &shape.shape.file);
749}
750
751fn retain_by_changed_path<T>(
752 items: &mut Vec<T>,
753 changed_files: &FxHashSet<PathBuf>,
754 path: impl Fn(&T) -> &Path,
755) {
756 items.retain(|item| contains_normalized(changed_files, path(item)));
757}
758
759fn security_finding_touches_changed_path(
760 finding: &SecurityFinding,
761 changed_files: &FxHashSet<PathBuf>,
762) -> bool {
763 contains_normalized(changed_files, &finding.path)
764 || finding
765 .trace
766 .iter()
767 .any(|hop| contains_normalized(changed_files, &hop.path))
768 || finding.reachability.as_ref().is_some_and(|reachability| {
769 reachability
770 .untrusted_source_trace
771 .iter()
772 .any(|hop| contains_normalized(changed_files, &hop.path))
773 })
774}
775
776fn normalize_changed_files_set(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<PathBuf> {
789 changed_files
790 .iter()
791 .map(|p| dunce::simplified(p).to_path_buf())
792 .collect()
793}
794
795fn contains_normalized(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
796 normalized.contains(dunce::simplified(path))
797}
798
799fn normalized_set_contains_path(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
800 contains_normalized(normalized, path)
801 || (path.is_relative() && normalized.iter().any(|changed| changed.ends_with(path)))
802}
803
804fn recompute_duplication_stats(report: &DuplicationReport) -> DuplicationStats {
810 let mut files_with_clones: FxHashSet<&Path> = FxHashSet::default();
811 let mut file_dup_lines: FxHashMap<&Path, FxHashSet<usize>> = FxHashMap::default();
812 let mut duplicated_tokens = 0_usize;
813 let mut clone_instances = 0_usize;
814
815 for group in &report.clone_groups {
816 for instance in &group.instances {
817 files_with_clones.insert(&instance.file);
818 clone_instances += 1;
819 let lines = file_dup_lines.entry(&instance.file).or_default();
820 for line in instance.start_line..=instance.end_line {
821 lines.insert(line);
822 }
823 }
824 duplicated_tokens += group.token_count * group.instances.len();
825 }
826
827 let duplicated_lines: usize = file_dup_lines.values().map(FxHashSet::len).sum();
828
829 DuplicationStats {
830 total_files: report.stats.total_files,
831 files_with_clones: files_with_clones.len(),
832 total_lines: report.stats.total_lines,
833 duplicated_lines,
834 total_tokens: report.stats.total_tokens,
835 duplicated_tokens,
836 clone_groups: report.clone_groups.len(),
837 clone_instances,
838 #[expect(
839 clippy::cast_precision_loss,
840 reason = "stat percentages are display-only; precision loss at usize::MAX line counts is acceptable"
841 )]
842 duplication_percentage: if report.stats.total_lines > 0 {
843 (duplicated_lines as f64 / report.stats.total_lines as f64) * 100.0
844 } else {
845 0.0
846 },
847 clone_groups_below_min_occurrences: report.stats.clone_groups_below_min_occurrences,
848 }
849}
850
851#[expect(
856 clippy::implicit_hasher,
857 reason = "fallow standardizes on FxHashSet across the workspace"
858)]
859pub fn filter_duplication_by_changed_files(
860 report: &mut DuplicationReport,
861 changed_files: &FxHashSet<PathBuf>,
862 root: &Path,
863) {
864 let cf = normalize_changed_files_set(changed_files);
865 report.clone_groups.retain(|g| {
866 g.instances
867 .iter()
868 .any(|i| contains_normalized(&cf, &i.file))
869 });
870 report.clone_families = families::group_into_families(&report.clone_groups, root);
871 report.mirrored_directories =
872 families::detect_mirrored_directories(&report.clone_families, root);
873 report.stats = recompute_duplication_stats(report);
874}
875
876#[cfg(test)]
877mod tests {
878 use super::*;
879 use crate::duplicates::{CloneGroup, CloneInstance};
880 use crate::results::{
881 BoundaryViolation, CircularDependency, EmptyCatalogGroup, SecurityFinding,
882 SecurityFindingKind, SecurityUnresolvedCalleeDiagnostic, TraceHop, TraceHopRole,
883 UnusedExport, UnusedFile,
884 };
885 use fallow_types::extract::{SkippedSecurityCalleeExpressionKind, SkippedSecurityCalleeReason};
886 use fallow_types::output_dead_code::{
887 BoundaryViolationFinding, CircularDependencyFinding, EmptyCatalogGroupFinding,
888 UnusedExportFinding, UnusedFileFinding,
889 };
890 use fallow_types::results::{SecurityReachability, SecuritySeverity};
891
892 #[test]
893 fn changed_files_error_describe_variants() {
894 assert!(
895 ChangedFilesError::InvalidRef("bad".to_owned())
896 .describe()
897 .contains("invalid git ref")
898 );
899 assert!(
900 ChangedFilesError::GitMissing("oops".to_owned())
901 .describe()
902 .contains("oops")
903 );
904 assert_eq!(
905 ChangedFilesError::NotARepository.describe(),
906 "not a git repository"
907 );
908 assert!(
909 ChangedFilesError::GitFailed("bad ref".to_owned())
910 .describe()
911 .contains("bad ref")
912 );
913 }
914
915 #[test]
916 fn augment_git_failed_appends_shallow_clone_hint_for_unknown_revision() {
917 let stderr = "fatal: ambiguous argument 'fallow-baseline...HEAD': unknown revision or path not in the working tree.";
918 let described = ChangedFilesError::GitFailed(stderr.to_owned()).describe();
919 assert!(described.contains(stderr), "original stderr preserved");
920 assert!(
921 described.contains("shallow clone"),
922 "hint surfaced: {described}"
923 );
924 assert!(
925 described.contains("fetch-depth: 0") || described.contains("git fetch --unshallow"),
926 "hint actionable: {described}"
927 );
928 }
929
930 #[test]
931 fn augment_git_failed_passthrough_for_other_errors() {
932 let stderr = "fatal: refusing to merge unrelated histories";
933 let described = ChangedFilesError::GitFailed(stderr.to_owned()).describe();
934 assert_eq!(described, stderr);
935 }
936
937 #[test]
938 fn validate_git_ref_rejects_leading_dash() {
939 assert!(validate_git_ref("--upload-pack=evil").is_err());
940 assert!(validate_git_ref("-flag").is_err());
941 }
942
943 #[test]
944 fn validate_git_ref_accepts_baseline_tag() {
945 assert_eq!(
946 validate_git_ref("fallow-baseline").unwrap(),
947 "fallow-baseline"
948 );
949 }
950
951 #[test]
952 fn changed_files_filter_scopes_unresolved_callee_diagnostics() {
953 let mut results = AnalysisResults::default();
954 results
955 .security_unresolved_callee_diagnostics
956 .push(SecurityUnresolvedCalleeDiagnostic {
957 path: PathBuf::from("/repo/src/changed.ts"),
958 line: 4,
959 col: 0,
960 reason: SkippedSecurityCalleeReason::DynamicDispatch,
961 expression_kind: SkippedSecurityCalleeExpressionKind::Other,
962 });
963 results
964 .security_unresolved_callee_diagnostics
965 .push(SecurityUnresolvedCalleeDiagnostic {
966 path: PathBuf::from("/repo/src/unchanged.ts"),
967 line: 4,
968 col: 0,
969 reason: SkippedSecurityCalleeReason::ComputedMember,
970 expression_kind: SkippedSecurityCalleeExpressionKind::ComputedMemberExpression,
971 });
972
973 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
974 changed.insert(PathBuf::from("/repo/src/changed.ts"));
975
976 filter_results_by_changed_files(&mut results, &changed);
977
978 assert_eq!(results.security_unresolved_callee_diagnostics.len(), 1);
979 assert_eq!(
980 results.security_unresolved_callee_diagnostics[0].path,
981 PathBuf::from("/repo/src/changed.ts")
982 );
983 }
984
985 #[test]
986 fn try_get_changed_files_rejects_invalid_ref() {
987 let err = try_get_changed_files(Path::new("/"), "--evil")
988 .expect_err("leading-dash ref must be rejected");
989 assert!(matches!(err, ChangedFilesError::InvalidRef(_)));
990 assert!(err.describe().contains("cannot start with"));
991 }
992
993 #[test]
994 fn validate_git_ref_rejects_option_like_ref() {
995 assert!(validate_git_ref("--output=/tmp/fallow-proof").is_err());
996 }
997
998 #[test]
999 fn validate_git_ref_allows_reflog_relative_date() {
1000 assert!(validate_git_ref("HEAD@{1 week ago}").is_ok());
1001 }
1002
1003 #[test]
1004 fn try_get_changed_files_rejects_option_like_ref_before_git() {
1005 let root = tempfile::tempdir().expect("create temp dir");
1006 let proof_path = root.path().join("proof");
1007
1008 let result = try_get_changed_files(
1009 root.path(),
1010 &format!("--output={}", proof_path.to_string_lossy()),
1011 );
1012
1013 assert!(matches!(result, Err(ChangedFilesError::InvalidRef(_))));
1014 assert!(
1015 !proof_path.exists(),
1016 "invalid changedSince ref must not be passed through to git as an option"
1017 );
1018 }
1019
1020 #[test]
1021 fn git_command_clears_parent_git_environment() {
1022 let command = git_command(Path::new("."), &["status", "--short"]);
1023 let overrides: Vec<_> = command.get_envs().collect();
1024
1025 for var in crate::git_env::AMBIENT_GIT_ENV_VARS {
1026 assert!(
1027 overrides
1028 .iter()
1029 .any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
1030 "git helper must clear inherited {var}",
1031 );
1032 }
1033 }
1034
1035 #[test]
1036 fn filter_results_keeps_only_changed_files() {
1037 let mut results = AnalysisResults::default();
1038 results
1039 .unused_files
1040 .push(UnusedFileFinding::with_actions(UnusedFile {
1041 path: "/a.ts".into(),
1042 }));
1043 results
1044 .unused_files
1045 .push(UnusedFileFinding::with_actions(UnusedFile {
1046 path: "/b.ts".into(),
1047 }));
1048 results
1049 .unused_exports
1050 .push(UnusedExportFinding::with_actions(UnusedExport {
1051 path: "/a.ts".into(),
1052 export_name: "foo".into(),
1053 is_type_only: false,
1054 line: 1,
1055 col: 0,
1056 span_start: 0,
1057 is_re_export: false,
1058 }));
1059
1060 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
1061 changed.insert("/a.ts".into());
1062
1063 filter_results_by_changed_files(&mut results, &changed);
1064
1065 assert_eq!(results.unused_files.len(), 1);
1066 assert_eq!(results.unused_files[0].file.path, PathBuf::from("/a.ts"));
1067 assert_eq!(results.unused_exports.len(), 1);
1068 }
1069
1070 #[test]
1071 fn filter_results_preserves_dependency_level_issues() {
1072 let mut results = AnalysisResults::default();
1073 results.unused_dependencies.push(
1074 fallow_types::output_dead_code::UnusedDependencyFinding::with_actions(
1075 crate::results::UnusedDependency {
1076 package_name: "lodash".into(),
1077 location: crate::results::DependencyLocation::Dependencies,
1078 path: "/pkg.json".into(),
1079 line: 3,
1080 used_in_workspaces: Vec::new(),
1081 },
1082 ),
1083 );
1084
1085 let changed: FxHashSet<PathBuf> = FxHashSet::default();
1086 filter_results_by_changed_files(&mut results, &changed);
1087
1088 assert_eq!(results.unused_dependencies.len(), 1);
1089 }
1090
1091 #[test]
1092 fn filter_results_keeps_circular_dep_when_any_file_changed() {
1093 let mut results = AnalysisResults::default();
1094 results
1095 .circular_dependencies
1096 .push(CircularDependencyFinding::with_actions(
1097 CircularDependency {
1098 files: vec!["/a.ts".into(), "/b.ts".into()],
1099 length: 2,
1100 line: 1,
1101 col: 0,
1102 edges: Vec::new(),
1103 is_cross_package: false,
1104 },
1105 ));
1106
1107 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
1108 changed.insert("/b.ts".into());
1109
1110 filter_results_by_changed_files(&mut results, &changed);
1111 assert_eq!(results.circular_dependencies.len(), 1);
1112 }
1113
1114 #[test]
1115 fn filter_results_drops_circular_dep_when_no_file_changed() {
1116 let mut results = AnalysisResults::default();
1117 results
1118 .circular_dependencies
1119 .push(CircularDependencyFinding::with_actions(
1120 CircularDependency {
1121 files: vec!["/a.ts".into(), "/b.ts".into()],
1122 length: 2,
1123 line: 1,
1124 col: 0,
1125 edges: Vec::new(),
1126 is_cross_package: false,
1127 },
1128 ));
1129
1130 let changed: FxHashSet<PathBuf> = FxHashSet::default();
1131 filter_results_by_changed_files(&mut results, &changed);
1132 assert!(results.circular_dependencies.is_empty());
1133 }
1134
1135 #[test]
1136 fn filter_results_drops_boundary_violation_when_importer_unchanged() {
1137 let mut results = AnalysisResults::default();
1138 results
1139 .boundary_violations
1140 .push(BoundaryViolationFinding::with_actions(BoundaryViolation {
1141 from_path: "/a.ts".into(),
1142 to_path: "/b.ts".into(),
1143 from_zone: "ui".into(),
1144 to_zone: "data".into(),
1145 import_specifier: "../data/db".into(),
1146 line: 1,
1147 col: 0,
1148 }));
1149
1150 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
1151 changed.insert("/b.ts".into());
1152
1153 filter_results_by_changed_files(&mut results, &changed);
1154 assert!(results.boundary_violations.is_empty());
1155 }
1156
1157 #[test]
1158 fn filter_results_keeps_security_finding_when_trace_file_changed() {
1159 let mut results = AnalysisResults::default();
1160 results.security_findings.push(SecurityFinding {
1161 finding_id: String::new(),
1162 candidate: fallow_types::results::SecurityCandidate::default(),
1163 taint_flow: None,
1164 attack_surface: None,
1165 kind: SecurityFindingKind::ClientServerLeak,
1166 category: None,
1167 cwe: None,
1168 path: "/project/src/client.tsx".into(),
1169 line: 2,
1170 col: 0,
1171 evidence: "candidate".into(),
1172 source_backed: false,
1173 source_read: None,
1174 severity: SecuritySeverity::Low,
1175 trace: vec![
1176 TraceHop {
1177 path: "/project/src/client.tsx".into(),
1178 line: 2,
1179 col: 0,
1180 role: TraceHopRole::ClientBoundary,
1181 },
1182 TraceHop {
1183 path: "/project/src/server.ts".into(),
1184 line: 1,
1185 col: 0,
1186 role: TraceHopRole::SecretSource,
1187 },
1188 ],
1189 actions: Vec::new(),
1190 dead_code: None,
1191 reachability: None,
1192 runtime: None,
1193 });
1194
1195 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
1196 changed.insert("/project/src/server.ts".into());
1197
1198 filter_results_by_changed_files(&mut results, &changed);
1199
1200 assert_eq!(results.security_findings.len(), 1);
1201 }
1202
1203 #[test]
1204 fn filter_results_keeps_security_finding_when_untrusted_source_trace_file_changed() {
1205 let mut results = AnalysisResults::default();
1206 results.security_findings.push(SecurityFinding {
1207 finding_id: String::new(),
1208 candidate: fallow_types::results::SecurityCandidate::default(),
1209 taint_flow: None,
1210 attack_surface: None,
1211 kind: SecurityFindingKind::TaintedSink,
1212 category: Some("command-injection".into()),
1213 cwe: Some(78),
1214 path: "/project/src/runner.ts".into(),
1215 line: 4,
1216 col: 2,
1217 evidence: "candidate".into(),
1218 source_backed: false,
1219 source_read: None,
1220 severity: SecuritySeverity::Low,
1221 trace: Vec::new(),
1222 actions: Vec::new(),
1223 dead_code: None,
1224 reachability: Some(SecurityReachability {
1225 reachable_from_entry: false,
1226 reachable_from_untrusted_source: true,
1227 taint_confidence: Some(fallow_types::results::TaintConfidence::ModuleLevel),
1228 untrusted_source_hop_count: Some(1),
1229 untrusted_source_trace: vec![
1230 TraceHop {
1231 path: "/project/src/route.ts".into(),
1232 line: 1,
1233 col: 0,
1234 role: TraceHopRole::UntrustedSource,
1235 },
1236 TraceHop {
1237 path: "/project/src/runner.ts".into(),
1238 line: 4,
1239 col: 2,
1240 role: TraceHopRole::Sink,
1241 },
1242 ],
1243 blast_radius: 0,
1244 crosses_boundary: false,
1245 }),
1246 runtime: None,
1247 });
1248
1249 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
1250 changed.insert("/project/src/route.ts".into());
1251
1252 filter_results_by_changed_files(&mut results, &changed);
1253
1254 assert_eq!(results.security_findings.len(), 1);
1255 }
1256
1257 #[test]
1258 fn filter_results_keeps_relative_empty_catalog_group_when_manifest_changed() {
1259 let mut results = AnalysisResults::default();
1260 results
1261 .empty_catalog_groups
1262 .push(EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
1263 catalog_name: "legacy".into(),
1264 path: PathBuf::from("pnpm-workspace.yaml"),
1265 line: 4,
1266 }));
1267
1268 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
1269 changed.insert(PathBuf::from("/repo/pnpm-workspace.yaml"));
1270
1271 filter_results_by_changed_files(&mut results, &changed);
1272
1273 assert_eq!(results.empty_catalog_groups.len(), 1);
1274 assert_eq!(results.empty_catalog_groups[0].group.catalog_name, "legacy");
1275 }
1276
1277 #[test]
1278 fn filter_duplication_keeps_groups_with_at_least_one_changed_instance() {
1279 let mut report = DuplicationReport {
1280 clone_groups: vec![CloneGroup {
1281 instances: vec![
1282 CloneInstance {
1283 file: "/a.ts".into(),
1284 start_line: 1,
1285 end_line: 5,
1286 start_col: 0,
1287 end_col: 10,
1288 fragment: "code".into(),
1289 },
1290 CloneInstance {
1291 file: "/b.ts".into(),
1292 start_line: 1,
1293 end_line: 5,
1294 start_col: 0,
1295 end_col: 10,
1296 fragment: "code".into(),
1297 },
1298 ],
1299 token_count: 20,
1300 line_count: 5,
1301 }],
1302 clone_families: vec![],
1303 mirrored_directories: vec![],
1304 stats: DuplicationStats {
1305 total_files: 2,
1306 files_with_clones: 2,
1307 total_lines: 100,
1308 duplicated_lines: 10,
1309 total_tokens: 200,
1310 duplicated_tokens: 40,
1311 clone_groups: 1,
1312 clone_instances: 2,
1313 duplication_percentage: 10.0,
1314 clone_groups_below_min_occurrences: 0,
1315 },
1316 };
1317
1318 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
1319 changed.insert("/a.ts".into());
1320
1321 filter_duplication_by_changed_files(&mut report, &changed, Path::new(""));
1322 assert_eq!(report.clone_groups.len(), 1);
1323 assert_eq!(report.stats.clone_groups, 1);
1324 assert_eq!(report.stats.clone_instances, 2);
1325 }
1326
1327 #[cfg(windows)]
1335 #[test]
1336 fn filter_duplication_normalises_verbatim_prefix_mismatch() {
1337 let mut report = DuplicationReport {
1338 clone_groups: vec![CloneGroup {
1339 instances: vec![
1340 CloneInstance {
1341 file: PathBuf::from(r"\\?\C:\repo\src\changed.ts"),
1342 start_line: 1,
1343 end_line: 5,
1344 start_col: 0,
1345 end_col: 10,
1346 fragment: "code".into(),
1347 },
1348 CloneInstance {
1349 file: PathBuf::from(r"\\?\C:\repo\src\focused-copy.ts"),
1350 start_line: 1,
1351 end_line: 5,
1352 start_col: 0,
1353 end_col: 10,
1354 fragment: "code".into(),
1355 },
1356 ],
1357 token_count: 20,
1358 line_count: 5,
1359 }],
1360 clone_families: vec![],
1361 mirrored_directories: vec![],
1362 stats: DuplicationStats {
1363 total_files: 2,
1364 files_with_clones: 2,
1365 total_lines: 100,
1366 duplicated_lines: 10,
1367 total_tokens: 200,
1368 duplicated_tokens: 40,
1369 clone_groups: 1,
1370 clone_instances: 2,
1371 duplication_percentage: 10.0,
1372 clone_groups_below_min_occurrences: 0,
1373 },
1374 };
1375
1376 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
1377 changed.insert(PathBuf::from(r"C:\repo\src\changed.ts"));
1378
1379 filter_duplication_by_changed_files(&mut report, &changed, Path::new(""));
1380 assert_eq!(
1381 report.clone_groups.len(),
1382 1,
1383 "verbatim instance path must match non-verbatim changed-file entry"
1384 );
1385 }
1386
1387 #[cfg(windows)]
1388 #[test]
1389 fn filter_results_normalises_verbatim_prefix_mismatch() {
1390 let mut results = AnalysisResults::default();
1391 results
1392 .unused_exports
1393 .push(UnusedExportFinding::with_actions(UnusedExport {
1394 path: PathBuf::from(r"\\?\C:\repo\src\a.ts"),
1395 export_name: "foo".into(),
1396 is_type_only: false,
1397 line: 1,
1398 col: 0,
1399 span_start: 0,
1400 is_re_export: false,
1401 }));
1402
1403 let mut changed: FxHashSet<PathBuf> = FxHashSet::default();
1404 changed.insert(PathBuf::from(r"C:\repo\src\a.ts"));
1405
1406 filter_results_by_changed_files(&mut results, &changed);
1407 assert_eq!(
1408 results.unused_exports.len(),
1409 1,
1410 "verbatim finding path must match non-verbatim changed-file entry"
1411 );
1412 }
1413
1414 fn init_repo(repo: &Path) -> PathBuf {
1426 run_git(repo, &["init", "--quiet", "--initial-branch=main"]);
1427 run_git(repo, &["config", "user.email", "test@example.com"]);
1428 run_git(repo, &["config", "user.name", "test"]);
1429 run_git(repo, &["config", "commit.gpgsign", "false"]);
1430 std::fs::write(repo.join("seed.txt"), "seed\n").unwrap();
1431 run_git(repo, &["add", "seed.txt"]);
1432 run_git(repo, &["commit", "--quiet", "-m", "initial"]);
1433 run_git(repo, &["tag", "fallow-baseline"]);
1434 dunce::canonicalize(repo).unwrap()
1435 }
1436
1437 fn run_git(cwd: &Path, args: &[&str]) {
1438 let output = std::process::Command::new("git")
1439 .args(args)
1440 .current_dir(cwd)
1441 .output()
1442 .expect("git available");
1443 assert!(
1444 output.status.success(),
1445 "git {args:?} failed: {}",
1446 String::from_utf8_lossy(&output.stderr)
1447 );
1448 }
1449
1450 #[test]
1453 fn try_get_changed_files_workspace_at_repo_root() {
1454 let tmp = tempfile::tempdir().unwrap();
1455 let repo = init_repo(tmp.path());
1456 std::fs::create_dir_all(repo.join("src")).unwrap();
1457 std::fs::write(repo.join("src/new.ts"), "export const x = 1;\n").unwrap();
1458
1459 let changed = try_get_changed_files(&repo, "fallow-baseline").unwrap();
1460
1461 let expected = repo.join("src/new.ts");
1462 assert!(
1463 changed.contains(&expected),
1464 "changed set should contain {expected:?}; actual: {changed:?}"
1465 );
1466 }
1467
1468 #[test]
1476 fn try_get_changed_files_workspace_in_subdirectory() {
1477 let tmp = tempfile::tempdir().unwrap();
1478 let repo = init_repo(tmp.path());
1479 let frontend = repo.join("frontend");
1480 std::fs::create_dir_all(frontend.join("src")).unwrap();
1481 std::fs::write(frontend.join("src/new.ts"), "export const x = 1;\n").unwrap();
1482
1483 let changed = try_get_changed_files(&frontend, "fallow-baseline").unwrap();
1484
1485 let expected = repo.join("frontend/src/new.ts");
1486 assert!(
1487 changed.contains(&expected),
1488 "changed set should contain canonical {expected:?}; actual: {changed:?}"
1489 );
1490 let bogus = frontend.join("frontend/src/new.ts");
1491 assert!(
1492 !changed.contains(&bogus),
1493 "changed set must not contain double-frontend path {bogus:?}"
1494 );
1495 }
1496
1497 #[test]
1512 fn try_get_changed_files_includes_committed_sibling_changes() {
1513 let tmp = tempfile::tempdir().unwrap();
1514 let repo = init_repo(tmp.path());
1515 let backend = repo.join("backend");
1516 std::fs::create_dir_all(&backend).unwrap();
1517 std::fs::write(backend.join("server.py"), "print('hi')\n").unwrap();
1518 run_git(&repo, &["add", "."]);
1519 run_git(&repo, &["commit", "--quiet", "-m", "add backend"]);
1520
1521 let frontend = repo.join("frontend");
1522 std::fs::create_dir_all(&frontend).unwrap();
1523
1524 let changed = try_get_changed_files(&frontend, "fallow-baseline").unwrap();
1525
1526 let expected = repo.join("backend/server.py");
1527 assert!(
1528 changed.contains(&expected),
1529 "committed sibling backend/server.py should be in the set: {changed:?}"
1530 );
1531 }
1532
1533 #[test]
1537 fn try_get_changed_files_includes_modified_tracked_file() {
1538 let tmp = tempfile::tempdir().unwrap();
1539 let repo = init_repo(tmp.path());
1540 let frontend = repo.join("frontend");
1541 std::fs::create_dir_all(frontend.join("src")).unwrap();
1542 std::fs::write(frontend.join("src/old.ts"), "export const x = 1;\n").unwrap();
1543 run_git(&repo, &["add", "."]);
1544 run_git(&repo, &["commit", "--quiet", "-m", "add old"]);
1545 run_git(&repo, &["tag", "fallow-baseline-v2"]);
1546 std::fs::write(frontend.join("src/old.ts"), "export const x = 2;\n").unwrap();
1547
1548 let changed = try_get_changed_files(&frontend, "fallow-baseline-v2").unwrap();
1549
1550 let expected = repo.join("frontend/src/old.ts");
1551 assert!(
1552 changed.contains(&expected),
1553 "modified tracked file {expected:?} missing from set: {changed:?}"
1554 );
1555 }
1556
1557 #[test]
1563 fn resolve_git_toplevel_returns_canonical_path() {
1564 let tmp = tempfile::tempdir().unwrap();
1565 let repo = init_repo(tmp.path());
1566 let frontend = repo.join("frontend");
1567 std::fs::create_dir_all(&frontend).unwrap();
1568
1569 let toplevel = resolve_git_toplevel(&frontend).unwrap();
1570 assert_eq!(toplevel, repo, "toplevel should equal canonical repo root");
1571 assert_eq!(
1572 toplevel,
1573 dunce::canonicalize(&toplevel).unwrap(),
1574 "resolved toplevel should already be canonical"
1575 );
1576 }
1577
1578 #[test]
1582 fn resolve_git_toplevel_not_a_repository() {
1583 let tmp = tempfile::tempdir().unwrap();
1584 let result = resolve_git_toplevel(tmp.path());
1585 assert!(
1586 matches!(result, Err(ChangedFilesError::NotARepository)),
1587 "expected NotARepository, got {result:?}"
1588 );
1589 }
1590
1591 #[test]
1596 fn resolve_git_common_dir_collapses_worktrees() {
1597 let tmp = tempfile::tempdir().unwrap();
1598 let repo = init_repo(tmp.path());
1599 let linked = tmp.path().join("linked-worktree");
1600 run_git(
1601 &repo,
1602 &[
1603 "worktree",
1604 "add",
1605 "--quiet",
1606 linked.to_str().unwrap(),
1607 "-b",
1608 "feat",
1609 ],
1610 );
1611
1612 let main_common = resolve_git_common_dir(&repo).unwrap();
1613 let linked_common = resolve_git_common_dir(&linked).unwrap();
1614 assert_eq!(
1615 main_common, linked_common,
1616 "worktrees of one repo must share a common dir"
1617 );
1618
1619 let main_top = resolve_git_toplevel(&repo).unwrap();
1621 let linked_top = resolve_git_toplevel(&linked).unwrap();
1622 assert_ne!(
1623 main_top, linked_top,
1624 "the two worktrees should have distinct toplevels"
1625 );
1626 }
1627
1628 #[test]
1631 fn resolve_git_common_dir_not_a_repository() {
1632 let tmp = tempfile::tempdir().unwrap();
1633 let result = resolve_git_common_dir(tmp.path());
1634 assert!(
1635 matches!(result, Err(ChangedFilesError::NotARepository)),
1636 "expected NotARepository, got {result:?}"
1637 );
1638 }
1639
1640 #[test]
1643 fn try_get_changed_files_not_a_repository() {
1644 let tmp = tempfile::tempdir().unwrap();
1645 let result = try_get_changed_files(tmp.path(), "main");
1646 assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
1647 }
1648
1649 #[test]
1650 fn filter_duplication_drops_groups_with_no_changed_instance() {
1651 let mut report = DuplicationReport {
1652 clone_groups: vec![CloneGroup {
1653 instances: vec![CloneInstance {
1654 file: "/a.ts".into(),
1655 start_line: 1,
1656 end_line: 5,
1657 start_col: 0,
1658 end_col: 10,
1659 fragment: "code".into(),
1660 }],
1661 token_count: 20,
1662 line_count: 5,
1663 }],
1664 clone_families: vec![],
1665 mirrored_directories: vec![],
1666 stats: DuplicationStats {
1667 total_files: 1,
1668 files_with_clones: 1,
1669 total_lines: 100,
1670 duplicated_lines: 5,
1671 total_tokens: 100,
1672 duplicated_tokens: 20,
1673 clone_groups: 1,
1674 clone_instances: 1,
1675 duplication_percentage: 5.0,
1676 clone_groups_below_min_occurrences: 0,
1677 },
1678 };
1679
1680 let changed: FxHashSet<PathBuf> = FxHashSet::default();
1681 filter_duplication_by_changed_files(&mut report, &changed, Path::new(""));
1682 assert!(report.clone_groups.is_empty());
1683 assert_eq!(report.stats.clone_groups, 0);
1684 assert_eq!(report.stats.clone_instances, 0);
1685 assert!((report.stats.duplication_percentage - 0.0).abs() < f64::EPSILON);
1686 }
1687}