import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { test } from "node:test"; import { commitBody, gitObject, mergeTrees, packfile, parseReport, treeBody } from "../gitwrite.ts"; const blob = (n: number) => n.toString(16).padStart(40, "0"); test("hashes objects as git does", async () => { assert.equal((await gitObject("tree", treeBody([]))).hash, "4b825dc642cb6eb9a060e54bf8d69288fbee4904"); const body = commitBody({ tree: "4b825dc642cb6eb9a060e54bf8d69288fbee4904", parents: [], author: { name: "A", email: "a@example.com" }, at: 0, message: "m" }); const expected = createHash("sha1").update(Buffer.concat([Buffer.from(`commit ${body.length}\0`), Buffer.from(body)])).digest("hex"); assert.equal((await gitObject("commit", body)).hash, expected); }); test("orders a directory as if its name ended in a slash", () => { const names = (body: Uint8Array) => [...Buffer.from(body).toString("latin1").matchAll(/\d+ ([^\0]+)\0/g)].map((match) => match[1]); assert.deepEqual(names(treeBody([{ name: "a", mode: "40000", hash: blob(1) }, { name: "a.txt", mode: "100644", hash: blob(2) }, { name: "a-b", mode: "100644", hash: blob(3) }])), ["a-b", "a.txt", "a"]); }); test("writes a version 2 pack with a trailing checksum", async () => { const pack = await packfile([await gitObject("tree", treeBody([]))]); assert.equal(Buffer.from(pack.subarray(0, 4)).toString(), "PACK"); assert.deepEqual([...pack.subarray(4, 12)], [0, 0, 0, 2, 0, 0, 0, 1]); assert.equal(Buffer.from(pack.subarray(-20)).toString("hex"), createHash("sha1").update(pack.subarray(0, -20)).digest("hex")); }); test("reads a receive-pack report", () => { const line = (text: string) => `${(text.length + 4).toString(16).padStart(4, "0")}${text}`; assert.deepEqual(parseReport(new TextEncoder().encode(`${line("unpack ok\n")}${line("ng refs/heads/main failed to update ref\n")}0000`)), ["unpack ok", "ng refs/heads/main failed to update ref"]); }); test("merges trees path by path and reports files both sides changed", async () => { const trees: Record = { base: [{ name: "a", mode: "100644", hash: blob(1), type: "blob" }, { name: "b", mode: "100644", hash: blob(2), type: "blob" }], ours: [{ name: "a", mode: "100644", hash: blob(11), type: "blob" }, { name: "b", mode: "100644", hash: blob(2), type: "blob" }], theirs: [{ name: "a", mode: "100644", hash: blob(1), type: "blob" }, { name: "c", mode: "100644", hash: blob(3), type: "blob" }], clash: [{ name: "a", mode: "100644", hash: blob(12), type: "blob" }, { name: "b", mode: "100644", hash: blob(2), type: "blob" }], }; const read = async (hash: string) => trees[hash] ?? null; const merged = await mergeTrees(read, "base", "ours", "theirs"); assert.deepEqual(merged.conflicts, []); assert.equal(merged.tree, (await gitObject("tree", treeBody([{ name: "a", mode: "100644", hash: blob(11) }, { name: "c", mode: "100644", hash: blob(3) }]))).hash); assert.deepEqual((await mergeTrees(read, "base", "ours", "clash")).conflicts, ["a"]); });