1use std::path::{Path, PathBuf};
4use std::process::{Command, Output};
5use std::sync::OnceLock;
6use std::sync::atomic::{AtomicBool, Ordering};
7
8use fallow_types::results::{AnalysisResults, SecurityFinding};
9use rustc_hash::FxHashSet;
10
11use crate::duplicates::{self, DuplicationReport};
12use crate::result_scope::{
13 Anchor, ComponentRule, OwnerRule, ProjectFinding, ResultScope, SiteRule,
14};
15
16pub use crate::git_env::{
17 AMBIENT_GIT_ENV_VARS, clear_ambient_git_env, git_command as git_command_in,
18};
19
20pub type ChangedFilesSpawnHook = fn(&mut std::process::Command) -> std::io::Result<Output>;
23
24static SPAWN_HOOK: OnceLock<ChangedFilesSpawnHook> = OnceLock::new();
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum ChangedFilesError {
29 InvalidRef(String),
31 GitMissing(String),
33 NotARepository,
35 GitFailed(String),
37}
38
39impl ChangedFilesError {
40 #[must_use]
42 pub fn describe(&self) -> String {
43 match self {
44 Self::InvalidRef(err) => format!("invalid git ref: {err}"),
45 Self::GitMissing(err) => format!("failed to run git: {err}"),
46 Self::NotARepository => "not a git repository".to_owned(),
47 Self::GitFailed(stderr) => augment_git_failed(stderr),
48 }
49 }
50
51 #[must_use]
57 pub const fn reason(&self) -> &'static str {
58 match self {
59 Self::InvalidRef(_) => "invalid-ref",
60 Self::GitMissing(_) => "git-missing",
61 Self::NotARepository => "not-a-repository",
62 Self::GitFailed(_) => "git-failed",
63 }
64 }
65
66 #[must_use]
77 pub fn changed_since_message(&self, git_ref: &str) -> String {
78 let cause = self
79 .describe()
80 .split_whitespace()
81 .collect::<Vec<_>>()
82 .join(" ");
83 format!(
84 "--changed-since '{git_ref}' was ignored because {cause}, so this report covers \
85 the whole project instead of the changed files. {}",
86 self.changed_since_remedy()
87 )
88 }
89
90 const fn changed_since_remedy(&self) -> &'static str {
92 match self {
93 Self::InvalidRef(_) => {
94 "Pass a ref git can resolve, such as a branch name or a commit sha."
95 }
96 Self::GitMissing(_) => {
97 "Install git and make it available on PATH, or drop --changed-since."
98 }
99 Self::NotARepository => {
100 "Run fallow from inside the repository, or drop --changed-since."
101 }
102 Self::GitFailed(_) => {
103 "Verify the ref exists in this repository, and check out with full history."
104 }
105 }
106 }
107}
108
109fn augment_git_failed(stderr: &str) -> String {
110 let lower = stderr.to_ascii_lowercase();
111 if lower.contains("not a valid object name")
112 || lower.contains("unknown revision")
113 || lower.contains("ambiguous argument")
114 {
115 format!(
116 "{stderr} (shallow clone? try `git fetch --unshallow`, or set `fetch-depth: 0` on actions/checkout / `GIT_DEPTH: 0` in GitLab CI)"
117 )
118 } else {
119 stderr.to_owned()
120 }
121}
122
123static EXCLUDE_UNTRACKED: AtomicBool = AtomicBool::new(false);
124
125pub fn exclude_untracked_files() {
132 EXCLUDE_UNTRACKED.store(true, Ordering::Relaxed);
133}
134
135fn untracked_files_excluded() -> bool {
136 EXCLUDE_UNTRACKED.load(Ordering::Relaxed)
137}
138
139pub fn set_spawn_hook(hook: ChangedFilesSpawnHook) {
141 let _ = SPAWN_HOOK.set(hook);
142}
143
144pub(crate) fn validate_git_ref(s: &str) -> Result<&str, String> {
146 if s.is_empty() {
147 return Err("git ref cannot be empty".to_string());
148 }
149 if s.starts_with('-') {
150 return Err("git ref cannot start with '-'".to_string());
151 }
152 let mut in_braces = false;
153 for c in s.chars() {
154 match c {
155 '{' => in_braces = true,
156 '}' => in_braces = false,
157 ':' | ' ' if in_braces => {}
158 c if c.is_ascii_alphanumeric()
159 || matches!(c, '.' | '_' | '-' | '/' | '~' | '^' | '@' | '{' | '}') => {}
160 _ => return Err(format!("git ref contains disallowed character: '{c}'")),
161 }
162 }
163 if in_braces {
164 return Err("git ref has unclosed '{'".to_string());
165 }
166 Ok(s)
167}
168
169pub fn resolve_git_toplevel(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
171 let output = spawn_output(&mut git_command(cwd, &["rev-parse", "--show-toplevel"]))
172 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
173
174 if !output.status.success() {
175 let stderr = String::from_utf8_lossy(&output.stderr);
176 return Err(if stderr.contains("not a git repository") {
177 ChangedFilesError::NotARepository
178 } else {
179 ChangedFilesError::GitFailed(stderr.trim().to_owned())
180 });
181 }
182
183 let raw = String::from_utf8_lossy(&output.stdout);
184 let trimmed = raw.trim();
185 if trimmed.is_empty() {
186 return Err(ChangedFilesError::GitFailed(
187 "git rev-parse --show-toplevel returned empty output".to_owned(),
188 ));
189 }
190
191 let path = PathBuf::from(trimmed);
192 Ok(dunce::canonicalize(&path).unwrap_or(path))
193}
194
195pub fn resolve_git_common_dir(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
197 let output = spawn_output(&mut git_command(
198 cwd,
199 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
200 ))
201 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
202
203 if !output.status.success() {
204 let stderr = String::from_utf8_lossy(&output.stderr);
205 return Err(if stderr.contains("not a git repository") {
206 ChangedFilesError::NotARepository
207 } else {
208 ChangedFilesError::GitFailed(stderr.trim().to_owned())
209 });
210 }
211
212 let raw = String::from_utf8_lossy(&output.stdout);
213 let trimmed = raw.trim();
214 if trimmed.is_empty() {
215 return Err(ChangedFilesError::GitFailed(
216 "git rev-parse --git-common-dir returned empty output".to_owned(),
217 ));
218 }
219
220 let path = PathBuf::from(trimmed);
221 Ok(dunce::canonicalize(&path).unwrap_or(path))
222}
223
224pub fn resolve_git_common_dir_and_toplevel(
238 cwd: &Path,
239) -> Result<(PathBuf, PathBuf), ChangedFilesError> {
240 let output = spawn_output(&mut git_command(
241 cwd,
242 &[
243 "rev-parse",
244 "--path-format=absolute",
245 "--git-common-dir",
246 "--show-toplevel",
247 ],
248 ))
249 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
250
251 if !output.status.success() {
252 let stderr = String::from_utf8_lossy(&output.stderr);
253 return Err(if stderr.contains("not a git repository") {
254 ChangedFilesError::NotARepository
255 } else {
256 ChangedFilesError::GitFailed(stderr.trim().to_owned())
257 });
258 }
259
260 let raw = String::from_utf8_lossy(&output.stdout);
261 let mut lines = raw.lines();
262 let (Some(common), Some(toplevel), None) = (lines.next(), lines.next(), lines.next()) else {
263 return Err(ChangedFilesError::GitFailed(
264 "git rev-parse did not print one common dir and one toplevel".to_owned(),
265 ));
266 };
267 let canonical = |line: &str| {
268 let path = PathBuf::from(line.trim());
269 dunce::canonicalize(&path).unwrap_or(path)
270 };
271 if common.trim().is_empty() || toplevel.trim().is_empty() {
272 return Err(ChangedFilesError::GitFailed(
273 "git rev-parse returned an empty path".to_owned(),
274 ));
275 }
276 Ok((canonical(common), canonical(toplevel)))
277}
278
279fn try_get_changed_files(
281 root: &Path,
282 git_ref: &str,
283) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
284 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
285 let toplevel = resolve_git_toplevel(root)?;
286 try_get_changed_files_with_toplevel(root, &toplevel, git_ref)
287}
288
289pub fn changed_files(root: &Path, git_ref: &str) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
295 try_get_changed_files(root, git_ref)
296}
297
298pub(crate) struct ChangedFilesBatch<'a> {
302 cwd: &'a Path,
303 toplevel: PathBuf,
304 working_tree: Option<FxHashSet<PathBuf>>,
305}
306
307impl<'a> ChangedFilesBatch<'a> {
308 pub(crate) fn new(cwd: &'a Path, first_ref: &str) -> Result<Self, ChangedFilesError> {
309 validate_git_ref(first_ref).map_err(ChangedFilesError::InvalidRef)?;
310 Ok(Self {
311 cwd,
312 toplevel: resolve_git_toplevel(cwd)?,
313 working_tree: None,
314 })
315 }
316
317 pub(crate) fn changed_files(
318 &mut self,
319 git_ref: &str,
320 ) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
321 let mut files = committed_changed_files(self.cwd, &self.toplevel, git_ref)?;
322 if self.working_tree.is_none() {
323 self.working_tree = Some(working_tree_changed_files(self.cwd, &self.toplevel)?);
324 }
325 if let Some(working_tree) = &self.working_tree {
326 files.extend(working_tree.iter().cloned());
327 }
328 Ok(files)
329 }
330}
331
332pub fn try_get_changed_files_with_toplevel(
334 cwd: &Path,
335 toplevel: &Path,
336 git_ref: &str,
337) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
338 let mut files = committed_changed_files(cwd, toplevel, git_ref)?;
339 files.extend(working_tree_changed_files(cwd, toplevel)?);
340 Ok(files)
341}
342
343fn committed_changed_files(
344 cwd: &Path,
345 toplevel: &Path,
346 git_ref: &str,
347) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
348 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
349 collect_git_paths(
350 cwd,
351 toplevel,
352 &[
353 "diff",
354 "--name-only",
355 "-z",
356 "--end-of-options",
357 &format!("{git_ref}...HEAD"),
358 ],
359 )
360}
361
362fn working_tree_changed_files(
363 cwd: &Path,
364 toplevel: &Path,
365) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
366 let mut files = collect_git_paths(cwd, toplevel, &["diff", "--name-only", "-z", "HEAD"])?;
367 if untracked_files_excluded() {
368 return Ok(files);
369 }
370 files.extend(collect_git_paths(
371 cwd,
372 toplevel,
373 &[
374 "ls-files",
375 "--full-name",
376 "--others",
377 "--exclude-standard",
378 "-z",
379 ],
380 )?);
381 Ok(files)
382}
383
384#[derive(Debug, Clone, PartialEq, Eq)]
387pub struct RenamedFile {
388 pub from: PathBuf,
390 pub to: PathBuf,
392}
393
394pub fn try_get_renamed_files(
406 root: &Path,
407 git_ref: &str,
408) -> Result<Vec<RenamedFile>, ChangedFilesError> {
409 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
410 let toplevel = resolve_git_toplevel(root)?;
411 let mut renames = collect_git_rename_pairs(
412 root,
413 &toplevel,
414 &[
415 "diff",
416 "--name-status",
417 "-z",
418 "--find-renames",
419 "--end-of-options",
420 &format!("{git_ref}...HEAD"),
421 ],
422 )?;
423 let staged = collect_git_rename_pairs(
424 root,
425 &toplevel,
426 &["diff", "--name-status", "-z", "--find-renames", "HEAD"],
427 )?;
428 for pair in staged {
429 if let Some(chained) = renames.iter_mut().find(|rename| rename.to == pair.from) {
430 chained.to = pair.to;
431 } else {
432 renames.push(pair);
433 }
434 }
435 Ok(renames)
436}
437
438fn collect_git_rename_pairs(
444 cwd: &Path,
445 toplevel: &Path,
446 args: &[&str],
447) -> Result<Vec<RenamedFile>, ChangedFilesError> {
448 let output = spawn_output(&mut git_command(cwd, args))
449 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
450
451 if !output.status.success() {
452 return Err(changed_files_error_from_output(&output));
453 }
454
455 let mut fields = output
456 .stdout
457 .split(|byte| *byte == 0)
458 .filter(|field| !field.is_empty());
459 let mut renames = Vec::new();
460 while let Some(status) = fields.next() {
461 let Some(first_path) = fields.next() else {
462 break;
463 };
464 match status.first() {
465 Some(b'R') => {
466 let Some(second_path) = fields.next() else {
467 break;
468 };
469 renames.push(RenamedFile {
470 from: toplevel.join(git_path_from_bytes(first_path)),
471 to: toplevel.join(git_path_from_bytes(second_path)),
472 });
473 }
474 Some(b'C') => {
477 let _ = fields.next();
478 }
479 _ => {}
480 }
481 }
482 Ok(renames)
483}
484
485pub fn try_get_changed_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
490 changed_diff(root, git_ref, false)
491}
492
493pub fn try_get_mutation_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
498 changed_diff(root, git_ref, true)
499}
500
501fn changed_diff(
502 root: &Path,
503 git_ref: &str,
504 detect_copies: bool,
505) -> Result<String, ChangedFilesError> {
506 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
507 let toplevel = resolve_git_toplevel(root)?;
508 let merge_base_output = spawn_output(&mut git_command(root, &["merge-base", git_ref, "HEAD"]))
509 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
510 if !merge_base_output.status.success() {
511 return Err(changed_files_error_from_output(&merge_base_output));
512 }
513 let merge_base = String::from_utf8_lossy(&merge_base_output.stdout)
514 .trim()
515 .to_owned();
516 if merge_base.is_empty() {
517 return Err(ChangedFilesError::GitFailed(
518 "git merge-base returned empty output".to_owned(),
519 ));
520 }
521
522 let mut args = vec!["diff", "--relative", "--unified=0"];
523 if detect_copies {
524 args.extend(["-M", "-C"]);
525 }
526 args.extend(["--end-of-options", &merge_base]);
527 let output = spawn_output(&mut git_command(root, &args))
528 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
529
530 if !output.status.success() {
531 return Err(changed_files_error_from_output(&output));
532 }
533
534 let mut diff = String::from_utf8_lossy(&output.stdout).into_owned();
535 append_untracked_diffs(root, &toplevel, &mut diff)?;
536 Ok(diff)
537}
538
539fn append_untracked_diffs(
540 root: &Path,
541 toplevel: &Path,
542 diff: &mut String,
543) -> Result<(), ChangedFilesError> {
544 if untracked_files_excluded() {
545 return Ok(());
546 }
547 let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
548 let mut untracked: Vec<PathBuf> = collect_git_paths(
549 root,
550 toplevel,
551 &[
552 "ls-files",
553 "--full-name",
554 "--others",
555 "--exclude-standard",
556 "-z",
557 ],
558 )?
559 .into_iter()
560 .filter_map(|path| {
561 path.strip_prefix(&canonical_root)
562 .ok()
563 .map(Path::to_path_buf)
564 })
565 .collect();
566 untracked.sort_unstable();
567
568 #[cfg(windows)]
569 let empty_file = "NUL";
570 #[cfg(not(windows))]
571 let empty_file = "/dev/null";
572
573 for path in untracked {
574 let mut command = git_command(root, &["diff", "--no-index", "--unified=0", "--"]);
575 command.arg(empty_file).arg(untracked_path_arg(&path));
576 let output =
577 spawn_output(&mut command).map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
578 if !output.status.success() && output.status.code() != Some(1) {
579 return Err(changed_files_error_from_output(&output));
580 }
581 if !diff.is_empty() && !diff.ends_with('\n') {
582 diff.push('\n');
583 }
584 diff.push_str(&String::from_utf8_lossy(&output.stdout));
585 }
586 Ok(())
587}
588
589fn untracked_path_arg(path: &Path) -> String {
594 path.to_string_lossy().replace('\\', "/")
595}
596
597fn changed_files_error_from_output(output: &Output) -> ChangedFilesError {
598 let stderr = String::from_utf8_lossy(&output.stderr);
599 if stderr.contains("not a git repository") {
600 ChangedFilesError::NotARepository
601 } else {
602 ChangedFilesError::GitFailed(stderr.trim().to_owned())
603 }
604}
605
606#[must_use]
608#[expect(
609 clippy::print_stderr,
610 reason = "intentional user-facing warning for the CLI's --changed-since fallback path; typed callers use try_get_changed_files instead"
611)]
612pub fn get_changed_files(root: &Path, git_ref: &str) -> Option<FxHashSet<PathBuf>> {
613 match try_get_changed_files(root, git_ref) {
614 Ok(files) => Some(files),
615 Err(err) => {
616 eprintln!("Warning: {}", err.changed_since_message(git_ref));
617 None
618 }
619 }
620}
621
622fn spawn_output(command: &mut Command) -> std::io::Result<Output> {
623 if let Some(hook) = SPAWN_HOOK.get() {
624 hook(command)
625 } else {
626 command.output()
627 }
628}
629
630fn collect_git_paths(
631 cwd: &Path,
632 toplevel: &Path,
633 args: &[&str],
634) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
635 let output = spawn_output(&mut git_command(cwd, args))
636 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
637
638 if !output.status.success() {
639 let stderr = String::from_utf8_lossy(&output.stderr);
640 return Err(if stderr.contains("not a git repository") {
641 ChangedFilesError::NotARepository
642 } else {
643 ChangedFilesError::GitFailed(stderr.trim().to_owned())
644 });
645 }
646
647 let files = output
648 .stdout
649 .split(|byte| *byte == 0)
650 .filter(|path| !path.is_empty())
651 .map(git_path_from_bytes)
652 .map(|path| toplevel.join(path))
653 .collect();
654
655 Ok(files)
656}
657
658#[cfg(unix)]
664pub(crate) fn git_path_from_bytes(path: &[u8]) -> PathBuf {
665 use std::ffi::OsString;
666 use std::os::unix::ffi::OsStringExt;
667
668 PathBuf::from(OsString::from_vec(path.to_vec()))
669}
670
671#[cfg(windows)]
674pub(crate) fn git_path_from_bytes(path: &[u8]) -> PathBuf {
675 PathBuf::from(String::from_utf8_lossy(path).replace('/', "\\"))
676}
677
678fn git_command(cwd: &Path, args: &[&str]) -> Command {
679 let mut command = crate::git_env::git_command(cwd);
680 command.args(args);
681 command
682}
683
684#[expect(
689 clippy::implicit_hasher,
690 reason = "fallow standardizes on FxHashSet across the workspace"
691)]
692pub fn filter_results_by_changed_files(
693 results: &mut AnalysisResults,
694 changed_files: &FxHashSet<PathBuf>,
695) {
696 filter_results_by_path_scope(results, &NormalizedChangedFiles::new(changed_files));
697}
698
699#[expect(
707 clippy::implicit_hasher,
708 reason = "fallow standardizes on FxHashSet across the workspace"
709)]
710pub fn filter_results_by_changed_files_keeping_unused_code(
711 results: &mut AnalysisResults,
712 changed_files: &FxHashSet<PathBuf>,
713) {
714 keeping_unused_code(results, |results| {
715 filter_results_by_changed_files(results, changed_files);
716 });
717}
718
719pub(crate) fn keeping_unused_code(
721 results: &mut AnalysisResults,
722 filter: impl FnOnce(&mut AnalysisResults),
723) {
724 let unused_files = std::mem::take(&mut results.unused_files);
725 let unused_exports = std::mem::take(&mut results.unused_exports);
726 filter(results);
727 results.unused_files = unused_files;
728 results.unused_exports = unused_exports;
729}
730
731pub(crate) trait ChangedPathScope {
734 fn contains(&self, path: &Path) -> bool;
735 fn contains_workspace(&self, path: &Path) -> bool {
736 self.contains(path)
737 }
738}
739
740#[derive(Debug, Clone, Default)]
742pub(crate) struct NormalizedChangedFiles(FxHashSet<PathBuf>);
743
744impl NormalizedChangedFiles {
745 pub(crate) fn new(changed_files: &FxHashSet<PathBuf>) -> Self {
746 Self(normalize_changed_files_set(changed_files))
747 }
748}
749
750impl ChangedPathScope for NormalizedChangedFiles {
751 fn contains(&self, path: &Path) -> bool {
752 contains_normalized(&self.0, path)
753 }
754
755 fn contains_workspace(&self, path: &Path) -> bool {
756 normalized_set_contains_path(&self.0, path)
757 }
758}
759
760struct ChangedPaths<'a, S: ChangedPathScope>(&'a S);
762
763impl<S: ChangedPathScope> ResultScope for ChangedPaths<'_, S> {
764 fn keeps(&self, anchor: Anchor<'_>) -> bool {
765 match anchor {
766 Anchor::Line { path, .. } | Anchor::File { path } => self.0.contains(path),
767 }
768 }
769
770 fn keeps_project_finding(&self, finding: ProjectFinding<'_>) -> bool {
771 match finding {
772 ProjectFinding::ManifestDependency { .. } | ProjectFinding::CatalogEntry => true,
773 ProjectFinding::EmptyCatalogGroup { path } => self.0.contains_workspace(path),
774 ProjectFinding::CatalogReference { path }
775 | ProjectFinding::DependencyOverride { path } => self.0.contains(path),
776 }
777 }
778
779 fn keeps_security_finding(&self, finding: &SecurityFinding) -> bool {
780 security_finding_touches_changed_path(finding, self.0)
781 }
782
783 fn site_rule(&self) -> SiteRule {
784 SiteRule::AnySite
785 }
786
787 fn owner_rule(&self) -> OwnerRule {
788 OwnerRule::TrimOwners
789 }
790
791 fn component_rule(&self) -> ComponentRule {
792 ComponentRule::All
793 }
794}
795
796pub(crate) fn filter_results_by_path_scope(
797 results: &mut AnalysisResults,
798 scope: &impl ChangedPathScope,
799) {
800 crate::result_scope::retain_in_scope(results, &ChangedPaths(scope));
801}
802
803fn security_finding_touches_changed_path(
804 finding: &SecurityFinding,
805 scope: &impl ChangedPathScope,
806) -> bool {
807 scope.contains(&finding.path)
808 || finding.trace.iter().any(|hop| scope.contains(&hop.path))
809 || finding.reachability.as_ref().is_some_and(|reachability| {
810 reachability
811 .untrusted_source_trace
812 .iter()
813 .any(|hop| scope.contains(&hop.path))
814 })
815}
816
817fn normalize_changed_files_set(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<PathBuf> {
818 changed_files
819 .iter()
820 .map(|p| dunce::simplified(p).to_path_buf())
821 .collect()
822}
823
824fn contains_normalized(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
825 normalized.contains(dunce::simplified(path))
826}
827
828fn normalized_set_contains_path(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
829 contains_normalized(normalized, path)
830 || (path.is_relative() && normalized.iter().any(|changed| changed.ends_with(path)))
831}
832
833#[expect(
835 clippy::implicit_hasher,
836 reason = "fallow standardizes on FxHashSet across the workspace"
837)]
838pub fn filter_duplication_by_changed_files(
839 report: &mut DuplicationReport,
840 changed_files: &FxHashSet<PathBuf>,
841 root: &Path,
842) {
843 filter_duplication_by_path_scope(report, &NormalizedChangedFiles::new(changed_files), root);
844}
845
846pub(crate) fn filter_duplication_by_path_scope(
847 report: &mut DuplicationReport,
848 scope: &impl ChangedPathScope,
849 root: &Path,
850) {
851 report.clone_groups.retain(|group| {
852 group
853 .instances
854 .iter()
855 .any(|instance| scope.contains(&instance.file))
856 });
857 report
858 .range_marker_problems
859 .retain(|finding| scope.contains(&finding.path));
860 duplicates::refresh_scoped_report(report, root);
861}
862
863#[cfg(test)]
864mod tests {
865 use super::*;
866 use fallow_types::{
867 duplicates::{CloneGroup, CloneInstance, DuplicationStats},
868 output_dead_code::{
869 EmptyCatalogGroupFinding, UnusedDependencyFinding, UnusedExportFinding,
870 UnusedFileFinding,
871 },
872 results::{
873 DependencyLocation, EmptyCatalogGroup, UnusedDependency, UnusedExport, UnusedFile,
874 },
875 };
876
877 #[test]
880 fn every_changed_files_cause_reports_its_own_reason() {
881 let reasons = [
882 ChangedFilesError::InvalidRef("unclosed brace".to_owned()).reason(),
883 ChangedFilesError::GitMissing("no such file".to_owned()).reason(),
884 ChangedFilesError::NotARepository.reason(),
885 ChangedFilesError::GitFailed("unknown revision".to_owned()).reason(),
886 ];
887 assert_eq!(
888 reasons,
889 [
890 "invalid-ref",
891 "git-missing",
892 "not-a-repository",
893 "git-failed"
894 ]
895 );
896 let unique: std::collections::BTreeSet<&str> = reasons.iter().copied().collect();
897 assert_eq!(
898 unique.len(),
899 reasons.len(),
900 "two causes must not share a token"
901 );
902 }
903
904 #[test]
909 fn the_changed_since_message_names_the_ref_the_widening_and_the_next_step() {
910 let message = ChangedFilesError::NotARepository.changed_since_message("origin/main");
911 assert!(
912 message.contains("--changed-since 'origin/main'"),
913 "{message}"
914 );
915 assert!(message.contains("covers the whole project"), "{message}");
916 assert!(message.ends_with("or drop --changed-since."), "{message}");
917 }
918
919 #[test]
923 fn the_changed_since_message_folds_git_stderr_onto_one_line() {
924 let message = ChangedFilesError::GitFailed(
925 "fatal: ambiguous argument 'x'\nUse '--' to separate paths".to_owned(),
926 )
927 .changed_since_message("x");
928 assert!(!message.contains('\n'), "{message}");
929 assert!(
930 message.contains("ambiguous argument 'x' Use '--'"),
931 "{message}"
932 );
933 }
934
935 #[test]
936 fn git_command_clears_parent_git_environment() {
937 let command = git_command(Path::new("."), &["status"]);
938 let envs: Vec<_> = command.get_envs().collect();
939
940 for var in AMBIENT_GIT_ENV_VARS {
941 assert!(
942 envs.iter()
943 .any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
944 "{var} should be cleared from the command env",
945 );
946 }
947 }
948
949 #[test]
950 fn try_get_changed_files_not_a_repository() {
951 let temp = tempfile::tempdir().expect("tempdir");
952 let result = try_get_changed_files(temp.path(), "main");
953 assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
954 }
955
956 #[test]
957 fn batched_refs_match_independent_changed_file_scopes() {
958 let repo = tempfile::tempdir().expect("tempdir");
959 for args in [
960 &["init", "--quiet"][..],
961 &["config", "user.email", "test@example.com"][..],
962 &["config", "user.name", "Test User"][..],
963 &["config", "commit.gpgsign", "false"][..],
964 ] {
965 run_git(repo.path(), args);
966 }
967 for name in ["committed.ts", "staged.ts", "unstaged.ts"] {
968 std::fs::write(repo.path().join(name), "old\n").expect("initial file");
969 }
970 run_git(repo.path(), &["add", "."]);
971 run_git(repo.path(), &["commit", "--quiet", "-m", "base"]);
972 run_git(repo.path(), &["branch", "base"]);
973
974 std::fs::write(repo.path().join("committed.ts"), "new\n").expect("committed change");
975 run_git(repo.path(), &["add", "committed.ts"]);
976 run_git(repo.path(), &["commit", "--quiet", "-m", "change"]);
977 std::fs::write(repo.path().join("staged.ts"), "new\n").expect("staged change");
978 run_git(repo.path(), &["add", "staged.ts"]);
979 std::fs::write(repo.path().join("unstaged.ts"), "new\n").expect("unstaged change");
980 std::fs::write(repo.path().join("untracked.ts"), "new\n").expect("untracked file");
981
982 let mut batch = ChangedFilesBatch::new(repo.path(), "base").expect("batch");
983 for reference in ["base", "HEAD"] {
984 let batched = batch.changed_files(reference).expect("batched changes");
985 let independent = changed_files(repo.path(), reference).expect("independent changes");
986 assert_eq!(batched, independent, "{reference} scope changed");
987 }
988 }
989
990 #[cfg(unix)]
991 #[test]
992 fn changed_files_preserve_special_filenames() {
993 let repo = tempfile::tempdir().expect("tempdir");
994 for args in [
995 &["init", "--quiet"][..],
996 &["config", "user.email", "test@example.com"][..],
997 &["config", "user.name", "Test User"][..],
998 &["config", "commit.gpgsign", "false"][..],
999 &["config", "tag.gpgsign", "false"][..],
1000 ] {
1001 run_git(repo.path(), args);
1002 }
1003 std::fs::write(repo.path().join("initial.ts"), "initial\n").expect("initial fixture");
1004 run_git(repo.path(), &["add", "."]);
1005 run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
1006 run_git(repo.path(), &["tag", "base"]);
1007
1008 let canonical_root = repo.path().canonicalize().expect("canonical repo");
1009 let special_files = [
1010 "src/line\nbreak.ts",
1011 "src/space name.ts",
1012 "src/quote\"name.ts",
1013 "src/back\\slash.ts",
1014 "src/unicode-λ.ts",
1015 ]
1016 .map(|path| canonical_root.join(path));
1017 std::fs::create_dir_all(canonical_root.join("src")).expect("source dir");
1018 for special in &special_files {
1019 std::fs::write(special, "changed\n").expect("special fixture");
1020 }
1021
1022 let changed = try_get_changed_files(repo.path(), "base").expect("changed files");
1023 for special in special_files {
1024 assert!(
1025 changed.contains(&special),
1026 "missing {special:?}: {changed:?}"
1027 );
1028 }
1029 }
1030
1031 #[cfg(windows)]
1032 #[test]
1033 fn git_path_bytes_use_windows_separators() {
1034 assert_eq!(
1035 git_path_from_bytes(b"src/nested/file.ts"),
1036 PathBuf::from(r"src\nested\file.ts")
1037 );
1038 }
1039
1040 #[test]
1041 fn changed_diff_covers_staged_unstaged_and_untracked_files() {
1042 let repo = tempfile::tempdir().expect("tempdir");
1043 for args in [
1044 &["init", "--quiet"][..],
1045 &["config", "user.email", "test@example.com"][..],
1046 &["config", "user.name", "Test User"][..],
1047 &["config", "commit.gpgsign", "false"][..],
1048 &["config", "tag.gpgsign", "false"][..],
1049 ] {
1050 run_git(repo.path(), args);
1051 }
1052 std::fs::write(repo.path().join("staged.ts"), "old\n").expect("staged fixture");
1053 std::fs::write(repo.path().join("unstaged.ts"), "old\n").expect("unstaged fixture");
1054 run_git(repo.path(), &["add", "."]);
1055 run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
1056 run_git(repo.path(), &["tag", "base"]);
1057
1058 std::fs::write(repo.path().join("committed.ts"), "committed\n").expect("committed fixture");
1059 run_git(repo.path(), &["add", "committed.ts"]);
1060 run_git(
1061 repo.path(),
1062 &["commit", "--quiet", "-m", "committed change"],
1063 );
1064
1065 std::fs::write(repo.path().join("staged.ts"), "staged\n").expect("staged edit");
1066 run_git(repo.path(), &["add", "staged.ts"]);
1067 std::fs::write(repo.path().join("unstaged.ts"), "unstaged\n").expect("unstaged edit");
1068 std::fs::write(repo.path().join("untracked.ts"), "untracked\n").expect("untracked edit");
1069
1070 for diff in [
1071 try_get_changed_diff(repo.path(), "base"),
1072 try_get_mutation_diff(repo.path(), "base"),
1073 ] {
1074 let diff = diff.expect("complete changeset diff");
1075 let index = fallow_output::DiffIndex::from_unified_diff(&diff);
1076
1077 assert!(diff.contains("b/committed.ts"), "{diff}");
1078 assert!(diff.contains("b/staged.ts"), "{diff}");
1079 assert!(diff.contains("b/unstaged.ts"), "{diff}");
1080 assert!(diff.contains("b/untracked.ts"), "{diff}");
1081 assert_eq!(index.hunk_count(), 4);
1082 assert_eq!(index.net_lines(), 2);
1083 }
1084 }
1085
1086 fn run_git(root: &Path, args: &[&str]) {
1087 let output = crate::git_fixture::fixture_git_command_with_identity(
1088 root,
1089 crate::git_fixture::FixtureIdentity::RepositoryConfig,
1090 )
1091 .args(args)
1092 .output()
1093 .expect("git command");
1094 assert!(
1095 output.status.success(),
1096 "git {args:?} failed: {}",
1097 String::from_utf8_lossy(&output.stderr)
1098 );
1099 }
1100
1101 #[test]
1102 fn untracked_path_arg_uses_forward_slashes() {
1103 assert_eq!(
1104 super::untracked_path_arg(Path::new("src\\nested\\b.ts")),
1105 "src/nested/b.ts"
1106 );
1107 assert_eq!(super::untracked_path_arg(Path::new("src/b.ts")), "src/b.ts");
1108 }
1109
1110 #[test]
1111 fn changed_files_error_describe_matches_core_contract() {
1112 assert_eq!(
1113 ChangedFilesError::InvalidRef("bad ref".to_string()).describe(),
1114 "invalid git ref: bad ref"
1115 );
1116 assert_eq!(
1117 ChangedFilesError::GitMissing("not found".to_string()).describe(),
1118 "failed to run git: not found"
1119 );
1120 assert_eq!(
1121 ChangedFilesError::NotARepository.describe(),
1122 "not a git repository"
1123 );
1124 assert!(
1125 ChangedFilesError::GitFailed("unknown revision main".to_string())
1126 .describe()
1127 .contains("fetch-depth: 0")
1128 );
1129 }
1130
1131 #[test]
1132 fn filter_results_keeps_only_changed_file_findings() {
1133 let mut results = AnalysisResults::default();
1134 results
1135 .unused_files
1136 .push(UnusedFileFinding::with_actions(UnusedFile {
1137 path: PathBuf::from("/repo/a.ts"),
1138 }));
1139 results
1140 .unused_files
1141 .push(UnusedFileFinding::with_actions(UnusedFile {
1142 path: PathBuf::from("/repo/b.ts"),
1143 }));
1144 results
1145 .unused_exports
1146 .push(UnusedExportFinding::with_actions(UnusedExport {
1147 path: PathBuf::from("/repo/a.ts"),
1148 export_name: "foo".to_owned(),
1149 is_type_only: false,
1150 line: 1,
1151 col: 0,
1152 span_start: 0,
1153 is_re_export: false,
1154 deprecated: false,
1155 deprecated_reason: None,
1156 }));
1157
1158 let mut changed = FxHashSet::default();
1159 changed.insert(PathBuf::from("/repo/a.ts"));
1160
1161 filter_results_by_changed_files(&mut results, &changed);
1162
1163 assert_eq!(results.unused_files.len(), 1);
1164 assert_eq!(
1165 results.unused_files[0].file.path,
1166 PathBuf::from("/repo/a.ts")
1167 );
1168 assert_eq!(results.unused_exports.len(), 1);
1169 }
1170
1171 #[test]
1172 fn filter_results_preserves_graph_global_dependency_findings() {
1173 let mut results = AnalysisResults::default();
1174 results
1175 .unused_dependencies
1176 .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1177 package_name: "lodash".to_owned(),
1178 location: DependencyLocation::Dependencies,
1179 path: PathBuf::from("/repo/package.json"),
1180 line: 3,
1181 used_in_workspaces: Vec::new(),
1182 declared_and_imported_in: Vec::new(),
1183 }));
1184
1185 let changed = FxHashSet::default();
1186 filter_results_by_changed_files(&mut results, &changed);
1187
1188 assert_eq!(results.unused_dependencies.len(), 1);
1189 }
1190
1191 #[test]
1195 fn filter_results_keeps_deprecated_export_only_when_its_declaring_file_changed() {
1196 let finding = |path: &str| {
1197 fallow_types::output_dead_code::DeprecatedExportInUseFinding::with_actions(
1198 fallow_types::results::DeprecatedExportInUse {
1199 path: PathBuf::from(path),
1200 export_name: "old".to_owned(),
1201 is_type_only: false,
1202 line: 2,
1203 col: 0,
1204 span_start: 0,
1205 deprecated_reason: None,
1206 consumer_count: 1,
1207 consumers: vec![fallow_types::results::DeprecatedExportConsumer {
1208 path: PathBuf::from("/repo/consumer.ts"),
1209 line: 1,
1210 col: 0,
1211 kind: fallow_types::results::DeprecatedConsumerKind::NamedImport,
1212 }],
1213 public_api: false,
1214 },
1215 )
1216 };
1217 let mut results = AnalysisResults::default();
1218 results
1219 .deprecated_exports_in_use
1220 .push(finding("/repo/a.ts"));
1221 results
1222 .deprecated_exports_in_use
1223 .push(finding("/repo/b.ts"));
1224
1225 let mut changed = FxHashSet::default();
1226 changed.insert(PathBuf::from("/repo/a.ts"));
1227 changed.insert(PathBuf::from("/repo/consumer.ts"));
1228 filter_results_by_changed_files(&mut results, &changed);
1229
1230 let kept: Vec<_> = results
1231 .deprecated_exports_in_use
1232 .iter()
1233 .map(|f| f.export.path.clone())
1234 .collect();
1235 assert_eq!(kept, vec![PathBuf::from("/repo/a.ts")]);
1236 }
1237
1238 #[test]
1239 fn filter_results_keeps_relative_manifest_finding_when_manifest_changed() {
1240 let mut results = AnalysisResults::default();
1241 results
1242 .empty_catalog_groups
1243 .push(EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
1244 catalog_name: "legacy".to_owned(),
1245 path: PathBuf::from("pnpm-workspace.yaml"),
1246 line: 4,
1247 }));
1248
1249 let mut changed = FxHashSet::default();
1250 changed.insert(PathBuf::from("/repo/pnpm-workspace.yaml"));
1251
1252 filter_results_by_changed_files(&mut results, &changed);
1253
1254 assert_eq!(results.empty_catalog_groups.len(), 1);
1255 }
1256
1257 #[test]
1258 fn filter_duplication_keeps_groups_with_changed_instances_and_recomputes_stats() {
1259 let mut report = DuplicationReport {
1260 clone_groups: vec![
1261 CloneGroup {
1262 instances: vec![
1263 CloneInstance {
1264 is_symlink: false,
1265 file: PathBuf::from("/repo/a.ts"),
1266 start_line: 1,
1267 end_line: 5,
1268 start_col: 0,
1269 end_col: 10,
1270 fragment: "code".to_owned(),
1271 },
1272 CloneInstance {
1273 is_symlink: false,
1274 file: PathBuf::from("/repo/b.ts"),
1275 start_line: 1,
1276 end_line: 5,
1277 start_col: 0,
1278 end_col: 10,
1279 fragment: "code".to_owned(),
1280 },
1281 ],
1282 token_count: 20,
1283 line_count: 5,
1284 similarity: None,
1285 },
1286 CloneGroup {
1287 instances: vec![
1288 CloneInstance {
1289 is_symlink: false,
1290 file: PathBuf::from("/repo/c.ts"),
1291 start_line: 1,
1292 end_line: 5,
1293 start_col: 0,
1294 end_col: 10,
1295 fragment: "other".to_owned(),
1296 },
1297 CloneInstance {
1298 is_symlink: false,
1299 file: PathBuf::from("/repo/d.ts"),
1300 start_line: 1,
1301 end_line: 5,
1302 start_col: 0,
1303 end_col: 10,
1304 fragment: "other".to_owned(),
1305 },
1306 ],
1307 token_count: 20,
1308 line_count: 5,
1309 similarity: None,
1310 },
1311 ],
1312 clone_families: Vec::new(),
1313 mirrored_directories: Vec::new(),
1314 range_marker_problems: Vec::new(),
1315 stats: DuplicationStats {
1316 total_files: 4,
1317 files_with_clones: 4,
1318 total_lines: 100,
1319 duplicated_lines: 20,
1320 total_tokens: 200,
1321 duplicated_tokens: 80,
1322 clone_groups: 2,
1323 clone_families: 0,
1324 clone_instances: 4,
1325 duplication_percentage: 20.0,
1326 clone_groups_below_min_occurrences: 0,
1327 clone_groups_ignored: 0,
1328 near_candidates_skipped: 0,
1329 },
1330 };
1331
1332 let mut changed = FxHashSet::default();
1333 changed.insert(PathBuf::from("/repo/a.ts"));
1334
1335 filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1336
1337 assert_eq!(report.clone_groups.len(), 1);
1338 assert_eq!(report.stats.clone_groups, 1);
1339 assert_eq!(report.stats.clone_instances, 2);
1340 }
1341
1342 #[test]
1346 fn changed_file_scope_orders_families_by_file_set() {
1347 let group = |files: [&str; 2], line_count: usize| CloneGroup {
1348 instances: files
1349 .iter()
1350 .map(|file| CloneInstance {
1351 is_symlink: false,
1352 file: PathBuf::from(file),
1353 start_line: 1,
1354 end_line: line_count,
1355 start_col: 0,
1356 end_col: 10,
1357 fragment: String::new(),
1358 })
1359 .collect(),
1360 token_count: line_count * 10,
1361 line_count,
1362 similarity: None,
1363 };
1364 let mut report = DuplicationReport {
1365 clone_groups: vec![
1366 group(["/repo/y.ts", "/repo/z.ts"], 46),
1367 group(["/repo/a.ts", "/repo/b.ts"], 7),
1368 ],
1369 clone_families: Vec::new(),
1370 mirrored_directories: Vec::new(),
1371 range_marker_problems: Vec::new(),
1372 stats: DuplicationStats::default(),
1373 };
1374 let changed: FxHashSet<PathBuf> = ["/repo/a.ts", "/repo/y.ts"]
1375 .into_iter()
1376 .map(PathBuf::from)
1377 .collect();
1378
1379 filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1380
1381 let order: Vec<&PathBuf> = report
1382 .clone_families
1383 .iter()
1384 .map(|family| &family.files[0])
1385 .collect();
1386 assert_eq!(
1387 order,
1388 [&PathBuf::from("/repo/a.ts"), &PathBuf::from("/repo/y.ts")]
1389 );
1390 }
1391
1392 #[test]
1395 fn one_probe_resolves_the_common_dir_and_the_toplevel() {
1396 let repo = tempfile::tempdir().expect("tempdir");
1397 run_git(repo.path(), &["init", "--quiet"]);
1398 let nested = repo.path().join("packages/app");
1399 std::fs::create_dir_all(&nested).expect("nested dir");
1400 for cwd in [repo.path(), nested.as_path()] {
1401 let (common, toplevel) =
1402 resolve_git_common_dir_and_toplevel(cwd).expect("combined probe");
1403 assert_eq!(common, resolve_git_common_dir(cwd).expect("common dir"));
1404 assert_eq!(toplevel, resolve_git_toplevel(cwd).expect("toplevel"));
1405 }
1406 }
1407
1408 #[test]
1411 fn the_combined_probe_fails_without_a_work_tree() {
1412 let repo = tempfile::tempdir().expect("tempdir");
1413 run_git(repo.path(), &["init", "--quiet", "--bare"]);
1414 assert!(resolve_git_common_dir_and_toplevel(repo.path()).is_err());
1415 assert!(resolve_git_common_dir(repo.path()).is_err());
1418 }
1419}