1use std::ffi::{OsStr, OsString};
8use std::io::{self, Read};
9use std::path::{Path, PathBuf};
10use std::process::{Command, Output, Stdio};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum FailureKind {
14 NotRepository,
16 NoCommit,
18 Other,
20}
21
22#[derive(Debug)]
23pub enum ProbeError {
24 Spawn(io::Error),
25 Failed { kind: FailureKind, output: Output },
26}
27
28pub fn command() -> Command {
30 let mut builder = crate::effective_path::new_command("git");
31 builder
35 .env("LC_ALL", "C")
36 .env("LANG", "C")
37 .env("LANGUAGE", "C");
38 #[cfg(any(test, feature = "test-support"))]
39 TEST_CHILD_ENV.with(|overrides| {
40 for (key, value) in overrides.borrow().iter() {
41 builder.env(key, value);
42 }
43 });
44 builder.build()
45}
46
47pub fn supervised_output(command: &mut Command) -> io::Result<Output> {
50 let mut child = command
51 .stdin(Stdio::null())
52 .stdout(Stdio::piped())
53 .stderr(Stdio::piped())
54 .spawn()?;
55 let stdout = child.stdout.take().expect("piped stdout");
56 let stderr = child.stderr.take().expect("piped stderr");
57 let (closed, events) = std::sync::mpsc::channel();
58 let drain = |mut pipe: Box<dyn Read + Send>, closed: std::sync::mpsc::Sender<()>| {
59 std::thread::spawn(move || {
60 let mut bytes = Vec::new();
61 let result = pipe.read_to_end(&mut bytes).map(|_| bytes);
62 let _ = closed.send(());
63 result
64 })
65 };
66 let stdout = drain(Box::new(stdout), closed.clone());
67 let stderr = drain(Box::new(stderr), closed);
68 let mut pipes = 2;
69 let mut exit_poll = std::time::Duration::from_millis(1);
70 let status = loop {
71 if let Some(status) = child.try_wait()? {
72 break status;
73 }
74 crate::tool_progress::report();
77 let pause = std::time::Duration::from_millis(50);
78 if pipes > 0 {
79 match events.recv_timeout(pause) {
80 Ok(()) => pipes -= 1,
81 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => pipes = 0,
82 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
83 }
84 } else {
85 std::thread::sleep(exit_poll);
86 exit_poll = (exit_poll * 2).min(pause);
87 }
88 };
89 let joined = |thread: std::thread::JoinHandle<io::Result<Vec<u8>>>| {
90 thread
91 .join()
92 .map_err(|_| io::Error::other("Git output reader panicked"))?
93 };
94 Ok(Output {
95 status,
96 stdout: joined(stdout)?,
97 stderr: joined(stderr)?,
98 })
99}
100
101#[cfg(any(test, feature = "test-support"))]
104pub fn toplevel(root: &Path) -> Result<Vec<u8>, ProbeError> {
105 Probe::new(root, ChildDirectory::Inherited).run(&["rev-parse", "--show-toplevel"])
106}
107
108pub fn toplevel_in_directory(root: &Path) -> Result<Vec<u8>, ProbeError> {
112 Probe::new(root, ChildDirectory::Root).run(&["rev-parse", "--show-toplevel"])
113}
114
115pub(crate) fn repository_marker_or_uncertainty_in_directory(root: &Path) -> bool {
117 let probe = Probe::new(root, ChildDirectory::Root);
118 repository_marker_or_uncertainty(root, &DiscoveryLimits::from_command(&probe.command()))
119}
120
121pub fn probe_in_directory(root: &Path, args: &[&str]) -> Result<Vec<u8>, ProbeError> {
124 Probe::new(root, ChildDirectory::Root).run(args)
125}
126
127pub fn root_commits(root: &Path, spawned: &mut usize) -> Result<Vec<u8>, ProbeError> {
131 let mut probe = Probe::new(root, ChildDirectory::Inherited);
132 let result = probe.run(&["rev-list", "--max-parents=0", "HEAD"]);
133 *spawned += probe.spawned;
134 result
135}
136
137pub fn head_commit(root: &Path, spawned: &mut usize) -> Result<Vec<u8>, ProbeError> {
139 let mut probe = Probe::new(root, ChildDirectory::Inherited);
140 let result = probe.run(&["rev-parse", "--verify", "HEAD^{commit}"]);
141 *spawned += probe.spawned;
142 result
143}
144
145#[derive(Clone, Copy)]
149enum ChildDirectory {
150 Inherited,
152 Root,
154}
155
156struct Probe<'a> {
157 root: &'a Path,
158 directory: ChildDirectory,
159 spawned: usize,
160}
161
162impl<'a> Probe<'a> {
163 fn new(root: &'a Path, directory: ChildDirectory) -> Self {
164 Self {
165 root,
166 directory,
167 spawned: 0,
168 }
169 }
170
171 fn command(&self) -> Command {
172 let mut command = command();
173 match self.directory {
174 ChildDirectory::Inherited => {
175 command.arg("-C").arg(self.root);
176 }
177 ChildDirectory::Root => {
178 command.current_dir(self.root);
179 }
180 }
181 command
182 }
183
184 fn output<I, S>(&mut self, args: I) -> io::Result<Output>
185 where
186 I: IntoIterator<Item = S>,
187 S: AsRef<OsStr>,
188 {
189 if !crate::developer_tools::git_usable() {
192 return Err(io::Error::new(
193 io::ErrorKind::Unsupported,
194 crate::developer_tools::MISSING_DEVELOPER_TOOLS_REASON,
195 ));
196 }
197 let output = supervised_output(self.command().args(args))?;
198 self.spawned += 1;
199 Ok(output)
200 }
201
202 fn run(&mut self, args: &[&str]) -> Result<Vec<u8>, ProbeError> {
203 let output = self.output(args).map_err(ProbeError::Spawn)?;
204 if output.status.success() {
205 return Ok(output.stdout);
206 }
207 let limits = DiscoveryLimits::from_command(&self.command());
210 let root = self.root;
211 classify_failure(root, &limits, args, output, || self.unborn_head())
212 }
213}
214
215struct DiscoveryLimits {
217 ceilings: Vec<PathBuf>,
219 one_filesystem: bool,
221}
222
223impl DiscoveryLimits {
224 fn from_command(command: &Command) -> Self {
225 Self {
226 ceilings: ceiling_directories(
227 child_environment_value(command, "GIT_CEILING_DIRECTORIES").as_deref(),
228 ),
229 one_filesystem: !child_environment_value(command, "GIT_DISCOVERY_ACROSS_FILESYSTEM")
230 .as_deref()
231 .is_some_and(git_env_bool),
232 }
233 }
234}
235
236fn child_environment_value(command: &Command, key: &str) -> Option<OsString> {
239 for (name, value) in command.get_envs() {
240 if name == OsStr::new(key) {
241 return value.map(OsStr::to_os_string);
242 }
243 }
244 std::env::var_os(key)
245}
246
247fn git_env_bool(value: &OsStr) -> bool {
250 let value = value.to_string_lossy().to_ascii_lowercase();
251 match value.as_str() {
252 "true" | "yes" | "on" => true,
253 "false" | "no" | "off" | "" => false,
254 number => number.parse::<i64>().map_or(true, |number| number != 0),
255 }
256}
257
258fn ceiling_directories(value: Option<&OsStr>) -> Vec<PathBuf> {
263 let Some(value) = value else {
264 return Vec::new();
265 };
266 let mut resolve = true;
267 let mut ceilings = Vec::new();
268 for entry in std::env::split_paths(value) {
269 if entry.as_os_str().is_empty() {
270 resolve = false;
271 continue;
272 }
273 if !entry.is_absolute() {
274 continue;
275 }
276 let ceiling = if resolve {
277 match std::fs::canonicalize(&entry) {
278 Ok(resolved) => comparable(resolved),
279 Err(_) => continue,
280 }
281 } else {
282 comparable(crate::path_identity::lexical_normalize(&entry))
283 };
284 ceilings.push(ceiling);
285 }
286 ceilings
287}
288
289fn comparable(path: PathBuf) -> PathBuf {
291 #[cfg(windows)]
292 {
293 crate::windows_path::normalize_windows_path(&path)
294 }
295 #[cfg(not(windows))]
296 {
297 path
298 }
299}
300
301fn classify_failure(
302 root: &Path,
303 limits: &DiscoveryLimits,
304 args: &[&str],
305 output: Output,
306 verify_unborn: impl FnOnce() -> bool,
307) -> Result<Vec<u8>, ProbeError> {
308 let stderr = String::from_utf8_lossy(&output.stderr);
309 let ordinary_fatal_exit = output.status.code() == Some(128);
312 let absence = stderr
313 .starts_with("fatal: not a git repository (or any of the parent directories):")
314 || stderr.starts_with("fatal: not a git repository (or any parent up to mount point");
315 let kind = if ordinary_fatal_exit && absence && !repository_marker_or_uncertainty(root, limits)
316 {
317 FailureKind::NotRepository
318 } else if ordinary_fatal_exit
319 && args == ["rev-list", "--max-parents=0", "HEAD"]
320 && (stderr.starts_with("fatal: ambiguous argument 'HEAD':")
321 || stderr.starts_with("fatal: bad revision 'HEAD'"))
322 && verify_unborn()
323 {
324 FailureKind::NoCommit
325 } else {
326 FailureKind::Other
327 };
328 Err(ProbeError::Failed { kind, output })
329}
330
331fn repository_marker_or_uncertainty(root: &Path, limits: &DiscoveryLimits) -> bool {
341 let start = comparable(std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()));
342 let ceiling = limits
345 .ceilings
346 .iter()
347 .filter(|ceiling| start != **ceiling && start.starts_with(ceiling))
348 .max_by_key(|ceiling| ceiling.components().count());
349 let start_device = if limits.one_filesystem {
350 match device_of(&start) {
351 Ok(device) => device,
352 Err(_) => return true,
353 }
354 } else {
355 None
356 };
357 for directory in start.ancestors() {
358 if directory != start {
359 if ceiling
360 .is_some_and(|ceiling| directory == ceiling || !directory.starts_with(ceiling))
361 {
362 break;
363 }
364 if let Some(start_device) = start_device {
365 match device_of(directory) {
366 Ok(Some(device)) if device != start_device => break,
367 Ok(_) => {}
368 Err(_) => return true,
369 }
370 }
371 }
372 if git_marker_is_repository_candidate(&directory.join(".git")) {
373 return true;
374 }
375 if directory.join("HEAD").exists()
377 && directory.join("objects").exists()
378 && directory.join("refs").exists()
379 {
380 return true;
381 }
382 }
383 false
384}
385
386fn device_of(path: &Path) -> io::Result<Option<u64>> {
389 #[cfg(any(test, feature = "test-support"))]
390 if let Some(device) = TEST_DEVICE_OF.with(|hook| hook.borrow().as_ref().map(|hook| hook(path)))
391 {
392 return Ok(device);
393 }
394 #[cfg(unix)]
395 {
396 use std::os::unix::fs::MetadataExt;
397 std::fs::metadata(path).map(|metadata| Some(metadata.dev()))
398 }
399 #[cfg(not(unix))]
400 {
401 let _ = path;
402 Ok(None)
403 }
404}
405
406fn git_marker_is_repository_candidate(marker: &Path) -> bool {
414 let absent = |error: &io::Error| {
415 matches!(
416 error.kind(),
417 io::ErrorKind::NotFound | io::ErrorKind::NotADirectory
418 )
419 };
420 match std::fs::metadata(marker) {
421 Ok(metadata) if metadata.is_dir() => match std::fs::symlink_metadata(marker.join("HEAD")) {
422 Ok(_) => true,
423 Err(error) => !absent(&error),
424 },
425 Ok(_) => true,
426 Err(error) => !absent(&error),
427 }
428}
429
430impl Probe<'_> {
431 fn unborn_head(&mut self) -> bool {
432 let Ok(repository) = self.output(["rev-parse", "--git-dir"]) else {
437 return false;
438 };
439 if !repository.status.success() {
440 return false;
441 }
442 let missing_head = self
443 .output(["rev-parse", "--verify", "--quiet", "HEAD"])
444 .is_ok_and(|output| output.status.code() == Some(1) && output.stderr.is_empty());
445 if !missing_head {
446 return false;
447 }
448 let Ok(symbolic) = self.output(["symbolic-ref", "--quiet", "HEAD"]) else {
449 return false;
450 };
451 if !symbolic.status.success() || !symbolic.stderr.is_empty() {
452 return false;
453 }
454 let Some(reference) = git_output_path(&symbolic.stdout) else {
455 return false;
456 };
457 let Some(loose) = self.git_path(reference.as_os_str()) else {
458 return false;
459 };
460 let Some(packed) = self.git_path(OsStr::new("packed-refs")) else {
461 return false;
462 };
463 #[cfg(any(test, feature = "test-support"))]
464 BEFORE_LOOSE_REF_CHECK.with(|slot| {
465 if let Some(hook) = slot.borrow_mut().take() {
466 hook(&loose);
467 }
468 });
469 if !matches!(std::fs::symlink_metadata(loose), Err(error) if error.kind() == io::ErrorKind::NotFound)
473 {
474 return false;
475 }
476 match std::fs::File::open(packed) {
477 Ok(_) => true,
478 Err(error) => error.kind() == io::ErrorKind::NotFound,
479 }
480 }
481
482 fn git_path(&mut self, name: &OsStr) -> Option<PathBuf> {
483 let output = self
484 .output([OsStr::new("rev-parse"), OsStr::new("--git-path"), name])
485 .ok()?;
486 if !output.status.success() || !output.stderr.is_empty() {
487 return None;
488 }
489 let path = git_output_path(&output.stdout)?;
490 Some(if path.is_absolute() {
491 path
492 } else {
493 self.root.join(path)
494 })
495 }
496}
497
498#[cfg(any(test, feature = "test-support"))]
501pub fn init_repository_with_corrupt_head_for_test(path: &Path) {
502 assert!(command()
503 .args(["init", "--quiet"])
504 .arg(path)
505 .status()
506 .unwrap()
507 .success());
508 std::fs::write(path.join(".git").join("HEAD"), "not a ref\n").unwrap();
509}
510
511#[cfg(any(test, feature = "test-support"))]
519pub struct NestedWorktreeFixture {
520 pub root: PathBuf,
521 pub worktree: PathBuf,
522 pub independent: PathBuf,
523 pub submodule: PathBuf,
524}
525
526#[cfg(any(test, feature = "test-support"))]
529pub fn init_repo_with_nested_worktree_for_test(root: &Path, marker: &str) -> NestedWorktreeFixture {
530 assert!(
531 crate::developer_tools::git_usable(),
532 "nested-worktree fixtures need git"
533 );
534 let root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
535 let git = |dir: &Path, args: &[&str]| {
536 let output = command()
537 .args([
538 "-c",
539 "user.name=AFT Tests",
540 "-c",
541 "user.email=aft-tests@example.com",
542 "-c",
543 "commit.gpgsign=false",
544 ])
545 .args(args)
546 .current_dir(dir)
547 .env("GIT_CONFIG_GLOBAL", "/dev/null")
548 .env("GIT_CONFIG_SYSTEM", "/dev/null")
549 .env("GIT_CONFIG_COUNT", "0")
550 .output()
551 .expect("git runs");
552 assert!(output.status.success(), "git {args:?}: {output:?}");
553 };
554 let source = format!("pub fn probe_marker() {{ let _ = \"{marker}\"; }}\n");
555 for relative in ["src/main.rs", "lib/util.rs"] {
556 let path = root.join(relative);
557 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
558 std::fs::write(path, &source).unwrap();
559 }
560 git(&root, &["init", "--quiet"]);
561 git(&root, &["add", "."]);
562 git(&root, &["commit", "--quiet", "-m", "initial"]);
563 git(&root, &["worktree", "add", "--quiet", "linked"]);
567 let worktree = root.join("linked");
568 std::fs::write(worktree.join("extra.rs"), &source).unwrap();
569 let independent = root.join("vendor").join("independent");
571 std::fs::create_dir_all(&independent).unwrap();
572 git(&independent, &["init", "--quiet"]);
573 std::fs::write(independent.join("inner.rs"), &source).unwrap();
574 let submodule = root.join("submod");
577 std::fs::create_dir_all(&submodule).unwrap();
578 std::fs::create_dir_all(root.join(".git").join("modules").join("submod")).unwrap();
579 std::fs::write(submodule.join(".git"), "gitdir: ../.git/modules/submod\n").unwrap();
580 std::fs::write(submodule.join("code.rs"), &source).unwrap();
581 NestedWorktreeFixture {
582 root,
583 worktree,
584 independent,
585 submodule,
586 }
587}
588
589#[cfg(any(test, feature = "test-support"))]
592pub fn write_stub_git_directory_for_test(path: &Path) {
593 let info = path.join(".git").join("info");
594 std::fs::create_dir_all(&info).unwrap();
595 std::fs::write(info.join("exclude"), "ignored/\n").unwrap();
596}
597
598#[cfg(any(test, feature = "test-support"))]
599type BeforeLooseRefCheck = Box<dyn FnOnce(&Path)>;
600#[cfg(any(test, feature = "test-support"))]
601type DeviceOf = Box<dyn Fn(&Path) -> Option<u64>>;
602#[cfg(any(test, feature = "test-support"))]
603thread_local! {
604 static BEFORE_LOOSE_REF_CHECK: std::cell::RefCell<Option<BeforeLooseRefCheck>> = const { std::cell::RefCell::new(None) };
606 static TEST_CHILD_ENV: std::cell::RefCell<Vec<(OsString, OsString)>> = const { std::cell::RefCell::new(Vec::new()) };
608 static TEST_DEVICE_OF: std::cell::RefCell<Option<DeviceOf>> = const { std::cell::RefCell::new(None) };
610}
611
612#[cfg(all(any(test, feature = "test-support"), unix))]
614pub fn write_stub_git_for_test(directory: &Path, output: &str) {
615 std::fs::create_dir_all(directory).unwrap();
616 let stub = directory.join("git");
617 crate::executable_cache::write_executable(
618 &stub,
619 format!("#!/bin/sh\nprintf '%s\\n' '{output}'\n").as_bytes(),
620 )
621 .unwrap();
622}
623
624#[cfg(all(any(test, feature = "test-support"), unix))]
628pub fn relative_bin_path_for_test() -> OsString {
629 let mut entries = vec![PathBuf::from("bin")];
630 entries.extend(std::env::split_paths(
631 crate::effective_path::effective_path(),
632 ));
633 std::env::join_paths(entries).unwrap()
634}
635
636#[cfg(any(test, feature = "test-support"))]
639pub fn with_child_env_for_test<R>(overrides: &[(&str, &OsStr)], body: impl FnOnce() -> R) -> R {
640 struct Reset;
641 impl Drop for Reset {
642 fn drop(&mut self) {
643 TEST_CHILD_ENV.with(|env| env.borrow_mut().clear());
644 }
645 }
646 TEST_CHILD_ENV.with(|env| {
647 *env.borrow_mut() = overrides
648 .iter()
649 .map(|(key, value)| (OsString::from(key), value.to_os_string()))
650 .collect();
651 });
652 let _reset = Reset;
653 body()
654}
655
656fn git_output_path(bytes: &[u8]) -> Option<PathBuf> {
658 let bytes = bytes.strip_suffix(b"\n").unwrap_or(bytes);
659 let bytes = bytes.strip_suffix(b"\r").unwrap_or(bytes);
660 if bytes.is_empty() {
661 return None;
662 }
663 #[cfg(unix)]
664 {
665 use std::os::unix::ffi::OsStringExt;
666 Some(PathBuf::from(std::ffi::OsString::from_vec(bytes.to_vec())))
667 }
668 #[cfg(not(unix))]
669 {
670 std::str::from_utf8(bytes).ok().map(PathBuf::from)
671 }
672}
673
674#[cfg(test)]
675mod tests {
676 #[cfg(unix)]
677 #[test]
678 fn call_keepalive_git_probe_supervises_quiet_child_without_changing_output() {
679 use std::sync::atomic::{AtomicU64, Ordering};
680 use std::sync::Arc;
681 use std::time::{Duration, Instant};
682 let dir = tempfile::tempdir().unwrap();
683 struct Release(PathBuf);
684 impl Drop for Release {
685 fn drop(&mut self) {
686 let _ = std::fs::write(&self.0, "");
687 }
688 }
689 let release = Release(dir.path().join("release"));
690 let clock = Arc::new(AtomicU64::new(0));
691 let (tx, pushes) = std::sync::mpsc::channel();
692 let origin = Instant::now();
693 let token = crate::executor::JobCancellation::new();
694 token.set_progress(crate::tool_progress::Progress::with_clock(
695 {
696 let clock = clock.clone();
697 move || origin + Duration::from_millis(clock.load(Ordering::SeqCst))
698 },
699 move |_| tx.send(()).is_ok(),
700 ));
701 let root = dir.path().to_owned();
702 let work = std::thread::spawn(move || {
703 let _token = crate::executor::install_job_cancellation(token);
704 supervised_output(Command::new("sh").current_dir(root).args([
705 "-c",
706 &format!(
707 "{}; printf out; printf err >&2; exit 7",
708 crate::test_gate::gate("release", "sleep 0.02")
709 ),
710 ]))
711 });
712 for at in [30_000, 60_000, 90_000, 120_000] {
713 clock.store(at, Ordering::SeqCst);
714 pushes
715 .recv_timeout(Duration::from_secs(5))
716 .expect("quiet Git child is supervised");
717 }
718 drop(release);
719 let result = work.join().unwrap().unwrap();
720 assert_eq!(result.status.code(), Some(7));
721 assert_eq!(result.stdout, b"out");
722 assert_eq!(result.stderr, b"err");
723 }
724
725 use super::*;
726
727 fn failure_kind(result: Result<Vec<u8>, ProbeError>) -> FailureKind {
728 match result.unwrap_err() {
729 ProbeError::Failed { kind, .. } => kind,
730 ProbeError::Spawn(error) => panic!("Git must be runnable for probe fixtures: {error}"),
731 }
732 }
733
734 #[cfg(unix)]
735 fn unlimited() -> DiscoveryLimits {
736 DiscoveryLimits {
737 ceilings: Vec::new(),
738 one_filesystem: false,
739 }
740 }
741
742 fn init_repository(path: &Path) {
743 assert!(command()
744 .args(["init", "--quiet"])
745 .arg(path)
746 .status()
747 .unwrap()
748 .success());
749 }
750
751 #[test]
752 fn machine_git_command_pins_its_diagnostic_locale() {
753 let command = command();
754 let env = command
755 .get_envs()
756 .collect::<std::collections::HashMap<_, _>>();
757 for key in ["LC_ALL", "LANG", "LANGUAGE"] {
758 assert_eq!(
759 env.get(std::ffi::OsStr::new(key)).copied().flatten(),
760 Some(std::ffi::OsStr::new("C")),
761 "Git diagnostic locale override missing: {key}"
762 );
763 }
764 }
765
766 #[test]
767 fn corrupt_git_metadata_is_not_repository_absence() {
768 let dir = tempfile::tempdir().unwrap();
769 crate::git_probe::init_repository_with_corrupt_head_for_test(dir.path());
770 assert_eq!(failure_kind(toplevel(dir.path())), FailureKind::Other);
771 assert_eq!(
772 failure_kind(root_commits(dir.path(), &mut 0)),
773 FailureKind::Other
774 );
775 }
776
777 #[test]
780 fn stub_git_directory_without_head_is_repository_absence() {
781 let dir = tempfile::tempdir().unwrap();
782 write_stub_git_directory_for_test(dir.path());
783 assert_eq!(
784 failure_kind(toplevel(dir.path())),
785 FailureKind::NotRepository
786 );
787 assert_eq!(
788 failure_kind(root_commits(dir.path(), &mut 0)),
789 FailureKind::NotRepository
790 );
791 }
792
793 #[test]
794 fn broken_head_reference_is_not_an_unborn_repository() {
795 let dir = tempfile::tempdir().unwrap();
796 init_repository(dir.path());
797 let head = std::fs::read_to_string(dir.path().join(".git/HEAD")).unwrap();
798 let reference = head.trim().strip_prefix("ref: ").unwrap();
799 std::fs::write(
800 dir.path().join(".git").join(reference),
801 "not an object id\n",
802 )
803 .unwrap();
804 assert_eq!(
805 failure_kind(root_commits(dir.path(), &mut 0)),
806 FailureKind::Other
807 );
808 }
809
810 #[test]
811 fn ref_appearing_after_head_verification_is_not_unborn() {
812 let dir = tempfile::tempdir().unwrap();
813 init_repository(dir.path());
814 let reached = std::rc::Rc::new(std::cell::Cell::new(false));
815 let observed = reached.clone();
816 BEFORE_LOOSE_REF_CHECK.with(|slot| {
817 *slot.borrow_mut() = Some(Box::new(move |reference| {
818 std::fs::write(reference, "not an object id\n").unwrap();
819 observed.set(true);
820 }));
821 });
822 assert_eq!(
823 failure_kind(root_commits(dir.path(), &mut 0)),
824 FailureKind::Other
825 );
826 assert!(
827 reached.get(),
828 "real Git missing-HEAD verification must reach the filesystem check"
829 );
830 }
831
832 #[test]
833 fn empty_directory_is_repository_absence_but_unborn_repo_has_no_commit() {
834 let dir = tempfile::tempdir().unwrap();
835 assert_eq!(
836 failure_kind(toplevel(dir.path())),
837 FailureKind::NotRepository
838 );
839 init_repository(dir.path());
840 assert!(toplevel(dir.path()).is_ok());
841 assert_eq!(
842 failure_kind(root_commits(dir.path(), &mut 0)),
843 FailureKind::NoCommit
844 );
845 }
846
847 #[cfg(unix)]
848 #[test]
849 fn ambiguous_head_diagnostic_requires_verified_unborn_repository() {
850 use std::os::unix::process::ExitStatusExt;
851 let dir = tempfile::tempdir().unwrap();
852 let output = Output {
853 status: std::process::ExitStatus::from_raw(128 << 8),
854 stdout: Vec::new(),
855 stderr: b"fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.\n".to_vec(),
856 };
857 assert_eq!(
858 failure_kind(classify_failure(
859 dir.path(),
860 &unlimited(),
861 &["rev-list", "--max-parents=0", "HEAD"],
862 output,
863 || false,
864 )),
865 FailureKind::Other
866 );
867 }
868
869 #[cfg(unix)]
870 #[test]
871 fn signalled_probe_is_not_absence_even_with_absence_diagnostic() {
872 use std::os::unix::process::ExitStatusExt;
873 let dir = tempfile::tempdir().unwrap();
874 let output = Output {
875 status: std::process::ExitStatus::from_raw(9),
877 stdout: Vec::new(),
878 stderr: b"fatal: not a git repository (or any of the parent directories): .git\n"
879 .to_vec(),
880 };
881 assert_eq!(
882 failure_kind(classify_failure(
883 dir.path(),
884 &unlimited(),
885 &[],
886 output,
887 || false
888 )),
889 FailureKind::Other
890 );
891 }
892
893 fn commit_empty(path: &Path) {
894 assert!(command()
895 .arg("-C")
896 .arg(path)
897 .args([
898 "-c",
899 "user.name=AFT Tests",
900 "-c",
901 "user.email=aft-tests@example.invalid",
902 "commit",
903 "--quiet",
904 "--allow-empty",
905 "-m",
906 "root",
907 ])
908 .status()
909 .unwrap()
910 .success());
911 }
912
913 #[test]
917 fn parent_repository_above_a_ceiling_is_not_searched() {
918 let parent = tempfile::tempdir().unwrap();
919 init_repository(parent.path());
920 let child = parent.path().join("work");
921 std::fs::create_dir(&child).unwrap();
922 let ceiling = parent.path().as_os_str().to_os_string();
923 with_child_env_for_test(&[("GIT_CEILING_DIRECTORIES", &ceiling)], || {
924 assert_eq!(failure_kind(toplevel(&child)), FailureKind::NotRepository);
925 assert_eq!(
926 failure_kind(root_commits(&child, &mut 0)),
927 FailureKind::NotRepository
928 );
929 });
930 }
931
932 #[cfg(unix)]
935 #[test]
936 fn parent_repository_on_another_device_is_not_searched() {
937 use std::os::unix::process::ExitStatusExt;
938 let parent = tempfile::tempdir().unwrap();
939 init_repository(parent.path());
940 let child = parent.path().join("mount");
941 std::fs::create_dir(&child).unwrap();
942 let mounted = std::fs::canonicalize(&child).unwrap();
943 TEST_DEVICE_OF.with(|hook| {
944 *hook.borrow_mut() = Some(Box::new(move |path: &Path| {
945 Some(if path == mounted { 2 } else { 1 })
946 }));
947 });
948 let absence = || Output {
949 status: std::process::ExitStatus::from_raw(128 << 8),
950 stdout: Vec::new(),
951 stderr: b"fatal: not a git repository (or any parent up to mount point /)\n".to_vec(),
952 };
953 let one_filesystem = DiscoveryLimits {
954 ceilings: Vec::new(),
955 one_filesystem: true,
956 };
957 let kind_on_one_filesystem = failure_kind(classify_failure(
958 &child,
959 &one_filesystem,
960 &[],
961 absence(),
962 || false,
963 ));
964 let kind_across = failure_kind(classify_failure(
965 &child,
966 &unlimited(),
967 &[],
968 absence(),
969 || false,
970 ));
971 TEST_DEVICE_OF.with(|hook| *hook.borrow_mut() = None);
972 assert_eq!(kind_on_one_filesystem, FailureKind::NotRepository);
973 assert_eq!(kind_across, FailureKind::Other);
974 }
975
976 #[test]
978 fn discovery_limits_follow_the_child_environment() {
979 for (value, one_filesystem) in [("0", true), ("false", true), ("true", false), ("1", false)]
980 {
981 let limits = with_child_env_for_test(
982 &[("GIT_DISCOVERY_ACROSS_FILESYSTEM", OsStr::new(value))],
983 || DiscoveryLimits::from_command(&command()),
984 );
985 assert_eq!(limits.one_filesystem, one_filesystem, "{value}");
986 }
987 }
988
989 #[cfg(unix)]
992 #[test]
993 fn ceiling_entries_follow_git_parsing_rules() {
994 let dir = tempfile::tempdir().unwrap();
995 let base = std::fs::canonicalize(dir.path()).unwrap();
996 std::fs::create_dir(base.join("real")).unwrap();
997 std::os::unix::fs::symlink(base.join("real"), base.join("link")).unwrap();
998 let link = base.join("link");
999 let value = std::env::join_paths([
1000 PathBuf::from("relative"),
1001 link.clone(),
1002 base.join("missing"),
1003 PathBuf::new(),
1004 link.clone(),
1005 ])
1006 .unwrap();
1007 assert_eq!(
1008 ceiling_directories(Some(&value)),
1009 vec![base.join("real"), link]
1010 );
1011 }
1012
1013 #[test]
1016 fn root_commit_probe_counts_every_spawned_git_process() {
1017 let dir = tempfile::tempdir().unwrap();
1018 init_repository(dir.path());
1019 let mut unborn = 0;
1020 assert_eq!(
1021 failure_kind(root_commits(dir.path(), &mut unborn)),
1022 FailureKind::NoCommit
1023 );
1024 assert_eq!(unborn, 6);
1025 commit_empty(dir.path());
1026 let mut committed = 0;
1027 assert!(root_commits(dir.path(), &mut committed).is_ok());
1028 assert_eq!(committed, 1);
1029 }
1030}