1use crate::{Error, ObjectFormat, ObjectId, oid::Hasher};
2use alloc::{format, vec::Vec};
3
4#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
5pub enum Kind {
6 Commit,
7 Tree,
8 Blob,
9 Tag,
10}
11
12impl Kind {
13 pub const fn name(self) -> &'static str {
14 match self {
15 Self::Commit => "commit",
16 Self::Tree => "tree",
17 Self::Blob => "blob",
18 Self::Tag => "tag",
19 }
20 }
21
22 pub fn from_name(name: &[u8]) -> Option<Self> {
23 match name {
24 b"commit" => Some(Self::Commit),
25 b"tree" => Some(Self::Tree),
26 b"blob" => Some(Self::Blob),
27 b"tag" => Some(Self::Tag),
28 _ => None,
29 }
30 }
31
32 pub(crate) const fn from_pack_type(code: u8) -> Option<Self> {
33 match code {
34 1 => Some(Self::Commit),
35 2 => Some(Self::Tree),
36 3 => Some(Self::Blob),
37 4 => Some(Self::Tag),
38 _ => None,
39 }
40 }
41}
42
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct Signature {
45 pub name: Vec<u8>,
46 pub email: Vec<u8>,
47 pub time: i64,
48 pub offset_minutes: i32,
49}
50
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub struct Commit {
53 pub tree: ObjectId,
54 pub parents: Vec<ObjectId>,
55 pub author: Signature,
56 pub committer: Signature,
57 pub encoding: Option<Vec<u8>>,
58 pub message: Vec<u8>,
59}
60
61#[derive(Clone, Debug, PartialEq, Eq)]
62pub struct Tag {
63 pub target: ObjectId,
64 pub target_kind: Kind,
65 pub name: Vec<u8>,
66 pub tagger: Option<Signature>,
67 pub message: Vec<u8>,
68}
69
70#[derive(Clone, Debug, PartialEq, Eq)]
71pub struct TreeEntry {
72 pub mode: u32,
73 pub name: Vec<u8>,
74 pub oid: ObjectId,
75}
76
77#[derive(Clone, Debug, PartialEq, Eq)]
78pub enum Object {
79 Commit(Commit),
80 Tree(Vec<TreeEntry>),
81 Blob(Vec<u8>),
82 Tag(Tag),
83}
84
85impl Object {
86 pub const fn kind(&self) -> Kind {
87 match self {
88 Self::Commit(_) => Kind::Commit,
89 Self::Tree(_) => Kind::Tree,
90 Self::Blob(_) => Kind::Blob,
91 Self::Tag(_) => Kind::Tag,
92 }
93 }
94
95 pub fn parse(format: ObjectFormat, kind: Kind, data: &[u8]) -> Result<Self, Error> {
96 Ok(match kind {
97 Kind::Commit => Self::Commit(parse_commit(format, data)?),
98 Kind::Tree => Self::Tree(parse_tree(format, data)?),
99 Kind::Blob => Self::Blob(data.to_vec()),
100 Kind::Tag => Self::Tag(parse_tag(format, data)?),
101 })
102 }
103}
104
105pub fn object_id(format: ObjectFormat, kind: Kind, data: &[u8]) -> ObjectId {
106 let mut hasher = Hasher::new(format);
107 hasher.update(format!("{} {}\0", kind.name(), data.len()).as_bytes());
108 hasher.update(data);
109 hasher.finish()
110}
111
112fn invalid(kind: &'static str) -> Error {
113 Error::Protocol(kind)
114}
115
116fn headers(data: &[u8]) -> (impl Iterator<Item = (&[u8], &[u8])>, &[u8]) {
117 let (head, message) = match data.windows(2).position(|pair| pair == b"\n\n") {
118 Some(end) => (&data[..end], &data[end + 2..]),
119 None => (data, &[][..]),
120 };
121 let lines = head
122 .split(|&byte| byte == b'\n')
123 .filter(|line| !line.is_empty() && !line.starts_with(b" "))
124 .map(|line| match line.iter().position(|&byte| byte == b' ') {
125 Some(space) => (&line[..space], &line[space + 1..]),
126 None => (line, &[][..]),
127 });
128 (lines, message)
129}
130
131fn hex(format: ObjectFormat, value: &[u8]) -> Result<ObjectId, Error> {
132 ObjectId::parse_hex(format, value).ok_or(invalid("invalid object ID in object"))
133}
134
135fn parse_signature(value: &[u8]) -> Result<Signature, Error> {
136 let error = || invalid("invalid signature");
137 let open = value
138 .iter()
139 .position(|&byte| byte == b'<')
140 .ok_or_else(error)?;
141 let close = open
142 + value[open..]
143 .iter()
144 .position(|&byte| byte == b'>')
145 .ok_or_else(error)?;
146 let name = value[..open].strip_suffix(b" ").unwrap_or(&value[..open]);
147 let mut rest = value[close + 1..].trim_ascii().split(|&byte| byte == b' ');
148 let (Some(time), Some(zone), None) = (rest.next(), rest.next(), rest.next()) else {
149 return Err(error());
150 };
151 let time = core::str::from_utf8(time)
152 .ok()
153 .and_then(|time| time.parse().ok())
154 .ok_or_else(error)?;
155 let (sign, digits) = match zone.split_first() {
156 Some((b'+', digits)) => (1, digits),
157 Some((b'-', digits)) => (-1, digits),
158 _ => return Err(error()),
159 };
160 if digits.len() != 4 || !digits.iter().all(u8::is_ascii_digit) {
161 return Err(error());
162 }
163 let number = |pair: &[u8]| i32::from(pair[0] - b'0') * 10 + i32::from(pair[1] - b'0');
164 Ok(Signature {
165 name: name.to_vec(),
166 email: value[open + 1..close].to_vec(),
167 time,
168 offset_minutes: sign * (number(&digits[..2]) * 60 + number(&digits[2..])),
169 })
170}
171
172fn parse_commit(format: ObjectFormat, data: &[u8]) -> Result<Commit, Error> {
173 let (lines, message) = headers(data);
174 let (mut tree, mut parents, mut author, mut committer, mut encoding) =
175 (None, Vec::new(), None, None, None);
176 for (key, value) in lines {
177 match key {
178 b"tree" if tree.is_none() => tree = Some(hex(format, value)?),
179 b"parent" => parents.push(hex(format, value)?),
180 b"author" if author.is_none() => author = Some(parse_signature(value)?),
181 b"committer" if committer.is_none() => committer = Some(parse_signature(value)?),
182 b"encoding" if encoding.is_none() => encoding = Some(value.to_vec()),
183 _ => {}
184 }
185 }
186 Ok(Commit {
187 tree: tree.ok_or(invalid("commit without tree"))?,
188 parents,
189 author: author.ok_or(invalid("commit without author"))?,
190 committer: committer.ok_or(invalid("commit without committer"))?,
191 encoding,
192 message: message.to_vec(),
193 })
194}
195
196fn parse_tag(format: ObjectFormat, data: &[u8]) -> Result<Tag, Error> {
197 let (lines, message) = headers(data);
198 let (mut target, mut target_kind, mut name, mut tagger) = (None, None, None, None);
199 for (key, value) in lines {
200 match key {
201 b"object" if target.is_none() => target = Some(hex(format, value)?),
202 b"type" if target_kind.is_none() => {
203 target_kind =
204 Some(Kind::from_name(value).ok_or(invalid("invalid tag target type"))?);
205 }
206 b"tag" if name.is_none() => name = Some(value.to_vec()),
207 b"tagger" if tagger.is_none() => tagger = Some(parse_signature(value)?),
208 _ => {}
209 }
210 }
211 Ok(Tag {
212 target: target.ok_or(invalid("tag without object"))?,
213 target_kind: target_kind.ok_or(invalid("tag without type"))?,
214 name: name.ok_or(invalid("tag without name"))?,
215 tagger,
216 message: message.to_vec(),
217 })
218}
219
220fn parse_tree(format: ObjectFormat, mut data: &[u8]) -> Result<Vec<TreeEntry>, Error> {
221 let error = || invalid("invalid tree entry");
222 let mut entries = Vec::new();
223 while !data.is_empty() {
224 let space = data
225 .iter()
226 .position(|&byte| byte == b' ')
227 .ok_or_else(error)?;
228 let nul = space
229 + data[space..]
230 .iter()
231 .position(|&byte| byte == 0)
232 .ok_or_else(error)?;
233 let mode = core::str::from_utf8(&data[..space])
234 .ok()
235 .and_then(|mode| u32::from_str_radix(mode, 8).ok())
236 .ok_or_else(error)?;
237 let end = nul + 1 + format.raw_len();
238 let oid = data
239 .get(nul + 1..end)
240 .and_then(|raw| ObjectId::from_raw(format, raw))
241 .ok_or_else(error)?;
242 entries.push(TreeEntry {
243 mode,
244 name: data[space + 1..nul].to_vec(),
245 oid,
246 });
247 data = &data[end..];
248 }
249 Ok(entries)
250}
251
252#[cfg(test)]
253mod tests {
254 use super::*;
255 use alloc::vec;
256
257 const TREE: &str = "2bfbd6378b73ff610bb4593cab58d200fd0ee64f";
258 const PARENT: &str = "28c677f5df3d8f072e45566ed931347ae6325d53";
259
260 #[test]
261 fn parses_signed_commit_and_skips_continuation_lines() {
262 let data = format!(
263 "tree {TREE}\nparent {PARENT}\nauthor Leo K <leo@example.com> 1783070851 +0200\ncommitter GitHub <noreply@github.com> 1783070851 -0130\ngpgsig -----BEGIN PGP SIGNATURE-----\n \n abc\n -----END PGP SIGNATURE-----\n\nRelease v2.0.5\n\nBody\n"
264 );
265 let Object::Commit(commit) =
266 Object::parse(ObjectFormat::Sha1, Kind::Commit, data.as_bytes()).unwrap()
267 else {
268 panic!("expected commit");
269 };
270 assert_eq!(commit.tree.to_hex(), TREE);
271 assert_eq!(commit.parents, vec![PARENT.parse().unwrap()]);
272 assert_eq!(commit.author.name, b"Leo K");
273 assert_eq!(commit.author.email, b"leo@example.com");
274 assert_eq!(commit.author.time, 1_783_070_851);
275 assert_eq!(commit.author.offset_minutes, 120);
276 assert_eq!(commit.committer.offset_minutes, -90);
277 assert_eq!(commit.encoding, None);
278 assert_eq!(commit.message, b"Release v2.0.5\n\nBody\n");
279 }
280
281 #[test]
282 fn parses_tag_and_tree() {
283 let data =
284 format!("object {TREE}\ntype tree\ntag snapshot\ntagger A <a@b> 0 +0000\n\nmsg\n");
285 let Object::Tag(tag) =
286 Object::parse(ObjectFormat::Sha1, Kind::Tag, data.as_bytes()).unwrap()
287 else {
288 panic!("expected tag");
289 };
290 assert_eq!(
291 (tag.target.to_hex().as_str(), tag.target_kind),
292 (TREE, Kind::Tree)
293 );
294 assert_eq!(
295 (tag.name.as_slice(), tag.message.as_slice()),
296 (&b"snapshot"[..], &b"msg\n"[..])
297 );
298 assert_eq!(tag.tagger.unwrap().time, 0);
299 let tree_oid: ObjectId = TREE.parse().unwrap();
300 let mut tree = b"100644 file\0".to_vec();
301 tree.extend_from_slice(tree_oid.as_bytes());
302 tree.extend_from_slice(b"40000 dir\0");
303 tree.extend_from_slice(tree_oid.as_bytes());
304 let Object::Tree(entries) = Object::parse(ObjectFormat::Sha1, Kind::Tree, &tree).unwrap()
305 else {
306 panic!("expected tree");
307 };
308 assert_eq!(entries[0].mode, 0o100644);
309 assert_eq!(entries[1].name, b"dir");
310 assert_eq!(entries[1].oid, tree_oid);
311 }
312
313 #[test]
314 fn hashes_like_git() {
315 assert_eq!(
316 object_id(ObjectFormat::Sha1, Kind::Blob, b"").to_hex(),
317 "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
318 );
319 assert_eq!(
320 object_id(ObjectFormat::Sha256, Kind::Blob, b"").to_hex(),
321 "473a0f4c3be8a93681a267e3b1e9a7dcda1185436fe141f7749120a303721813"
322 );
323 }
324
325 #[test]
326 fn rejects_incomplete_objects() {
327 assert!(
328 Object::parse(ObjectFormat::Sha1, Kind::Commit, b"author A <a> 0 +0000\n").is_err()
329 );
330 let bad_zone = format!("tree {TREE}\nauthor A <a> 0 0200\ncommitter A <a> 0 +0000\n");
331 assert!(Object::parse(ObjectFormat::Sha1, Kind::Commit, bad_zone.as_bytes()).is_err());
332 assert!(Object::parse(ObjectFormat::Sha1, Kind::Tag, b"type commit\ntag x\n").is_err());
333 assert!(Object::parse(ObjectFormat::Sha1, Kind::Tree, b"100644 file\0short").is_err());
334 }
335}