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 = spawn_output(&mut git_command(root, args)).expect("git command");
1088 assert!(
1089 output.status.success(),
1090 "git {args:?} failed: {}",
1091 String::from_utf8_lossy(&output.stderr)
1092 );
1093 }
1094
1095 #[test]
1096 fn untracked_path_arg_uses_forward_slashes() {
1097 assert_eq!(
1098 super::untracked_path_arg(Path::new("src\\nested\\b.ts")),
1099 "src/nested/b.ts"
1100 );
1101 assert_eq!(super::untracked_path_arg(Path::new("src/b.ts")), "src/b.ts");
1102 }
1103
1104 #[test]
1105 fn changed_files_error_describe_matches_core_contract() {
1106 assert_eq!(
1107 ChangedFilesError::InvalidRef("bad ref".to_string()).describe(),
1108 "invalid git ref: bad ref"
1109 );
1110 assert_eq!(
1111 ChangedFilesError::GitMissing("not found".to_string()).describe(),
1112 "failed to run git: not found"
1113 );
1114 assert_eq!(
1115 ChangedFilesError::NotARepository.describe(),
1116 "not a git repository"
1117 );
1118 assert!(
1119 ChangedFilesError::GitFailed("unknown revision main".to_string())
1120 .describe()
1121 .contains("fetch-depth: 0")
1122 );
1123 }
1124
1125 #[test]
1126 fn filter_results_keeps_only_changed_file_findings() {
1127 let mut results = AnalysisResults::default();
1128 results
1129 .unused_files
1130 .push(UnusedFileFinding::with_actions(UnusedFile {
1131 path: PathBuf::from("/repo/a.ts"),
1132 }));
1133 results
1134 .unused_files
1135 .push(UnusedFileFinding::with_actions(UnusedFile {
1136 path: PathBuf::from("/repo/b.ts"),
1137 }));
1138 results
1139 .unused_exports
1140 .push(UnusedExportFinding::with_actions(UnusedExport {
1141 path: PathBuf::from("/repo/a.ts"),
1142 export_name: "foo".to_owned(),
1143 is_type_only: false,
1144 line: 1,
1145 col: 0,
1146 span_start: 0,
1147 is_re_export: false,
1148 deprecated: false,
1149 deprecated_reason: None,
1150 }));
1151
1152 let mut changed = FxHashSet::default();
1153 changed.insert(PathBuf::from("/repo/a.ts"));
1154
1155 filter_results_by_changed_files(&mut results, &changed);
1156
1157 assert_eq!(results.unused_files.len(), 1);
1158 assert_eq!(
1159 results.unused_files[0].file.path,
1160 PathBuf::from("/repo/a.ts")
1161 );
1162 assert_eq!(results.unused_exports.len(), 1);
1163 }
1164
1165 #[test]
1166 fn filter_results_preserves_graph_global_dependency_findings() {
1167 let mut results = AnalysisResults::default();
1168 results
1169 .unused_dependencies
1170 .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1171 package_name: "lodash".to_owned(),
1172 location: DependencyLocation::Dependencies,
1173 path: PathBuf::from("/repo/package.json"),
1174 line: 3,
1175 used_in_workspaces: Vec::new(),
1176 declared_and_imported_in: Vec::new(),
1177 }));
1178
1179 let changed = FxHashSet::default();
1180 filter_results_by_changed_files(&mut results, &changed);
1181
1182 assert_eq!(results.unused_dependencies.len(), 1);
1183 }
1184
1185 #[test]
1189 fn filter_results_keeps_deprecated_export_only_when_its_declaring_file_changed() {
1190 let finding = |path: &str| {
1191 fallow_types::output_dead_code::DeprecatedExportInUseFinding::with_actions(
1192 fallow_types::results::DeprecatedExportInUse {
1193 path: PathBuf::from(path),
1194 export_name: "old".to_owned(),
1195 is_type_only: false,
1196 line: 2,
1197 col: 0,
1198 span_start: 0,
1199 deprecated_reason: None,
1200 consumer_count: 1,
1201 consumers: vec![fallow_types::results::DeprecatedExportConsumer {
1202 path: PathBuf::from("/repo/consumer.ts"),
1203 line: 1,
1204 col: 0,
1205 kind: fallow_types::results::DeprecatedConsumerKind::NamedImport,
1206 }],
1207 public_api: false,
1208 },
1209 )
1210 };
1211 let mut results = AnalysisResults::default();
1212 results
1213 .deprecated_exports_in_use
1214 .push(finding("/repo/a.ts"));
1215 results
1216 .deprecated_exports_in_use
1217 .push(finding("/repo/b.ts"));
1218
1219 let mut changed = FxHashSet::default();
1220 changed.insert(PathBuf::from("/repo/a.ts"));
1221 changed.insert(PathBuf::from("/repo/consumer.ts"));
1222 filter_results_by_changed_files(&mut results, &changed);
1223
1224 let kept: Vec<_> = results
1225 .deprecated_exports_in_use
1226 .iter()
1227 .map(|f| f.export.path.clone())
1228 .collect();
1229 assert_eq!(kept, vec![PathBuf::from("/repo/a.ts")]);
1230 }
1231
1232 #[test]
1233 fn filter_results_keeps_relative_manifest_finding_when_manifest_changed() {
1234 let mut results = AnalysisResults::default();
1235 results
1236 .empty_catalog_groups
1237 .push(EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
1238 catalog_name: "legacy".to_owned(),
1239 path: PathBuf::from("pnpm-workspace.yaml"),
1240 line: 4,
1241 }));
1242
1243 let mut changed = FxHashSet::default();
1244 changed.insert(PathBuf::from("/repo/pnpm-workspace.yaml"));
1245
1246 filter_results_by_changed_files(&mut results, &changed);
1247
1248 assert_eq!(results.empty_catalog_groups.len(), 1);
1249 }
1250
1251 #[test]
1252 fn filter_duplication_keeps_groups_with_changed_instances_and_recomputes_stats() {
1253 let mut report = DuplicationReport {
1254 clone_groups: vec![
1255 CloneGroup {
1256 instances: vec![
1257 CloneInstance {
1258 is_symlink: false,
1259 file: PathBuf::from("/repo/a.ts"),
1260 start_line: 1,
1261 end_line: 5,
1262 start_col: 0,
1263 end_col: 10,
1264 fragment: "code".to_owned(),
1265 },
1266 CloneInstance {
1267 is_symlink: false,
1268 file: PathBuf::from("/repo/b.ts"),
1269 start_line: 1,
1270 end_line: 5,
1271 start_col: 0,
1272 end_col: 10,
1273 fragment: "code".to_owned(),
1274 },
1275 ],
1276 token_count: 20,
1277 line_count: 5,
1278 similarity: None,
1279 },
1280 CloneGroup {
1281 instances: vec![
1282 CloneInstance {
1283 is_symlink: false,
1284 file: PathBuf::from("/repo/c.ts"),
1285 start_line: 1,
1286 end_line: 5,
1287 start_col: 0,
1288 end_col: 10,
1289 fragment: "other".to_owned(),
1290 },
1291 CloneInstance {
1292 is_symlink: false,
1293 file: PathBuf::from("/repo/d.ts"),
1294 start_line: 1,
1295 end_line: 5,
1296 start_col: 0,
1297 end_col: 10,
1298 fragment: "other".to_owned(),
1299 },
1300 ],
1301 token_count: 20,
1302 line_count: 5,
1303 similarity: None,
1304 },
1305 ],
1306 clone_families: Vec::new(),
1307 mirrored_directories: Vec::new(),
1308 range_marker_problems: Vec::new(),
1309 stats: DuplicationStats {
1310 total_files: 4,
1311 files_with_clones: 4,
1312 total_lines: 100,
1313 duplicated_lines: 20,
1314 total_tokens: 200,
1315 duplicated_tokens: 80,
1316 clone_groups: 2,
1317 clone_families: 0,
1318 clone_instances: 4,
1319 duplication_percentage: 20.0,
1320 clone_groups_below_min_occurrences: 0,
1321 clone_groups_ignored: 0,
1322 near_candidates_skipped: 0,
1323 },
1324 };
1325
1326 let mut changed = FxHashSet::default();
1327 changed.insert(PathBuf::from("/repo/a.ts"));
1328
1329 filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1330
1331 assert_eq!(report.clone_groups.len(), 1);
1332 assert_eq!(report.stats.clone_groups, 1);
1333 assert_eq!(report.stats.clone_instances, 2);
1334 }
1335
1336 #[test]
1340 fn changed_file_scope_orders_families_by_file_set() {
1341 let group = |files: [&str; 2], line_count: usize| CloneGroup {
1342 instances: files
1343 .iter()
1344 .map(|file| CloneInstance {
1345 is_symlink: false,
1346 file: PathBuf::from(file),
1347 start_line: 1,
1348 end_line: line_count,
1349 start_col: 0,
1350 end_col: 10,
1351 fragment: String::new(),
1352 })
1353 .collect(),
1354 token_count: line_count * 10,
1355 line_count,
1356 similarity: None,
1357 };
1358 let mut report = DuplicationReport {
1359 clone_groups: vec![
1360 group(["/repo/y.ts", "/repo/z.ts"], 46),
1361 group(["/repo/a.ts", "/repo/b.ts"], 7),
1362 ],
1363 clone_families: Vec::new(),
1364 mirrored_directories: Vec::new(),
1365 range_marker_problems: Vec::new(),
1366 stats: DuplicationStats::default(),
1367 };
1368 let changed: FxHashSet<PathBuf> = ["/repo/a.ts", "/repo/y.ts"]
1369 .into_iter()
1370 .map(PathBuf::from)
1371 .collect();
1372
1373 filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1374
1375 let order: Vec<&PathBuf> = report
1376 .clone_families
1377 .iter()
1378 .map(|family| &family.files[0])
1379 .collect();
1380 assert_eq!(
1381 order,
1382 [&PathBuf::from("/repo/a.ts"), &PathBuf::from("/repo/y.ts")]
1383 );
1384 }
1385
1386 #[test]
1389 fn one_probe_resolves_the_common_dir_and_the_toplevel() {
1390 let repo = tempfile::tempdir().expect("tempdir");
1391 run_git(repo.path(), &["init", "--quiet"]);
1392 let nested = repo.path().join("packages/app");
1393 std::fs::create_dir_all(&nested).expect("nested dir");
1394 for cwd in [repo.path(), nested.as_path()] {
1395 let (common, toplevel) =
1396 resolve_git_common_dir_and_toplevel(cwd).expect("combined probe");
1397 assert_eq!(common, resolve_git_common_dir(cwd).expect("common dir"));
1398 assert_eq!(toplevel, resolve_git_toplevel(cwd).expect("toplevel"));
1399 }
1400 }
1401
1402 #[test]
1405 fn the_combined_probe_fails_without_a_work_tree() {
1406 let repo = tempfile::tempdir().expect("tempdir");
1407 run_git(repo.path(), &["init", "--quiet", "--bare"]);
1408 assert!(resolve_git_common_dir_and_toplevel(repo.path()).is_err());
1409 assert!(resolve_git_common_dir(repo.path()).is_err());
1412 }
1413}