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