synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-git / src / object.rs
| 1 | //! Git object model for the bridge (ADR 0003 step H1): the four object kinds, object IDs, and |
| 2 | //! the links between objects (a tree's entries, a commit's tree and parents, a tag's target), |
| 3 | //! following `gitformat-pack` (object types) and Git's object encoding |
| 4 | //! (`<kind> <size>\0<payload>`, SHA-1 of that). |
| 5 | //! |
| 6 | //! Parsers here read only what the bridge needs to walk history. Every other byte of a commit |
| 7 | //! or tag (author, committer, signatures, extra headers, message) is kept as opaque data and |
| 8 | //! never rewritten, so a stored object re-encodes to the same Git object ID. |
| 9 | |
| 10 | use synapse_core::{GitOid, RefusalCode, SynapseError, SynapseResult}; |
| 11 | |
| 12 | fn corrupt(msg: impl Into<String>) -> SynapseError { |
| 13 | SynapseError::new(RefusalCode::GitObjectCorrupt, msg) |
| 14 | } |
| 15 | |
| 16 | /// The four Git object kinds; the discriminant is the pack type number (`OBJ_COMMIT` = 1 to |
| 17 | /// `OBJ_TAG` = 4 in `gitformat-pack`). |
| 18 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 19 | pub enum ObjectKind { |
| 20 | Commit = 1, |
| 21 | Tree = 2, |
| 22 | Blob = 3, |
| 23 | Tag = 4, |
| 24 | } |
| 25 | |
| 26 | impl ObjectKind { |
| 27 | /// The kind name in an object header (`commit`, `tree`, `blob`, `tag`). |
| 28 | pub fn name(self) -> &'static str { |
| 29 | match self { |
| 30 | Self::Commit => "commit", |
| 31 | Self::Tree => "tree", |
| 32 | Self::Blob => "blob", |
| 33 | Self::Tag => "tag", |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | pub fn from_name(name: &[u8]) -> SynapseResult<Self> { |
| 38 | match name { |
| 39 | b"commit" => Ok(Self::Commit), |
| 40 | b"tree" => Ok(Self::Tree), |
| 41 | b"blob" => Ok(Self::Blob), |
| 42 | b"tag" => Ok(Self::Tag), |
| 43 | other => Err(corrupt(format!( |
| 44 | "unknown Git object kind {:?}", |
| 45 | String::from_utf8_lossy(other) |
| 46 | ))), |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /// The pack type number (1 to 4). |
| 51 | pub fn pack_type(self) -> u8 { |
| 52 | self as u8 |
| 53 | } |
| 54 | |
| 55 | pub fn from_pack_type(t: u8) -> SynapseResult<Self> { |
| 56 | match t { |
| 57 | 1 => Ok(Self::Commit), |
| 58 | 2 => Ok(Self::Tree), |
| 59 | 3 => Ok(Self::Blob), |
| 60 | 4 => Ok(Self::Tag), |
| 61 | other => Err(corrupt(format!( |
| 62 | "pack type {other} is not a base object kind" |
| 63 | ))), |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | /// One Git object: its kind and payload (the bytes after the `<kind> <size>\0` header). |
| 69 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 70 | pub struct GitObject { |
| 71 | pub kind: ObjectKind, |
| 72 | pub payload: Vec<u8>, |
| 73 | } |
| 74 | |
| 75 | impl GitObject { |
| 76 | pub fn new(kind: ObjectKind, payload: Vec<u8>) -> Self { |
| 77 | Self { kind, payload } |
| 78 | } |
| 79 | |
| 80 | /// The object's SHA-1 Git object ID. |
| 81 | pub fn oid(&self) -> GitOid { |
| 82 | GitOid::compute_git_object(self.kind.name(), &self.payload) |
| 83 | } |
| 84 | |
| 85 | /// The loose object encoding `<kind> <size>\0<payload>` (before zlib). |
| 86 | pub fn encode_loose(&self) -> Vec<u8> { |
| 87 | let header = format!("{} {}\0", self.kind.name(), self.payload.len()); |
| 88 | let mut out = Vec::with_capacity(header.len() + self.payload.len()); |
| 89 | out.extend_from_slice(header.as_bytes()); |
| 90 | out.extend_from_slice(&self.payload); |
| 91 | out |
| 92 | } |
| 93 | |
| 94 | /// Parse a decompressed loose object `<kind> <size>\0<payload>`; the size must match. |
| 95 | pub fn decode_loose(raw: &[u8]) -> SynapseResult<Self> { |
| 96 | let nul = raw |
| 97 | .iter() |
| 98 | .position(|&b| b == 0) |
| 99 | .ok_or_else(|| corrupt("loose object header has no NUL"))?; |
| 100 | let header = &raw[..nul]; |
| 101 | let space = header |
| 102 | .iter() |
| 103 | .position(|&b| b == b' ') |
| 104 | .ok_or_else(|| corrupt("loose object header has no space"))?; |
| 105 | let kind = ObjectKind::from_name(&header[..space])?; |
| 106 | let size = parse_decimal(&header[space + 1..])?; |
| 107 | let payload = &raw[nul + 1..]; |
| 108 | if payload.len() as u64 != size { |
| 109 | return Err(corrupt(format!( |
| 110 | "loose object declares {size} bytes but holds {}", |
| 111 | payload.len() |
| 112 | ))); |
| 113 | } |
| 114 | Ok(Self::new(kind, payload.to_vec())) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | fn parse_decimal(digits: &[u8]) -> SynapseResult<u64> { |
| 119 | if digits.is_empty() || (digits.len() > 1 && digits[0] == b'0') { |
| 120 | return Err(corrupt("object size is not canonical decimal")); |
| 121 | } |
| 122 | let mut value: u64 = 0; |
| 123 | for &d in digits { |
| 124 | if !d.is_ascii_digit() { |
| 125 | return Err(corrupt("object size is not decimal")); |
| 126 | } |
| 127 | value = value |
| 128 | .checked_mul(10) |
| 129 | .and_then(|v| v.checked_add(u64::from(d - b'0'))) |
| 130 | .ok_or_else(|| corrupt("object size overflows u64"))?; |
| 131 | } |
| 132 | Ok(value) |
| 133 | } |
| 134 | |
| 135 | /// One entry of a Git tree: the mode exactly as written (ASCII octal), the name bytes, and the |
| 136 | /// object ID it names. |
| 137 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 138 | pub struct GitTreeEntry { |
| 139 | pub mode: Vec<u8>, |
| 140 | pub name: Vec<u8>, |
| 141 | pub oid: GitOid, |
| 142 | } |
| 143 | |
| 144 | impl GitTreeEntry { |
| 145 | /// The kind of object this entry names, from its mode: `40000` a tree, `160000` a commit |
| 146 | /// (a gitlink, never present in this repository's object store), anything else a blob. |
| 147 | pub fn target_kind(&self) -> ObjectKind { |
| 148 | match self.mode.as_slice() { |
| 149 | b"40000" | b"040000" => ObjectKind::Tree, |
| 150 | b"160000" => ObjectKind::Commit, |
| 151 | _ => ObjectKind::Blob, |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | /// Parse a tree payload: `(<mode> <name>\0<20-byte oid>)*`. |
| 157 | pub fn parse_tree(payload: &[u8]) -> SynapseResult<Vec<GitTreeEntry>> { |
| 158 | let mut entries = Vec::new(); |
| 159 | let mut rest = payload; |
| 160 | while !rest.is_empty() { |
| 161 | let space = rest |
| 162 | .iter() |
| 163 | .position(|&b| b == b' ') |
| 164 | .ok_or_else(|| corrupt("tree entry has no space after its mode"))?; |
| 165 | let mode = &rest[..space]; |
| 166 | if mode.is_empty() || !mode.iter().all(|b| (b'0'..=b'7').contains(b)) { |
| 167 | return Err(corrupt("tree entry mode is not octal")); |
| 168 | } |
| 169 | let after = &rest[space + 1..]; |
| 170 | let nul = after |
| 171 | .iter() |
| 172 | .position(|&b| b == 0) |
| 173 | .ok_or_else(|| corrupt("tree entry name has no NUL"))?; |
| 174 | let oid_bytes = after |
| 175 | .get(nul + 1..nul + 21) |
| 176 | .ok_or_else(|| corrupt("tree entry truncated before its object ID"))?; |
| 177 | let mut oid = [0u8; 20]; |
| 178 | oid.copy_from_slice(oid_bytes); |
| 179 | entries.push(GitTreeEntry { |
| 180 | mode: mode.to_vec(), |
| 181 | name: after[..nul].to_vec(), |
| 182 | oid: GitOid(oid), |
| 183 | }); |
| 184 | rest = &after[nul + 21..]; |
| 185 | } |
| 186 | Ok(entries) |
| 187 | } |
| 188 | |
| 189 | /// Encode tree entries in the order given (callers keep Git's tree order). |
| 190 | pub fn encode_tree(entries: &[GitTreeEntry]) -> Vec<u8> { |
| 191 | let mut out = Vec::new(); |
| 192 | for e in entries { |
| 193 | out.extend_from_slice(&e.mode); |
| 194 | out.push(b' '); |
| 195 | out.extend_from_slice(&e.name); |
| 196 | out.push(0); |
| 197 | out.extend_from_slice(&e.oid.0); |
| 198 | } |
| 199 | out |
| 200 | } |
| 201 | |
| 202 | fn header_oid(value: &[u8], what: &str) -> SynapseResult<GitOid> { |
| 203 | let hex = std::str::from_utf8(value).map_err(|_| corrupt(format!("{what} is not hex")))?; |
| 204 | if hex.len() != 40 || hex.bytes().any(|b| b.is_ascii_uppercase()) { |
| 205 | return Err(corrupt(format!("{what} is not 40 lowercase hex digits"))); |
| 206 | } |
| 207 | GitOid::from_hex(hex) |
| 208 | } |
| 209 | |
| 210 | /// Header lines of a commit or tag up to the blank line (continuation lines starting with a |
| 211 | /// space belong to the header above them and are skipped). |
| 212 | fn header_lines(payload: &[u8]) -> impl Iterator<Item = &[u8]> { |
| 213 | let end = payload |
| 214 | .windows(2) |
| 215 | .position(|w| w == b"\n\n") |
| 216 | .map_or(payload.len(), |p| p + 1); |
| 217 | payload[..end] |
| 218 | .split(|&b| b == b'\n') |
| 219 | .filter(|l| !l.is_empty() && l[0] != b' ') |
| 220 | } |
| 221 | |
| 222 | /// The links of a commit: its tree and parents in their written order. |
| 223 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 224 | pub struct CommitLinks { |
| 225 | pub tree: GitOid, |
| 226 | pub parents: Vec<GitOid>, |
| 227 | } |
| 228 | |
| 229 | /// Parse a commit's `tree` line (first) and `parent` lines (immediately after, in order). |
| 230 | pub fn parse_commit_links(payload: &[u8]) -> SynapseResult<CommitLinks> { |
| 231 | let mut lines = header_lines(payload); |
| 232 | let tree = match lines.next() { |
| 233 | Some(l) if l.starts_with(b"tree ") => header_oid(&l[5..], "commit tree")?, |
| 234 | _ => return Err(corrupt("commit does not start with a tree line")), |
| 235 | }; |
| 236 | let mut parents = Vec::new(); |
| 237 | for l in lines { |
| 238 | if let Some(hex) = l.strip_prefix(b"parent ") { |
| 239 | parents.push(header_oid(hex, "commit parent")?); |
| 240 | } else { |
| 241 | break; |
| 242 | } |
| 243 | } |
| 244 | Ok(CommitLinks { tree, parents }) |
| 245 | } |
| 246 | |
| 247 | /// The target of an annotated tag: its `object` and `type` lines. |
| 248 | pub fn parse_tag_target(payload: &[u8]) -> SynapseResult<(GitOid, ObjectKind)> { |
| 249 | let mut lines = header_lines(payload); |
| 250 | let object = match lines.next() { |
| 251 | Some(l) if l.starts_with(b"object ") => header_oid(&l[7..], "tag object")?, |
| 252 | _ => return Err(corrupt("tag does not start with an object line")), |
| 253 | }; |
| 254 | let kind = match lines.next() { |
| 255 | Some(l) if l.starts_with(b"type ") => ObjectKind::from_name(&l[5..])?, |
| 256 | _ => return Err(corrupt("tag has no type line after its object line")), |
| 257 | }; |
| 258 | Ok((object, kind)) |
| 259 | } |
| 260 | |
| 261 | /// Every object ID `object` links to, with the kind it must have: tree entries (gitlinks |
| 262 | /// excluded: they name commits of another repository), a commit's tree and parents, a tag's |
| 263 | /// target. |
| 264 | pub fn object_links(object: &GitObject) -> SynapseResult<Vec<(GitOid, ObjectKind)>> { |
| 265 | Ok(match object.kind { |
| 266 | ObjectKind::Blob => Vec::new(), |
| 267 | ObjectKind::Tree => parse_tree(&object.payload)? |
| 268 | .into_iter() |
| 269 | .filter(|e| e.target_kind() != ObjectKind::Commit) |
| 270 | .map(|e| { |
| 271 | let kind = e.target_kind(); |
| 272 | (e.oid, kind) |
| 273 | }) |
| 274 | .collect(), |
| 275 | ObjectKind::Commit => { |
| 276 | let links = parse_commit_links(&object.payload)?; |
| 277 | let mut out = vec![(links.tree, ObjectKind::Tree)]; |
| 278 | out.extend(links.parents.into_iter().map(|p| (p, ObjectKind::Commit))); |
| 279 | out |
| 280 | } |
| 281 | ObjectKind::Tag => vec![parse_tag_target(&object.payload)?], |
| 282 | }) |
| 283 | } |
| 284 | |
| 285 | #[cfg(test)] |
| 286 | mod tests { |
| 287 | use super::*; |
| 288 | |
| 289 | #[test] |
| 290 | fn loose_encoding_round_trips_and_ids_match_git_known_values() { |
| 291 | // `git hash-object -t blob /dev/null` and `git mktree < /dev/null`. |
| 292 | let empty_blob = GitObject::new(ObjectKind::Blob, Vec::new()); |
| 293 | assert_eq!( |
| 294 | empty_blob.oid().to_hex(), |
| 295 | "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391" |
| 296 | ); |
| 297 | let empty_tree = GitObject::new(ObjectKind::Tree, Vec::new()); |
| 298 | assert_eq!( |
| 299 | empty_tree.oid().to_hex(), |
| 300 | "4b825dc642cb6eb9a060e54bf8d69288fbee4904" |
| 301 | ); |
| 302 | let raw = empty_blob.encode_loose(); |
| 303 | assert_eq!(GitObject::decode_loose(&raw).unwrap(), empty_blob); |
| 304 | assert!(GitObject::decode_loose(b"blob 01\0x").is_err()); |
| 305 | assert!(GitObject::decode_loose(b"blob 2\0x").is_err()); |
| 306 | assert!(GitObject::decode_loose(b"blub 1\0x").is_err()); |
| 307 | } |
| 308 | |
| 309 | #[test] |
| 310 | fn commit_and_tag_links_parse_and_keep_parent_order() { |
| 311 | let c = b"tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\ |
| 312 | parent 2222222222222222222222222222222222222222\n\ |
| 313 | parent 1111111111111111111111111111111111111111\n\ |
| 314 | author A <a@x> 1 +0000\ncommitter A <a@x> 1 +0000\n\nparent ffff\n"; |
| 315 | let links = parse_commit_links(c).unwrap(); |
| 316 | assert_eq!(links.parents.len(), 2); |
| 317 | assert_eq!(links.parents[0].0[0], 0x22); |
| 318 | let t = b"object 4b825dc642cb6eb9a060e54bf8d69288fbee4904\ntype tree\ntag v\n\nmsg\n"; |
| 319 | assert_eq!(parse_tag_target(t).unwrap().1, ObjectKind::Tree); |
| 320 | assert!(parse_commit_links(b"parent x\n").is_err()); |
| 321 | } |
| 322 | |
| 323 | #[test] |
| 324 | fn tree_entries_parse_and_re_encode_exactly() { |
| 325 | let mut payload = Vec::new(); |
| 326 | payload.extend_from_slice(b"100644 a.txt\0"); |
| 327 | payload.extend_from_slice(&[1u8; 20]); |
| 328 | payload.extend_from_slice(b"40000 dir\0"); |
| 329 | payload.extend_from_slice(&[2u8; 20]); |
| 330 | let entries = parse_tree(&payload).unwrap(); |
| 331 | assert_eq!(entries[1].target_kind(), ObjectKind::Tree); |
| 332 | assert_eq!(encode_tree(&entries), payload); |
| 333 | assert!(parse_tree(&payload[..payload.len() - 1]).is_err()); |
| 334 | } |
| 335 | } |