| 1 | /// Whether one path component names the repository metadata directory as the |
| 2 | /// filesystem resolves it, not just as spelled: `.git` in any letter case |
| 3 | /// (macOS and Windows default to case-insensitive names) and, on Windows, |
| 4 | /// with the trailing dots/spaces or `:stream` suffix it drops and the `GIT~N` |
| 5 | /// short-name alias. The one `.git` rule for workspace file routes, file |
| 6 | /// restore, displayed workspace paths, the write carve-out and sub-agent |
| 7 | /// deliverables. |
| 8 | pub fn is_git_metadata_name(name: &std::ffi::OsStr) -> bool { |
| 9 | git_metadata_name(&name.to_string_lossy(), cfg!(windows)) |
| 10 | } |
| 11 | |
| 12 | pub fn git_metadata_name(name: &str, windows: bool) -> bool { |
| 13 | let name = if windows { |
| 14 | name.split(':') |
| 15 | .next() |
| 16 | .unwrap_or_default() |
| 17 | .trim_end_matches(['.', ' ']) |
| 18 | } else { |
| 19 | name |
| 20 | }; |
| 21 | name.eq_ignore_ascii_case(".git") |
| 22 | || (windows |
| 23 | && name.len() > 4 |
| 24 | && name |
| 25 | .get(..4) |
| 26 | .is_some_and(|prefix| prefix.eq_ignore_ascii_case("git~")) |
| 27 | && name[4..].bytes().all(|byte| byte.is_ascii_digit())) |
| 28 | } |
| 29 | |
| 30 | use std::path::Path; |
| 31 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 32 | |
| 33 | const MAX_GITDIR_POINTER_BYTES: u64 = 64 * 1024; |
| 34 | const MAX_HEAD_OR_CONFIG_BYTES: u64 = 1024 * 1024; |
| 35 | const ABBREVIATED_ID_LEN: usize = 7; |
| 36 | |
| 37 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 38 | pub struct GitHead { |
| 39 | pub branch: Option<String>, |
| 40 | pub id: Option<String>, |
| 41 | } |
| 42 | |
| 43 | impl GitHead { |
| 44 | pub fn short_id(&self) -> Option<&str> { |
| 45 | self.id |
| 46 | .as_deref() |
| 47 | .map(|id| id.get(..ABBREVIATED_ID_LEN).unwrap_or(id)) |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | #[derive(Debug, thiserror::Error)] |
| 52 | pub enum GitReadError { |
| 53 | #[error("not inside a git repository")] |
| 54 | NotRepository, |
| 55 | #[error("unsupported git repository: {0}")] |
| 56 | Unsupported(String), |
| 57 | #[error("corrupt git repository: {0}")] |
| 58 | Corrupt(String), |
| 59 | #[error("git read cancelled")] |
| 60 | Cancelled, |
| 61 | } |
| 62 | |
| 63 | pub fn read_head(workspace: &Path, cancel: &AtomicBool) -> Result<GitHead, GitReadError> { |
| 64 | check_cancelled(cancel)?; |
| 65 | precheck_metadata_sizes(workspace)?; |
| 66 | let options = gix::open::Options::isolated() |
| 67 | .bail_if_untrusted(true) |
| 68 | .strict_config(true) |
| 69 | .config_overrides(["core.useReplaceRefs=false", "core.fsmonitor=false"]); |
| 70 | let repository = match gix::discover_opts(workspace, Default::default(), options) { |
| 71 | Ok(repository) => repository, |
| 72 | Err(error) => { |
| 73 | return Err( |
| 74 | match error.downcast_any_ref::<gix::discover::upwards::Error>() { |
| 75 | Some( |
| 76 | gix::discover::upwards::Error::NoGitRepository { .. } |
| 77 | | gix::discover::upwards::Error::NoGitRepositoryWithinCeiling { .. } |
| 78 | | gix::discover::upwards::Error::NoGitRepositoryWithinFs { .. }, |
| 79 | ) => GitReadError::NotRepository, |
| 80 | _ => GitReadError::Unsupported(error.to_string()), |
| 81 | }, |
| 82 | ); |
| 83 | } |
| 84 | }; |
| 85 | if repository.workdir().is_none() { |
| 86 | return Err(GitReadError::NotRepository); |
| 87 | } |
| 88 | check_cancelled(cancel)?; |
| 89 | let head = repository |
| 90 | .head() |
| 91 | .map_err(|error| GitReadError::Corrupt(error.to_string()))?; |
| 92 | let branch = match head.referent_name() { |
| 93 | Some(name) => Some( |
| 94 | name.as_bstr() |
| 95 | .strip_prefix(b"refs/heads/") |
| 96 | .and_then(|branch| std::str::from_utf8(branch).ok()) |
| 97 | .map(str::to_owned) |
| 98 | .ok_or_else(|| { |
| 99 | GitReadError::Corrupt("HEAD does not name a local branch".to_string()) |
| 100 | })?, |
| 101 | ), |
| 102 | None => None, |
| 103 | }; |
| 104 | let id = head.id().map(|id| id.to_string()); |
| 105 | check_cancelled(cancel)?; |
| 106 | Ok(GitHead { branch, id }) |
| 107 | } |
| 108 | |
| 109 | fn check_cancelled(cancel: &AtomicBool) -> Result<(), GitReadError> { |
| 110 | if cancel.load(Ordering::Relaxed) { |
| 111 | Err(GitReadError::Cancelled) |
| 112 | } else { |
| 113 | Ok(()) |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | fn precheck_metadata_sizes(workspace: &Path) -> Result<(), GitReadError> { |
| 118 | for directory in workspace.ancestors() { |
| 119 | let marker = directory.join(".git"); |
| 120 | let Ok(metadata) = std::fs::metadata(&marker) else { |
| 121 | continue; |
| 122 | }; |
| 123 | if metadata.is_file() { |
| 124 | if metadata.len() > MAX_GITDIR_POINTER_BYTES { |
| 125 | return Err(GitReadError::Unsupported( |
| 126 | ".git pointer file is too large".to_string(), |
| 127 | )); |
| 128 | } |
| 129 | } else if metadata.is_dir() { |
| 130 | for name in ["HEAD", "config"] { |
| 131 | if let Ok(metadata) = std::fs::metadata(marker.join(name)) |
| 132 | && (!metadata.is_file() || metadata.len() > MAX_HEAD_OR_CONFIG_BYTES) |
| 133 | { |
| 134 | return Err(GitReadError::Unsupported(format!( |
| 135 | ".git/{name} is not a regular file within the size bound" |
| 136 | ))); |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | return Ok(()); |
| 141 | } |
| 142 | Ok(()) |
| 143 | } |
| 144 |