const encoder = new TextEncoder(); const decoder = new TextDecoder(); type Bytes = Uint8Array; const PACK_TYPES = { commit: 1, tree: 2, blob: 3 } as const; export interface GitObject { readonly type: "commit" | "tree" | "blob"; readonly body: Bytes; readonly hash: string; } export interface TreeEntry { readonly name: string; readonly mode: string; readonly hash: string; } function concat(parts: readonly Uint8Array[]): Bytes { const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0)); let at = 0; for (const part of parts) { out.set(part, at); at += part.length; } return out; } function toHex(bytes: Uint8Array): string { return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); } function fromHex(hash: string): Bytes { return Uint8Array.from(hash.match(/../g)!.map((pair) => parseInt(pair, 16))); } async function sha1(bytes: Bytes): Promise { return new Uint8Array(await crypto.subtle.digest("SHA-1", bytes)); } export async function gitObject(type: GitObject["type"], body: Bytes): Promise { return { type, body, hash: toHex(await sha1(concat([encoder.encode(`${type} ${body.length}\0`), body]))) }; } /** A tree object's body, with entries in git's order: byte order of the name, a directory's name ending in "/". */ export function treeBody(entries: readonly TreeEntry[]): Bytes { const key = (entry: TreeEntry) => encoder.encode(entry.mode === "40000" ? `${entry.name}/` : entry.name); const compare = (a: Uint8Array, b: Uint8Array) => { for (let index = 0; index < Math.min(a.length, b.length); index++) if (a[index] !== b[index]) return a[index] - b[index]; return a.length - b.length; }; const sorted = [...entries].sort((a, b) => compare(key(a), key(b))); return concat(sorted.flatMap((entry) => [encoder.encode(`${entry.mode} ${entry.name}\0`), fromHex(entry.hash)])); } export function commitBody(input: { tree: string; parents: readonly string[]; author: { name: string; email: string }; at: number; message: string }): Bytes { const identity = `${input.author.name.replace(/[<>\n]/g, "")} <${input.author.email.replace(/[<>\n]/g, "")}> ${input.at} +0000`; return encoder.encode(`tree ${input.tree}\n${input.parents.map((parent) => `parent ${parent}\n`).join("")}author ${identity}\ncommitter ${identity}\n\n${input.message.replace(/\n*$/, "\n")}`); } async function deflate(bytes: Bytes): Promise { return new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate"))).arrayBuffer()); } /** A version 2 packfile holding `objects` whole, each zlib-compressed. */ export async function packfile(objects: readonly GitObject[]): Promise { const header = new Uint8Array(12); header.set(encoder.encode("PACK")); new DataView(header.buffer).setUint32(4, 2); new DataView(header.buffer).setUint32(8, objects.length); const entries = await Promise.all( objects.map(async (object) => { let size = object.body.length; const head = [(PACK_TYPES[object.type] << 4) | (size & 0x0f)]; size >>= 4; while (size > 0) { head[head.length - 1] |= 0x80; head.push(size & 0x7f); size >>= 7; } return concat([Uint8Array.from(head), await deflate(object.body)]); }), ); const body = concat([header, ...entries]); return concat([body, await sha1(body)]); } function pktLine(text: string): Bytes { const payload = encoder.encode(text); return concat([encoder.encode((payload.length + 4).toString(16).padStart(4, "0")), payload]); } /** The ref update lines in a receive-pack report: `ok ` or `ng `, and `unpack `. */ export function parseReport(bytes: Uint8Array): string[] { const lines: string[] = []; for (let at = 0; at + 4 <= bytes.length; ) { const length = parseInt(decoder.decode(bytes.subarray(at, at + 4)), 16); if (!length) { at += 4; continue; } lines.push(decoder.decode(bytes.subarray(at + 4, at + length)).replace(/\n$/, "")); at += length; } return lines; } /** * Moves `ref` from `from` to `to` in the repository, sending `objects` with it, over git's receive-pack. The * update is refused unless `ref` still points at `from`, so a concurrent push is never overwritten. */ export async function pushRef(handle: ArtifactsRepo, ref: string, from: string, to: string, objects: readonly GitObject[]): Promise<{ ok: true } | { ok: false; reason: string }> { const [info, token] = await Promise.all([handle.info(), handle.createToken("write", 60)]); const body = concat([pktLine(`${from} ${to} ${ref}\0report-status\n`), encoder.encode("0000"), await packfile(objects)]); const response = await fetch(`${info.remote}/git-receive-pack`, { method: "POST", headers: { authorization: `Bearer ${token.plaintext}`, "content-type": "application/x-git-receive-pack-request", accept: "application/x-git-receive-pack-result" }, body, }); if (!response.ok) return { ok: false, reason: `the git server answered ${response.status}` }; const report = parseReport(new Uint8Array(await response.arrayBuffer())); const unpack = report.find((line) => line.startsWith("unpack ")); const result = report.find((line) => line === `ok ${ref}` || line.startsWith(`ng ${ref} `)); if (unpack !== "unpack ok") return { ok: false, reason: unpack ?? "the git server sent no report" }; if (result !== `ok ${ref}`) return { ok: false, reason: result?.replace(`ng ${ref} `, "") ?? "the git server did not update the branch" }; return { ok: true }; } type Entry = Pick; /** * Three-way merges trees path by path, as git does. A path changed on one side only takes that side, and a * directory changed on both sides (or added or removed on one) merges file by file. A file both sides changed * differently, or a file on one side where the other has a directory, is a conflict. `null` is an empty or * absent tree. Returns the merged tree (null when it ends up empty) and the new tree objects it needs, or the * conflicting paths. */ export async function mergeTrees( readTree: (hash: string) => Promise, base: string | null, ours: string | null, theirs: string | null, prefix = "", ): Promise<{ tree: string | null; objects: GitObject[]; conflicts: string[] }> { if (ours === theirs || base === theirs) return { tree: ours, objects: [], conflicts: [] }; if (base === ours) return { tree: theirs, objects: [], conflicts: [] }; const read = async (hash: string | null) => { if (!hash) return []; const entries = await readTree(hash); if (!entries) throw new Error(`Tree ${hash} not found`); return entries; }; const [baseEntries, ourEntries, theirEntries] = await Promise.all([read(base), read(ours), read(theirs)]); const byName = (entries: readonly Entry[]) => new Map(entries.map((entry) => [entry.name, entry])); const [b, o, t] = [byName(baseEntries), byName(ourEntries), byName(theirEntries)]; const same = (x?: Entry, y?: Entry) => x?.hash === y?.hash && x?.mode === y?.mode; const directory = (entry?: Entry) => (entry?.type === "tree" ? entry.hash : null); const entries: TreeEntry[] = []; const objects: GitObject[] = []; const conflicts: string[] = []; for (const name of new Set([...o.keys(), ...t.keys()])) { const [was, mine, other] = [b.get(name), o.get(name), t.get(name)]; const path = prefix ? `${prefix}/${name}` : name; if (same(mine, other) || same(was, other)) { if (mine) entries.push({ name, mode: mine.mode, hash: mine.hash }); } else if (same(was, mine)) { if (other) entries.push({ name, mode: other.mode, hash: other.hash }); } else if ((!mine || mine.type === "tree") && (!other || other.type === "tree")) { const merged = await mergeTrees(readTree, directory(was), directory(mine), directory(other), path); objects.push(...merged.objects); conflicts.push(...merged.conflicts); if (merged.tree) entries.push({ name, mode: "40000", hash: merged.tree }); } else conflicts.push(path); } if (conflicts.length) return { tree: ours, objects: [], conflicts }; if (!entries.length) return { tree: null, objects, conflicts: [] }; const tree = await gitObject("tree", treeBody(entries)); return { tree: tree.hash, objects: [...objects, tree], conflicts: [] }; }