Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 22.0 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The raw bytes of git objects: the few fields braid reads from them, and the
5//! canonical form it writes.
6//!
7//! Braid keeps the original bytes of every imported commit and tag, and of
8//! every tree it cannot regenerate exactly, so these parsers only need the
9//! fields that link objects together and the fields a changeset records. They
10//! are total where they can be: odd author lines or extra headers never stop an
11//! import, because the original bytes travel with the changeset.
12//!
13//! Written from git's documented object format; no code comes from git.
14
15use core::cmp::Ordering;
16
17use braid_format::Signature;
18
19use crate::oid::GitOid;
20
21/// What a git tree entry is, by the file type bits of its mode.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum EntryType {
24 /// A regular file.
25 File,
26 /// A regular file the owner may execute.
27 Executable,
28 /// A symlink; its blob is the target.
29 Symlink,
30 /// A directory.
31 Tree,
32 /// A submodule commit.
33 Gitlink,
34}
35
36impl EntryType {
37 /// The type of an entry with this mode, written in octal as in a tree.
38 /// A regular file is executable when the owner may execute it, so a
39 /// non-canonical mode such as `100664` still has a type; `None` means the
40 /// file type bits name nothing git can store.
41 pub fn from_mode(mode: &[u8]) -> Option<EntryType> {
42 let value = parse_octal(mode)?;
43 match value & 0o170_000 {
44 0o100_000 if value & 0o100 != 0 => Some(EntryType::Executable),
45 0o100_000 => Some(EntryType::File),
46 0o120_000 => Some(EntryType::Symlink),
47 0o040_000 => Some(EntryType::Tree),
48 0o160_000 => Some(EntryType::Gitlink),
49 _ => None,
50 }
51 }
52
53 /// The mode git writes for this type.
54 pub(crate) const fn canonical_mode(self) -> &'static [u8] {
55 match self {
56 EntryType::File => b"100644",
57 EntryType::Executable => b"100755",
58 EntryType::Symlink => b"120000",
59 EntryType::Tree => b"40000",
60 EntryType::Gitlink => b"160000",
61 }
62 }
63}
64
65fn parse_octal(digits: &[u8]) -> Option<u32> {
66 if digits.is_empty() {
67 return None;
68 }
69 digits.iter().try_fold(0u32, |value, digit| match digit {
70 b'0'..=b'7' => value.checked_mul(8)?.checked_add(u32::from(digit - b'0')),
71 _ => None,
72 })
73}
74
75/// One entry of a git tree, as written.
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub struct RawEntry<'a> {
78 /// The mode, in octal digits.
79 pub mode: &'a [u8],
80 /// The name.
81 pub name: &'a [u8],
82 /// The object the entry names.
83 pub oid: GitOid,
84}
85
86/// Splits a tree into its entries, in the order they are written.
87pub fn parse_tree(data: &[u8]) -> Result<Vec<RawEntry<'_>>, &'static str> {
88 let mut entries = Vec::new();
89 let mut rest = data;
90 while !rest.is_empty() {
91 let space = find_byte(rest, b' ').ok_or("an entry has no space after its mode")?;
92 let mode = &rest[..space];
93 let after = &rest[space + 1..];
94 let nul = find_byte(after, 0).ok_or("an entry name has no terminating NUL")?;
95 let name = &after[..nul];
96 let id: [u8; 20] = after
97 .get(nul + 1..nul + 1 + GitOid::LEN)
98 .and_then(|bytes| bytes.try_into().ok())
99 .ok_or("an entry id is cut short")?;
100 entries.push(RawEntry {
101 mode,
102 name,
103 oid: GitOid::from_bytes(id),
104 });
105 rest = &after[nul + 1 + GitOid::LEN..];
106 }
107 Ok(entries)
108}
109
110/// One entry of a tree to write.
111#[derive(Clone, Copy, Debug)]
112pub(crate) struct TreeItem<'a> {
113 pub kind: EntryType,
114 pub name: &'a [u8],
115 pub oid: GitOid,
116}
117
118/// Writes a tree as git does: canonical modes, and entries sorted by name
119/// bytes with a directory compared as if its name ended in `/`.
120pub(crate) fn encode_tree(items: &mut [TreeItem<'_>]) -> Vec<u8> {
121 items.sort_by(|a, b| {
122 git_order(
123 a.name,
124 a.kind == EntryType::Tree,
125 b.name,
126 b.kind == EntryType::Tree,
127 )
128 });
129 let size = items
130 .iter()
131 .map(|item| item.kind.canonical_mode().len() + item.name.len() + 2 + GitOid::LEN)
132 .sum();
133 let mut out = Vec::with_capacity(size);
134 for item in items.iter() {
135 out.extend_from_slice(item.kind.canonical_mode());
136 out.push(b' ');
137 out.extend_from_slice(item.name);
138 out.push(0);
139 out.extend_from_slice(item.oid.as_bytes());
140 }
141 out
142}
143
144/// Git's order of tree entries: by name bytes, with a directory's name
145/// followed by `/`.
146pub(crate) fn git_order(a: &[u8], a_dir: bool, b: &[u8], b_dir: bool) -> Ordering {
147 let common = a.len().min(b.len());
148 a[..common].cmp(&b[..common]).then_with(|| {
149 let next = |name: &[u8], dir: bool| name.get(common).copied().or(dir.then_some(b'/'));
150 next(a, a_dir).cmp(&next(b, b_dir))
151 })
152}
153
154/// The fields of a commit that braid reads.
155#[derive(Clone, Debug, PartialEq, Eq)]
156pub struct CommitFields<'a> {
157 /// The tree.
158 pub tree: GitOid,
159 /// The parents, in order.
160 pub parents: Vec<GitOid>,
161 /// The value of the first `author` header.
162 pub author: Option<&'a [u8]>,
163 /// The value of the first `committer` header.
164 pub committer: Option<&'a [u8]>,
165 /// Everything after the first empty line.
166 pub message: &'a [u8],
167}
168
169/// Splits an object at its first empty line into the header lines (each one
170/// ending in a newline) and the message.
171fn split_message(data: &[u8]) -> (&[u8], &[u8]) {
172 if data.first() == Some(&b'\n') {
173 return (&[], &data[1..]);
174 }
175 match data.windows(2).position(|pair| pair == b"\n\n") {
176 Some(end) => (&data[..end + 1], &data[end + 2..]),
177 None => (data, &[]),
178 }
179}
180
181/// The header lines as key and value. Continuation lines, which start with a
182/// space and belong to a multi-line header such as a signature, are skipped.
183fn header_lines(headers: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
184 headers
185 .split(|byte| *byte == b'\n')
186 .filter(|line| line.first().is_some_and(|byte| *byte != b' '))
187 .map(|line| match find_byte(line, b' ') {
188 Some(space) => (&line[..space], &line[space + 1..]),
189 None => (line, &line[line.len()..]),
190 })
191}
192
193/// Reads the tree, the parents, the author and committer lines and the
194/// message of a commit.
195///
196/// The tree is the first header and the parents are the `parent` headers right
197/// after it. The author and committer are the first headers with those names,
198/// wherever they are; the message is everything after the first empty line.
199pub fn parse_commit(data: &[u8]) -> Result<CommitFields<'_>, &'static str> {
200 let (headers, message) = split_message(data);
201 let mut lines = header_lines(headers).peekable();
202 let tree = match lines.next() {
203 Some((b"tree", value)) => {
204 GitOid::parse_hex(value).ok_or("the tree header does not hold an object id")?
205 }
206 _ => return Err("the first header is not a tree"),
207 };
208 let mut parents = Vec::new();
209 while let Some((b"parent", value)) = lines.peek() {
210 parents.push(GitOid::parse_hex(value).ok_or("a parent header does not hold an object id")?);
211 lines.next();
212 }
213 let mut author = None;
214 let mut committer = None;
215 for (key, value) in lines {
216 match key {
217 b"author" if author.is_none() => author = Some(value),
218 b"committer" if committer.is_none() => committer = Some(value),
219 _ => {}
220 }
221 }
222 Ok(CommitFields {
223 tree,
224 parents,
225 author,
226 committer,
227 message,
228 })
229}
230
231/// Reads the object an annotated tag points to: its first header.
232pub fn parse_tag(data: &[u8]) -> Result<GitOid, &'static str> {
233 let (headers, _) = split_message(data);
234 match header_lines(headers).next() {
235 Some((b"object", value)) => {
236 GitOid::parse_hex(value).ok_or("the object header does not hold an object id")
237 }
238 _ => Err("the first header is not an object"),
239 }
240}
241
242/// Reads an author or committer line: `Name <email> seconds ±HHMM`.
243///
244/// The rule is fixed, because these fields are hashed into the changeset id:
245///
246/// - The name is everything before the first `<`, without surrounding ASCII
247/// whitespace; the email is everything between it and the next `>`.
248/// - After the `>`, the first word is the time in seconds and the second the
249/// offset as `±HHMM`. A missing or unreadable value is 0.
250/// - A line without `<` and a later `>` is all name, with no email and time 0.
251///
252/// Nothing is lost: the original line stays in the commit bytes.
253pub fn parse_signature(line: &[u8]) -> Signature {
254 let parts = find_byte(line, b'<').and_then(|open| {
255 let close = open + 1 + find_byte(&line[open + 1..], b'>')?;
256 Some((&line[..open], &line[open + 1..close], &line[close + 1..]))
257 });
258 let Some((name, email, rest)) = parts else {
259 return Signature {
260 name: line.trim_ascii().to_vec(),
261 email: Vec::new(),
262 seconds: 0,
263 offset_minutes: 0,
264 };
265 };
266 let mut words = rest
267 .split(|byte| byte.is_ascii_whitespace())
268 .filter(|word| !word.is_empty());
269 let seconds = words.next().and_then(parse_decimal).unwrap_or(0);
270 let offset_minutes = words.next().and_then(parse_offset).unwrap_or(0);
271 Signature {
272 name: name.trim_ascii().to_vec(),
273 email: email.to_vec(),
274 seconds,
275 offset_minutes,
276 }
277}
278
279/// An optional sign followed by decimal digits, if it fits in an `i64`.
280fn parse_decimal(word: &[u8]) -> Option<i64> {
281 let (negative, digits) = match word.split_first() {
282 Some((b'-', rest)) => (true, rest),
283 Some((b'+', rest)) => (false, rest),
284 _ => (false, word),
285 };
286 if digits.is_empty() {
287 return None;
288 }
289 let magnitude = digits.iter().try_fold(0i64, |value, digit| match digit {
290 b'0'..=b'9' => value.checked_mul(10)?.checked_add(i64::from(digit - b'0')),
291 _ => None,
292 })?;
293 Some(if negative { -magnitude } else { magnitude })
294}
295
296/// `±HHMM` as minutes.
297fn parse_offset(word: &[u8]) -> Option<i64> {
298 let value = parse_decimal(word)?;
299 let minutes = (value.abs() / 100)
300 .checked_mul(60)?
301 .checked_add(value.abs() % 100)?;
302 Some(if value < 0 { -minutes } else { minutes })
303}
304
305/// Appends `key Name <email> seconds ±HHMM` and a newline.
306fn write_signature(out: &mut Vec<u8>, key: &[u8], signature: &Signature) -> Result<(), String> {
307 let forbidden = |byte: &u8| matches!(byte, b'<' | b'>' | b'\n' | 0);
308 if signature.name.iter().any(forbidden) {
309 return Err("a name holds '<', '>', a newline or NUL".into());
310 }
311 if signature.email.iter().any(forbidden) {
312 return Err("an email holds '<', '>', a newline or NUL".into());
313 }
314 let magnitude = signature.offset_minutes.unsigned_abs();
315 if magnitude / 60 > 99 {
316 return Err(format!(
317 "the offset of {} minutes does not fit in ±HHMM",
318 signature.offset_minutes
319 ));
320 }
321 out.extend_from_slice(key);
322 out.push(b' ');
323 out.extend_from_slice(&signature.name);
324 out.extend_from_slice(b" <");
325 out.extend_from_slice(&signature.email);
326 out.extend_from_slice(b"> ");
327 out.extend_from_slice(signature.seconds.to_string().as_bytes());
328 let sign = if signature.offset_minutes < 0 {
329 '-'
330 } else {
331 '+'
332 };
333 let offset = format!(" {sign}{:02}{:02}\n", magnitude / 60, magnitude % 60);
334 out.extend_from_slice(offset.as_bytes());
335 Ok(())
336}
337
338/// The headers a commit generated by braid writes itself, which an extra must
339/// not repeat.
340const RESERVED_HEADERS: [&[u8]; 4] = [b"tree", b"parent", b"author", b"committer"];
341
342/// Writes a commit for a changeset that did not come from git.
343///
344/// The headers are `tree`, `parent` for each parent, `author`, `committer`,
345/// then one header per extra in order, a multi-line value continuing on lines
346/// that start with a space; then an empty line and the message, unchanged.
347pub fn encode_commit(
348 tree: GitOid,
349 parents: &[GitOid],
350 author: &Signature,
351 committer: &Signature,
352 extras: &[(Vec<u8>, Vec<u8>)],
353 message: &[u8],
354) -> Result<Vec<u8>, String> {
355 let mut out = Vec::with_capacity(256 + message.len());
356 out.extend_from_slice(b"tree ");
357 out.extend_from_slice(tree.to_hex().as_bytes());
358 out.push(b'\n');
359 for parent in parents {
360 out.extend_from_slice(b"parent ");
361 out.extend_from_slice(parent.to_hex().as_bytes());
362 out.push(b'\n');
363 }
364 write_signature(&mut out, b"author", author)?;
365 write_signature(&mut out, b"committer", committer)?;
366 for (key, value) in extras {
367 if key.is_empty()
368 || key.iter().any(|byte| matches!(byte, b' ' | b'\n' | 0))
369 || RESERVED_HEADERS.contains(&key.as_slice())
370 {
371 return Err(format!(
372 "the extra {:?} cannot be a header",
373 String::from_utf8_lossy(key)
374 ));
375 }
376 if value.contains(&0) {
377 return Err(format!(
378 "the extra {:?} holds a NUL byte",
379 String::from_utf8_lossy(key)
380 ));
381 }
382 out.extend_from_slice(key);
383 out.push(b' ');
384 for (index, line) in value.split(|byte| *byte == b'\n').enumerate() {
385 if index > 0 {
386 out.extend_from_slice(b"\n ");
387 }
388 out.extend_from_slice(line);
389 }
390 out.push(b'\n');
391 }
392 out.push(b'\n');
393 out.extend_from_slice(message);
394 Ok(out)
395}
396
397fn find_byte(haystack: &[u8], needle: u8) -> Option<usize> {
398 haystack.iter().position(|byte| *byte == needle)
399}
400
401#[cfg(test)]
402mod tests {
403 use super::*;
404
405 fn oid(byte: u8) -> GitOid {
406 GitOid::from_bytes([byte; 20])
407 }
408
409 #[test]
410 fn modes() {
411 use EntryType::*;
412 let cases: &[(&[u8], Option<EntryType>)] = &[
413 (b"100644", Some(File)),
414 (b"100664", Some(File)),
415 (b"100600", Some(File)),
416 (b"0100644", Some(File)),
417 (b"100755", Some(Executable)),
418 (b"100775", Some(Executable)),
419 (b"100700", Some(Executable)),
420 (b"120000", Some(Symlink)),
421 (b"40000", Some(Tree)),
422 (b"040000", Some(Tree)),
423 (b"160000", Some(Gitlink)),
424 (b"", None),
425 (b"100648", None),
426 (b"777777777777", None),
427 (b"20000", None),
428 (b"0", None),
429 ];
430 for (mode, expected) in cases {
431 assert_eq!(
432 EntryType::from_mode(mode),
433 *expected,
434 "{}",
435 String::from_utf8_lossy(mode)
436 );
437 }
438 for kind in [File, Executable, Symlink, Tree, Gitlink] {
439 assert_eq!(EntryType::from_mode(kind.canonical_mode()), Some(kind));
440 }
441 }
442
443 #[test]
444 fn git_orders_directories_as_if_they_ended_in_a_slash() {
445 use Ordering::*;
446 assert_eq!(git_order(b"a", false, b"b", false), Less);
447 assert_eq!(git_order(b"a.c", false, b"a", true), Less); // "a.c" < "a/"
448 assert_eq!(git_order(b"a", true, b"a0", false), Less); // "a/" < "a0"
449 assert_eq!(git_order(b"a", false, b"a.c", false), Less);
450 assert_eq!(git_order(b"a", false, b"a", true), Less);
451 assert_eq!(git_order(b"ab", true, b"a", true), Greater);
452 let mut items = [
453 TreeItem {
454 kind: EntryType::Tree,
455 name: b"a",
456 oid: oid(1),
457 },
458 TreeItem {
459 kind: EntryType::File,
460 name: b"a.c",
461 oid: oid(2),
462 },
463 TreeItem {
464 kind: EntryType::File,
465 name: b"a0",
466 oid: oid(3),
467 },
468 ];
469 let bytes = encode_tree(&mut items);
470 let names: Vec<&[u8]> = parse_tree(&bytes).unwrap().iter().map(|e| e.name).collect();
471 assert_eq!(names, [&b"a.c"[..], b"a", b"a0"]);
472 }
473
474 #[test]
475 fn tree_round_trip_and_errors() {
476 let mut items = [
477 TreeItem {
478 kind: EntryType::Executable,
479 name: b"run",
480 oid: oid(7),
481 },
482 TreeItem {
483 kind: EntryType::Gitlink,
484 name: b"sub",
485 oid: oid(8),
486 },
487 ];
488 let bytes = encode_tree(&mut items);
489 assert!(bytes.starts_with(b"100755 run\0"));
490 let entries = parse_tree(&bytes).unwrap();
491 assert_eq!(entries.len(), 2);
492 assert_eq!(entries[1].mode, b"160000");
493 assert_eq!(entries[1].oid, oid(8));
494 assert!(parse_tree(b"").unwrap().is_empty());
495 assert!(parse_tree(b"100644").is_err());
496 assert!(parse_tree(b"100644 name").is_err());
497 assert!(parse_tree(&bytes[..bytes.len() - 1]).is_err());
498 }
499
500 #[test]
501 fn commits() {
502 let tree = oid(0xaa).to_hex();
503 let parent = oid(0xbb).to_hex();
504 let text = format!(
505 "tree {tree}\nparent {parent}\nparent {}\nauthor A U Thor <a@example.org> 1700000000 +0130\n\
506 committer C O Mitter <c@example.org> 1700000001 -0800\nencoding ISO-8859-1\n\
507 gpgsig -----BEGIN-----\n \n line\n -----END-----\n\nsubject\n\nbody\n",
508 parent.to_uppercase()
509 );
510 let fields = parse_commit(text.as_bytes()).unwrap();
511 assert_eq!(fields.tree, oid(0xaa));
512 assert_eq!(fields.parents, [oid(0xbb), oid(0xbb)]);
513 assert_eq!(
514 parse_signature(fields.author.unwrap()),
515 Signature {
516 name: b"A U Thor".to_vec(),
517 email: b"a@example.org".to_vec(),
518 seconds: 1_700_000_000,
519 offset_minutes: 90,
520 }
521 );
522 assert_eq!(
523 parse_signature(fields.committer.unwrap()).offset_minutes,
524 -480
525 );
526 assert_eq!(fields.message, b"subject\n\nbody\n");
527
528 // No message at all, and an empty one.
529 let bare = format!("tree {tree}\nauthor x <y> 1 +0000\n");
530 assert_eq!(parse_commit(bare.as_bytes()).unwrap().message, b"");
531 let empty = format!("tree {tree}\n\n");
532 let fields = parse_commit(empty.as_bytes()).unwrap();
533 assert_eq!(fields.message, b"");
534 assert_eq!(fields.author, None);
535
536 // A parent after another header is not a parent.
537 let late = format!("tree {tree}\nauthor x <y> 1 +0000\nparent {parent}\n\n");
538 assert!(parse_commit(late.as_bytes()).unwrap().parents.is_empty());
539
540 assert!(parse_commit(b"").is_err());
541 assert!(parse_commit(b"parent x\n").is_err());
542 assert!(parse_commit(b"tree 1234\n").is_err());
543 }
544
545 /// Name, email, seconds and offset.
546 type Expected<'a> = (&'a [u8], &'a [u8], i64, i64);
547
548 #[test]
549 fn odd_signatures_never_fail() {
550 let cases: &[(&[u8], Expected<'_>)] = &[
551 (b"Name <e> 5 +0000", (b"Name", b"e", 5, 0)),
552 (b"Name<e>5 -0130", (b"Name", b"e", 5, -90)),
553 (b" Spaced <e> 7 +0200 ", (b"Spaced", b"e", 7, 120)),
554 (b"<> 0 +0000", (b"", b"", 0, 0)),
555 (b"No email at all", (b"No email at all", b"", 0, 0)),
556 (b"Open <bracket only", (b"Open <bracket only", b"", 0, 0)),
557 (b"Name <e>", (b"Name", b"e", 0, 0)),
558 (b"Name <e> garbage +0100", (b"Name", b"e", 0, 60)),
559 (b"Name <e> -5 +0000", (b"Name", b"e", -5, 0)),
560 (
561 b"Name <e> 99999999999999999999 +0000",
562 (b"Name", b"e", 0, 0),
563 ),
564 (b"Name <e> 1 +05030", (b"Name", b"e", 1, 3030)),
565 // The email ends at the first '>'; the next words are read as
566 // they come, so "b>" is an unreadable time and "1" the offset.
567 (b"Name <a> b> 1 +0000", (b"Name", b"a", 0, 1)),
568 ];
569 for (line, (name, email, seconds, offset)) in cases {
570 let signature = parse_signature(line);
571 assert_eq!(
572 (
573 signature.name.as_slice(),
574 signature.email.as_slice(),
575 signature.seconds,
576 signature.offset_minutes
577 ),
578 (*name, *email, *seconds, *offset),
579 "{}",
580 String::from_utf8_lossy(line)
581 );
582 }
583 }
584
585 #[test]
586 fn generated_commits_read_back() {
587 let author = Signature {
588 name: b"Ada Lovelace".to_vec(),
589 email: b"ada@example.org".to_vec(),
590 seconds: 1_700_000_000,
591 offset_minutes: -330,
592 };
593 let extras = vec![(b"x-note".to_vec(), b"one\ntwo".to_vec())];
594 let bytes = encode_commit(oid(1), &[oid(2)], &author, &author, &extras, b"msg\n").unwrap();
595 let text = String::from_utf8(bytes.clone()).unwrap();
596 assert!(text.contains("author Ada Lovelace <ada@example.org> 1700000000 -0530\n"));
597 assert!(text.contains("x-note one\n two\n\nmsg\n"));
598 let fields = parse_commit(&bytes).unwrap();
599 assert_eq!(fields.tree, oid(1));
600 assert_eq!(fields.parents, [oid(2)]);
601 assert_eq!(parse_signature(fields.author.unwrap()), author);
602 assert_eq!(fields.message, b"msg\n");
603
604 let mut bad = author.clone();
605 bad.name = b"a <b>".to_vec();
606 assert!(encode_commit(oid(1), &[], &bad, &author, &[], b"").is_err());
607 let mut far = author.clone();
608 far.offset_minutes = 100 * 60;
609 assert!(encode_commit(oid(1), &[], &far, &author, &[], b"").is_err());
610 for key in [&b""[..], b"tree", b"a b", b"a\nb"] {
611 let extras = vec![(key.to_vec(), b"v".to_vec())];
612 assert!(encode_commit(oid(1), &[], &author, &author, &extras, b"").is_err());
613 }
614 }
615
616 #[test]
617 fn tags() {
618 let target = oid(0x42);
619 let text = format!(
620 "object {target}\ntype commit\ntag v1\ntagger T <t@example.org> 1 +0000\n\nmsg\n"
621 );
622 assert_eq!(parse_tag(text.as_bytes()), Ok(target));
623 assert!(parse_tag(b"type commit\n").is_err());
624 }
625}