gunnar_server/
first_commit.rs1use std::io::Write as _;
16
17pub const AUTHOR: &str = "Gunnar <noreply@gunnar.invalid>";
19
20const OBJ_COMMIT: u8 = 1;
22const OBJ_TREE: u8 = 2;
23const OBJ_BLOB: u8 = 3;
24
25struct Object {
27 num: u8,
28 word: &'static str,
29 content: Vec<u8>,
30}
31
32pub fn object_id(kind: gix_hash::Kind, word: &str, content: &[u8]) -> Result<gix_hash::ObjectId, String> {
34 let mut h = gix_hash::hasher(kind);
35 h.update(format!("{word} {}\0", content.len()).as_bytes());
36 h.update(content);
37 h.try_finalize().map_err(|e| format!("hashing a {word}: {e:?}"))
38}
39
40pub fn first_commit_pack(kind: gix_hash::Kind, name: &str, text: &[u8], message: &str, when_unix: i64) -> Result<(Vec<u8>, String), String> {
44 if name.is_empty() || name.contains('/') || name.contains('\0') {
45 return Err(format!("{name:?} is not a file name at the repository's root"));
46 }
47 let blob_id = object_id(kind, "blob", text)?;
48 let mut tree = Vec::new();
49 tree.extend_from_slice(format!("100644 {name}\0").as_bytes());
50 tree.extend_from_slice(blob_id.as_bytes());
51 let tree_id = object_id(kind, "tree", &tree)?;
52 let ident = format!("{AUTHOR} {when_unix} +0000");
53 let message = if message.ends_with('\n') { message.to_string() } else { format!("{message}\n") };
54 let commit = format!("tree {}\nauthor {ident}\ncommitter {ident}\n\n{message}", tree_id.to_hex()).into_bytes();
55 let commit_id = object_id(kind, "commit", &commit)?;
56 let objects = [
57 Object { num: OBJ_BLOB, word: "blob", content: text.to_vec() },
58 Object { num: OBJ_TREE, word: "tree", content: tree },
59 Object { num: OBJ_COMMIT, word: "commit", content: commit },
60 ];
61 Ok((pack(kind, &objects)?, commit_id.to_hex().to_string()))
62}
63
64fn pack(kind: gix_hash::Kind, objects: &[Object]) -> Result<Vec<u8>, String> {
66 let mut out = Vec::new();
67 out.extend_from_slice(b"PACK");
68 out.extend_from_slice(&2u32.to_be_bytes());
69 out.extend_from_slice(&(objects.len() as u32).to_be_bytes());
70 for o in objects {
71 debug_assert!(!o.word.is_empty());
72 let mut size = o.content.len() as u64;
74 let mut byte = (o.num << 4) | (size & 0x0f) as u8;
75 size >>= 4;
76 while size > 0 {
77 out.push(byte | 0x80);
78 byte = (size & 0x7f) as u8;
79 size >>= 7;
80 }
81 out.push(byte);
82 let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default());
83 z.write_all(&o.content).map_err(|e| e.to_string())?;
84 out.extend_from_slice(&z.finish().map_err(|e| e.to_string())?);
85 }
86 let mut h = gix_hash::hasher(kind);
87 h.update(&out);
88 let trailer = h.try_finalize().map_err(|e| format!("the pack's trailer: {e:?}"))?;
89 out.extend_from_slice(trailer.as_bytes());
90 Ok(out)
91}
92
93