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
169#[must_use]
175pub fn git_path_line(stdout: &[u8]) -> Option<&str> {
176 let text = std::str::from_utf8(stdout).ok()?;
177 let text = text.strip_suffix('\n').unwrap_or(text);
178 Some(text.strip_suffix('\r').unwrap_or(text))
179}
180
181fn non_utf8_output(query: &str) -> ChangedFilesError {
182 ChangedFilesError::GitFailed(format!(
183 "git rev-parse {query} printed a path that is not UTF-8"
184 ))
185}
186
187pub fn resolve_git_toplevel(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
189 let output = spawn_output(&mut git_command(cwd, &["rev-parse", "--show-toplevel"]))
190 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
191
192 if !output.status.success() {
193 let stderr = String::from_utf8_lossy(&output.stderr);
194 return Err(if stderr.contains("not a git repository") {
195 ChangedFilesError::NotARepository
196 } else {
197 ChangedFilesError::GitFailed(stderr.trim().to_owned())
198 });
199 }
200
201 let trimmed =
202 git_path_line(&output.stdout).ok_or_else(|| non_utf8_output("--show-toplevel"))?;
203 if trimmed.is_empty() {
204 return Err(ChangedFilesError::GitFailed(
205 "git rev-parse --show-toplevel returned empty output".to_owned(),
206 ));
207 }
208
209 let path = PathBuf::from(trimmed);
210 Ok(dunce::canonicalize(&path).unwrap_or(path))
211}
212
213pub fn resolve_git_common_dir(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
215 let output = spawn_output(&mut git_command(
216 cwd,
217 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
218 ))
219 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
220
221 if !output.status.success() {
222 let stderr = String::from_utf8_lossy(&output.stderr);
223 return Err(if stderr.contains("not a git repository") {
224 ChangedFilesError::NotARepository
225 } else {
226 ChangedFilesError::GitFailed(stderr.trim().to_owned())
227 });
228 }
229
230 let trimmed =
231 git_path_line(&output.stdout).ok_or_else(|| non_utf8_output("--git-common-dir"))?;
232 if trimmed.is_empty() {
233 return Err(ChangedFilesError::GitFailed(
234 "git rev-parse --git-common-dir returned empty output".to_owned(),
235 ));
236 }
237
238 let path = PathBuf::from(trimmed);
239 Ok(dunce::canonicalize(&path).unwrap_or(path))
240}
241
242pub fn resolve_git_hooks_dir(cwd: &Path) -> Result<PathBuf, ChangedFilesError> {
255 let output = spawn_output(&mut git_command(cwd, &["rev-parse", "--git-path", "hooks"]))
256 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
257 if !output.status.success() {
258 let stderr = String::from_utf8_lossy(&output.stderr);
259 return Err(if stderr.contains("not a git repository") {
260 ChangedFilesError::NotARepository
261 } else {
262 ChangedFilesError::GitFailed(stderr.trim().to_owned())
263 });
264 }
265 let trimmed =
266 git_path_line(&output.stdout).ok_or_else(|| non_utf8_output("--git-path hooks"))?;
267 if trimmed.is_empty() || trimmed.lines().count() != 1 {
268 return Err(ChangedFilesError::GitFailed(format!(
269 "git rev-parse --git-path hooks printed {trimmed:?}"
270 )));
271 }
272 let base = dunce::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());
273 Ok(normalize_lexically(&base.join(trimmed)))
274}
275
276fn normalize_lexically(path: &Path) -> PathBuf {
279 use std::path::Component;
280 let mut out = PathBuf::new();
281 for component in path.components() {
282 match component {
283 Component::CurDir => {}
284 Component::ParentDir => {
285 out.pop();
286 }
287 other => out.push(other),
288 }
289 }
290 out
291}
292
293pub fn resolve_git_common_dir_and_toplevel(
307 cwd: &Path,
308) -> Result<(PathBuf, PathBuf), ChangedFilesError> {
309 let output = spawn_output(&mut git_command(
310 cwd,
311 &[
312 "rev-parse",
313 "--path-format=absolute",
314 "--git-common-dir",
315 "--show-toplevel",
316 ],
317 ))
318 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
319
320 if !output.status.success() {
321 let stderr = String::from_utf8_lossy(&output.stderr);
322 return Err(if stderr.contains("not a git repository") {
323 ChangedFilesError::NotARepository
324 } else {
325 ChangedFilesError::GitFailed(stderr.trim().to_owned())
326 });
327 }
328
329 let raw =
330 std::str::from_utf8(&output.stdout).map_err(|_| non_utf8_output("--show-toplevel"))?;
331 let raw = raw.strip_suffix('\n').unwrap_or(raw);
332 let mut lines = raw
333 .split('\n')
334 .map(|line| line.strip_suffix('\r').unwrap_or(line));
335 let (Some(common), Some(toplevel), None) = (lines.next(), lines.next(), lines.next()) else {
336 return Err(ChangedFilesError::GitFailed(
337 "git rev-parse did not print one common dir and one toplevel".to_owned(),
338 ));
339 };
340 let canonical = |line: &str| {
341 let path = PathBuf::from(line);
342 dunce::canonicalize(&path).unwrap_or(path)
343 };
344 if common.is_empty() || toplevel.is_empty() {
345 return Err(ChangedFilesError::GitFailed(
346 "git rev-parse returned an empty path".to_owned(),
347 ));
348 }
349 Ok((canonical(common), canonical(toplevel)))
350}
351
352fn try_get_changed_files(
354 root: &Path,
355 git_ref: &str,
356) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
357 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
358 let toplevel = resolve_git_toplevel(root)?;
359 try_get_changed_files_with_toplevel(root, &toplevel, git_ref)
360}
361
362pub fn changed_files(root: &Path, git_ref: &str) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
368 try_get_changed_files(root, git_ref)
369}
370
371pub(crate) struct ChangedFilesBatch<'a> {
375 cwd: &'a Path,
376 toplevel: PathBuf,
377 working_tree: Option<FxHashSet<PathBuf>>,
378}
379
380impl<'a> ChangedFilesBatch<'a> {
381 pub(crate) fn new(cwd: &'a Path, first_ref: &str) -> Result<Self, ChangedFilesError> {
382 validate_git_ref(first_ref).map_err(ChangedFilesError::InvalidRef)?;
383 Ok(Self {
384 cwd,
385 toplevel: resolve_git_toplevel(cwd)?,
386 working_tree: None,
387 })
388 }
389
390 pub(crate) fn changed_files(
391 &mut self,
392 git_ref: &str,
393 ) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
394 let mut files = committed_changed_files(self.cwd, &self.toplevel, git_ref)?;
395 if self.working_tree.is_none() {
396 self.working_tree = Some(working_tree_changed_files(self.cwd, &self.toplevel)?);
397 }
398 if let Some(working_tree) = &self.working_tree {
399 files.extend(working_tree.iter().cloned());
400 }
401 Ok(files)
402 }
403}
404
405pub fn try_get_changed_files_with_toplevel(
407 cwd: &Path,
408 toplevel: &Path,
409 git_ref: &str,
410) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
411 let mut files = committed_changed_files(cwd, toplevel, git_ref)?;
412 files.extend(working_tree_changed_files(cwd, toplevel)?);
413 Ok(files)
414}
415
416fn committed_changed_files(
417 cwd: &Path,
418 toplevel: &Path,
419 git_ref: &str,
420) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
421 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
422 collect_git_paths(
423 cwd,
424 toplevel,
425 &[
426 "diff",
427 "--name-only",
428 "-z",
429 "--end-of-options",
430 &format!("{git_ref}...HEAD"),
431 ],
432 )
433}
434
435fn working_tree_changed_files(
436 cwd: &Path,
437 toplevel: &Path,
438) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
439 let mut files = collect_git_paths(cwd, toplevel, &["diff", "--name-only", "-z", "HEAD"])?;
440 if untracked_files_excluded() {
441 return Ok(files);
442 }
443 files.extend(collect_git_paths(
444 cwd,
445 toplevel,
446 &[
447 "ls-files",
448 "--full-name",
449 "--others",
450 "--exclude-standard",
451 "-z",
452 ],
453 )?);
454 Ok(files)
455}
456
457#[derive(Debug, Clone, PartialEq, Eq)]
460pub struct RenamedFile {
461 pub from: PathBuf,
463 pub to: PathBuf,
465}
466
467pub fn try_get_renamed_files(
479 root: &Path,
480 git_ref: &str,
481) -> Result<Vec<RenamedFile>, ChangedFilesError> {
482 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
483 let toplevel = resolve_git_toplevel(root)?;
484 let mut renames = collect_git_rename_pairs(
485 root,
486 &toplevel,
487 &[
488 "diff",
489 "--name-status",
490 "-z",
491 "--find-renames",
492 "--end-of-options",
493 &format!("{git_ref}...HEAD"),
494 ],
495 )?;
496 let staged = collect_git_rename_pairs(
497 root,
498 &toplevel,
499 &["diff", "--name-status", "-z", "--find-renames", "HEAD"],
500 )?;
501 for pair in staged {
502 if let Some(chained) = renames.iter_mut().find(|rename| rename.to == pair.from) {
503 chained.to = pair.to;
504 } else {
505 renames.push(pair);
506 }
507 }
508 Ok(renames)
509}
510
511fn collect_git_rename_pairs(
517 cwd: &Path,
518 toplevel: &Path,
519 args: &[&str],
520) -> Result<Vec<RenamedFile>, ChangedFilesError> {
521 let output = spawn_output(&mut git_command(cwd, args))
522 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
523
524 if !output.status.success() {
525 return Err(changed_files_error_from_output(&output));
526 }
527
528 let mut fields = output
529 .stdout
530 .split(|byte| *byte == 0)
531 .filter(|field| !field.is_empty());
532 let mut renames = Vec::new();
533 while let Some(status) = fields.next() {
534 let Some(first_path) = fields.next() else {
535 break;
536 };
537 match status.first() {
538 Some(b'R') => {
539 let Some(second_path) = fields.next() else {
540 break;
541 };
542 renames.push(RenamedFile {
543 from: toplevel.join(git_path_from_bytes(first_path)),
544 to: toplevel.join(git_path_from_bytes(second_path)),
545 });
546 }
547 Some(b'C') => {
550 let _ = fields.next();
551 }
552 _ => {}
553 }
554 }
555 Ok(renames)
556}
557
558pub fn try_get_changed_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
563 changed_diff(root, git_ref, false)
564}
565
566pub fn try_get_mutation_diff(root: &Path, git_ref: &str) -> Result<String, ChangedFilesError> {
571 changed_diff(root, git_ref, true)
572}
573
574fn changed_diff(
575 root: &Path,
576 git_ref: &str,
577 detect_copies: bool,
578) -> Result<String, ChangedFilesError> {
579 validate_git_ref(git_ref).map_err(ChangedFilesError::InvalidRef)?;
580 let toplevel = resolve_git_toplevel(root)?;
581 let merge_base_output = spawn_output(&mut git_command(root, &["merge-base", git_ref, "HEAD"]))
582 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
583 if !merge_base_output.status.success() {
584 return Err(changed_files_error_from_output(&merge_base_output));
585 }
586 let merge_base = String::from_utf8_lossy(&merge_base_output.stdout)
587 .trim()
588 .to_owned();
589 if merge_base.is_empty() {
590 return Err(ChangedFilesError::GitFailed(
591 "git merge-base returned empty output".to_owned(),
592 ));
593 }
594
595 let mut args = vec!["diff", "--relative", "--unified=0"];
596 if detect_copies {
597 args.extend(["-M", "-C"]);
598 }
599 args.extend(["--end-of-options", &merge_base]);
600 let output = spawn_output(&mut git_command(root, &args))
601 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
602
603 if !output.status.success() {
604 return Err(changed_files_error_from_output(&output));
605 }
606
607 let mut diff = String::from_utf8_lossy(&output.stdout).into_owned();
608 append_untracked_diffs(root, &toplevel, &mut diff)?;
609 Ok(diff)
610}
611
612fn append_untracked_diffs(
613 root: &Path,
614 toplevel: &Path,
615 diff: &mut String,
616) -> Result<(), ChangedFilesError> {
617 if untracked_files_excluded() {
618 return Ok(());
619 }
620 let canonical_root = dunce::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
621 let mut untracked: Vec<PathBuf> = collect_git_paths(
622 root,
623 toplevel,
624 &[
625 "ls-files",
626 "--full-name",
627 "--others",
628 "--exclude-standard",
629 "-z",
630 ],
631 )?
632 .into_iter()
633 .filter_map(|path| {
634 path.strip_prefix(&canonical_root)
635 .ok()
636 .map(Path::to_path_buf)
637 })
638 .collect();
639 untracked.sort_unstable();
640
641 #[cfg(windows)]
642 let empty_file = "NUL";
643 #[cfg(not(windows))]
644 let empty_file = "/dev/null";
645
646 for path in untracked {
647 let mut command = git_command(root, &["diff", "--no-index", "--unified=0", "--"]);
648 command.arg(empty_file).arg(untracked_path_arg(&path));
649 let output =
650 spawn_output(&mut command).map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
651 if !output.status.success() && output.status.code() != Some(1) {
652 return Err(changed_files_error_from_output(&output));
653 }
654 if !diff.is_empty() && !diff.ends_with('\n') {
655 diff.push('\n');
656 }
657 diff.push_str(&String::from_utf8_lossy(&output.stdout));
658 }
659 Ok(())
660}
661
662fn untracked_path_arg(path: &Path) -> String {
667 path.to_string_lossy().replace('\\', "/")
668}
669
670fn changed_files_error_from_output(output: &Output) -> ChangedFilesError {
671 let stderr = String::from_utf8_lossy(&output.stderr);
672 if stderr.contains("not a git repository") {
673 ChangedFilesError::NotARepository
674 } else {
675 ChangedFilesError::GitFailed(stderr.trim().to_owned())
676 }
677}
678
679#[must_use]
681#[expect(
682 clippy::print_stderr,
683 reason = "intentional user-facing warning for the CLI's --changed-since fallback path; typed callers use try_get_changed_files instead"
684)]
685pub fn get_changed_files(root: &Path, git_ref: &str) -> Option<FxHashSet<PathBuf>> {
686 match try_get_changed_files(root, git_ref) {
687 Ok(files) => Some(files),
688 Err(err) => {
689 eprintln!("Warning: {}", err.changed_since_message(git_ref));
690 None
691 }
692 }
693}
694
695fn spawn_output(command: &mut Command) -> std::io::Result<Output> {
696 if let Some(hook) = SPAWN_HOOK.get() {
697 hook(command)
698 } else {
699 command.output()
700 }
701}
702
703fn collect_git_paths(
704 cwd: &Path,
705 toplevel: &Path,
706 args: &[&str],
707) -> Result<FxHashSet<PathBuf>, ChangedFilesError> {
708 let output = spawn_output(&mut git_command(cwd, args))
709 .map_err(|e| ChangedFilesError::GitMissing(e.to_string()))?;
710
711 if !output.status.success() {
712 let stderr = String::from_utf8_lossy(&output.stderr);
713 return Err(if stderr.contains("not a git repository") {
714 ChangedFilesError::NotARepository
715 } else {
716 ChangedFilesError::GitFailed(stderr.trim().to_owned())
717 });
718 }
719
720 let files = output
721 .stdout
722 .split(|byte| *byte == 0)
723 .filter(|path| !path.is_empty())
724 .map(git_path_from_bytes)
725 .map(|path| toplevel.join(path))
726 .collect();
727
728 Ok(files)
729}
730
731#[cfg(unix)]
737pub(crate) fn git_path_from_bytes(path: &[u8]) -> PathBuf {
738 use std::ffi::OsString;
739 use std::os::unix::ffi::OsStringExt;
740
741 PathBuf::from(OsString::from_vec(path.to_vec()))
742}
743
744#[cfg(windows)]
747pub(crate) fn git_path_from_bytes(path: &[u8]) -> PathBuf {
748 PathBuf::from(String::from_utf8_lossy(path).replace('/', "\\"))
749}
750
751fn git_command(cwd: &Path, args: &[&str]) -> Command {
752 let mut command = crate::git_env::git_command(cwd);
753 command.args(["-c", "diff.relative=false"]).args(args);
755 command
756}
757
758#[expect(
763 clippy::implicit_hasher,
764 reason = "fallow standardizes on FxHashSet across the workspace"
765)]
766pub fn filter_results_by_changed_files(
767 results: &mut AnalysisResults,
768 changed_files: &FxHashSet<PathBuf>,
769) {
770 filter_results_by_path_scope(results, &NormalizedChangedFiles::new(changed_files));
771}
772
773#[expect(
781 clippy::implicit_hasher,
782 reason = "fallow standardizes on FxHashSet across the workspace"
783)]
784pub fn filter_results_by_changed_files_keeping_unused_code(
785 results: &mut AnalysisResults,
786 changed_files: &FxHashSet<PathBuf>,
787) {
788 keeping_unused_code(results, |results| {
789 filter_results_by_changed_files(results, changed_files);
790 });
791}
792
793pub(crate) fn keeping_unused_code(
795 results: &mut AnalysisResults,
796 filter: impl FnOnce(&mut AnalysisResults),
797) {
798 let unused_files = std::mem::take(&mut results.unused_files);
799 let unused_exports = std::mem::take(&mut results.unused_exports);
800 filter(results);
801 results.unused_files = unused_files;
802 results.unused_exports = unused_exports;
803}
804
805pub(crate) trait ChangedPathScope {
808 fn contains(&self, path: &Path) -> bool;
809 fn contains_workspace(&self, path: &Path) -> bool {
810 self.contains(path)
811 }
812}
813
814#[derive(Debug, Clone, Default)]
816pub(crate) struct NormalizedChangedFiles(FxHashSet<PathBuf>);
817
818impl NormalizedChangedFiles {
819 pub(crate) fn new(changed_files: &FxHashSet<PathBuf>) -> Self {
820 Self(normalize_changed_files_set(changed_files))
821 }
822}
823
824impl ChangedPathScope for NormalizedChangedFiles {
825 fn contains(&self, path: &Path) -> bool {
826 contains_normalized(&self.0, path)
827 }
828
829 fn contains_workspace(&self, path: &Path) -> bool {
830 normalized_set_contains_path(&self.0, path)
831 }
832}
833
834struct ChangedPaths<'a, S: ChangedPathScope>(&'a S);
836
837impl<S: ChangedPathScope> ResultScope for ChangedPaths<'_, S> {
838 fn keeps(&self, anchor: Anchor<'_>) -> bool {
839 match anchor {
840 Anchor::Line { path, .. } | Anchor::File { path } => self.0.contains(path),
841 }
842 }
843
844 fn keeps_project_finding(&self, finding: ProjectFinding<'_>) -> bool {
845 match finding {
846 ProjectFinding::ManifestDependency { .. } | ProjectFinding::CatalogEntry => true,
847 ProjectFinding::EmptyCatalogGroup { path } => self.0.contains_workspace(path),
848 ProjectFinding::CatalogReference { path }
849 | ProjectFinding::DependencyOverride { path } => self.0.contains(path),
850 }
851 }
852
853 fn keeps_security_finding(&self, finding: &SecurityFinding) -> bool {
854 security_finding_touches_changed_path(finding, self.0)
855 }
856
857 fn site_rule(&self) -> SiteRule {
858 SiteRule::AnySite
859 }
860
861 fn owner_rule(&self) -> OwnerRule {
862 OwnerRule::TrimOwners
863 }
864
865 fn component_rule(&self) -> ComponentRule {
866 ComponentRule::All
867 }
868}
869
870pub(crate) fn filter_results_by_path_scope(
871 results: &mut AnalysisResults,
872 scope: &impl ChangedPathScope,
873) {
874 crate::result_scope::retain_in_scope(results, &ChangedPaths(scope));
875}
876
877fn security_finding_touches_changed_path(
878 finding: &SecurityFinding,
879 scope: &impl ChangedPathScope,
880) -> bool {
881 scope.contains(&finding.path)
882 || finding.trace.iter().any(|hop| scope.contains(&hop.path))
883 || finding.reachability.as_ref().is_some_and(|reachability| {
884 reachability
885 .untrusted_source_trace
886 .iter()
887 .any(|hop| scope.contains(&hop.path))
888 })
889}
890
891fn normalize_changed_files_set(changed_files: &FxHashSet<PathBuf>) -> FxHashSet<PathBuf> {
892 changed_files
893 .iter()
894 .map(|p| dunce::simplified(p).to_path_buf())
895 .collect()
896}
897
898fn contains_normalized(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
899 normalized.contains(dunce::simplified(path))
900}
901
902fn normalized_set_contains_path(normalized: &FxHashSet<PathBuf>, path: &Path) -> bool {
903 contains_normalized(normalized, path)
904 || (path.is_relative() && normalized.iter().any(|changed| changed.ends_with(path)))
905}
906
907#[expect(
909 clippy::implicit_hasher,
910 reason = "fallow standardizes on FxHashSet across the workspace"
911)]
912pub fn filter_duplication_by_changed_files(
913 report: &mut DuplicationReport,
914 changed_files: &FxHashSet<PathBuf>,
915 root: &Path,
916) {
917 filter_duplication_by_path_scope(report, &NormalizedChangedFiles::new(changed_files), root);
918}
919
920pub(crate) fn filter_duplication_by_path_scope(
921 report: &mut DuplicationReport,
922 scope: &impl ChangedPathScope,
923 root: &Path,
924) {
925 report.clone_groups.retain(|group| {
926 group
927 .instances
928 .iter()
929 .any(|instance| scope.contains(&instance.file))
930 });
931 report
932 .range_marker_problems
933 .retain(|finding| scope.contains(&finding.path));
934 duplicates::refresh_scoped_report(report, root);
935}
936
937#[cfg(test)]
938mod tests {
939 use super::*;
940 use fallow_types::{
941 duplicates::{CloneGroup, CloneInstance, DuplicationStats},
942 output_dead_code::{
943 EmptyCatalogGroupFinding, UnusedDependencyFinding, UnusedExportFinding,
944 UnusedFileFinding,
945 },
946 results::{
947 DependencyLocation, EmptyCatalogGroup, UnusedDependency, UnusedExport, UnusedFile,
948 },
949 };
950
951 #[test]
952 fn git_path_line_strips_only_the_line_end() {
953 assert_eq!(git_path_line(b"/work/web \n"), Some("/work/web "));
954 assert_eq!(git_path_line(b"/work/web\t\r\n"), Some("/work/web\t"));
955 assert_eq!(git_path_line(b" /work/web"), Some(" /work/web"));
956 assert_eq!(git_path_line(b"/work/web\n\n"), Some("/work/web\n"));
957 assert_eq!(git_path_line(b"/work/\xff\n"), None);
958 }
959
960 #[test]
963 fn every_changed_files_cause_reports_its_own_reason() {
964 let reasons = [
965 ChangedFilesError::InvalidRef("unclosed brace".to_owned()).reason(),
966 ChangedFilesError::GitMissing("no such file".to_owned()).reason(),
967 ChangedFilesError::NotARepository.reason(),
968 ChangedFilesError::GitFailed("unknown revision".to_owned()).reason(),
969 ];
970 assert_eq!(
971 reasons,
972 [
973 "invalid-ref",
974 "git-missing",
975 "not-a-repository",
976 "git-failed"
977 ]
978 );
979 let unique: std::collections::BTreeSet<&str> = reasons.iter().copied().collect();
980 assert_eq!(
981 unique.len(),
982 reasons.len(),
983 "two causes must not share a token"
984 );
985 }
986
987 #[test]
992 fn the_changed_since_message_names_the_ref_the_widening_and_the_next_step() {
993 let message = ChangedFilesError::NotARepository.changed_since_message("origin/main");
994 assert!(
995 message.contains("--changed-since 'origin/main'"),
996 "{message}"
997 );
998 assert!(message.contains("covers the whole project"), "{message}");
999 assert!(message.ends_with("or drop --changed-since."), "{message}");
1000 }
1001
1002 #[test]
1006 fn the_changed_since_message_folds_git_stderr_onto_one_line() {
1007 let message = ChangedFilesError::GitFailed(
1008 "fatal: ambiguous argument 'x'\nUse '--' to separate paths".to_owned(),
1009 )
1010 .changed_since_message("x");
1011 assert!(!message.contains('\n'), "{message}");
1012 assert!(
1013 message.contains("ambiguous argument 'x' Use '--'"),
1014 "{message}"
1015 );
1016 }
1017
1018 #[test]
1019 fn git_diff_sets_relative_paths_through_config() {
1020 let command = git_command(Path::new("."), &["diff", "--name-only"]);
1021 let args: Vec<_> = command.get_args().filter_map(|arg| arg.to_str()).collect();
1022 assert!(args.ends_with(&["-c", "diff.relative=false", "diff", "--name-only"]));
1023 assert!(!args.contains(&"--no-relative"));
1024 }
1025
1026 #[test]
1027 fn git_command_clears_parent_git_environment() {
1028 let command = git_command(Path::new("."), &["status"]);
1029 let envs: Vec<_> = command.get_envs().collect();
1030
1031 for var in AMBIENT_GIT_ENV_VARS {
1032 assert!(
1033 envs.iter()
1034 .any(|(key, value)| key.to_str() == Some(*var) && value.is_none()),
1035 "{var} should be cleared from the command env",
1036 );
1037 }
1038 }
1039
1040 #[test]
1041 fn try_get_changed_files_not_a_repository() {
1042 let temp = tempfile::tempdir().expect("tempdir");
1043 let result = try_get_changed_files(temp.path(), "main");
1044 assert!(matches!(result, Err(ChangedFilesError::NotARepository)));
1045 }
1046
1047 #[test]
1048 fn batched_refs_match_independent_changed_file_scopes() {
1049 let repo = tempfile::tempdir().expect("tempdir");
1050 for args in [
1051 &["init", "--quiet"][..],
1052 &["config", "user.email", "test@example.com"][..],
1053 &["config", "user.name", "Test User"][..],
1054 &["config", "commit.gpgsign", "false"][..],
1055 ] {
1056 run_git(repo.path(), args);
1057 }
1058 for name in ["committed.ts", "staged.ts", "unstaged.ts"] {
1059 std::fs::write(repo.path().join(name), "old\n").expect("initial file");
1060 }
1061 run_git(repo.path(), &["add", "."]);
1062 run_git(repo.path(), &["commit", "--quiet", "-m", "base"]);
1063 run_git(repo.path(), &["branch", "base"]);
1064
1065 std::fs::write(repo.path().join("committed.ts"), "new\n").expect("committed change");
1066 run_git(repo.path(), &["add", "committed.ts"]);
1067 run_git(repo.path(), &["commit", "--quiet", "-m", "change"]);
1068 std::fs::write(repo.path().join("staged.ts"), "new\n").expect("staged change");
1069 run_git(repo.path(), &["add", "staged.ts"]);
1070 std::fs::write(repo.path().join("unstaged.ts"), "new\n").expect("unstaged change");
1071 std::fs::write(repo.path().join("untracked.ts"), "new\n").expect("untracked file");
1072
1073 let mut batch = ChangedFilesBatch::new(repo.path(), "base").expect("batch");
1074 for reference in ["base", "HEAD"] {
1075 let batched = batch.changed_files(reference).expect("batched changes");
1076 let independent = changed_files(repo.path(), reference).expect("independent changes");
1077 assert_eq!(batched, independent, "{reference} scope changed");
1078 }
1079 }
1080
1081 #[test]
1082 fn relative_diff_config_preserves_repository_paths_from_a_subdirectory() {
1083 let repo = tempfile::tempdir().unwrap();
1084 let root = dunce::canonicalize(repo.path()).unwrap();
1085 let sub = root.join("sub");
1086 std::fs::create_dir(&sub).unwrap();
1087 run_git(&root, &["init", "--quiet"]);
1088 run_git(&root, &["config", "user.email", "test@example.com"]);
1089 run_git(&root, &["config", "user.name", "Test User"]);
1090 run_git(&root, &["config", "diff.relative", "true"]);
1091 std::fs::write(sub.join("a.ts"), "export const a = 1;").unwrap();
1092 run_git(&root, &["add", "."]);
1093 run_git(&root, &["commit", "-qm", "base"]);
1094 run_git(&root, &["branch", "base"]);
1095 run_git(&sub, &["mv", "a.ts", "b.ts"]);
1096 run_git(&root, &["commit", "-qm", "rename"]);
1097 run_git(&sub, &["mv", "b.ts", "c.ts"]);
1098
1099 let changed = changed_files(&sub, "base").unwrap();
1100 for name in ["b.ts", "c.ts"] {
1101 assert!(changed.contains(&sub.join(name)), "{changed:?}");
1102 }
1103 assert_eq!(
1104 try_get_renamed_files(&sub, "base").unwrap(),
1105 vec![RenamedFile {
1106 from: sub.join("a.ts"),
1107 to: sub.join("c.ts")
1108 }]
1109 );
1110 }
1111
1112 #[cfg(unix)]
1113 #[test]
1114 fn changed_files_preserve_special_filenames() {
1115 let repo = tempfile::tempdir().expect("tempdir");
1116 for args in [
1117 &["init", "--quiet"][..],
1118 &["config", "user.email", "test@example.com"][..],
1119 &["config", "user.name", "Test User"][..],
1120 &["config", "commit.gpgsign", "false"][..],
1121 &["config", "tag.gpgsign", "false"][..],
1122 ] {
1123 run_git(repo.path(), args);
1124 }
1125 std::fs::write(repo.path().join("initial.ts"), "initial\n").expect("initial fixture");
1126 run_git(repo.path(), &["add", "."]);
1127 run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
1128 run_git(repo.path(), &["tag", "base"]);
1129
1130 let canonical_root = repo.path().canonicalize().expect("canonical repo");
1131 let special_files = [
1132 "src/line\nbreak.ts",
1133 "src/space name.ts",
1134 "src/quote\"name.ts",
1135 "src/back\\slash.ts",
1136 "src/unicode-λ.ts",
1137 ]
1138 .map(|path| canonical_root.join(path));
1139 std::fs::create_dir_all(canonical_root.join("src")).expect("source dir");
1140 for special in &special_files {
1141 std::fs::write(special, "changed\n").expect("special fixture");
1142 }
1143
1144 let changed = try_get_changed_files(repo.path(), "base").expect("changed files");
1145 for special in special_files {
1146 assert!(
1147 changed.contains(&special),
1148 "missing {special:?}: {changed:?}"
1149 );
1150 }
1151 }
1152
1153 #[cfg(windows)]
1154 #[test]
1155 fn git_path_bytes_use_windows_separators() {
1156 assert_eq!(
1157 git_path_from_bytes(b"src/nested/file.ts"),
1158 PathBuf::from(r"src\nested\file.ts")
1159 );
1160 }
1161
1162 #[test]
1163 fn changed_diff_covers_staged_unstaged_and_untracked_files() {
1164 let repo = tempfile::tempdir().expect("tempdir");
1165 for args in [
1166 &["init", "--quiet"][..],
1167 &["config", "user.email", "test@example.com"][..],
1168 &["config", "user.name", "Test User"][..],
1169 &["config", "commit.gpgsign", "false"][..],
1170 &["config", "tag.gpgsign", "false"][..],
1171 ] {
1172 run_git(repo.path(), args);
1173 }
1174 std::fs::write(repo.path().join("staged.ts"), "old\n").expect("staged fixture");
1175 std::fs::write(repo.path().join("unstaged.ts"), "old\n").expect("unstaged fixture");
1176 run_git(repo.path(), &["add", "."]);
1177 run_git(repo.path(), &["commit", "--quiet", "-m", "initial"]);
1178 run_git(repo.path(), &["tag", "base"]);
1179
1180 std::fs::write(repo.path().join("committed.ts"), "committed\n").expect("committed fixture");
1181 run_git(repo.path(), &["add", "committed.ts"]);
1182 run_git(
1183 repo.path(),
1184 &["commit", "--quiet", "-m", "committed change"],
1185 );
1186
1187 std::fs::write(repo.path().join("staged.ts"), "staged\n").expect("staged edit");
1188 run_git(repo.path(), &["add", "staged.ts"]);
1189 std::fs::write(repo.path().join("unstaged.ts"), "unstaged\n").expect("unstaged edit");
1190 std::fs::write(repo.path().join("untracked.ts"), "untracked\n").expect("untracked edit");
1191
1192 for diff in [
1193 try_get_changed_diff(repo.path(), "base"),
1194 try_get_mutation_diff(repo.path(), "base"),
1195 ] {
1196 let diff = diff.expect("complete changeset diff");
1197 let index = fallow_output::DiffIndex::from_unified_diff(&diff);
1198
1199 assert!(diff.contains("b/committed.ts"), "{diff}");
1200 assert!(diff.contains("b/staged.ts"), "{diff}");
1201 assert!(diff.contains("b/unstaged.ts"), "{diff}");
1202 assert!(diff.contains("b/untracked.ts"), "{diff}");
1203 assert_eq!(index.hunk_count(), 4);
1204 assert_eq!(index.net_lines(), 2);
1205 }
1206 }
1207
1208 fn run_git(root: &Path, args: &[&str]) {
1209 let output = crate::git_fixture::fixture_git_command_with_identity(
1210 root,
1211 crate::git_fixture::FixtureIdentity::RepositoryConfig,
1212 )
1213 .args(args)
1214 .output()
1215 .expect("git command");
1216 assert!(
1217 output.status.success(),
1218 "git {args:?} failed: {}",
1219 String::from_utf8_lossy(&output.stderr)
1220 );
1221 }
1222
1223 #[test]
1224 fn untracked_path_arg_uses_forward_slashes() {
1225 assert_eq!(
1226 super::untracked_path_arg(Path::new("src\\nested\\b.ts")),
1227 "src/nested/b.ts"
1228 );
1229 assert_eq!(super::untracked_path_arg(Path::new("src/b.ts")), "src/b.ts");
1230 }
1231
1232 #[test]
1233 fn changed_files_error_describe_matches_core_contract() {
1234 assert_eq!(
1235 ChangedFilesError::InvalidRef("bad ref".to_string()).describe(),
1236 "invalid git ref: bad ref"
1237 );
1238 assert_eq!(
1239 ChangedFilesError::GitMissing("not found".to_string()).describe(),
1240 "failed to run git: not found"
1241 );
1242 assert_eq!(
1243 ChangedFilesError::NotARepository.describe(),
1244 "not a git repository"
1245 );
1246 assert!(
1247 ChangedFilesError::GitFailed("unknown revision main".to_string())
1248 .describe()
1249 .contains("fetch-depth: 0")
1250 );
1251 }
1252
1253 #[test]
1254 fn filter_results_keeps_only_changed_file_findings() {
1255 let mut results = AnalysisResults::default();
1256 results
1257 .unused_files
1258 .push(UnusedFileFinding::with_actions(UnusedFile {
1259 path: PathBuf::from("/repo/a.ts"),
1260 }));
1261 results
1262 .unused_files
1263 .push(UnusedFileFinding::with_actions(UnusedFile {
1264 path: PathBuf::from("/repo/b.ts"),
1265 }));
1266 results
1267 .unused_exports
1268 .push(UnusedExportFinding::with_actions(UnusedExport {
1269 path: PathBuf::from("/repo/a.ts"),
1270 export_name: "foo".to_owned(),
1271 is_type_only: false,
1272 line: 1,
1273 col: 0,
1274 span_start: 0,
1275 is_re_export: false,
1276 deprecated: false,
1277 deprecated_reason: None,
1278 }));
1279
1280 let mut changed = FxHashSet::default();
1281 changed.insert(PathBuf::from("/repo/a.ts"));
1282
1283 filter_results_by_changed_files(&mut results, &changed);
1284
1285 assert_eq!(results.unused_files.len(), 1);
1286 assert_eq!(
1287 results.unused_files[0].file.path,
1288 PathBuf::from("/repo/a.ts")
1289 );
1290 assert_eq!(results.unused_exports.len(), 1);
1291 }
1292
1293 #[test]
1294 fn filter_results_preserves_graph_global_dependency_findings() {
1295 let mut results = AnalysisResults::default();
1296 results
1297 .unused_dependencies
1298 .push(UnusedDependencyFinding::with_actions(UnusedDependency {
1299 package_name: "lodash".to_owned(),
1300 location: DependencyLocation::Dependencies,
1301 path: PathBuf::from("/repo/package.json"),
1302 line: 3,
1303 used_in_workspaces: Vec::new(),
1304 declared_and_imported_in: Vec::new(),
1305 }));
1306
1307 let changed = FxHashSet::default();
1308 filter_results_by_changed_files(&mut results, &changed);
1309
1310 assert_eq!(results.unused_dependencies.len(), 1);
1311 }
1312
1313 #[test]
1317 fn filter_results_keeps_deprecated_export_only_when_its_declaring_file_changed() {
1318 let finding = |path: &str| {
1319 fallow_types::output_dead_code::DeprecatedExportInUseFinding::with_actions(
1320 fallow_types::results::DeprecatedExportInUse {
1321 path: PathBuf::from(path),
1322 export_name: "old".to_owned(),
1323 is_type_only: false,
1324 line: 2,
1325 col: 0,
1326 span_start: 0,
1327 deprecated_reason: None,
1328 consumer_count: 1,
1329 consumers: vec![fallow_types::results::DeprecatedExportConsumer {
1330 path: PathBuf::from("/repo/consumer.ts"),
1331 line: 1,
1332 col: 0,
1333 kind: fallow_types::results::DeprecatedConsumerKind::NamedImport,
1334 }],
1335 public_api: false,
1336 },
1337 )
1338 };
1339 let mut results = AnalysisResults::default();
1340 results
1341 .deprecated_exports_in_use
1342 .push(finding("/repo/a.ts"));
1343 results
1344 .deprecated_exports_in_use
1345 .push(finding("/repo/b.ts"));
1346
1347 let mut changed = FxHashSet::default();
1348 changed.insert(PathBuf::from("/repo/a.ts"));
1349 changed.insert(PathBuf::from("/repo/consumer.ts"));
1350 filter_results_by_changed_files(&mut results, &changed);
1351
1352 let kept: Vec<_> = results
1353 .deprecated_exports_in_use
1354 .iter()
1355 .map(|f| f.export.path.clone())
1356 .collect();
1357 assert_eq!(kept, vec![PathBuf::from("/repo/a.ts")]);
1358 }
1359
1360 #[test]
1361 fn filter_results_keeps_relative_manifest_finding_when_manifest_changed() {
1362 let mut results = AnalysisResults::default();
1363 results
1364 .empty_catalog_groups
1365 .push(EmptyCatalogGroupFinding::with_actions(EmptyCatalogGroup {
1366 catalog_name: "legacy".to_owned(),
1367 path: PathBuf::from("pnpm-workspace.yaml"),
1368 line: 4,
1369 }));
1370
1371 let mut changed = FxHashSet::default();
1372 changed.insert(PathBuf::from("/repo/pnpm-workspace.yaml"));
1373
1374 filter_results_by_changed_files(&mut results, &changed);
1375
1376 assert_eq!(results.empty_catalog_groups.len(), 1);
1377 }
1378
1379 #[test]
1380 fn filter_duplication_keeps_groups_with_changed_instances_and_recomputes_stats() {
1381 let mut report = DuplicationReport {
1382 clone_groups: vec![
1383 CloneGroup {
1384 instances: vec![
1385 CloneInstance {
1386 is_symlink: false,
1387 file: PathBuf::from("/repo/a.ts"),
1388 start_line: 1,
1389 end_line: 5,
1390 start_col: 0,
1391 end_col: 10,
1392 fragment: "code".to_owned(),
1393 },
1394 CloneInstance {
1395 is_symlink: false,
1396 file: PathBuf::from("/repo/b.ts"),
1397 start_line: 1,
1398 end_line: 5,
1399 start_col: 0,
1400 end_col: 10,
1401 fragment: "code".to_owned(),
1402 },
1403 ],
1404 token_count: 20,
1405 line_count: 5,
1406 similarity: None,
1407 },
1408 CloneGroup {
1409 instances: vec![
1410 CloneInstance {
1411 is_symlink: false,
1412 file: PathBuf::from("/repo/c.ts"),
1413 start_line: 1,
1414 end_line: 5,
1415 start_col: 0,
1416 end_col: 10,
1417 fragment: "other".to_owned(),
1418 },
1419 CloneInstance {
1420 is_symlink: false,
1421 file: PathBuf::from("/repo/d.ts"),
1422 start_line: 1,
1423 end_line: 5,
1424 start_col: 0,
1425 end_col: 10,
1426 fragment: "other".to_owned(),
1427 },
1428 ],
1429 token_count: 20,
1430 line_count: 5,
1431 similarity: None,
1432 },
1433 ],
1434 clone_families: Vec::new(),
1435 mirrored_directories: Vec::new(),
1436 range_marker_problems: Vec::new(),
1437 stats: DuplicationStats {
1438 total_files: 4,
1439 files_with_clones: 4,
1440 total_lines: 100,
1441 duplicated_lines: 20,
1442 total_tokens: 200,
1443 duplicated_tokens: 80,
1444 clone_groups: 2,
1445 clone_families: 0,
1446 clone_instances: 4,
1447 duplication_percentage: 20.0,
1448 clone_groups_below_min_occurrences: 0,
1449 clone_groups_ignored: 0,
1450 near_candidates_skipped: 0,
1451 },
1452 };
1453
1454 let mut changed = FxHashSet::default();
1455 changed.insert(PathBuf::from("/repo/a.ts"));
1456
1457 filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1458
1459 assert_eq!(report.clone_groups.len(), 1);
1460 assert_eq!(report.stats.clone_groups, 1);
1461 assert_eq!(report.stats.clone_instances, 2);
1462 }
1463
1464 #[test]
1468 fn changed_file_scope_orders_families_by_file_set() {
1469 let group = |files: [&str; 2], line_count: usize| CloneGroup {
1470 instances: files
1471 .iter()
1472 .map(|file| CloneInstance {
1473 is_symlink: false,
1474 file: PathBuf::from(file),
1475 start_line: 1,
1476 end_line: line_count,
1477 start_col: 0,
1478 end_col: 10,
1479 fragment: String::new(),
1480 })
1481 .collect(),
1482 token_count: line_count * 10,
1483 line_count,
1484 similarity: None,
1485 };
1486 let mut report = DuplicationReport {
1487 clone_groups: vec![
1488 group(["/repo/y.ts", "/repo/z.ts"], 46),
1489 group(["/repo/a.ts", "/repo/b.ts"], 7),
1490 ],
1491 clone_families: Vec::new(),
1492 mirrored_directories: Vec::new(),
1493 range_marker_problems: Vec::new(),
1494 stats: DuplicationStats::default(),
1495 };
1496 let changed: FxHashSet<PathBuf> = ["/repo/a.ts", "/repo/y.ts"]
1497 .into_iter()
1498 .map(PathBuf::from)
1499 .collect();
1500
1501 filter_duplication_by_changed_files(&mut report, &changed, Path::new("/repo"));
1502
1503 let order: Vec<&PathBuf> = report
1504 .clone_families
1505 .iter()
1506 .map(|family| &family.files[0])
1507 .collect();
1508 assert_eq!(
1509 order,
1510 [&PathBuf::from("/repo/a.ts"), &PathBuf::from("/repo/y.ts")]
1511 );
1512 }
1513
1514 #[test]
1517 fn one_probe_resolves_the_common_dir_and_the_toplevel() {
1518 let repo = tempfile::tempdir().expect("tempdir");
1519 run_git(repo.path(), &["init", "--quiet"]);
1520 let nested = repo.path().join("packages/app");
1521 std::fs::create_dir_all(&nested).expect("nested dir");
1522 for cwd in [repo.path(), nested.as_path()] {
1523 let (common, toplevel) =
1524 resolve_git_common_dir_and_toplevel(cwd).expect("combined probe");
1525 assert_eq!(common, resolve_git_common_dir(cwd).expect("common dir"));
1526 assert_eq!(toplevel, resolve_git_toplevel(cwd).expect("toplevel"));
1527 }
1528 }
1529
1530 #[test]
1533 fn the_combined_probe_fails_without_a_work_tree() {
1534 let repo = tempfile::tempdir().expect("tempdir");
1535 run_git(repo.path(), &["init", "--quiet", "--bare"]);
1536 assert!(resolve_git_common_dir_and_toplevel(repo.path()).is_err());
1537 assert!(resolve_git_common_dir(repo.path()).is_err());
1540 }
1541}