Skip to content
refs
History
180 lines · 8.3 KBRaw
1const encoder = new TextEncoder();
2const decoder = new TextDecoder();
3
4type Bytes = Uint8Array<ArrayBuffer>;
5
6const PACK_TYPES = { commit: 1, tree: 2, blob: 3 } as const;
7
8export interface GitObject {
9 readonly type: "commit" | "tree" | "blob";
10 readonly body: Bytes;
11 readonly hash: string;
12}
13
14export interface TreeEntry {
15 readonly name: string;
16 readonly mode: string;
17 readonly hash: string;
18}
19
20function concat(parts: readonly Uint8Array[]): Bytes {
21 const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
22 let at = 0;
23 for (const part of parts) {
24 out.set(part, at);
25 at += part.length;
26 }
27 return out;
28}
29
30function toHex(bytes: Uint8Array): string {
31 return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join("");
32}
33
34function fromHex(hash: string): Bytes {
35 return Uint8Array.from(hash.match(/../g)!.map((pair) => parseInt(pair, 16)));
36}
37
38async function sha1(bytes: Bytes): Promise<Bytes> {
39 return new Uint8Array(await crypto.subtle.digest("SHA-1", bytes));
40}
41
42export async function gitObject(type: GitObject["type"], body: Bytes): Promise<GitObject> {
43 return { type, body, hash: toHex(await sha1(concat([encoder.encode(`${type} ${body.length}\0`), body]))) };
44}
45
46/** A tree object's body, with entries in git's order: byte order of the name, a directory's name ending in "/". */
47export function treeBody(entries: readonly TreeEntry[]): Bytes {
48 const key = (entry: TreeEntry) => encoder.encode(entry.mode === "40000" ? `${entry.name}/` : entry.name);
49 const compare = (a: Uint8Array, b: Uint8Array) => {
50 for (let index = 0; index < Math.min(a.length, b.length); index++) if (a[index] !== b[index]) return a[index] - b[index];
51 return a.length - b.length;
52 };
53 const sorted = [...entries].sort((a, b) => compare(key(a), key(b)));
54 return concat(sorted.flatMap((entry) => [encoder.encode(`${entry.mode} ${entry.name}\0`), fromHex(entry.hash)]));
55}
56
57export function commitBody(input: { tree: string; parents: readonly string[]; author: { name: string; email: string }; at: number; message: string }): Bytes {
58 const identity = `${input.author.name.replace(/[<>\n]/g, "")} <${input.author.email.replace(/[<>\n]/g, "")}> ${input.at} +0000`;
59 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")}`);
60}
61
62async function deflate(bytes: Bytes): Promise<Bytes> {
63 return new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate"))).arrayBuffer());
64}
65
66/** A version 2 packfile holding `objects` whole, each zlib-compressed. */
67export async function packfile(objects: readonly GitObject[]): Promise<Bytes> {
68 const header = new Uint8Array(12);
69 header.set(encoder.encode("PACK"));
70 new DataView(header.buffer).setUint32(4, 2);
71 new DataView(header.buffer).setUint32(8, objects.length);
72 const entries = await Promise.all(
73 objects.map(async (object) => {
74 let size = object.body.length;
75 const head = [(PACK_TYPES[object.type] << 4) | (size & 0x0f)];
76 size >>= 4;
77 while (size > 0) {
78 head[head.length - 1] |= 0x80;
79 head.push(size & 0x7f);
80 size >>= 7;
81 }
82 return concat([Uint8Array.from(head), await deflate(object.body)]);
83 }),
84 );
85 const body = concat([header, ...entries]);
86 return concat([body, await sha1(body)]);
87}
88
89function pktLine(text: string): Bytes {
90 const payload = encoder.encode(text);
91 return concat([encoder.encode((payload.length + 4).toString(16).padStart(4, "0")), payload]);
92}
93
94/** The ref update lines in a receive-pack report: `ok <ref>` or `ng <ref> <reason>`, and `unpack <status>`. */
95export function parseReport(bytes: Uint8Array): string[] {
96 const lines: string[] = [];
97 for (let at = 0; at + 4 <= bytes.length; ) {
98 const length = parseInt(decoder.decode(bytes.subarray(at, at + 4)), 16);
99 if (!length) {
100 at += 4;
101 continue;
102 }
103 lines.push(decoder.decode(bytes.subarray(at + 4, at + length)).replace(/\n$/, ""));
104 at += length;
105 }
106 return lines;
107}
108
109/**
110 * Moves `ref` from `from` to `to` in the repository, sending `objects` with it, over git's receive-pack. The
111 * update is refused unless `ref` still points at `from`, so a concurrent push is never overwritten.
112 */
113export async function pushRef(handle: ArtifactsRepo, ref: string, from: string, to: string, objects: readonly GitObject[]): Promise<{ ok: true } | { ok: false; reason: string }> {
114 const [info, token] = await Promise.all([handle.info(), handle.createToken("write", 60)]);
115 const body = concat([pktLine(`${from} ${to} ${ref}\0report-status\n`), encoder.encode("0000"), await packfile(objects)]);
116 const response = await fetch(`${info.remote}/git-receive-pack`, {
117 method: "POST",
118 headers: { authorization: `Bearer ${token.plaintext}`, "content-type": "application/x-git-receive-pack-request", accept: "application/x-git-receive-pack-result" },
119 body,
120 });
121 if (!response.ok) return { ok: false, reason: `the git server answered ${response.status}` };
122 const report = parseReport(new Uint8Array(await response.arrayBuffer()));
123 const unpack = report.find((line) => line.startsWith("unpack "));
124 const result = report.find((line) => line === `ok ${ref}` || line.startsWith(`ng ${ref} `));
125 if (unpack !== "unpack ok") return { ok: false, reason: unpack ?? "the git server sent no report" };
126 if (result !== `ok ${ref}`) return { ok: false, reason: result?.replace(`ng ${ref} `, "") ?? "the git server did not update the branch" };
127 return { ok: true };
128}
129
130type Entry = Pick<ArtifactsTreeEntry, "name" | "mode" | "hash" | "type">;
131
132/**
133 * Three-way merges trees path by path, as git does. A path changed on one side only takes that side, and a
134 * directory changed on both sides (or added or removed on one) merges file by file. A file both sides changed
135 * differently, or a file on one side where the other has a directory, is a conflict. `null` is an empty or
136 * absent tree. Returns the merged tree (null when it ends up empty) and the new tree objects it needs, or the
137 * conflicting paths.
138 */
139export async function mergeTrees(
140 readTree: (hash: string) => Promise<readonly Entry[] | null>,
141 base: string | null,
142 ours: string | null,
143 theirs: string | null,
144 prefix = "",
145): Promise<{ tree: string | null; objects: GitObject[]; conflicts: string[] }> {
146 if (ours === theirs || base === theirs) return { tree: ours, objects: [], conflicts: [] };
147 if (base === ours) return { tree: theirs, objects: [], conflicts: [] };
148 const read = async (hash: string | null) => {
149 if (!hash) return [];
150 const entries = await readTree(hash);
151 if (!entries) throw new Error(`Tree ${hash} not found`);
152 return entries;
153 };
154 const [baseEntries, ourEntries, theirEntries] = await Promise.all([read(base), read(ours), read(theirs)]);
155 const byName = (entries: readonly Entry[]) => new Map(entries.map((entry) => [entry.name, entry]));
156 const [b, o, t] = [byName(baseEntries), byName(ourEntries), byName(theirEntries)];
157 const same = (x?: Entry, y?: Entry) => x?.hash === y?.hash && x?.mode === y?.mode;
158 const directory = (entry?: Entry) => (entry?.type === "tree" ? entry.hash : null);
159 const entries: TreeEntry[] = [];
160 const objects: GitObject[] = [];
161 const conflicts: string[] = [];
162 for (const name of new Set([...o.keys(), ...t.keys()])) {
163 const [was, mine, other] = [b.get(name), o.get(name), t.get(name)];
164 const path = prefix ? `${prefix}/${name}` : name;
165 if (same(mine, other) || same(was, other)) {
166 if (mine) entries.push({ name, mode: mine.mode, hash: mine.hash });
167 } else if (same(was, mine)) {
168 if (other) entries.push({ name, mode: other.mode, hash: other.hash });
169 } else if ((!mine || mine.type === "tree") && (!other || other.type === "tree")) {
170 const merged = await mergeTrees(readTree, directory(was), directory(mine), directory(other), path);
171 objects.push(...merged.objects);
172 conflicts.push(...merged.conflicts);
173 if (merged.tree) entries.push({ name, mode: "40000", hash: merged.tree });
174 } else conflicts.push(path);
175 }
176 if (conflicts.length) return { tree: ours, objects: [], conflicts };
177 if (!entries.length) return { tree: null, objects, conflicts: [] };
178 const tree = await gitObject("tree", treeBody(entries));
179 return { tree: tree.hash, objects: [...objects, tree], conflicts: [] };
180}