1use std::path::{Path, PathBuf};
4use std::process::{Command, Output};
5use std::sync::OnceLock;
6
7use fallow_types::{
8 output_dead_code::{
9 CircularDependencyFinding, DuplicateExportFinding, DuplicatePropShapeFinding,
10 PropDrillingChainFinding, ReExportCycleFinding, UnlistedDependencyFinding,
11 },
12 results::{AnalysisResults, SecurityFinding},
13};
14use rustc_hash::FxHashSet;
15
16use crate::duplicates::{self, DuplicationReport};
17
18pub use crate::git_env::{AMBIENT_GIT_ENV_VARS, clear_ambient_git_env};
19
20pub type ChangedFilesSpawnHook = fn(&mut std::process::Command) -> std::io::Result<Output>;
23
24static SPAWN_HOOK: OnceLock<ChangedFilesSpawnHook> = OnceLock::new();
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum ChangedFilesError {
29 InvalidRef(String),
31 GitMissing(String),
33 NotARepository,
35 GitFailed(String),
37}
38
39impl ChangedFilesError {
40 #[must_use]
42 pub fn describe(&self) -> String {
43 match self {
44 Self::InvalidRef(err) => format!("invalid git ref: {err}"),
45 Self::GitMissing(err) => format!("failed to run git: {err}"),
46 Self::NotARepository => "not a git repository".to_owned(),
47 Self::GitFailed(stderr) => augment_git_failed(stderr),
48 }
49 }
50}
51
52fn augment_git_failed(stderr: &str) -> String {
53 let lower = stderr.to_ascii_lowercase();
54 if lower.contains("not a valid object name")
55 || lower.contains("unknown revision")
56 || lower.contains("ambiguous argument")
57 {
58 format!(
59 "{stderr} (shallow clone? try `git fetch --unshallow`, or set `fetch-depth: 0` on actions/checkout / `GIT_DEPTH: 0` in GitLab CI)"
60 )
61 } else {
62 stderr.to_owned()
63 }
64}
65
66pub fn set_spawn_hook(hook: ChangedFilesSpawnHook) {
68 let _ = SPAWN_HOOK.set(hook);
69}
70
71pub fn validate_git_ref(s: &str) -> Result<&str, String> {
73 if s.is_empty() {
74 return Err("git ref cannot be empty".to_string());
75 }
76 if s.starts_with('-') {
77 return Err("git ref cannot start with '-'".to_string());
78 }
79 let mut in_braces = false;
80 for c in s.chars() {
81 match c {
82 '{' => in_braces = true,
83 '}' => in_braces = false,
84 ':' | ' ' if in_braces => {}
85 c if c.is_ascii_alphanumeric()
86 || matches!(c, '.' | '_' | '-' | '/' | '~' | '^' | '@' | '{' | '}') => {}
87 _ => return Err(format!("git ref contains disallowed character: '{c}'")),
88 }
89 }
90 if in_braces {
91 return Err("git ref has unclosed '{'".to_string());
92 }
93 Ok(s)
94}
95
96pub fn resolve_git_toplevel(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
98 let output = spawn_output(&mut git_command(cwd, &["rev-parse", "--show-toplevel"]))
99 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
100
101 if !output.status.success() {
102 let stderr = String::from_utf8_lossy(&output.stderr);
103 return Err(if stderr.contains("not a git repository") {
104 ChangedFilesError::NotARepository
105 } else {
106 ChangedFilesError::GitFailed(stderr.trim().to_owned())
107 });
108 }
109
110 let raw = String::from_utf8_lossy(&output.stdout);
111 let trimmed = raw.trim();
112 if trimmed.is_empty() {
113 return Err(ChangedFilesError::GitFailed(
114 "git rev-parse --show-toplevel returned empty output".to_owned(),
115 ));
116 }
117
118 let path = PathBuf::from(trimmed);
119 Ok(dunce::canonicalize(&path).unwrap_or(path))
120}
121
122pub fn resolve_git_common_dir(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
124 let output = spawn_output(&mut git_command(
125 cwd,
126 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
127 ))
128 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
129
130 if !output.status.success() {
131 let stderr = String::from_utf8_lossy(&output.stderr);
132 return Err(if stderr.contains("not a git repository") {
133 ChangedFilesError::NotARepository
134 } else {
135 ChangedFilesError::GitFailed(stderr.trim().to_owned())
136 });
137 }
138
139 let raw = String::from_utf8_lossy(&output.stdout);
140 let trimmed = raw.trim();
141 if trimmed.is_empty() {
142 return Err(ChangedFilesError::GitFailed(
143 "git rev-parse --git-common-dir returned empty output".to_owned(),
144 ));
145 }
146
147 let path = PathBuf::from(trimmed);
148 Ok(dunce::canonicalize(&path).unwrap_or(path))
149}
150
151pub fn try_get_changed_files(
153 root: &Path,
154 git_ref: &str,
155) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
156 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
157 let toplevel = resolve_git_toplevel(root)?;
158 try_get_changed_files_with_toplevel(root, &toplevel, git_ref)
159}
160
161pub fn changed_files(root: &Path, git_ref: &str) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
167 try_get_changed_files(root, git_ref)
168}
169
170pub fn try_get_changed_files_with_toplevel(
172 cwd: &Path,
173 toplevel: &Path,
174 git_ref: &str,
175) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
176 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
177
178 let mut files = collect_git_paths(
179 cwd,
180 toplevel,
181 &[
182 "diff",
183 "--name-only",
184 "-z",
185 "--end-of-options",
186 &format!("{git_ref}...HEAD"),
187 ],
188 )?;
189 files.extend(collect_git_paths(
190 cwd,
191 toplevel,
192 &["diff", "--name-only", "-z", "HEAD"],
193 )?);
194 files.extend(collect_git_paths(
195 cwd,
196 toplevel,
197 &[
198 "ls-files",
199 "--full-name",
200 "--others",
201 "--exclude-standard",
202 "-z",
203 ],
204 )?);
205 Ok(files)
206}
207
208pub fn try_get_changed_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
213 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
214 let toplevel = resolve_git_toplevel(root)?;
215 let merge_base_output = spawn_output(&mut git_command(root, &["merge-base", git_ref, "HEAD"]))
216 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
217 if !merge_base_output.status.success() {
218 return Err(changed_files_error_from_output(&merge_base_output));
219 }
220 let merge_base = String::from_utf8_lossy(&merge_base_output.stdout)
221 .trim()
222 .to_owned();
223 if merge_base.is_empty() {
224 return Err(ChangedFilesError::GitFailed(
225 "git merge-base returned empty output".to_owned(),
226 ));
227 }
228
229 let output = spawn_output(&mut git_command(
230 root,
231 &[
232 "diff",
233 "--relative",
234 "--unified=0",
235 "--end-of-options",
236 &merge_base,
237 ],
238 ))
239 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
240
241 if !output.status.success() {
242 return Err(changed_files_error_from_output(&output));
243 }
244
245 let mut diff = String::from_utf8_lossy(&output.stdout).into_owned();
246 append_untracked_diffs(root, &toplevel, &mut diff)?;
247 Ok(diff)
248}
249
250fn append_untracked_diffs(
251 root: &Path,
252 toplevel: &Path,
253 diff: &mut String,
254) -> Result<(), ChangedFilesError> {
255 let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
256 let mut untracked: Vec<PathBuf> = collect_git_paths(
257 root,
258 toplevel,
259 &[
260 "ls-files",
261 "--full-name",
262 "--others",
263 "--exclude-standard",
264 "-z",
265 ],
266 )?
267 .into_iter()
268 .filter_map(|path| {
269 path.strip_prefix(&canonical_root)
270 .ok()
271 .map(Path::to_path_buf)
272 })
273 .collect();
274 untracked.sort_unstable();
275
276 #[cfg(windows)]
277 let empty_file = "NUL";
278 #[cfg(not(windows))]
279 let empty_file = "/dev/null";
280
281 for path in untracked {
282 let mut command = git_command(root, &["diff", "--no-index", "--unified=0", "--"]);
283 command.arg(empty_file).arg(&path);
284 let output =
285 spawn_output(&mut command).map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
286 if !output.status.success() && output.status.code() != Some(1) {
287 return Err(changed_files_error_from_output(&output));
288 }
289 if !diff.is_empty() && !diff.ends_with('\n') {
290 diff.push('\n');
291 }
292 diff.push_str(&String::from_utf8_lossy(&output.stdout));
293 }
294 Ok(())
295}
296
297fn changed_files_error_from_output(output: &Output) -> ChangedFilesError {
298 let stderr = String::from_utf8_lossy(&output.stderr);
299 if stderr.contains("not a git repository") {
300 ChangedFilesError::NotARepository
301 } else {
302 ChangedFilesError::GitFailed(stderr.trim().to_owned())
303 }
304}
305
306#[must_use]
308#[expect(
309 clippy::print_stderr,
310 reason = "intentional user-facing warning for the CLI's --changed-since fallback path; typed callers use try_get_changed_files instead"
311)]
312pub fn get_changed_files(root: &Path, git_ref: &str) -> Option<FxHashSet<PathBuf>> {
313 match try_get_changed_files(root, git_ref) {
314 Ok(files) => Some(files),
315 Err(ChangedFilesError::InvalidRef(e)) => {
316 eprintln!("Warning: --changed-since ignored: invalid git ref: {e}");
317 None
318 }
319 Err(ChangedFilesError::GitMissing(e)) => {
320 eprintln!("Warning: --changed-since ignored: failed to run git: {e}");
321 None
322 }
323 Err(ChangedFilesError::NotARepository) => {
324 eprintln!("Warning: --changed-since ignored: not a git repository");
325 None
326 }
327 Err(ChangedFilesError::GitFailed(stderr)) => {
328 eprintln!("Warning: --changed-since failed for ref '{git_ref}': {stderr}");
329 None
330 }
331 }
332}
333
334fn spawn_output(command: &mut Command) -> std::io::Result<Output> {
335 if let Some(hook) = SPAWN_HOOK.get() {
336 hook(command)
337 } else {
338 command.output()
339 }
340}
341
342fn collect_git_paths(
343 cwd: &Path,
344 toplevel: &Path,
345 args: &[&str],
346) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
347 let output = spawn_output(&mut git_command(cwd, args))
348 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
349
350 if !output.status.success() {
351 let stderr = String::from_utf8_lossy(&output.stderr);
352 return Err(if stderr.contains("not a git repository") {
353 ChangedFilesError::NotARepository
354 } else {
355 ChangedFilesError::GitFailed(stderr.trim().to_owned())
356 });
357 }
358
359 let files = output
360 .stdout
361 .split(|byte| *byte == 0)
362 .filter(|path| !path.is_empty())
363 .map(git_path_from_bytes)
364 .map(|path| toplevel.join(path))
365 .collect();
366
367 Ok(files)
368}
369
370#[cfg(unix)]
371fn git_path_from_bytes(path: &[u8]) -> PathBuf {
372 use std::ffi::OsString;
373 use std::os::unix::ffi::OsStringExt;
374
375 PathBuf::from(OsString::from_vec(path.to_vec()))
376}
377
378#[cfg(windows)]
379fn git_path_from_bytes(path: &[u8]) -> PathBuf {
380 PathBuf::from(String::from_utf8_lossy(path).replace('/', "\\"))
381}
382
383#[expect(
384 clippy::disallowed_methods,
385 reason = "canonical engine-owned git spawn wrapper for changed-file orchestration"
386)]
387fn git_command(cwd: &Path, args: &[&str]) -> Command {
388 let mut command = Command::new("git");
389 clear_ambient_git_env(&mut command);
390 command.args(args).current_dir(cwd);
391 command
392}
393
394#[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,
422 unused_dev_dependencies: _unused_dev_dependencies,
423 unused_optional_dependencies: _unused_optional_dependencies,
424 unused_enum_members: _unused_enum_members,
425 unused_class_members: _unused_class_members,
426 unused_store_members: _unused_store_members,
427 unresolved_imports: _unresolved_imports,
428 unlisted_dependencies: _unlisted_dependencies,
429 duplicate_exports: _duplicate_exports,
430 type_only_dependencies: _type_only_dependencies,
431 test_only_dependencies: _test_only_dependencies,
432 dev_dependencies_in_production: _dev_dependencies_in_production,
433 circular_dependencies: _circular_dependencies,
434 re_export_cycles: _re_export_cycles,
435 boundary_violations: _boundary_violations,
436 boundary_coverage_violations: _boundary_coverage_violations,
437 boundary_call_violations: _boundary_call_violations,
438 policy_violations: _policy_violations,
439 stale_suppressions: _stale_suppressions,
440 unused_catalog_entries: _unused_catalog_entries,
441 empty_catalog_groups: _empty_catalog_groups,
442 unresolved_catalog_references: _unresolved_catalog_references,
443 unused_dependency_overrides: _unused_dependency_overrides,
444 misconfigured_dependency_overrides: _misconfigured_dependency_overrides,
445 invalid_client_exports: _invalid_client_exports,
446 mixed_client_server_barrels: _mixed_client_server_barrels,
447 misplaced_directives: _misplaced_directives,
448 unprovided_injects: _unprovided_injects,
449 unrendered_components: _unrendered_components,
450 route_collisions: _route_collisions,
451 dynamic_segment_name_conflicts: _dynamic_segment_name_conflicts,
452 unused_component_props: _unused_component_props,
453 unused_component_emits: _unused_component_emits,
454 unused_component_inputs: _unused_component_inputs,
455 unused_component_outputs: _unused_component_outputs,
456 unused_svelte_events: _unused_svelte_events,
457 unused_server_actions: _unused_server_actions,
458 unused_load_data_keys: _unused_load_data_keys,
459 unused_load_data_keys_global_abstain: _unused_load_data_keys_global_abstain,
460 prop_drilling_chains: _prop_drilling_chains,
461 thin_wrappers: _thin_wrappers,
462 duplicate_prop_shapes: _duplicate_prop_shapes,
463 suppression_count: _suppression_count,
464 unused_component_props_exempted: _unused_component_props_exempted,
465 active_suppressions: _active_suppressions,
466 feature_flags: _feature_flags,
467 security_findings: _security_findings,
468 security_unresolved_edge_files: _security_unresolved_edge_files,
469 security_unresolved_callee_sites: _security_unresolved_callee_sites,
470 security_unresolved_callee_diagnostics: _security_unresolved_callee_diagnostics,
471 export_usages: _export_usages,
472 entry_point_summary: _entry_point_summary,
473 render_fan_in: _render_fan_in,
474 react_component_intel: _react_component_intel,
475 } = results;
476}
477
478fn retain_basic_issue_findings_by_changed_path(
479 results: &mut AnalysisResults,
480 changed_files: &FxHashSet<PathBuf>,
481) {
482 retain_by_changed_path(&mut results.unused_files, changed_files, |f| &f.file.path);
483 retain_by_changed_path(&mut results.unused_exports, changed_files, |e| {
484 &e.export.path
485 });
486 retain_by_changed_path(&mut results.unused_types, changed_files, |e| &e.export.path);
487 retain_by_changed_path(&mut results.private_type_leaks, changed_files, |e| {
488 &e.leak.path
489 });
490 retain_by_changed_path(&mut results.unused_enum_members, changed_files, |m| {
491 &m.member.path
492 });
493 retain_by_changed_path(&mut results.unused_class_members, changed_files, |m| {
494 &m.member.path
495 });
496 retain_by_changed_path(&mut results.unused_store_members, changed_files, |m| {
497 &m.member.path
498 });
499 retain_by_changed_path(&mut results.unresolved_imports, changed_files, |i| {
500 &i.import.path
501 });
502}
503
504fn retain_graph_findings_by_changed_files(
505 results: &mut AnalysisResults,
506 changed_files: &FxHashSet<PathBuf>,
507) {
508 retain_unlisted_dependencies_by_import_site(&mut results.unlisted_dependencies, changed_files);
509 retain_duplicate_exports_by_changed_locations(&mut results.duplicate_exports, changed_files);
510 retain_circular_dependencies_by_changed_file(&mut results.circular_dependencies, changed_files);
511 retain_re_export_cycles_by_changed_file(&mut results.re_export_cycles, changed_files);
512}
513
514fn retain_boundary_policy_and_suppression_findings(
515 results: &mut AnalysisResults,
516 changed_files: &FxHashSet<PathBuf>,
517) {
518 retain_by_changed_path(&mut results.boundary_violations, changed_files, |v| {
519 &v.violation.from_path
520 });
521 retain_by_changed_path(
522 &mut results.boundary_coverage_violations,
523 changed_files,
524 |v| &v.violation.path,
525 );
526 retain_by_changed_path(&mut results.boundary_call_violations, changed_files, |v| {
527 &v.violation.path
528 });
529 retain_by_changed_path(&mut results.policy_violations, changed_files, |v| {
530 &v.violation.path
531 });
532 retain_by_changed_path(&mut results.stale_suppressions, changed_files, |s| &s.path);
533}
534
535fn retain_security_and_workspace_findings(
536 results: &mut AnalysisResults,
537 changed_files: &FxHashSet<PathBuf>,
538) {
539 retain_security_findings_by_changed_path(&mut results.security_findings, changed_files);
540 retain_by_changed_path(
541 &mut results.security_unresolved_callee_diagnostics,
542 changed_files,
543 |d| &d.path,
544 );
545 retain_by_changed_path(
546 &mut results.unresolved_catalog_references,
547 changed_files,
548 |r| &r.reference.path,
549 );
550 results
551 .empty_catalog_groups
552 .retain(|g| normalized_set_contains_path(changed_files, &g.group.path));
553 retain_by_changed_path(
554 &mut results.unused_dependency_overrides,
555 changed_files,
556 |o| &o.entry.path,
557 );
558 retain_by_changed_path(
559 &mut results.misconfigured_dependency_overrides,
560 changed_files,
561 |o| &o.entry.path,
562 );
563}
564
565fn retain_framework_findings_by_changed_files(
566 results: &mut AnalysisResults,
567 changed_files: &FxHashSet<PathBuf>,
568) {
569 retain_client_boundary_findings_by_changed_files(results, changed_files);
570 retain_component_contract_findings_by_changed_files(results, changed_files);
571 retain_react_health_findings_by_changed_files(results, changed_files);
572 retain_nextjs_findings_by_changed_files(results, changed_files);
573}
574
575fn retain_client_boundary_findings_by_changed_files(
576 results: &mut AnalysisResults,
577 changed_files: &FxHashSet<PathBuf>,
578) {
579 let AnalysisResults {
580 invalid_client_exports,
581 mixed_client_server_barrels,
582 misplaced_directives,
583 ..
584 } = results;
585
586 retain_by_changed_path(invalid_client_exports, changed_files, |e| &e.export.path);
587 retain_by_changed_path(mixed_client_server_barrels, changed_files, |b| {
588 &b.barrel.path
589 });
590 retain_by_changed_path(misplaced_directives, changed_files, |d| {
591 &d.directive_site.path
592 });
593}
594
595fn retain_component_contract_findings_by_changed_files(
596 results: &mut AnalysisResults,
597 changed_files: &FxHashSet<PathBuf>,
598) {
599 let AnalysisResults {
600 unprovided_injects,
601 unrendered_components,
602 unused_component_props,
603 unused_component_emits,
604 unused_component_inputs,
605 unused_component_outputs,
606 unused_svelte_events,
607 unused_server_actions,
608 unused_load_data_keys,
609 ..
610 } = results;
611
612 retain_by_changed_path(unprovided_injects, changed_files, |i| &i.inject.path);
613 retain_by_changed_path(unrendered_components, changed_files, |c| &c.component.path);
614 retain_by_changed_path(unused_component_props, changed_files, |p| &p.prop.path);
615 retain_by_changed_path(unused_component_emits, changed_files, |e| &e.emit.path);
616 retain_by_changed_path(unused_component_inputs, changed_files, |i| &i.input.path);
617 retain_by_changed_path(unused_component_outputs, changed_files, |o| &o.output.path);
618 retain_by_changed_path(unused_svelte_events, changed_files, |e| &e.event.path);
619 retain_by_changed_path(unused_server_actions, changed_files, |a| &a.action.path);
620 retain_by_changed_path(unused_load_data_keys, changed_files, |k| &k.key.path);
621}
622
623fn retain_react_health_findings_by_changed_files(
624 results: &mut AnalysisResults,
625 changed_files: &FxHashSet<PathBuf>,
626) {
627 let AnalysisResults {
628 prop_drilling_chains,
629 thin_wrappers,
630 duplicate_prop_shapes,
631 ..
632 } = results;
633
634 retain_prop_drilling_chains_by_anchor(prop_drilling_chains, changed_files);
635 retain_by_changed_path(thin_wrappers, changed_files, |w| &w.wrapper.file);
636 retain_duplicate_prop_shapes_by_anchor(duplicate_prop_shapes, changed_files);
637}
638
639fn retain_nextjs_findings_by_changed_files(
640 results: &mut AnalysisResults,
641 changed_files: &FxHashSet<PathBuf>,
642) {
643 let AnalysisResults {
644 route_collisions,
645 dynamic_segment_name_conflicts,
646 ..
647 } = results;
648
649 retain_by_changed_path(route_collisions, changed_files, |c| &c.collision.path);
650 retain_by_changed_path(dynamic_segment_name_conflicts, changed_files, |c| {
651 &c.conflict.path
652 });
653}
654
655fn retain_unlisted_dependencies_by_import_site(
656 dependencies: &mut Vec<UnlistedDependencyFinding>,
657 changed_files: &FxHashSet<PathBuf>,
658) {
659 dependencies.retain(|dependency| {
660 dependency
661 .dep
662 .imported_from
663 .iter()
664 .any(|site| contains_normalized(changed_files, &site.path))
665 });
666}
667
668fn retain_duplicate_exports_by_changed_locations(
669 duplicate_exports: &mut Vec<DuplicateExportFinding>,
670 changed_files: &FxHashSet<PathBuf>,
671) {
672 for duplicate in &mut *duplicate_exports {
673 duplicate
674 .export
675 .locations
676 .retain(|location| contains_normalized(changed_files, &location.path));
677 }
678 duplicate_exports.retain(|duplicate| duplicate.export.locations.len() >= 2);
679}
680
681fn retain_circular_dependencies_by_changed_file(
682 cycles: &mut Vec<CircularDependencyFinding>,
683 changed_files: &FxHashSet<PathBuf>,
684) {
685 cycles.retain(|cycle| {
686 cycle
687 .cycle
688 .files
689 .iter()
690 .any(|file| contains_normalized(changed_files, file))
691 });
692}
693
694fn retain_re_export_cycles_by_changed_file(
695 cycles: &mut Vec<ReExportCycleFinding>,
696 changed_files: &FxHashSet<PathBuf>,
697) {
698 cycles.retain(|cycle| {
699 cycle
700 .cycle
701 .files
702 .iter()
703 .any(|file| contains_normalized(changed_files, file))
704 });
705}
706
707fn retain_security_findings_by_changed_path(
708 findings: &mut Vec<SecurityFinding>,
709 changed_files: &FxHashSet<PathBuf>,
710) {
711 findings.retain(|finding| security_finding_touches_changed_path(finding, changed_files));
712}
713
714fn retain_prop_drilling_chains_by_anchor(
715 chains: &mut Vec<PropDrillingChainFinding>,
716 changed_files: &FxHashSet<PathBuf>,
717) {
718 chains.retain(|chain| {
719 chain
720 .chain
721 .hops
722 .first()
723 .is_some_and(|hop| contains_normalized(changed_files, &hop.file))
724 });
725}
726
727fn retain_duplicate_prop_shapes_by_anchor(
728 shapes: &mut Vec<DuplicatePropShapeFinding>,
729 changed_files: &FxHashSet<PathBuf>,
730) {
731 retain_by_changed_path(shapes, changed_files, |shape| &shape.shape.file);
732}
733
734fn retain_by_changed_path<T>(
735 items: &mut Vec<T>,
736 changed_files: &FxHashSet<PathBuf>,
737 path: impl Fn(&T) -> &Path,
738) {
739 items.retain(|item| contains_normalized(changed_files, path(item)));
740}
741
742fn security_finding_touches_changed_path(
743 finding: &SecurityFinding,
744 changed_files: &FxHashSet<PathBuf>,
745) -> bool {
746 contains_normalized(changed_files, &finding.path)
747 || finding
748 .trace
749 .iter()
750 .any(|hop| contains_normalized(changed_files, &hop.path))
751 || finding.reachability.as_ref().is_some_and(|reachability| {
752 reachability
753 .untrusted_source_trace
754 .iter()
755 .any(|hop| contains_normalized(changed_files, &hop.path))
756 })
757}
758
759fn normalize_changed_files_set(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<PathBuf> {
760 changed_files
761 .iter()
762 .map(|p| dunce::simplified(p).to_path_buf())
763 .collect()
764}
765
766fn contains_normalized(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
767 normalized.contains(dunce::simplified(path))
768}
769
770fn normalized_set_contains_path(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
771 contains_normalized(normalized, path)
772 || (path.is_relative() && normalized.iter().any(|changed| changed.ends_with(path)))
773}
774
775#[expect(
777 clippy::implicit_hasher,
778 reason = "fallow standardizes on FxHashSet across the workspace"
779)]
780pub fn filter_duplication_by_changed_files(
781 report: &mut DuplicationReport,
782 changed_files: &FxHashSet<PathBuf>,
783 root: &Path,
784) {
785 let cf = normalize_changed_files_set(changed_files);
786 report.clone_groups.retain(|group| {
787 group
788 .instances
789 .iter()
790 .any(|instance| contains_normalized(&cf, &instance.file))
791 });
792 duplicates::refresh_clone_families(report, root);
793 report.stats = duplicates::recompute_stats(report);
794}
795
796#[cfg(test)]
797mod tests {
798 use super::*;
799 use fallow_types::{
800 duplicates::{CloneGroup, CloneInstance, DuplicationStats},
801 output_dead_code::{
802 EmptyCatalogGroupFinding, UnusedDependencyFinding, UnusedExportFinding,
803 UnusedFileFinding,
804 },
805 results::{
806 DependencyLocation, EmptyCatalogGroup, UnusedDependency, UnusedExport, UnusedFile,
807 },
808 };
809
810 #[test]
811 fn validate_git_ref_rejects_option_like_ref() {
812 assert!(validate_git_ref("--upload-pack=evil").is_err());
813 assert!(validate_git_ref("-flag").is_err());
814 }
815
816 #[test]
817 fn validate_git_ref_allows_reflog_relative_date() {
818 assert!(validate_git_ref("HEAD@{1 week ago}").is_ok());
819 }
820
821 #[test]
822 fn git_command_clears_parent_git_environment() {
823 let command = git_command(Path::new("."), &["status"]);
824 let envs: Vec<_> = command.get_envs().collect();
825
826 for var in AMBIENT_GIT_ENV_VARS {
827 assert!(
828 envs.iter()
829 .any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
830 "{var} should be cleared from the command env",
831 );
832 }
833 }
834
835 #[test]
836 fn try_get_changed_files_not_a_repository() {
837 let temp = tempfile::tempdir().expect("tempdir");
838 let result = try_get_changed_files(temp.path(), "main");
839 assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
840 }
841
842 #[cfg(unix)]
843 #[test]
844 fn changed_files_preserve_special_filenames() {
845 let repo = tempfile::tempdir().expect("tempdir");
846 for args in [
847 &["init", "--quiet"][..],
848 &["config", "user.email", "test@example.com"][..],
849 &["config", "user.name", "Test User"][..],
850 &["config", "commit.gpgsign", "false"][..],
851 ] {
852 run_git(repo.path(), args);
853 }
854 std::fs::write(repo.path().join("initial.ts"), "initial\n").expect("initial fixture");
855 run_git(repo.path(), &["add", "."]);
856 run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
857 run_git(repo.path(), &["tag", "base"]);
858
859 let canonical_root = repo.path().canonicalize().expect("canonical repo");
860 let special_files = [
861 "src/line\nbreak.ts",
862 "src/space name.ts",
863 "src/quote\"name.ts",
864 "src/back\\slash.ts",
865 "src/unicode-λ.ts",
866 ]
867 .map(|path| canonical_root.join(path));
868 std::fs::create_dir_all(canonical_root.join("src")).expect("source dir");
869 for special in &special_files {
870 std::fs::write(special, "changed\n").expect("special fixture");
871 }
872
873 let changed = try_get_changed_files(repo.path(), "base").expect("changed files");
874 for special in special_files {
875 assert!(
876 changed.contains(&special),
877 "missing {special:?}: {changed:?}"
878 );
879 }
880 }
881
882 #[cfg(windows)]
883 #[test]
884 fn git_path_bytes_use_windows_separators() {
885 assert_eq!(
886 git_path_from_bytes(b"src/nested/file.ts"),
887 PathBuf::from(r"src\nested\file.ts")
888 );
889 }
890
891 #[test]
892 fn changed_diff_covers_staged_unstaged_and_untracked_files() {
893 let repo = tempfile::tempdir().expect("tempdir");
894 for args in [
895 &["init", "--quiet"][..],
896 &["config", "user.email", "test@example.com"][..],
897 &["config", "user.name", "Test User"][..],
898 &["config", "commit.gpgsign", "false"][..],
899 ] {
900 run_git(repo.path(), args);
901 }
902 std::fs::write(repo.path().join("staged.ts"), "old\n").expect("staged fixture");
903 std::fs::write(repo.path().join("unstaged.ts"), "old\n").expect("unstaged fixture");
904 run_git(repo.path(), &["add", "."]);
905 run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
906 run_git(repo.path(), &["tag", "base"]);
907
908 std::fs::write(repo.path().join("committed.ts"), "committed\n").expect("committed fixture");
909 run_git(repo.path(), &["add", "committed.ts"]);
910 run_git(
911 repo.path(),
912 &["commit", "--quiet", "-m", "committed change"],
913 );
914
915 std::fs::write(repo.path().join("staged.ts"), "staged\n").expect("staged edit");
916 run_git(repo.path(), &["add", "staged.ts"]);
917 std::fs::write(repo.path().join("unstaged.ts"), "unstaged\n").expect("unstaged edit");
918 std::fs::write(repo.path().join("untracked.ts"), "untracked\n").expect("untracked edit");
919
920 let diff = try_get_changed_diff(repo.path(), "base").expect("complete changeset diff");
921 let index = fallow_output::DiffIndex::from_unified_diff(&diff);
922
923 assert!(diff.contains("b/committed.ts"), "{diff}");
924 assert!(diff.contains("b/staged.ts"), "{diff}");
925 assert!(diff.contains("b/unstaged.ts"), "{diff}");
926 assert!(diff.contains("b/untracked.ts"), "{diff}");
927 assert_eq!(index.hunk_count(), 4);
928 assert_eq!(index.net_lines(), 2);
929 }
930
931 fn run_git(root: &Path, args: &[&str]) {
932 let output = spawn_output(&mut git_command(root, args)).expect("git command");
933 assert!(
934 output.status.success(),
935 "git {args:?} failed: {}",
936 String::from_utf8_lossy(&output.stderr)
937 );
938 }
939
940 #[test]
941 fn changed_files_error_describe_matches_core_contract() {
942 assert_eq!(
943 ChangedFilesError::InvalidRef("bad ref".to_string()).describe(),
944 "invalid git ref: bad ref"
945 );
946 assert_eq!(
947 ChangedFilesError::GitMissing("not found".to_string()).describe(),
948 "failed to run git: not found"
949 );
950 assert_eq!(
951 ChangedFilesError::NotARepository.describe(),
952 "not a git repository"
953 );
954 assert!(
955 ChangedFilesError::GitFailed("unknown revision main".to_string())
956 .describe()
957 .contains("fetch-depth: 0")
958 );
959 }
960
961 #[test]
962 fn filter_results_keeps_only_changed_file_findings() {
963 let mut results = AnalysisResults::default();
964 results
965 .unused_files
966 .push(UnusedFileFinding::with_actions(UnusedFile {
967 path: PathBuf::from("/repo/a.ts"),
968 }));
969 results
970 .unused_files
971 .push(UnusedFileFinding::with_actions(UnusedFile {
972 path: PathBuf::from("/repo/b.ts"),
973 }));
974 results
975 .unused_exports
976 .push(UnusedExportFinding::with_actions(UnusedExport {
977 path: PathBuf::from("/repo/a.ts"),
978 export_name: "foo".to_owned(),
979 is_type_only: false,
980 line: 1,
981 col: 0,
982 span_start: 0,
983 is_re_export: false,
984 }));
985
986 let mut changed = FxHashSet::default();
987 changed.insert(PathBuf::from("/repo/a.ts"));
988
989 filter_results_by_changed_files(&mut results, &changed);
990
991 assert_eq!(results.unused_files.len(), 1);
992 assert_eq!(
993 results.unused_files[0].file.path,
994 PathBuf::from("/repo/a.ts")
995 );
996 assert_eq!(results.unused_exports.len(), 1);
997 }
998
999 #[test]
1000 fn filter_results_preserves_graph_global_dependency_findings() {
1001 let mut results = AnalysisResults::default();
1002 results
1003 .unused_dependencies
1004 .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1005 package_name: "lodash".to_owned(),
1006 location: DependencyLocation::Dependencies,
1007 path: PathBuf::from("/repo/package.json"),
1008 line: 3,
1009 used_in_workspaces: Vec::new(),
1010 }));
1011
1012 let changed = FxHashSet::default();
1013 filter_results_by_changed_files(&mut results, &changed);
1014
1015 assert_eq!(results.unused_dependencies.len(), 1);
1016 }
1017
1018 #[test]
1019 fn filter_results_keeps_relative_manifest_finding_when_manifest_changed() {
1020 let mut results = AnalysisResults::default();
1021 results
1022 .empty_catalog_groups
1023 .push(EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
1024 catalog_name: "legacy".to_owned(),
1025 path: PathBuf::from("pnpm-workspace.yaml"),
1026 line: 4,
1027 }));
1028
1029 let mut changed = FxHashSet::default();
1030 changed.insert(PathBuf::from("/repo/pnpm-workspace.yaml"));
1031
1032 filter_results_by_changed_files(&mut results, &changed);
1033
1034 assert_eq!(results.empty_catalog_groups.len(), 1);
1035 }
1036
1037 #[test]
1038 fn filter_duplication_keeps_groups_with_changed_instances_and_recomputes_stats() {
1039 let mut report = DuplicationReport {
1040 clone_groups: vec![
1041 CloneGroup {
1042 instances: vec![
1043 CloneInstance {
1044 file: PathBuf::from("/repo/a.ts"),
1045 start_line: 1,
1046 end_line: 5,
1047 start_col: 0,
1048 end_col: 10,
1049 fragment: "code".to_owned(),
1050 },
1051 CloneInstance {
1052 file: PathBuf::from("/repo/b.ts"),
1053 start_line: 1,
1054 end_line: 5,
1055 start_col: 0,
1056 end_col: 10,
1057 fragment: "code".to_owned(),
1058 },
1059 ],
1060 token_count: 20,
1061 line_count: 5,
1062 },
1063 CloneGroup {
1064 instances: vec![
1065 CloneInstance {
1066 file: PathBuf::from("/repo/c.ts"),
1067 start_line: 1,
1068 end_line: 5,
1069 start_col: 0,
1070 end_col: 10,
1071 fragment: "other".to_owned(),
1072 },
1073 CloneInstance {
1074 file: PathBuf::from("/repo/d.ts"),
1075 start_line: 1,
1076 end_line: 5,
1077 start_col: 0,
1078 end_col: 10,
1079 fragment: "other".to_owned(),
1080 },
1081 ],
1082 token_count: 20,
1083 line_count: 5,
1084 },
1085 ],
1086 clone_families: Vec::new(),
1087 mirrored_directories: Vec::new(),
1088 stats: DuplicationStats {
1089 total_files: 4,
1090 files_with_clones: 4,
1091 total_lines: 100,
1092 duplicated_lines: 20,
1093 total_tokens: 200,
1094 duplicated_tokens: 80,
1095 clone_groups: 2,
1096 clone_instances: 4,
1097 duplication_percentage: 20.0,
1098 clone_groups_below_min_occurrences: 0,
1099 },
1100 };
1101
1102 let mut changed = FxHashSet::default();
1103 changed.insert(PathBuf::from("/repo/a.ts"));
1104
1105 filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1106
1107 assert_eq!(report.clone_groups.len(), 1);
1108 assert_eq!(report.stats.clone_groups, 1);
1109 assert_eq!(report.stats.clone_instances, 2);
1110 }
1111}