| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Git object ids and kinds. |
| 5 | |
| 6 | use core::fmt; |
| 7 | use core::str::FromStr; |
| 8 | |
| 9 | use braid_format::GitId; |
| 10 | |
| 11 | use crate::error::Error; |
| 12 | |
| 13 | /// The four kinds of git object. |
| 14 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 15 | pub enum GitKind { |
| 16 | /// A commit. |
| 17 | Commit, |
| 18 | /// A directory listing. |
| 19 | Tree, |
| 20 | /// File content, or the target of a symlink. |
| 21 | Blob, |
| 22 | /// An annotated tag. |
| 23 | Tag, |
| 24 | } |
| 25 | |
| 26 | impl GitKind { |
| 27 | /// The name git writes in object headers: `commit`, `tree`, `blob` or `tag`. |
| 28 | pub const fn name(self) -> &'static str { |
| 29 | match self { |
| 30 | GitKind::Commit => "commit", |
| 31 | GitKind::Tree => "tree", |
| 32 | GitKind::Blob => "blob", |
| 33 | GitKind::Tag => "tag", |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | /// The code used in serialized maps. |
| 38 | pub(crate) const fn code(self) -> u8 { |
| 39 | match self { |
| 40 | GitKind::Commit => 1, |
| 41 | GitKind::Tree => 2, |
| 42 | GitKind::Blob => 3, |
| 43 | GitKind::Tag => 4, |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | /// The kind with this map code. |
| 48 | pub(crate) const fn from_code(code: u8) -> Option<Self> { |
| 49 | match code { |
| 50 | 1 => Some(GitKind::Commit), |
| 51 | 2 => Some(GitKind::Tree), |
| 52 | 3 => Some(GitKind::Blob), |
| 53 | 4 => Some(GitKind::Tag), |
| 54 | _ => None, |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | pub(crate) fn to_gix(self) -> gix::objs::Kind { |
| 59 | match self { |
| 60 | GitKind::Commit => gix::objs::Kind::Commit, |
| 61 | GitKind::Tree => gix::objs::Kind::Tree, |
| 62 | GitKind::Blob => gix::objs::Kind::Blob, |
| 63 | GitKind::Tag => gix::objs::Kind::Tag, |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | pub(crate) fn from_gix(kind: gix::objs::Kind) -> Self { |
| 68 | match kind { |
| 69 | gix::objs::Kind::Commit => GitKind::Commit, |
| 70 | gix::objs::Kind::Tree => GitKind::Tree, |
| 71 | gix::objs::Kind::Blob => GitKind::Blob, |
| 72 | gix::objs::Kind::Tag => GitKind::Tag, |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | impl fmt::Display for GitKind { |
| 78 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 79 | f.write_str(self.name()) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// A git object id: the SHA-1 of the object's header and content. Its text |
| 84 | /// form is 40 lowercase hex digits. |
| 85 | #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 86 | pub struct GitOid([u8; 20]); |
| 87 | |
| 88 | impl GitOid { |
| 89 | /// Length of an id in bytes. |
| 90 | pub const LEN: usize = 20; |
| 91 | |
| 92 | /// Wraps raw id bytes. |
| 93 | pub const fn from_bytes(bytes: [u8; 20]) -> Self { |
| 94 | Self(bytes) |
| 95 | } |
| 96 | |
| 97 | /// The raw id bytes. |
| 98 | pub const fn as_bytes(&self) -> &[u8; 20] { |
| 99 | &self.0 |
| 100 | } |
| 101 | |
| 102 | /// The full text form: 40 lowercase hex digits. |
| 103 | pub fn to_hex(&self) -> String { |
| 104 | self.to_string() |
| 105 | } |
| 106 | |
| 107 | /// The id git gives an object of `kind` holding `data`. |
| 108 | /// |
| 109 | /// The hash runs with SHA-1 collision detection, as git's does: data that |
| 110 | /// carries a known collision attack gets an error instead of an id. |
| 111 | pub fn for_object(kind: GitKind, data: &[u8]) -> Result<Self, Error> { |
| 112 | let id = gix::objs::compute_hash(gix::hash::Kind::Sha1, kind.to_gix(), data) |
| 113 | .map_err(|_| Error::Collision { kind })?; |
| 114 | Ok(Self::from_gix(&id).expect("a SHA-1 hash has 20 bytes")) |
| 115 | } |
| 116 | |
| 117 | /// The id, if `id` is a SHA-1 id. |
| 118 | pub(crate) fn from_gix(id: &gix::oid) -> Option<Self> { |
| 119 | <[u8; 20]>::try_from(id.as_bytes()).ok().map(Self) |
| 120 | } |
| 121 | |
| 122 | pub(crate) fn to_gix(self) -> gix::ObjectId { |
| 123 | gix::ObjectId::Sha1(self.0) |
| 124 | } |
| 125 | |
| 126 | /// Parses 40 hex digits of either case, as found inside git objects. |
| 127 | pub(crate) fn parse_hex(digits: &[u8]) -> Option<Self> { |
| 128 | if digits.len() != 40 { |
| 129 | return None; |
| 130 | } |
| 131 | let mut bytes = [0u8; 20]; |
| 132 | for (byte, pair) in bytes.iter_mut().zip(digits.as_chunks::<2>().0) { |
| 133 | *byte = (hex_value(pair[0])? << 4) | hex_value(pair[1])?; |
| 134 | } |
| 135 | Some(Self(bytes)) |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | fn hex_value(digit: u8) -> Option<u8> { |
| 140 | match digit { |
| 141 | b'0'..=b'9' => Some(digit - b'0'), |
| 142 | b'a'..=b'f' => Some(digit - b'a' + 10), |
| 143 | b'A'..=b'F' => Some(digit - b'A' + 10), |
| 144 | _ => None, |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | const HEX_DIGITS: &[u8; 16] = b"0123456789abcdef"; |
| 149 | |
| 150 | impl fmt::Display for GitOid { |
| 151 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 152 | let mut text = [0u8; 40]; |
| 153 | for (i, byte) in self.0.iter().enumerate() { |
| 154 | text[2 * i] = HEX_DIGITS[usize::from(byte >> 4)]; |
| 155 | text[2 * i + 1] = HEX_DIGITS[usize::from(byte & 0x0f)]; |
| 156 | } |
| 157 | // Every byte written above is an ASCII hex digit. |
| 158 | f.write_str(core::str::from_utf8(&text).map_err(|_| fmt::Error)?) |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | impl fmt::Debug for GitOid { |
| 163 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 164 | write!(f, "GitOid({self})") |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | /// Why a string is not a git object id. |
| 169 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 170 | pub struct ParseGitOidError; |
| 171 | |
| 172 | impl fmt::Display for ParseGitOidError { |
| 173 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 174 | f.write_str("a git object id is 40 lowercase hex digits") |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | impl std::error::Error for ParseGitOidError {} |
| 179 | |
| 180 | impl FromStr for GitOid { |
| 181 | type Err = ParseGitOidError; |
| 182 | |
| 183 | /// Parses the 40-digit form. Only lowercase is accepted, so two equal ids |
| 184 | /// always have equal text. |
| 185 | fn from_str(text: &str) -> Result<Self, Self::Err> { |
| 186 | if text.bytes().any(|b| b.is_ascii_uppercase()) { |
| 187 | return Err(ParseGitOidError); |
| 188 | } |
| 189 | Self::parse_hex(text.as_bytes()).ok_or(ParseGitOidError) |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | impl From<GitOid> for GitId { |
| 194 | fn from(oid: GitOid) -> Self { |
| 195 | GitId::Sha1(oid.0) |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | #[cfg(test)] |
| 200 | mod tests { |
| 201 | use super::*; |
| 202 | |
| 203 | #[test] |
| 204 | fn well_known_ids() { |
| 205 | // The empty blob and the empty tree have ids every git user has seen. |
| 206 | assert_eq!( |
| 207 | GitOid::for_object(GitKind::Blob, b"").unwrap().to_hex(), |
| 208 | "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391" |
| 209 | ); |
| 210 | assert_eq!( |
| 211 | GitOid::for_object(GitKind::Tree, b"").unwrap().to_hex(), |
| 212 | "4b825dc642cb6eb9a060e54bf8d69288fbee4904" |
| 213 | ); |
| 214 | assert_eq!( |
| 215 | GitOid::for_object(GitKind::Blob, b"hello\n") |
| 216 | .unwrap() |
| 217 | .to_hex(), |
| 218 | "ce013625030ba8dba906f756967f9e9ca394464a" |
| 219 | ); |
| 220 | } |
| 221 | |
| 222 | #[test] |
| 223 | fn text_round_trip() { |
| 224 | let oid = GitOid::for_object(GitKind::Blob, b"x").unwrap(); |
| 225 | let text = oid.to_hex(); |
| 226 | assert_eq!(text.parse::<GitOid>(), Ok(oid)); |
| 227 | assert_eq!(format!("{oid:?}"), format!("GitOid({text})")); |
| 228 | assert_eq!(text.to_uppercase().parse::<GitOid>(), Err(ParseGitOidError)); |
| 229 | assert_eq!(GitOid::parse_hex(text.to_uppercase().as_bytes()), Some(oid)); |
| 230 | assert_eq!(text[..39].parse::<GitOid>(), Err(ParseGitOidError)); |
| 231 | assert_eq!(GitOid::parse_hex(b"zz"), None); |
| 232 | } |
| 233 | |
| 234 | #[test] |
| 235 | fn kind_codes_round_trip() { |
| 236 | for kind in [GitKind::Commit, GitKind::Tree, GitKind::Blob, GitKind::Tag] { |
| 237 | assert_eq!(GitKind::from_code(kind.code()), Some(kind)); |
| 238 | assert_eq!(GitKind::from_gix(kind.to_gix()), kind); |
| 239 | } |
| 240 | assert_eq!(GitKind::from_code(0), None); |
| 241 | assert_eq!(GitKind::from_code(5), None); |
| 242 | } |
| 243 | } |