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