1use std::path::{Path, PathBuf};
4use std::process::{Command, Output, Stdio};
5use std::sync::OnceLock;
6
7use fallow_types::{
8 output_dead_code::{
9 CircularDependencyFinding, DuplicateExportFinding, DuplicatePropShapeFinding,
10 PackageCycleFinding, PropDrillingChainFinding, ReExportCycleFinding,
11 UnlistedDependencyFinding,
12 },
13 results::{AnalysisResults, SecurityFinding},
14};
15use rustc_hash::FxHashSet;
16
17use crate::duplicates::{self, DuplicationReport};
18
19pub use crate::git_env::{AMBIENT_GIT_ENV_VARS, clear_ambient_git_env};
20
21pub type ChangedFilesSpawnHook = fn(&mut std::process::Command) -> std::io::Result<Output>;
24
25static SPAWN_HOOK: OnceLock<ChangedFilesSpawnHook> = OnceLock::new();
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum ChangedFilesError {
30 InvalidRef(String),
32 GitMissing(String),
34 NotARepository,
36 GitFailed(String),
38}
39
40impl ChangedFilesError {
41 #[must_use]
43 pub fn describe(&self) -> String {
44 match self {
45 Self::InvalidRef(err) => format!("invalid git ref: {err}"),
46 Self::GitMissing(err) => format!("failed to run git: {err}"),
47 Self::NotARepository => "not a git repository".to_owned(),
48 Self::GitFailed(stderr) => augment_git_failed(stderr),
49 }
50 }
51
52 #[must_use]
58 pub const fn reason(&self) -> &'static str {
59 match self {
60 Self::InvalidRef(_) => "invalid-ref",
61 Self::GitMissing(_) => "git-missing",
62 Self::NotARepository => "not-a-repository",
63 Self::GitFailed(_) => "git-failed",
64 }
65 }
66
67 #[must_use]
78 pub fn changed_since_message(&self, git_ref: &str) -> String {
79 let cause = self
80 .describe()
81 .split_whitespace()
82 .collect::<Vec<_>>()
83 .join(" ");
84 format!(
85 "--changed-since '{git_ref}' was ignored because {cause}, so this report covers \
86 the whole project instead of the changed files. {}",
87 self.changed_since_remedy()
88 )
89 }
90
91 const fn changed_since_remedy(&self) -> &'static str {
93 match self {
94 Self::InvalidRef(_) => {
95 "Pass a ref git can resolve, such as a branch name or a commit sha."
96 }
97 Self::GitMissing(_) => {
98 "Install git and make it available on PATH, or drop --changed-since."
99 }
100 Self::NotARepository => {
101 "Run fallow from inside the repository, or drop --changed-since."
102 }
103 Self::GitFailed(_) => {
104 "Verify the ref exists in this repository, and check out with full history."
105 }
106 }
107 }
108}
109
110fn augment_git_failed(stderr: &str) -> String {
111 let lower = stderr.to_ascii_lowercase();
112 if lower.contains("not a valid object name")
113 || lower.contains("unknown revision")
114 || lower.contains("ambiguous argument")
115 {
116 format!(
117 "{stderr} (shallow clone? try `git fetch --unshallow`, or set `fetch-depth: 0` on actions/checkout / `GIT_DEPTH: 0` in GitLab CI)"
118 )
119 } else {
120 stderr.to_owned()
121 }
122}
123
124pub fn set_spawn_hook(hook: ChangedFilesSpawnHook) {
126 let _ = SPAWN_HOOK.set(hook);
127}
128
129pub(crate) fn validate_git_ref(s: &str) -> Result<&str, String> {
131 if s.is_empty() {
132 return Err("git ref cannot be empty".to_string());
133 }
134 if s.starts_with('-') {
135 return Err("git ref cannot start with '-'".to_string());
136 }
137 let mut in_braces = false;
138 for c in s.chars() {
139 match c {
140 '{' => in_braces = true,
141 '}' => in_braces = false,
142 ':' | ' ' if in_braces => {}
143 c if c.is_ascii_alphanumeric()
144 || matches!(c, '.' | '_' | '-' | '/' | '~' | '^' | '@' | '{' | '}') => {}
145 _ => return Err(format!("git ref contains disallowed character: '{c}'")),
146 }
147 }
148 if in_braces {
149 return Err("git ref has unclosed '{'".to_string());
150 }
151 Ok(s)
152}
153
154pub fn resolve_git_toplevel(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
156 let output = spawn_output(&mut git_command(cwd, &["rev-parse", "--show-toplevel"]))
157 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
158
159 if !output.status.success() {
160 let stderr = String::from_utf8_lossy(&output.stderr);
161 return Err(if stderr.contains("not a git repository") {
162 ChangedFilesError::NotARepository
163 } else {
164 ChangedFilesError::GitFailed(stderr.trim().to_owned())
165 });
166 }
167
168 let raw = String::from_utf8_lossy(&output.stdout);
169 let trimmed = raw.trim();
170 if trimmed.is_empty() {
171 return Err(ChangedFilesError::GitFailed(
172 "git rev-parse --show-toplevel returned empty output".to_owned(),
173 ));
174 }
175
176 let path = PathBuf::from(trimmed);
177 Ok(dunce::canonicalize(&path).unwrap_or(path))
178}
179
180pub fn resolve_git_common_dir(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
182 let output = spawn_output(&mut git_command(
183 cwd,
184 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
185 ))
186 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
187
188 if !output.status.success() {
189 let stderr = String::from_utf8_lossy(&output.stderr);
190 return Err(if stderr.contains("not a git repository") {
191 ChangedFilesError::NotARepository
192 } else {
193 ChangedFilesError::GitFailed(stderr.trim().to_owned())
194 });
195 }
196
197 let raw = String::from_utf8_lossy(&output.stdout);
198 let trimmed = raw.trim();
199 if trimmed.is_empty() {
200 return Err(ChangedFilesError::GitFailed(
201 "git rev-parse --git-common-dir returned empty output".to_owned(),
202 ));
203 }
204
205 let path = PathBuf::from(trimmed);
206 Ok(dunce::canonicalize(&path).unwrap_or(path))
207}
208
209pub fn resolve_git_common_dir_and_toplevel(
223 cwd: &Path,
224) -> Result<(PathBuf, PathBuf), ChangedFilesError> {
225 let output = spawn_output(&mut git_command(
226 cwd,
227 &[
228 "rev-parse",
229 "--path-format=absolute",
230 "--git-common-dir",
231 "--show-toplevel",
232 ],
233 ))
234 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
235
236 if !output.status.success() {
237 let stderr = String::from_utf8_lossy(&output.stderr);
238 return Err(if stderr.contains("not a git repository") {
239 ChangedFilesError::NotARepository
240 } else {
241 ChangedFilesError::GitFailed(stderr.trim().to_owned())
242 });
243 }
244
245 let raw = String::from_utf8_lossy(&output.stdout);
246 let mut lines = raw.lines();
247 let (Some(common), Some(toplevel), None) = (lines.next(), lines.next(), lines.next()) else {
248 return Err(ChangedFilesError::GitFailed(
249 "git rev-parse did not print one common dir and one toplevel".to_owned(),
250 ));
251 };
252 let canonical = |line: &str| {
253 let path = PathBuf::from(line.trim());
254 dunce::canonicalize(&path).unwrap_or(path)
255 };
256 if common.trim().is_empty() || toplevel.trim().is_empty() {
257 return Err(ChangedFilesError::GitFailed(
258 "git rev-parse returned an empty path".to_owned(),
259 ));
260 }
261 Ok((canonical(common), canonical(toplevel)))
262}
263
264fn try_get_changed_files(
266 root: &Path,
267 git_ref: &str,
268) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
269 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
270 let toplevel = resolve_git_toplevel(root)?;
271 try_get_changed_files_with_toplevel(root, &toplevel, git_ref)
272}
273
274pub fn changed_files(root: &Path, git_ref: &str) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
280 try_get_changed_files(root, git_ref)
281}
282
283pub(crate) struct ChangedFilesBatch<'a> {
287 cwd: &'a Path,
288 toplevel: PathBuf,
289 working_tree: Option<FxHashSet<PathBuf>>,
290}
291
292impl<'a> ChangedFilesBatch<'a> {
293 pub(crate) fn new(cwd: &'a Path, first_ref: &str) -> Result<Self, ChangedFilesError> {
294 validate_git_ref(first_ref).map_err(ChangedFilesError::InvalidRef)?;
295 Ok(Self {
296 cwd,
297 toplevel: resolve_git_toplevel(cwd)?,
298 working_tree: None,
299 })
300 }
301
302 pub(crate) fn changed_files(
303 &mut self,
304 git_ref: &str,
305 ) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
306 let mut files = committed_changed_files(self.cwd, &self.toplevel, git_ref)?;
307 if self.working_tree.is_none() {
308 self.working_tree = Some(working_tree_changed_files(self.cwd, &self.toplevel)?);
309 }
310 if let Some(working_tree) = &self.working_tree {
311 files.extend(working_tree.iter().cloned());
312 }
313 Ok(files)
314 }
315}
316
317pub fn try_get_changed_files_with_toplevel(
319 cwd: &Path,
320 toplevel: &Path,
321 git_ref: &str,
322) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
323 let mut files = committed_changed_files(cwd, toplevel, git_ref)?;
324 files.extend(working_tree_changed_files(cwd, toplevel)?);
325 Ok(files)
326}
327
328fn committed_changed_files(
329 cwd: &Path,
330 toplevel: &Path,
331 git_ref: &str,
332) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
333 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
334 collect_git_paths(
335 cwd,
336 toplevel,
337 &[
338 "diff",
339 "--name-only",
340 "-z",
341 "--end-of-options",
342 &format!("{git_ref}...HEAD"),
343 ],
344 )
345}
346
347fn working_tree_changed_files(
348 cwd: &Path,
349 toplevel: &Path,
350) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
351 let mut files = collect_git_paths(cwd, toplevel, &["diff", "--name-only", "-z", "HEAD"])?;
352 files.extend(collect_git_paths(
353 cwd,
354 toplevel,
355 &[
356 "ls-files",
357 "--full-name",
358 "--others",
359 "--exclude-standard",
360 "-z",
361 ],
362 )?);
363 Ok(files)
364}
365
366#[derive(Debug, Clone, PartialEq, Eq)]
369pub struct RenamedFile {
370 pub from: PathBuf,
372 pub to: PathBuf,
374}
375
376pub fn try_get_renamed_files(
388 root: &Path,
389 git_ref: &str,
390) -> Result<Vec<RenamedFile>, ChangedFilesError> {
391 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
392 let toplevel = resolve_git_toplevel(root)?;
393 let mut renames = collect_git_rename_pairs(
394 root,
395 &toplevel,
396 &[
397 "diff",
398 "--name-status",
399 "-z",
400 "--find-renames",
401 "--end-of-options",
402 &format!("{git_ref}...HEAD"),
403 ],
404 )?;
405 let staged = collect_git_rename_pairs(
406 root,
407 &toplevel,
408 &["diff", "--name-status", "-z", "--find-renames", "HEAD"],
409 )?;
410 for pair in staged {
411 if let Some(chained) = renames.iter_mut().find(|rename| rename.to == pair.from) {
412 chained.to = pair.to;
413 } else {
414 renames.push(pair);
415 }
416 }
417 Ok(renames)
418}
419
420fn collect_git_rename_pairs(
426 cwd: &Path,
427 toplevel: &Path,
428 args: &[&str],
429) -> Result<Vec<RenamedFile>, ChangedFilesError> {
430 let output = spawn_output(&mut git_command(cwd, args))
431 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
432
433 if !output.status.success() {
434 return Err(changed_files_error_from_output(&output));
435 }
436
437 let mut fields = output
438 .stdout
439 .split(|byte| *byte == 0)
440 .filter(|field| !field.is_empty());
441 let mut renames = Vec::new();
442 while let Some(status) = fields.next() {
443 let Some(first_path) = fields.next() else {
444 break;
445 };
446 match status.first() {
447 Some(b'R') => {
448 let Some(second_path) = fields.next() else {
449 break;
450 };
451 renames.push(RenamedFile {
452 from: toplevel.join(git_path_from_bytes(first_path)),
453 to: toplevel.join(git_path_from_bytes(second_path)),
454 });
455 }
456 Some(b'C') => {
459 let _ = fields.next();
460 }
461 _ => {}
462 }
463 }
464 Ok(renames)
465}
466
467pub fn try_get_changed_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
472 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
473 let toplevel = resolve_git_toplevel(root)?;
474 let merge_base_output = spawn_output(&mut git_command(root, &["merge-base", git_ref, "HEAD"]))
475 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
476 if !merge_base_output.status.success() {
477 return Err(changed_files_error_from_output(&merge_base_output));
478 }
479 let merge_base = String::from_utf8_lossy(&merge_base_output.stdout)
480 .trim()
481 .to_owned();
482 if merge_base.is_empty() {
483 return Err(ChangedFilesError::GitFailed(
484 "git merge-base returned empty output".to_owned(),
485 ));
486 }
487
488 let output = spawn_output(&mut git_command(
489 root,
490 &[
491 "diff",
492 "--relative",
493 "--unified=0",
494 "--end-of-options",
495 &merge_base,
496 ],
497 ))
498 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
499
500 if !output.status.success() {
501 return Err(changed_files_error_from_output(&output));
502 }
503
504 let mut diff = String::from_utf8_lossy(&output.stdout).into_owned();
505 append_untracked_diffs(root, &toplevel, &mut diff)?;
506 Ok(diff)
507}
508
509fn append_untracked_diffs(
510 root: &Path,
511 toplevel: &Path,
512 diff: &mut String,
513) -> Result<(), ChangedFilesError> {
514 let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
515 let mut untracked: Vec<PathBuf> = collect_git_paths(
516 root,
517 toplevel,
518 &[
519 "ls-files",
520 "--full-name",
521 "--others",
522 "--exclude-standard",
523 "-z",
524 ],
525 )?
526 .into_iter()
527 .filter_map(|path| {
528 path.strip_prefix(&canonical_root)
529 .ok()
530 .map(Path::to_path_buf)
531 })
532 .collect();
533 untracked.sort_unstable();
534
535 #[cfg(windows)]
536 let empty_file = "NUL";
537 #[cfg(not(windows))]
538 let empty_file = "/dev/null";
539
540 for path in untracked {
541 let mut command = git_command(root, &["diff", "--no-index", "--unified=0", "--"]);
542 command.arg(empty_file).arg(untracked_path_arg(&path));
543 let output =
544 spawn_output(&mut command).map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
545 if !output.status.success() && output.status.code() != Some(1) {
546 return Err(changed_files_error_from_output(&output));
547 }
548 if !diff.is_empty() && !diff.ends_with('\n') {
549 diff.push('\n');
550 }
551 diff.push_str(&String::from_utf8_lossy(&output.stdout));
552 }
553 Ok(())
554}
555
556fn untracked_path_arg(path: &Path) -> String {
561 path.to_string_lossy().replace('\\', "/")
562}
563
564fn changed_files_error_from_output(output: &Output) -> ChangedFilesError {
565 let stderr = String::from_utf8_lossy(&output.stderr);
566 if stderr.contains("not a git repository") {
567 ChangedFilesError::NotARepository
568 } else {
569 ChangedFilesError::GitFailed(stderr.trim().to_owned())
570 }
571}
572
573#[must_use]
575#[expect(
576 clippy::print_stderr,
577 reason = "intentional user-facing warning for the CLI's --changed-since fallback path; typed callers use try_get_changed_files instead"
578)]
579pub fn get_changed_files(root: &Path, git_ref: &str) -> Option<FxHashSet<PathBuf>> {
580 match try_get_changed_files(root, git_ref) {
581 Ok(files) => Some(files),
582 Err(err) => {
583 eprintln!("Warning: {}", err.changed_since_message(git_ref));
584 None
585 }
586 }
587}
588
589fn spawn_output(command: &mut Command) -> std::io::Result<Output> {
590 if let Some(hook) = SPAWN_HOOK.get() {
591 hook(command)
592 } else {
593 command.output()
594 }
595}
596
597fn collect_git_paths(
598 cwd: &Path,
599 toplevel: &Path,
600 args: &[&str],
601) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
602 let output = spawn_output(&mut git_command(cwd, args))
603 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
604
605 if !output.status.success() {
606 let stderr = String::from_utf8_lossy(&output.stderr);
607 return Err(if stderr.contains("not a git repository") {
608 ChangedFilesError::NotARepository
609 } else {
610 ChangedFilesError::GitFailed(stderr.trim().to_owned())
611 });
612 }
613
614 let files = output
615 .stdout
616 .split(|byte| *byte == 0)
617 .filter(|path| !path.is_empty())
618 .map(git_path_from_bytes)
619 .map(|path| toplevel.join(path))
620 .collect();
621
622 Ok(files)
623}
624
625#[cfg(unix)]
631pub(crate) fn git_path_from_bytes(path: &[u8]) -> PathBuf {
632 use std::ffi::OsString;
633 use std::os::unix::ffi::OsStringExt;
634
635 PathBuf::from(OsString::from_vec(path.to_vec()))
636}
637
638#[cfg(windows)]
641pub(crate) fn git_path_from_bytes(path: &[u8]) -> PathBuf {
642 PathBuf::from(String::from_utf8_lossy(path).replace('/', "\\"))
643}
644
645#[expect(
646 clippy::disallowed_methods,
647 reason = "canonical engine-owned git spawn wrapper for changed-file orchestration"
648)]
649fn git_command(cwd: &Path, args: &[&str]) -> Command {
650 let mut command = Command::new("git");
651 clear_ambient_git_env(&mut command);
652 command.stdin(Stdio::null()).args(args).current_dir(cwd);
654 command
655}
656
657#[expect(
662 clippy::implicit_hasher,
663 reason = "fallow standardizes on FxHashSet across the workspace"
664)]
665pub fn filter_results_by_changed_files(
666 results: &mut AnalysisResults,
667 changed_files: &FxHashSet<PathBuf>,
668) {
669 filter_results_by_path_scope(results, &NormalizedChangedFiles::new(changed_files));
670}
671
672pub(crate) trait ChangedPathScope {
675 fn contains(&self, path: &Path) -> bool;
676 fn contains_workspace(&self, path: &Path) -> bool {
677 self.contains(path)
678 }
679}
680
681#[derive(Debug, Clone, Default)]
683pub(crate) struct NormalizedChangedFiles(FxHashSet<PathBuf>);
684
685impl NormalizedChangedFiles {
686 pub(crate) fn new(changed_files: &FxHashSet<PathBuf>) -> Self {
687 Self(normalize_changed_files_set(changed_files))
688 }
689}
690
691impl ChangedPathScope for NormalizedChangedFiles {
692 fn contains(&self, path: &Path) -> bool {
693 contains_normalized(&self.0, path)
694 }
695
696 fn contains_workspace(&self, path: &Path) -> bool {
697 normalized_set_contains_path(&self.0, path)
698 }
699}
700
701pub(crate) fn filter_results_by_path_scope(
702 results: &mut AnalysisResults,
703 scope: &impl ChangedPathScope,
704) {
705 classify_changed_file_filter_fields(results);
706 retain_basic_issue_findings_by_changed_path(results, scope);
707 retain_graph_findings_by_changed_files(results, scope);
708 retain_boundary_policy_and_suppression_findings(results, scope);
709 retain_security_and_workspace_findings(results, scope);
710 retain_framework_findings_by_changed_files(results, scope);
711}
712
713fn classify_changed_file_filter_fields(results: &AnalysisResults) {
714 let AnalysisResults {
715 unused_files: _unused_files,
716 unused_exports: _unused_exports,
717 unused_types: _unused_types,
718 private_type_leaks: _private_type_leaks,
719 deprecated_exports_in_use: _deprecated_exports_in_use,
720 unused_dependencies: _unused_dependencies,
721 unused_dev_dependencies: _unused_dev_dependencies,
722 unused_optional_dependencies: _unused_optional_dependencies,
723 unused_enum_members: _unused_enum_members,
724 unused_class_members: _unused_class_members,
725 unused_store_members: _unused_store_members,
726 unresolved_imports: _unresolved_imports,
727 unlisted_dependencies: _unlisted_dependencies,
728 duplicate_exports: _duplicate_exports,
729 type_only_dependencies: _type_only_dependencies,
730 test_only_dependencies: _test_only_dependencies,
731 dev_dependencies_in_production: _dev_dependencies_in_production,
732 circular_dependencies: _circular_dependencies,
733 re_export_cycles: _re_export_cycles,
734 package_cycles: _package_cycles,
735 boundary_violations: _boundary_violations,
736 boundary_coverage_violations: _boundary_coverage_violations,
737 boundary_call_violations: _boundary_call_violations,
738 policy_violations: _policy_violations,
739 stale_suppressions: _stale_suppressions,
740 unused_catalog_entries: _unused_catalog_entries,
741 empty_catalog_groups: _empty_catalog_groups,
742 unresolved_catalog_references: _unresolved_catalog_references,
743 unused_dependency_overrides: _unused_dependency_overrides,
744 misconfigured_dependency_overrides: _misconfigured_dependency_overrides,
745 invalid_client_exports: _invalid_client_exports,
746 mixed_client_server_barrels: _mixed_client_server_barrels,
747 misplaced_directives: _misplaced_directives,
748 unprovided_injects: _unprovided_injects,
749 unrendered_components: _unrendered_components,
750 route_collisions: _route_collisions,
751 dynamic_segment_name_conflicts: _dynamic_segment_name_conflicts,
752 unused_component_props: _unused_component_props,
753 unused_component_emits: _unused_component_emits,
754 unused_component_inputs: _unused_component_inputs,
755 unused_component_outputs: _unused_component_outputs,
756 unused_svelte_events: _unused_svelte_events,
757 unused_server_actions: _unused_server_actions,
758 unused_load_data_keys: _unused_load_data_keys,
759 unused_load_data_keys_global_abstain: _unused_load_data_keys_global_abstain,
760 prop_drilling_chains: _prop_drilling_chains,
761 thin_wrappers: _thin_wrappers,
762 duplicate_prop_shapes: _duplicate_prop_shapes,
763 suppression_count: _suppression_count,
764 unused_component_props_exempted: _unused_component_props_exempted,
765 active_suppressions: _active_suppressions,
766 feature_flags: _feature_flags,
767 security_findings: _security_findings,
768 security_unresolved_edge_files: _security_unresolved_edge_files,
769 security_unresolved_callee_sites: _security_unresolved_callee_sites,
770 security_unresolved_callee_diagnostics: _security_unresolved_callee_diagnostics,
771 export_usages: _export_usages,
772 entry_point_summary: _entry_point_summary,
773 render_fan_in: _render_fan_in,
774 react_component_intel: _react_component_intel,
775 semantic_framework_contracts: _semantic_framework_contracts,
776 } = results;
777}
778
779fn retain_basic_issue_findings_by_changed_path(
780 results: &mut AnalysisResults,
781 scope: &impl ChangedPathScope,
782) {
783 retain_by_changed_path(&mut results.unused_files, scope, |f| &f.file.path);
784 retain_by_changed_path(&mut results.unused_exports, scope, |e| &e.export.path);
785 retain_by_changed_path(&mut results.unused_types, scope, |e| &e.export.path);
786 retain_by_changed_path(&mut results.private_type_leaks, scope, |e| &e.leak.path);
787 retain_by_changed_path(&mut results.deprecated_exports_in_use, scope, |e| {
788 &e.export.path
789 });
790 retain_by_changed_path(&mut results.unused_enum_members, scope, |m| &m.member.path);
791 retain_by_changed_path(&mut results.unused_class_members, scope, |m| &m.member.path);
792 retain_by_changed_path(&mut results.unused_store_members, scope, |m| &m.member.path);
793 retain_by_changed_path(&mut results.unresolved_imports, scope, |i| &i.import.path);
794}
795
796fn retain_graph_findings_by_changed_files(
797 results: &mut AnalysisResults,
798 scope: &impl ChangedPathScope,
799) {
800 retain_unlisted_dependencies_by_import_site(&mut results.unlisted_dependencies, scope);
801 retain_duplicate_exports_by_changed_locations(&mut results.duplicate_exports, scope);
802 retain_circular_dependencies_by_changed_file(&mut results.circular_dependencies, scope);
803 retain_re_export_cycles_by_changed_file(&mut results.re_export_cycles, scope);
804 retain_package_cycles_by_changed_file(&mut results.package_cycles, scope);
805}
806
807fn retain_boundary_policy_and_suppression_findings(
808 results: &mut AnalysisResults,
809 scope: &impl ChangedPathScope,
810) {
811 retain_by_changed_path(&mut results.boundary_violations, scope, |v| {
812 &v.violation.from_path
813 });
814 retain_by_changed_path(&mut results.boundary_coverage_violations, scope, |v| {
815 &v.violation.path
816 });
817 retain_by_changed_path(&mut results.boundary_call_violations, scope, |v| {
818 &v.violation.path
819 });
820 retain_by_changed_path(&mut results.policy_violations, scope, |v| &v.violation.path);
821 retain_by_changed_path(&mut results.stale_suppressions, scope, |s| &s.path);
822}
823
824fn retain_security_and_workspace_findings(
825 results: &mut AnalysisResults,
826 scope: &impl ChangedPathScope,
827) {
828 retain_security_findings_by_changed_path(&mut results.security_findings, scope);
829 retain_by_changed_path(
830 &mut results.security_unresolved_callee_diagnostics,
831 scope,
832 |d| &d.path,
833 );
834 retain_by_changed_path(&mut results.unresolved_catalog_references, scope, |r| {
835 &r.reference.path
836 });
837 results
838 .empty_catalog_groups
839 .retain(|g| scope.contains_workspace(&g.group.path));
840 retain_by_changed_path(&mut results.unused_dependency_overrides, scope, |o| {
841 &o.entry.path
842 });
843 retain_by_changed_path(
844 &mut results.misconfigured_dependency_overrides,
845 scope,
846 |o| &o.entry.path,
847 );
848}
849
850fn retain_framework_findings_by_changed_files(
851 results: &mut AnalysisResults,
852 scope: &impl ChangedPathScope,
853) {
854 retain_client_boundary_findings_by_changed_files(results, scope);
855 retain_component_contract_findings_by_changed_files(results, scope);
856 retain_react_health_findings_by_changed_files(results, scope);
857 retain_nextjs_findings_by_changed_files(results, scope);
858}
859
860fn retain_client_boundary_findings_by_changed_files(
861 results: &mut AnalysisResults,
862 scope: &impl ChangedPathScope,
863) {
864 let AnalysisResults {
865 invalid_client_exports,
866 mixed_client_server_barrels,
867 misplaced_directives,
868 ..
869 } = results;
870
871 retain_by_changed_path(invalid_client_exports, scope, |e| &e.export.path);
872 retain_by_changed_path(mixed_client_server_barrels, scope, |b| &b.barrel.path);
873 retain_by_changed_path(misplaced_directives, scope, |d| &d.directive_site.path);
874}
875
876fn retain_component_contract_findings_by_changed_files(
877 results: &mut AnalysisResults,
878 scope: &impl ChangedPathScope,
879) {
880 let AnalysisResults {
881 unprovided_injects,
882 unrendered_components,
883 unused_component_props,
884 unused_component_emits,
885 unused_component_inputs,
886 unused_component_outputs,
887 unused_svelte_events,
888 unused_server_actions,
889 unused_load_data_keys,
890 ..
891 } = results;
892
893 retain_by_changed_path(unprovided_injects, scope, |i| &i.inject.path);
894 retain_by_changed_path(unrendered_components, scope, |c| &c.component.path);
895 retain_by_changed_path(unused_component_props, scope, |p| &p.prop.path);
896 retain_by_changed_path(unused_component_emits, scope, |e| &e.emit.path);
897 retain_by_changed_path(unused_component_inputs, scope, |i| &i.input.path);
898 retain_by_changed_path(unused_component_outputs, scope, |o| &o.output.path);
899 retain_by_changed_path(unused_svelte_events, scope, |e| &e.event.path);
900 retain_by_changed_path(unused_server_actions, scope, |a| &a.action.path);
901 retain_by_changed_path(unused_load_data_keys, scope, |k| &k.key.path);
902}
903
904fn retain_react_health_findings_by_changed_files(
905 results: &mut AnalysisResults,
906 scope: &impl ChangedPathScope,
907) {
908 let AnalysisResults {
909 prop_drilling_chains,
910 thin_wrappers,
911 duplicate_prop_shapes,
912 ..
913 } = results;
914
915 retain_prop_drilling_chains_by_anchor(prop_drilling_chains, scope);
916 retain_by_changed_path(thin_wrappers, scope, |w| &w.wrapper.file);
917 retain_duplicate_prop_shapes_by_anchor(duplicate_prop_shapes, scope);
918}
919
920fn retain_nextjs_findings_by_changed_files(
921 results: &mut AnalysisResults,
922 scope: &impl ChangedPathScope,
923) {
924 let AnalysisResults {
925 route_collisions,
926 dynamic_segment_name_conflicts,
927 ..
928 } = results;
929
930 retain_by_changed_path(route_collisions, scope, |c| &c.collision.path);
931 retain_by_changed_path(dynamic_segment_name_conflicts, scope, |c| &c.conflict.path);
932}
933
934fn retain_unlisted_dependencies_by_import_site(
935 dependencies: &mut Vec<UnlistedDependencyFinding>,
936 scope: &impl ChangedPathScope,
937) {
938 dependencies.retain(|dependency| {
939 dependency
940 .dep
941 .imported_from
942 .iter()
943 .any(|site| scope.contains(&site.path))
944 });
945}
946
947fn retain_duplicate_exports_by_changed_locations(
948 duplicate_exports: &mut Vec<DuplicateExportFinding>,
949 scope: &impl ChangedPathScope,
950) {
951 for duplicate in &mut *duplicate_exports {
952 duplicate
953 .export
954 .locations
955 .retain(|location| scope.contains(&location.path));
956 }
957 duplicate_exports.retain(|duplicate| duplicate.export.locations.len() >= 2);
958}
959
960fn retain_circular_dependencies_by_changed_file(
961 cycles: &mut Vec<CircularDependencyFinding>,
962 scope: &impl ChangedPathScope,
963) {
964 cycles.retain(|cycle| cycle.cycle.files.iter().any(|file| scope.contains(file)));
965}
966
967fn retain_re_export_cycles_by_changed_file(
968 cycles: &mut Vec<ReExportCycleFinding>,
969 scope: &impl ChangedPathScope,
970) {
971 cycles.retain(|cycle| cycle.cycle.files.iter().any(|file| scope.contains(file)));
972}
973
974fn retain_package_cycles_by_changed_file(
975 cycles: &mut Vec<PackageCycleFinding>,
976 scope: &impl ChangedPathScope,
977) {
978 cycles.retain(|cycle| {
979 cycle
980 .cycle
981 .edges
982 .iter()
983 .any(|edge| scope.contains(&edge.path))
984 });
985}
986
987fn retain_security_findings_by_changed_path(
988 findings: &mut Vec<SecurityFinding>,
989 scope: &impl ChangedPathScope,
990) {
991 findings.retain(|finding| security_finding_touches_changed_path(finding, scope));
992}
993
994fn retain_prop_drilling_chains_by_anchor(
995 chains: &mut Vec<PropDrillingChainFinding>,
996 scope: &impl ChangedPathScope,
997) {
998 chains.retain(|chain| {
999 chain
1000 .chain
1001 .hops
1002 .first()
1003 .is_some_and(|hop| scope.contains(&hop.file))
1004 });
1005}
1006
1007fn retain_duplicate_prop_shapes_by_anchor(
1008 shapes: &mut Vec<DuplicatePropShapeFinding>,
1009 scope: &impl ChangedPathScope,
1010) {
1011 retain_by_changed_path(shapes, scope, |shape| &shape.shape.file);
1012}
1013
1014fn retain_by_changed_path<T>(
1015 items: &mut Vec<T>,
1016 scope: &impl ChangedPathScope,
1017 path: impl Fn(&T) -> &Path,
1018) {
1019 items.retain(|item| scope.contains(path(item)));
1020}
1021
1022fn security_finding_touches_changed_path(
1023 finding: &SecurityFinding,
1024 scope: &impl ChangedPathScope,
1025) -> bool {
1026 scope.contains(&finding.path)
1027 || finding.trace.iter().any(|hop| scope.contains(&hop.path))
1028 || finding.reachability.as_ref().is_some_and(|reachability| {
1029 reachability
1030 .untrusted_source_trace
1031 .iter()
1032 .any(|hop| scope.contains(&hop.path))
1033 })
1034}
1035
1036fn normalize_changed_files_set(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<PathBuf> {
1037 changed_files
1038 .iter()
1039 .map(|p| dunce::simplified(p).to_path_buf())
1040 .collect()
1041}
1042
1043fn contains_normalized(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
1044 normalized.contains(dunce::simplified(path))
1045}
1046
1047fn normalized_set_contains_path(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
1048 contains_normalized(normalized, path)
1049 || (path.is_relative() && normalized.iter().any(|changed| changed.ends_with(path)))
1050}
1051
1052#[expect(
1054 clippy::implicit_hasher,
1055 reason = "fallow standardizes on FxHashSet across the workspace"
1056)]
1057pub fn filter_duplication_by_changed_files(
1058 report: &mut DuplicationReport,
1059 changed_files: &FxHashSet<PathBuf>,
1060 root: &Path,
1061) {
1062 filter_duplication_by_path_scope(report, &NormalizedChangedFiles::new(changed_files), root);
1063}
1064
1065pub(crate) fn filter_duplication_by_path_scope(
1066 report: &mut DuplicationReport,
1067 scope: &impl ChangedPathScope,
1068 root: &Path,
1069) {
1070 report.clone_groups.retain(|group| {
1071 group
1072 .instances
1073 .iter()
1074 .any(|instance| scope.contains(&instance.file))
1075 });
1076 duplicates::refresh_clone_families(report, root);
1077 report.stats = duplicates::recompute_stats(report);
1078}
1079
1080#[cfg(test)]
1081mod tests {
1082 use super::*;
1083 use fallow_types::{
1084 duplicates::{CloneGroup, CloneInstance, DuplicationStats},
1085 output_dead_code::{
1086 EmptyCatalogGroupFinding, UnusedDependencyFinding, UnusedExportFinding,
1087 UnusedFileFinding,
1088 },
1089 results::{
1090 DependencyLocation, EmptyCatalogGroup, UnusedDependency, UnusedExport, UnusedFile,
1091 },
1092 };
1093
1094 #[test]
1097 fn every_changed_files_cause_reports_its_own_reason() {
1098 let reasons = [
1099 ChangedFilesError::InvalidRef("unclosed brace".to_owned()).reason(),
1100 ChangedFilesError::GitMissing("no such file".to_owned()).reason(),
1101 ChangedFilesError::NotARepository.reason(),
1102 ChangedFilesError::GitFailed("unknown revision".to_owned()).reason(),
1103 ];
1104 assert_eq!(
1105 reasons,
1106 [
1107 "invalid-ref",
1108 "git-missing",
1109 "not-a-repository",
1110 "git-failed"
1111 ]
1112 );
1113 let unique: std::collections::BTreeSet<&str> = reasons.iter().copied().collect();
1114 assert_eq!(
1115 unique.len(),
1116 reasons.len(),
1117 "two causes must not share a token"
1118 );
1119 }
1120
1121 #[test]
1126 fn the_changed_since_message_names_the_ref_the_widening_and_the_next_step() {
1127 let message = ChangedFilesError::NotARepository.changed_since_message("origin/main");
1128 assert!(
1129 message.contains("--changed-since 'origin/main'"),
1130 "{message}"
1131 );
1132 assert!(message.contains("covers the whole project"), "{message}");
1133 assert!(message.ends_with("or drop --changed-since."), "{message}");
1134 }
1135
1136 #[test]
1140 fn the_changed_since_message_folds_git_stderr_onto_one_line() {
1141 let message = ChangedFilesError::GitFailed(
1142 "fatal: ambiguous argument 'x'\nUse '--' to separate paths".to_owned(),
1143 )
1144 .changed_since_message("x");
1145 assert!(!message.contains('\n'), "{message}");
1146 assert!(
1147 message.contains("ambiguous argument 'x' Use '--'"),
1148 "{message}"
1149 );
1150 }
1151
1152 #[test]
1153 fn git_command_clears_parent_git_environment() {
1154 let command = git_command(Path::new("."), &["status"]);
1155 let envs: Vec<_> = command.get_envs().collect();
1156
1157 for var in AMBIENT_GIT_ENV_VARS {
1158 assert!(
1159 envs.iter()
1160 .any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
1161 "{var} should be cleared from the command env",
1162 );
1163 }
1164 }
1165
1166 #[test]
1167 fn try_get_changed_files_not_a_repository() {
1168 let temp = tempfile::tempdir().expect("tempdir");
1169 let result = try_get_changed_files(temp.path(), "main");
1170 assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
1171 }
1172
1173 #[test]
1174 fn batched_refs_match_independent_changed_file_scopes() {
1175 let repo = tempfile::tempdir().expect("tempdir");
1176 for args in [
1177 &["init", "--quiet"][..],
1178 &["config", "user.email", "test@example.com"][..],
1179 &["config", "user.name", "Test User"][..],
1180 &["config", "commit.gpgsign", "false"][..],
1181 ] {
1182 run_git(repo.path(), args);
1183 }
1184 for name in ["committed.ts", "staged.ts", "unstaged.ts"] {
1185 std::fs::write(repo.path().join(name), "old\n").expect("initial file");
1186 }
1187 run_git(repo.path(), &["add", "."]);
1188 run_git(repo.path(), &["commit", "--quiet", "-m", "base"]);
1189 run_git(repo.path(), &["branch", "base"]);
1190
1191 std::fs::write(repo.path().join("committed.ts"), "new\n").expect("committed change");
1192 run_git(repo.path(), &["add", "committed.ts"]);
1193 run_git(repo.path(), &["commit", "--quiet", "-m", "change"]);
1194 std::fs::write(repo.path().join("staged.ts"), "new\n").expect("staged change");
1195 run_git(repo.path(), &["add", "staged.ts"]);
1196 std::fs::write(repo.path().join("unstaged.ts"), "new\n").expect("unstaged change");
1197 std::fs::write(repo.path().join("untracked.ts"), "new\n").expect("untracked file");
1198
1199 let mut batch = ChangedFilesBatch::new(repo.path(), "base").expect("batch");
1200 for reference in ["base", "HEAD"] {
1201 let batched = batch.changed_files(reference).expect("batched changes");
1202 let independent = changed_files(repo.path(), reference).expect("independent changes");
1203 assert_eq!(batched, independent, "{reference} scope changed");
1204 }
1205 }
1206
1207 #[cfg(unix)]
1208 #[test]
1209 fn changed_files_preserve_special_filenames() {
1210 let repo = tempfile::tempdir().expect("tempdir");
1211 for args in [
1212 &["init", "--quiet"][..],
1213 &["config", "user.email", "test@example.com"][..],
1214 &["config", "user.name", "Test User"][..],
1215 &["config", "commit.gpgsign", "false"][..],
1216 ] {
1217 run_git(repo.path(), args);
1218 }
1219 std::fs::write(repo.path().join("initial.ts"), "initial\n").expect("initial fixture");
1220 run_git(repo.path(), &["add", "."]);
1221 run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
1222 run_git(repo.path(), &["tag", "base"]);
1223
1224 let canonical_root = repo.path().canonicalize().expect("canonical repo");
1225 let special_files = [
1226 "src/line\nbreak.ts",
1227 "src/space name.ts",
1228 "src/quote\"name.ts",
1229 "src/back\\slash.ts",
1230 "src/unicode-λ.ts",
1231 ]
1232 .map(|path| canonical_root.join(path));
1233 std::fs::create_dir_all(canonical_root.join("src")).expect("source dir");
1234 for special in &special_files {
1235 std::fs::write(special, "changed\n").expect("special fixture");
1236 }
1237
1238 let changed = try_get_changed_files(repo.path(), "base").expect("changed files");
1239 for special in special_files {
1240 assert!(
1241 changed.contains(&special),
1242 "missing {special:?}: {changed:?}"
1243 );
1244 }
1245 }
1246
1247 #[cfg(windows)]
1248 #[test]
1249 fn git_path_bytes_use_windows_separators() {
1250 assert_eq!(
1251 git_path_from_bytes(b"src/nested/file.ts"),
1252 PathBuf::from(r"src\nested\file.ts")
1253 );
1254 }
1255
1256 #[test]
1257 fn changed_diff_covers_staged_unstaged_and_untracked_files() {
1258 let repo = tempfile::tempdir().expect("tempdir");
1259 for args in [
1260 &["init", "--quiet"][..],
1261 &["config", "user.email", "test@example.com"][..],
1262 &["config", "user.name", "Test User"][..],
1263 &["config", "commit.gpgsign", "false"][..],
1264 ] {
1265 run_git(repo.path(), args);
1266 }
1267 std::fs::write(repo.path().join("staged.ts"), "old\n").expect("staged fixture");
1268 std::fs::write(repo.path().join("unstaged.ts"), "old\n").expect("unstaged fixture");
1269 run_git(repo.path(), &["add", "."]);
1270 run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
1271 run_git(repo.path(), &["tag", "base"]);
1272
1273 std::fs::write(repo.path().join("committed.ts"), "committed\n").expect("committed fixture");
1274 run_git(repo.path(), &["add", "committed.ts"]);
1275 run_git(
1276 repo.path(),
1277 &["commit", "--quiet", "-m", "committed change"],
1278 );
1279
1280 std::fs::write(repo.path().join("staged.ts"), "staged\n").expect("staged edit");
1281 run_git(repo.path(), &["add", "staged.ts"]);
1282 std::fs::write(repo.path().join("unstaged.ts"), "unstaged\n").expect("unstaged edit");
1283 std::fs::write(repo.path().join("untracked.ts"), "untracked\n").expect("untracked edit");
1284
1285 let diff = try_get_changed_diff(repo.path(), "base").expect("complete changeset diff");
1286 let index = fallow_output::DiffIndex::from_unified_diff(&diff);
1287
1288 assert!(diff.contains("b/committed.ts"), "{diff}");
1289 assert!(diff.contains("b/staged.ts"), "{diff}");
1290 assert!(diff.contains("b/unstaged.ts"), "{diff}");
1291 assert!(diff.contains("b/untracked.ts"), "{diff}");
1292 assert_eq!(index.hunk_count(), 4);
1293 assert_eq!(index.net_lines(), 2);
1294 }
1295
1296 fn run_git(root: &Path, args: &[&str]) {
1297 let output = spawn_output(&mut git_command(root, args)).expect("git command");
1298 assert!(
1299 output.status.success(),
1300 "git {args:?} failed: {}",
1301 String::from_utf8_lossy(&output.stderr)
1302 );
1303 }
1304
1305 #[test]
1306 fn untracked_path_arg_uses_forward_slashes() {
1307 assert_eq!(
1308 super::untracked_path_arg(Path::new("src\\nested\\b.ts")),
1309 "src/nested/b.ts"
1310 );
1311 assert_eq!(super::untracked_path_arg(Path::new("src/b.ts")), "src/b.ts");
1312 }
1313
1314 #[test]
1315 fn changed_files_error_describe_matches_core_contract() {
1316 assert_eq!(
1317 ChangedFilesError::InvalidRef("bad ref".to_string()).describe(),
1318 "invalid git ref: bad ref"
1319 );
1320 assert_eq!(
1321 ChangedFilesError::GitMissing("not found".to_string()).describe(),
1322 "failed to run git: not found"
1323 );
1324 assert_eq!(
1325 ChangedFilesError::NotARepository.describe(),
1326 "not a git repository"
1327 );
1328 assert!(
1329 ChangedFilesError::GitFailed("unknown revision main".to_string())
1330 .describe()
1331 .contains("fetch-depth: 0")
1332 );
1333 }
1334
1335 #[test]
1336 fn filter_results_keeps_only_changed_file_findings() {
1337 let mut results = AnalysisResults::default();
1338 results
1339 .unused_files
1340 .push(UnusedFileFinding::with_actions(UnusedFile {
1341 path: PathBuf::from("/repo/a.ts"),
1342 }));
1343 results
1344 .unused_files
1345 .push(UnusedFileFinding::with_actions(UnusedFile {
1346 path: PathBuf::from("/repo/b.ts"),
1347 }));
1348 results
1349 .unused_exports
1350 .push(UnusedExportFinding::with_actions(UnusedExport {
1351 path: PathBuf::from("/repo/a.ts"),
1352 export_name: "foo".to_owned(),
1353 is_type_only: false,
1354 line: 1,
1355 col: 0,
1356 span_start: 0,
1357 is_re_export: false,
1358 deprecated: false,
1359 deprecated_reason: None,
1360 }));
1361
1362 let mut changed = FxHashSet::default();
1363 changed.insert(PathBuf::from("/repo/a.ts"));
1364
1365 filter_results_by_changed_files(&mut results, &changed);
1366
1367 assert_eq!(results.unused_files.len(), 1);
1368 assert_eq!(
1369 results.unused_files[0].file.path,
1370 PathBuf::from("/repo/a.ts")
1371 );
1372 assert_eq!(results.unused_exports.len(), 1);
1373 }
1374
1375 #[test]
1376 fn filter_results_preserves_graph_global_dependency_findings() {
1377 let mut results = AnalysisResults::default();
1378 results
1379 .unused_dependencies
1380 .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1381 package_name: "lodash".to_owned(),
1382 location: DependencyLocation::Dependencies,
1383 path: PathBuf::from("/repo/package.json"),
1384 line: 3,
1385 used_in_workspaces: Vec::new(),
1386 }));
1387
1388 let changed = FxHashSet::default();
1389 filter_results_by_changed_files(&mut results, &changed);
1390
1391 assert_eq!(results.unused_dependencies.len(), 1);
1392 }
1393
1394 #[test]
1398 fn filter_results_keeps_deprecated_export_only_when_its_declaring_file_changed() {
1399 let finding = |path: &str| {
1400 fallow_types::output_dead_code::DeprecatedExportInUseFinding::with_actions(
1401 fallow_types::results::DeprecatedExportInUse {
1402 path: PathBuf::from(path),
1403 export_name: "old".to_owned(),
1404 is_type_only: false,
1405 line: 2,
1406 col: 0,
1407 span_start: 0,
1408 deprecated_reason: None,
1409 consumer_count: 1,
1410 consumers: vec![fallow_types::results::DeprecatedExportConsumer {
1411 path: PathBuf::from("/repo/consumer.ts"),
1412 line: 1,
1413 col: 0,
1414 kind: fallow_types::results::DeprecatedConsumerKind::NamedImport,
1415 }],
1416 public_api: false,
1417 },
1418 )
1419 };
1420 let mut results = AnalysisResults::default();
1421 results
1422 .deprecated_exports_in_use
1423 .push(finding("/repo/a.ts"));
1424 results
1425 .deprecated_exports_in_use
1426 .push(finding("/repo/b.ts"));
1427
1428 let mut changed = FxHashSet::default();
1429 changed.insert(PathBuf::from("/repo/a.ts"));
1430 changed.insert(PathBuf::from("/repo/consumer.ts"));
1431 filter_results_by_changed_files(&mut results, &changed);
1432
1433 let kept: Vec<_> = results
1434 .deprecated_exports_in_use
1435 .iter()
1436 .map(|f| f.export.path.clone())
1437 .collect();
1438 assert_eq!(kept, vec![PathBuf::from("/repo/a.ts")]);
1439 }
1440
1441 #[test]
1442 fn filter_results_keeps_relative_manifest_finding_when_manifest_changed() {
1443 let mut results = AnalysisResults::default();
1444 results
1445 .empty_catalog_groups
1446 .push(EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
1447 catalog_name: "legacy".to_owned(),
1448 path: PathBuf::from("pnpm-workspace.yaml"),
1449 line: 4,
1450 }));
1451
1452 let mut changed = FxHashSet::default();
1453 changed.insert(PathBuf::from("/repo/pnpm-workspace.yaml"));
1454
1455 filter_results_by_changed_files(&mut results, &changed);
1456
1457 assert_eq!(results.empty_catalog_groups.len(), 1);
1458 }
1459
1460 #[test]
1461 fn filter_duplication_keeps_groups_with_changed_instances_and_recomputes_stats() {
1462 let mut report = DuplicationReport {
1463 clone_groups: vec![
1464 CloneGroup {
1465 instances: vec![
1466 CloneInstance {
1467 file: PathBuf::from("/repo/a.ts"),
1468 start_line: 1,
1469 end_line: 5,
1470 start_col: 0,
1471 end_col: 10,
1472 fragment: "code".to_owned(),
1473 },
1474 CloneInstance {
1475 file: PathBuf::from("/repo/b.ts"),
1476 start_line: 1,
1477 end_line: 5,
1478 start_col: 0,
1479 end_col: 10,
1480 fragment: "code".to_owned(),
1481 },
1482 ],
1483 token_count: 20,
1484 line_count: 5,
1485 similarity: None,
1486 },
1487 CloneGroup {
1488 instances: vec![
1489 CloneInstance {
1490 file: PathBuf::from("/repo/c.ts"),
1491 start_line: 1,
1492 end_line: 5,
1493 start_col: 0,
1494 end_col: 10,
1495 fragment: "other".to_owned(),
1496 },
1497 CloneInstance {
1498 file: PathBuf::from("/repo/d.ts"),
1499 start_line: 1,
1500 end_line: 5,
1501 start_col: 0,
1502 end_col: 10,
1503 fragment: "other".to_owned(),
1504 },
1505 ],
1506 token_count: 20,
1507 line_count: 5,
1508 similarity: None,
1509 },
1510 ],
1511 clone_families: Vec::new(),
1512 mirrored_directories: Vec::new(),
1513 stats: DuplicationStats {
1514 total_files: 4,
1515 files_with_clones: 4,
1516 total_lines: 100,
1517 duplicated_lines: 20,
1518 total_tokens: 200,
1519 duplicated_tokens: 80,
1520 clone_groups: 2,
1521 clone_families: 0,
1522 clone_instances: 4,
1523 duplication_percentage: 20.0,
1524 clone_groups_below_min_occurrences: 0,
1525 clone_groups_ignored: 0,
1526 near_candidates_skipped: 0,
1527 },
1528 };
1529
1530 let mut changed = FxHashSet::default();
1531 changed.insert(PathBuf::from("/repo/a.ts"));
1532
1533 filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1534
1535 assert_eq!(report.clone_groups.len(), 1);
1536 assert_eq!(report.stats.clone_groups, 1);
1537 assert_eq!(report.stats.clone_instances, 2);
1538 }
1539
1540 #[test]
1543 fn one_probe_resolves_the_common_dir_and_the_toplevel() {
1544 let repo = tempfile::tempdir().expect("tempdir");
1545 run_git(repo.path(), &["init", "--quiet"]);
1546 let nested = repo.path().join("packages/app");
1547 std::fs::create_dir_all(&nested).expect("nested dir");
1548 for cwd in [repo.path(), nested.as_path()] {
1549 let (common, toplevel) =
1550 resolve_git_common_dir_and_toplevel(cwd).expect("combined probe");
1551 assert_eq!(common, resolve_git_common_dir(cwd).expect("common dir"));
1552 assert_eq!(toplevel, resolve_git_toplevel(cwd).expect("toplevel"));
1553 }
1554 }
1555
1556 #[test]
1559 fn the_combined_probe_fails_without_a_work_tree() {
1560 let repo = tempfile::tempdir().expect("tempdir");
1561 run_git(repo.path(), &["init", "--quiet", "--bare"]);
1562 assert!(resolve_git_common_dir_and_toplevel(repo.path()).is_err());
1563 assert!(resolve_git_common_dir(repo.path()).is_ok());
1564 }
1565}