| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Raw access to git repositories through gitoxide. |
| 5 | //! |
| 6 | //! Objects are read and written as raw bytes: no filters, no line-ending |
| 7 | //! conversion, no LFS. Replacement objects (`refs/replace/`) are ignored and |
| 8 | //! grafts are never read, so every object is exactly what its id names. Only |
| 9 | //! the repository's own configuration is read; the user's, the system's and |
| 10 | //! the environment's are not. |
| 11 | |
| 12 | use std::path::Path; |
| 13 | |
| 14 | use gix::bstr::{BStr, ByteSlice}; |
| 15 | use gix::objs::{Exists, Find, FindHeader, Write}; |
| 16 | |
| 17 | use crate::error::{Error, ShowBytes}; |
| 18 | use crate::oid::{GitKind, GitOid}; |
| 19 | |
| 20 | /// Memory for the cache of decoded pack deltas, per open repository. |
| 21 | const PACK_CACHE_BYTES: usize = 64 * 1024 * 1024; |
| 22 | |
| 23 | /// The same, for each extra handle that a thread of a parallel import reads |
| 24 | /// through. |
| 25 | const WORKER_PACK_CACHE_BYTES: usize = 16 * 1024 * 1024; |
| 26 | |
| 27 | /// Whether `name` can be the name of a git branch: `refs/heads/<name>` |
| 28 | /// follows git's rules for ref names (no `..`, no `:`, `?`, `*`, `[`, `\`, |
| 29 | /// `^`, `~`, space or control character, no component that starts with `.` |
| 30 | /// or ends with `.lock`, and so on), and is not `refs/heads/HEAD`. |
| 31 | pub fn is_branch_name(name: &str) -> bool { |
| 32 | let full = format!("refs/heads/{name}"); |
| 33 | gix::validate::reference::branch_name(full.as_bytes().as_bstr()).is_ok() |
| 34 | } |
| 35 | |
| 36 | /// The id of the empty tree. |
| 37 | const EMPTY_TREE: GitOid = GitOid::from_bytes([ |
| 38 | 0x4b, 0x82, 0x5d, 0xc6, 0x42, 0xcb, 0x6e, 0xb9, 0xa0, 0x60, 0xe5, 0x4b, 0xf8, 0xd6, 0x92, 0x88, |
| 39 | 0xfb, 0xee, 0x49, 0x04, |
| 40 | ]); |
| 41 | |
| 42 | /// An open git repository. |
| 43 | pub(crate) struct GitRepo { |
| 44 | repo: gix::Repository, |
| 45 | } |
| 46 | |
| 47 | impl GitRepo { |
| 48 | /// Opens the repository at `path`, its work tree or its git directory. |
| 49 | /// SHA-256 repositories are refused. |
| 50 | pub(crate) fn open(path: &Path) -> Result<Self, Error> { |
| 51 | let mut repo = gix::open_opts(path, gix::open::Options::isolated()).map_err(|err| { |
| 52 | Error::git( |
| 53 | format!("cannot open a git repository at {}", path.display()), |
| 54 | err, |
| 55 | ) |
| 56 | })?; |
| 57 | if repo.object_hash() != gix::hash::Kind::Sha1 { |
| 58 | return Err(Error::Sha256); |
| 59 | } |
| 60 | repo.objects.ignore_replacements = true; |
| 61 | repo.objects.set_pack_cache(|| { |
| 62 | Box::new(gix::odb::pack::cache::lru::MemoryCappedHashmap::new( |
| 63 | PACK_CACHE_BYTES, |
| 64 | )) |
| 65 | }); |
| 66 | Ok(Self { repo }) |
| 67 | } |
| 68 | |
| 69 | /// Another handle on the same repository, for another thread: it reads |
| 70 | /// the same objects the same way (replacements ignored), with a smaller |
| 71 | /// cache of its own. |
| 72 | pub(crate) fn worker_handle(&self) -> Self { |
| 73 | let mut repo = self.repo.clone(); |
| 74 | repo.objects.ignore_replacements = true; |
| 75 | repo.objects.set_pack_cache(|| { |
| 76 | Box::new(gix::odb::pack::cache::lru::MemoryCappedHashmap::new( |
| 77 | WORKER_PACK_CACHE_BYTES, |
| 78 | )) |
| 79 | }); |
| 80 | Self { repo } |
| 81 | } |
| 82 | |
| 83 | /// Creates an empty bare repository at `path` and opens it. |
| 84 | pub(crate) fn init_bare(path: &Path) -> Result<Self, Error> { |
| 85 | gix::init_bare(path).map_err(|err| { |
| 86 | Error::git( |
| 87 | format!("cannot create a bare repository at {}", path.display()), |
| 88 | err, |
| 89 | ) |
| 90 | })?; |
| 91 | Self::open(path) |
| 92 | } |
| 93 | |
| 94 | /// Whether the repository is a shallow clone. |
| 95 | pub(crate) fn is_shallow(&self) -> Result<bool, Error> { |
| 96 | self.repo |
| 97 | .is_shallow() |
| 98 | .map_err(|err| Error::git("cannot tell whether the repository is shallow", err)) |
| 99 | } |
| 100 | |
| 101 | /// Reads an object and checks that its bytes hash to its id. |
| 102 | /// |
| 103 | /// The empty tree reads as itself even when it is not stored: git treats |
| 104 | /// it as always present, and does not store it when a commit uses it. |
| 105 | pub(crate) fn read(&self, oid: &GitOid) -> Result<(GitKind, Vec<u8>), Error> { |
| 106 | let mut buf = Vec::new(); |
| 107 | let found = self |
| 108 | .repo |
| 109 | .objects |
| 110 | .try_find(&oid.to_gix(), &mut buf) |
| 111 | .map_err(|err| Error::git(format!("cannot read git object {oid}"), err))?; |
| 112 | let (kind, bytes) = match found { |
| 113 | Some(data) => (GitKind::from_gix(data.kind), data.data.to_vec()), |
| 114 | None if *oid == EMPTY_TREE => (GitKind::Tree, Vec::new()), |
| 115 | None => return Err(Error::MissingObject(*oid)), |
| 116 | }; |
| 117 | if GitOid::for_object(kind, &bytes)? != *oid { |
| 118 | return Err(Error::CorruptObject(*oid)); |
| 119 | } |
| 120 | Ok((kind, bytes)) |
| 121 | } |
| 122 | |
| 123 | /// Reads an object that must be of `expected` kind. |
| 124 | pub(crate) fn read_kind(&self, oid: &GitOid, expected: GitKind) -> Result<Vec<u8>, Error> { |
| 125 | let (found, bytes) = self.read(oid)?; |
| 126 | if found != expected { |
| 127 | return Err(Error::WrongKind { |
| 128 | oid: *oid, |
| 129 | expected, |
| 130 | found, |
| 131 | }); |
| 132 | } |
| 133 | Ok(bytes) |
| 134 | } |
| 135 | |
| 136 | /// The kind of an object, from its header alone. |
| 137 | pub(crate) fn kind(&self, oid: &GitOid) -> Result<GitKind, Error> { |
| 138 | let header = self |
| 139 | .repo |
| 140 | .objects |
| 141 | .try_header(&oid.to_gix()) |
| 142 | .map_err(|err| Error::git(format!("cannot read git object {oid}"), err))?; |
| 143 | match header { |
| 144 | Some(header) => Ok(GitKind::from_gix(header.kind)), |
| 145 | None if *oid == EMPTY_TREE => Ok(GitKind::Tree), |
| 146 | None => Err(Error::MissingObject(*oid)), |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | /// Whether the object is stored in the repository. Unlike git, this does |
| 151 | /// not count the empty tree as always present, so that a copy gets it. |
| 152 | pub(crate) fn contains(&self, oid: &GitOid) -> bool { |
| 153 | self.repo.objects.exists(&oid.to_gix()) |
| 154 | } |
| 155 | |
| 156 | /// Writes an object and returns the id gitoxide computed for it. |
| 157 | pub(crate) fn write(&self, kind: GitKind, bytes: &[u8]) -> Result<GitOid, Error> { |
| 158 | let id = self |
| 159 | .repo |
| 160 | .objects |
| 161 | .write_buf(kind.to_gix(), bytes) |
| 162 | .map_err(|err| Error::git(format!("cannot write a git {kind}"), err))?; |
| 163 | GitOid::from_gix(&id).ok_or(Error::Sha256) |
| 164 | } |
| 165 | |
| 166 | /// The refs to import, sorted by name, each with the object it points to |
| 167 | /// after following symbolic refs (an annotated tag stays a tag). |
| 168 | /// |
| 169 | /// With no `names`, every branch (`refs/heads/`) and tag (`refs/tags/`). |
| 170 | /// Otherwise the named refs, which must exist; a short name is looked up |
| 171 | /// the way git does, and reported under its full name. |
| 172 | pub(crate) fn refs(&self, names: &[Vec<u8>]) -> Result<Vec<(Vec<u8>, GitOid)>, Error> { |
| 173 | let mut found = Vec::new(); |
| 174 | let mut add = |reference: &mut gix::Reference<'_>| -> Result<(), Error> { |
| 175 | let name = reference.name().as_bstr().to_vec(); |
| 176 | let id = reference.follow_to_object().map_err(|err| { |
| 177 | Error::git(format!("cannot resolve ref {}", ShowBytes(&name)), err) |
| 178 | })?; |
| 179 | found.push((name, GitOid::from_gix(&id).ok_or(Error::Sha256)?)); |
| 180 | Ok(()) |
| 181 | }; |
| 182 | if names.is_empty() { |
| 183 | let platform = self |
| 184 | .repo |
| 185 | .references() |
| 186 | .map_err(|err| Error::git("cannot list refs", err))?; |
| 187 | let branches = platform |
| 188 | .local_branches() |
| 189 | .map_err(|err| Error::git("cannot list branches", err))?; |
| 190 | let tags = platform |
| 191 | .tags() |
| 192 | .map_err(|err| Error::git("cannot list tags", err))?; |
| 193 | for reference in branches.chain(tags) { |
| 194 | let mut reference = |
| 195 | reference.map_err(|err| Error::git("cannot read a ref", err))?; |
| 196 | add(&mut reference)?; |
| 197 | } |
| 198 | } else { |
| 199 | for name in names { |
| 200 | let mut reference = self |
| 201 | .repo |
| 202 | .try_find_reference(BStr::new(name.as_slice())) |
| 203 | .map_err(|err| Error::git(format!("cannot read ref {}", ShowBytes(name)), err))? |
| 204 | .ok_or_else(|| Error::MissingRef(name.clone()))?; |
| 205 | add(&mut reference)?; |
| 206 | } |
| 207 | } |
| 208 | found.sort(); |
| 209 | found.dedup(); |
| 210 | Ok(found) |
| 211 | } |
| 212 | |
| 213 | /// The object a ref points to, after following symbolic refs. |
| 214 | pub(crate) fn resolve_ref(&self, name: &[u8]) -> Result<Option<GitOid>, Error> { |
| 215 | let Some(mut reference) = self |
| 216 | .repo |
| 217 | .try_find_reference(BStr::new(name)) |
| 218 | .map_err(|err| Error::git(format!("cannot read ref {}", ShowBytes(name)), err))? |
| 219 | else { |
| 220 | return Ok(None); |
| 221 | }; |
| 222 | let id = reference |
| 223 | .follow_to_object() |
| 224 | .map_err(|err| Error::git(format!("cannot resolve ref {}", ShowBytes(name)), err))?; |
| 225 | Ok(Some(GitOid::from_gix(&id).ok_or(Error::Sha256)?)) |
| 226 | } |
| 227 | |
| 228 | /// Points each ref at its object in one transaction, whatever it pointed |
| 229 | /// to before. Reflogs, where the repository keeps them, name the |
| 230 | /// configured committer, or a generic one when there is none. |
| 231 | pub(crate) fn set_refs( |
| 232 | &mut self, |
| 233 | refs: &[(Vec<u8>, GitOid)], |
| 234 | message: &str, |
| 235 | ) -> Result<(), Error> { |
| 236 | use gix::refs::transaction::{Change, LogChange, PreviousValue, RefEdit, RefLog}; |
| 237 | |
| 238 | let mut edits = Vec::with_capacity(refs.len()); |
| 239 | for (name, oid) in refs { |
| 240 | let full_name = gix::refs::FullName::try_from(name.as_bstr()) |
| 241 | .map_err(|err| Error::git(format!("invalid ref name {}", ShowBytes(name)), err))?; |
| 242 | edits.push(RefEdit { |
| 243 | change: Change::Update { |
| 244 | log: LogChange { |
| 245 | mode: RefLog::AndReference, |
| 246 | force_create_reflog: false, |
| 247 | message: message.into(), |
| 248 | }, |
| 249 | expected: PreviousValue::Any, |
| 250 | new: gix::refs::Target::Object(oid.to_gix()), |
| 251 | }, |
| 252 | name: full_name, |
| 253 | deref: false, |
| 254 | }); |
| 255 | } |
| 256 | self.repo |
| 257 | .committer_or_set_generic_fallback() |
| 258 | .map_err(|err| Error::git("cannot set up a reflog identity", err))?; |
| 259 | self.repo |
| 260 | .edit_references(edits) |
| 261 | .map_err(|err| Error::git("cannot update refs", err))?; |
| 262 | Ok(()) |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | #[cfg(test)] |
| 267 | mod tests { |
| 268 | use super::*; |
| 269 | |
| 270 | #[test] |
| 271 | fn branch_names() { |
| 272 | for good in ["main", "feature/x", "v1.0", "a-b_c", "caf\u{e9}"] { |
| 273 | assert!(is_branch_name(good), "{good}"); |
| 274 | } |
| 275 | for bad in [ |
| 276 | "", "a b", "a:b", "a..b", "a*", "a?", "a[b", "a\\b", "a^", "a~1", "/a", "a/", "a//b", |
| 277 | ".a", "a/.b", "a.lock", "a.", "a@{1}", "HEAD", "a\nb", "a\0b", |
| 278 | ] { |
| 279 | assert!(!is_branch_name(bad), "{bad:?}"); |
| 280 | } |
| 281 | } |
| 282 | } |