Skip to main content

aft_base/
git_head.rs

1//! Where a checkout's Git `HEAD` lives and when it last changed, read from
2//! the `.git` directory or `gitdir:` marker without running Git.
3
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::time::SystemTime;
7
8#[derive(Clone, Debug, Eq, PartialEq)]
9pub struct GitHeadMetadata {
10    pub head_path: PathBuf,
11    pub head_mtime: Option<SystemTime>,
12    pub resolved_ref_path: Option<PathBuf>,
13    pub resolved_ref_mtime: Option<SystemTime>,
14}
15
16impl GitHeadMetadata {
17    pub fn matches_path(&self, path: &Path) -> bool {
18        same_file_path(path, &self.head_path)
19            || self
20                .resolved_ref_path
21                .as_deref()
22                .is_some_and(|resolved| same_file_path(path, resolved))
23    }
24
25    pub fn watch_paths(&self) -> impl Iterator<Item = &Path> {
26        std::iter::once(self.head_path.as_path()).chain(self.resolved_ref_path.as_deref())
27    }
28}
29
30/// Find the checkout's `HEAD` file (following a linked worktree's `gitdir:`
31/// marker) and the branch ref it names, with their modification times.
32pub fn capture_git_head_metadata(
33    repo_root: &Path,
34    git_common_dir: Option<&Path>,
35) -> std::io::Result<GitHeadMetadata> {
36    let dot_git = repo_root.join(".git");
37    let git_dir = if dot_git.is_dir() {
38        canonical_or_original(dot_git)
39    } else {
40        let marker = fs::read_to_string(&dot_git)
41            .map_err(|e| crate::io_accounting::at("reading Git directory marker", &dot_git, e))?;
42        let relative = marker
43            .trim()
44            .strip_prefix("gitdir:")
45            .map(str::trim)
46            .ok_or_else(|| {
47                std::io::Error::new(
48                    std::io::ErrorKind::InvalidData,
49                    format!("invalid gitdir marker at {}", dot_git.display()),
50                )
51            })?;
52        let path = PathBuf::from(relative);
53        canonical_or_original(if path.is_absolute() {
54            path
55        } else {
56            repo_root.join(path)
57        })
58    };
59    let head_path = canonical_or_original(git_dir.join("HEAD"));
60    let head = fs::read_to_string(&head_path)
61        .map_err(|e| crate::io_accounting::at("reading Git HEAD", &head_path, e))?;
62    let resolved_ref_path = head
63        .trim()
64        .strip_prefix("ref:")
65        .map(str::trim)
66        .filter(|reference| !reference.is_empty())
67        .map(|reference| canonical_or_original(git_common_dir.unwrap_or(&git_dir).join(reference)));
68    Ok(GitHeadMetadata {
69        head_mtime: modified_time(&head_path),
70        resolved_ref_mtime: resolved_ref_path.as_deref().and_then(modified_time),
71        head_path,
72        resolved_ref_path,
73    })
74}
75
76fn canonical_or_original(path: PathBuf) -> PathBuf {
77    fs::canonicalize(&path).unwrap_or(path)
78}
79
80fn modified_time(path: &Path) -> Option<SystemTime> {
81    fs::metadata(path)
82        .and_then(|metadata| metadata.modified())
83        .ok()
84}
85
86fn same_file_path(path: &Path, target: &Path) -> bool {
87    path == target
88        || fs::canonicalize(target)
89            .map(|target| path == target)
90            .unwrap_or(false)
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    #[test]
98    fn directory_head_error_names_operation_and_path() {
99        let root = tempfile::tempdir().unwrap();
100        let head = root.path().join(".git").join("HEAD");
101        fs::create_dir_all(&head).unwrap();
102        let error = capture_git_head_metadata(root.path(), None)
103            .unwrap_err()
104            .to_string();
105        assert!(error.contains("reading Git HEAD"), "{error}");
106        // Windows reports the root in its verbatim `\\?\` spelling, so accept
107        // the canonical form as well as the path the test built.
108        let canonical = fs::canonicalize(&head).unwrap();
109        assert!(
110            error.contains(&head.display().to_string())
111                || error.contains(&canonical.display().to_string()),
112            "{error}"
113        );
114        assert!(head.is_dir());
115    }
116}