@catamorphic/git 0.0.0-stage → 0.1.0-alpha.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE.txt +202 -0
  2. package/NOTICE.txt +32 -0
  3. package/dist/checkout-remote-backend.d.ts +12 -0
  4. package/dist/checkout-remote-backend.d.ts.map +1 -0
  5. package/dist/file-reads.d.ts +15 -0
  6. package/dist/file-reads.d.ts.map +1 -0
  7. package/dist/fs-backend.d.ts +30 -0
  8. package/dist/fs-backend.d.ts.map +1 -0
  9. package/dist/fs-remote-backend.d.ts +47 -0
  10. package/dist/fs-remote-backend.d.ts.map +1 -0
  11. package/dist/git-object-codec.d.ts +31 -0
  12. package/dist/git-object-codec.d.ts.map +1 -0
  13. package/dist/git-sync.d.ts +61 -0
  14. package/dist/git-sync.d.ts.map +1 -0
  15. package/dist/in-memory-object-store.d.ts +23 -0
  16. package/dist/in-memory-object-store.d.ts.map +1 -0
  17. package/dist/index.d.ts +24 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +4746 -0
  20. package/dist/index.js.map +32 -0
  21. package/dist/migrate-workflow.d.ts +12 -0
  22. package/dist/migrate-workflow.d.ts.map +1 -0
  23. package/dist/native-git.d.ts +25 -0
  24. package/dist/native-git.d.ts.map +1 -0
  25. package/dist/native-project-repo.d.ts +57 -0
  26. package/dist/native-project-repo.d.ts.map +1 -0
  27. package/dist/network-sync.d.ts +58 -0
  28. package/dist/network-sync.d.ts.map +1 -0
  29. package/dist/network.d.ts +81 -0
  30. package/dist/network.d.ts.map +1 -0
  31. package/dist/object-remote-backend.d.ts +95 -0
  32. package/dist/object-remote-backend.d.ts.map +1 -0
  33. package/dist/object-store.d.ts +42 -0
  34. package/dist/object-store.d.ts.map +1 -0
  35. package/dist/origin-draft.d.ts +264 -0
  36. package/dist/origin-draft.d.ts.map +1 -0
  37. package/dist/origin-objects.d.ts +201 -0
  38. package/dist/origin-objects.d.ts.map +1 -0
  39. package/dist/personal-files.d.ts +6 -0
  40. package/dist/personal-files.d.ts.map +1 -0
  41. package/dist/project-manager.d.ts +214 -0
  42. package/dist/project-manager.d.ts.map +1 -0
  43. package/dist/project-repo.d.ts +79 -0
  44. package/dist/project-repo.d.ts.map +1 -0
  45. package/dist/ref-moved-error.d.ts +13 -0
  46. package/dist/ref-moved-error.d.ts.map +1 -0
  47. package/dist/ref-names.d.ts +18 -0
  48. package/dist/ref-names.d.ts.map +1 -0
  49. package/dist/types.d.ts +276 -0
  50. package/dist/types.d.ts.map +1 -0
  51. package/dist/workspace-mirror.d.ts +110 -0
  52. package/dist/workspace-mirror.d.ts.map +1 -0
  53. package/package.json +53 -4
  54. package/src/checkout-remote-backend.ts +154 -0
  55. package/src/diff3.d.ts +16 -0
  56. package/src/file-reads.ts +53 -0
  57. package/src/fs-backend.ts +206 -0
  58. package/src/fs-remote-backend.ts +252 -0
  59. package/src/git-object-codec.ts +87 -0
  60. package/src/git-sync.ts +539 -0
  61. package/src/in-memory-object-store.ts +60 -0
  62. package/src/index.ts +110 -0
  63. package/src/migrate-workflow.ts +30 -0
  64. package/src/native-git.ts +177 -0
  65. package/src/native-project-repo.ts +515 -0
  66. package/src/network-sync.ts +239 -0
  67. package/src/network.ts +269 -0
  68. package/src/object-remote-backend.ts +366 -0
  69. package/src/object-store.ts +41 -0
  70. package/src/origin-draft.ts +1033 -0
  71. package/src/origin-objects.ts +906 -0
  72. package/src/personal-files.ts +57 -0
  73. package/src/project-manager.ts +743 -0
  74. package/src/project-repo.ts +800 -0
  75. package/src/ref-moved-error.ts +18 -0
  76. package/src/ref-names.ts +47 -0
  77. package/src/types.ts +289 -0
  78. package/src/workspace-mirror.ts +400 -0
  79. package/README.md +0 -3
@@ -0,0 +1,906 @@
1
+ import diff3Merge from "diff3";
2
+ import ignore, { type Ignore } from "ignore";
3
+ import {
4
+ type GitObjectType,
5
+ type ParsedCommit,
6
+ parseCommit,
7
+ } from "./git-object-codec.js";
8
+ import { isPersonalFile } from "./personal-files.js";
9
+ import type { ConflictEntry, OriginRepo } from "./types.js";
10
+
11
+ /**
12
+ * Object-level reads and writes against a project's origin, with no working
13
+ * copy (ADR 0191): trees are walked, rebuilt, and merged in memory, and new
14
+ * blobs, trees, and commits are written straight to the origin. Git objects
15
+ * are immutable, so every read may go through a process-wide cache keyed by
16
+ * origin and object id, which is safe to lose.
17
+ */
18
+
19
+ export interface TreeEntry {
20
+ mode: string;
21
+ /** The name as text, for matching paths. */
22
+ name: string;
23
+ /** The name exactly as stored, so names that are not UTF-8 survive. */
24
+ nameBytes: Uint8Array;
25
+ oid: string;
26
+ }
27
+
28
+ /** A file in a tree: its blob id and mode (`100644`, `100755`, `120000`). */
29
+ export interface TreeFile {
30
+ oid: string;
31
+ mode: string;
32
+ }
33
+
34
+ /**
35
+ * One change to apply to a tree: a blob already written (keeping the old
36
+ * entry's mode unless one is given), or `null` to delete.
37
+ */
38
+ export type TreeChange = { oid: string; mode?: string } | null;
39
+
40
+ export const EMPTY_TREE_ID = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
41
+ const FILE_MODE = "100644";
42
+ export const SYMLINK_MODE = "120000";
43
+ const SUBMODULE_MODE = "160000";
44
+ /** Folders a project's history never contains, as the checkout walker skips them. */
45
+ const ALWAYS_IGNORED = new Set(["node_modules", ".git", "dist", ".turbo"]);
46
+ /** Object writes in flight at once. */
47
+ const WRITE_CONCURRENCY = 16;
48
+
49
+ export function isTreeMode(mode: string): boolean {
50
+ return mode === "40000" || mode === "040000";
51
+ }
52
+
53
+ /** An error with a Node-style `code`, as filesystem-backed repos throw. */
54
+ export class DraftPathError extends Error {
55
+ readonly code: "ENOENT" | "ENOTDIR" | "EISDIR" | "ELOOP";
56
+ constructor(input: {
57
+ code: "ENOENT" | "ENOTDIR" | "EISDIR" | "ELOOP";
58
+ path: string;
59
+ }) {
60
+ super(
61
+ input.code === "ENOENT"
62
+ ? `No such file: ${input.path}`
63
+ : input.code === "EISDIR"
64
+ ? `${input.path} is a folder`
65
+ : input.code === "ENOTDIR"
66
+ ? `A parent of ${input.path} is a file`
67
+ : "Symbolic links cannot be read or written here",
68
+ );
69
+ this.name = "DraftPathError";
70
+ this.code = input.code;
71
+ }
72
+ }
73
+
74
+ /** Paths the project's ignore rules keep out of its history. */
75
+ export class DraftIgnoredPathError extends Error {
76
+ readonly paths: readonly string[];
77
+ constructor(paths: readonly string[]) {
78
+ super(
79
+ `${paths.join(", ")} ${paths.length === 1 ? "is" : "are"} ignored by the project's .gitignore and never become part of the program.`,
80
+ );
81
+ this.name = "DraftIgnoredPathError";
82
+ this.paths = paths;
83
+ }
84
+ }
85
+
86
+ /** A text resolution offered for a file that is not text. */
87
+ export class DraftBinaryResolutionError extends Error {
88
+ readonly paths: readonly string[];
89
+ constructor(paths: readonly string[]) {
90
+ super(
91
+ `${paths.join(", ")} ${paths.length === 1 ? "is not a text file" : "are not text files"}, so text cannot resolve ${paths.length === 1 ? "it" : "them"}. Discard your draft's change or publish it again after taking the published version.`,
92
+ );
93
+ this.name = "DraftBinaryResolutionError";
94
+ this.paths = paths;
95
+ }
96
+ }
97
+
98
+ /**
99
+ * Immutable objects read from origins, bounded by bytes and evicted least
100
+ * recently used. One per process is plenty; losing it only costs re-reads.
101
+ */
102
+ export class GitObjectCache {
103
+ private readonly entries = new Map<
104
+ string,
105
+ { type: GitObjectType; data: Uint8Array }
106
+ >();
107
+ private bytes = 0;
108
+
109
+ constructor(private readonly maxBytes = 64 * 1024 * 1024) {}
110
+
111
+ get(key: string): { type: GitObjectType; data: Uint8Array } | undefined {
112
+ const entry = this.entries.get(key);
113
+ if (!entry) return undefined;
114
+ this.entries.delete(key);
115
+ this.entries.set(key, entry);
116
+ return entry;
117
+ }
118
+
119
+ set(key: string, value: { type: GitObjectType; data: Uint8Array }): void {
120
+ if (this.entries.has(key) || value.data.byteLength > this.maxBytes / 16)
121
+ return;
122
+ this.entries.set(key, value);
123
+ this.bytes += value.data.byteLength;
124
+ for (const [oldest, entry] of this.entries) {
125
+ if (this.bytes <= this.maxBytes) break;
126
+ this.entries.delete(oldest);
127
+ this.bytes -= entry.data.byteLength;
128
+ }
129
+ }
130
+ }
131
+
132
+ /** Map with at most `limit` calls in flight, keeping input order. */
133
+ export async function mapLimit<T, R>(
134
+ items: readonly T[],
135
+ limit: number,
136
+ fn: (item: T) => Promise<R>,
137
+ ): Promise<R[]> {
138
+ const results: R[] = new Array(items.length);
139
+ let next = 0;
140
+ const worker = async () => {
141
+ while (next < items.length) {
142
+ const index = next++;
143
+ const item = items[index];
144
+ if (item !== undefined) results[index] = await fn(item);
145
+ }
146
+ };
147
+ await Promise.all(
148
+ Array.from({ length: Math.min(limit, items.length) }, worker),
149
+ );
150
+ return results;
151
+ }
152
+
153
+ export function parseTree(data: Uint8Array): TreeEntry[] {
154
+ const entries: TreeEntry[] = [];
155
+ const decoder = new TextDecoder("utf-8");
156
+ let i = 0;
157
+ while (i < data.length) {
158
+ let space = i;
159
+ while (space < data.length && data[space] !== 0x20) space++;
160
+ let nul = space + 1;
161
+ while (nul < data.length && data[nul] !== 0x00) nul++;
162
+ const oid = Array.from(data.slice(nul + 1, nul + 21))
163
+ .map((byte) => byte.toString(16).padStart(2, "0"))
164
+ .join("");
165
+ const nameBytes = data.slice(space + 1, nul);
166
+ entries.push({
167
+ mode: decoder.decode(data.slice(i, space)),
168
+ name: decoder.decode(nameBytes),
169
+ nameBytes,
170
+ oid,
171
+ });
172
+ i = nul + 21;
173
+ }
174
+ return entries;
175
+ }
176
+
177
+ /** A map key for a stored name: its bytes, not their UTF-8 reading. */
178
+ function nameKey(bytes: Uint8Array): string {
179
+ return Buffer.from(bytes).toString("hex");
180
+ }
181
+
182
+ /** A new entry named by text. */
183
+ function entryNamed(name: string, mode: string, oid: string): TreeEntry {
184
+ return { name, nameBytes: new TextEncoder().encode(name), mode, oid };
185
+ }
186
+
187
+ /** Git's tree order: bytewise by name, a tree sorting as if named `name/`. */
188
+ function treeSortKey(entry: TreeEntry): Uint8Array {
189
+ if (!isTreeMode(entry.mode)) return entry.nameBytes;
190
+ const key = new Uint8Array(entry.nameBytes.length + 1);
191
+ key.set(entry.nameBytes);
192
+ key[entry.nameBytes.length] = 0x2f;
193
+ return key;
194
+ }
195
+
196
+ function compareBytes(a: Uint8Array, b: Uint8Array): number {
197
+ const length = Math.min(a.length, b.length);
198
+ for (let i = 0; i < length; i++) {
199
+ const delta = (a[i] ?? 0) - (b[i] ?? 0);
200
+ if (delta !== 0) return delta;
201
+ }
202
+ return a.length - b.length;
203
+ }
204
+
205
+ export function serializeTree(entries: readonly TreeEntry[]): Uint8Array {
206
+ const sorted = [...entries].sort((a, b) =>
207
+ compareBytes(treeSortKey(a), treeSortKey(b)),
208
+ );
209
+ const parts: Uint8Array[] = [];
210
+ for (const entry of sorted) {
211
+ const mode = isTreeMode(entry.mode) ? "40000" : entry.mode;
212
+ parts.push(new TextEncoder().encode(`${mode} `));
213
+ parts.push(entry.nameBytes);
214
+ const oid = new Uint8Array(21);
215
+ for (let i = 0; i < 20; i++)
216
+ oid[i + 1] = Number.parseInt(entry.oid.slice(i * 2, i * 2 + 2), 16);
217
+ parts.push(oid);
218
+ }
219
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
220
+ const out = new Uint8Array(total);
221
+ let offset = 0;
222
+ for (const part of parts) {
223
+ out.set(part, offset);
224
+ offset += part.length;
225
+ }
226
+ return out;
227
+ }
228
+
229
+ function signature(author: { name: string; email: string }): string {
230
+ const clean = (value: string) => value.replace(/[<>\n]/g, "").trim();
231
+ return `${clean(author.name)} <${clean(author.email)}> ${Math.floor(Date.now() / 1000)} +0000`;
232
+ }
233
+
234
+ export function serializeCommit(input: {
235
+ tree: string;
236
+ parents: readonly string[];
237
+ author: { name: string; email: string };
238
+ message: string;
239
+ }): Uint8Array {
240
+ const lines = [
241
+ `tree ${input.tree}`,
242
+ ...input.parents.map((parent) => `parent ${parent}`),
243
+ `author ${signature(input.author)}`,
244
+ `committer ${signature(input.author)}`,
245
+ ];
246
+ const message = input.message.endsWith("\n")
247
+ ? input.message
248
+ : `${input.message}\n`;
249
+ return new TextEncoder().encode(`${lines.join("\n")}\n\n${message}`);
250
+ }
251
+
252
+ /** `.gitignore` matchers by directory, read once per operation. */
253
+ export type IgnoreRules = Map<string, Ignore | null>;
254
+
255
+ /** One path's difference between two trees. */
256
+ export interface TreeDifference {
257
+ path: string;
258
+ before: TreeFile | null;
259
+ after: TreeFile | null;
260
+ }
261
+
262
+ /** Reads and writes of one origin's objects through a shared cache. */
263
+ export class OriginObjects {
264
+ constructor(
265
+ readonly origin: OriginRepo,
266
+ private readonly cache: GitObjectCache,
267
+ ) {}
268
+
269
+ async read(oid: string): Promise<{ type: GitObjectType; data: Uint8Array }> {
270
+ const key = `${this.origin.gitdir}\0${oid}`;
271
+ const cached = this.cache.get(key);
272
+ if (cached) return cached;
273
+ const object = await this.origin.readObject(oid);
274
+ this.cache.set(key, object);
275
+ return object;
276
+ }
277
+
278
+ async write(input: {
279
+ type: GitObjectType;
280
+ data: Uint8Array;
281
+ }): Promise<string> {
282
+ const oid = await this.origin.writeObject(input);
283
+ this.cache.set(`${this.origin.gitdir}\0${oid}`, input);
284
+ return oid;
285
+ }
286
+
287
+ /** Write file contents as blobs, several at once; ids in input order. */
288
+ writeBlobs(contents: readonly Uint8Array[]): Promise<string[]> {
289
+ return mapLimit(contents, WRITE_CONCURRENCY, (data) =>
290
+ this.write({ type: "blob", data }),
291
+ );
292
+ }
293
+
294
+ async commit(oid: string): Promise<ParsedCommit> {
295
+ const object = await this.read(oid);
296
+ if (object.type !== "commit") throw new Error(`${oid} is not a commit`);
297
+ return parseCommit(object.data);
298
+ }
299
+
300
+ async tree(oid: string): Promise<TreeEntry[]> {
301
+ if (oid === EMPTY_TREE_ID) return [];
302
+ const object = await this.read(oid);
303
+ if (object.type !== "tree") throw new Error(`${oid} is not a tree`);
304
+ return parseTree(object.data);
305
+ }
306
+
307
+ async blob(oid: string): Promise<Uint8Array> {
308
+ const object = await this.read(oid);
309
+ if (object.type !== "blob") throw new Error(`${oid} is not a file`);
310
+ return object.data;
311
+ }
312
+
313
+ /**
314
+ * Every file of a tree, keyed by path, optionally only under `prefix`
315
+ * (a directory with its trailing slash, or one file's path). Personal
316
+ * files and submodules are never part of the result.
317
+ */
318
+ async files(
319
+ treeOid: string,
320
+ prefix?: string,
321
+ ): Promise<Map<string, TreeFile>> {
322
+ const files = new Map<string, TreeFile>();
323
+ const walk = async (oid: string, base: string): Promise<void> => {
324
+ const entries = await this.tree(oid);
325
+ await Promise.all(
326
+ entries.map(async (entry) => {
327
+ const filePath = `${base}${entry.name}`;
328
+ if (isPersonalFile(filePath) || entry.mode === SUBMODULE_MODE) return;
329
+ if (prefix !== undefined) {
330
+ const inside = filePath.startsWith(prefix);
331
+ const onTheWay = prefix.startsWith(`${filePath}/`);
332
+ if (!inside && !onTheWay) return;
333
+ }
334
+ if (isTreeMode(entry.mode)) await walk(entry.oid, `${filePath}/`);
335
+ else if (prefix === undefined || filePath.startsWith(prefix))
336
+ files.set(filePath, { oid: entry.oid, mode: entry.mode });
337
+ }),
338
+ );
339
+ };
340
+ await walk(treeOid, "");
341
+ return files;
342
+ }
343
+
344
+ /** One path's entry in a tree, or null when absent. */
345
+ async entry(treeOid: string, filePath: string): Promise<TreeEntry | null> {
346
+ const segments = filePath.split("/").filter(Boolean);
347
+ let current = treeOid;
348
+ for (const [index, segment] of segments.entries()) {
349
+ const found = (await this.tree(current)).find(
350
+ (entry) => entry.name === segment,
351
+ );
352
+ if (!found) return null;
353
+ if (index === segments.length - 1) return found;
354
+ if (found.mode === SYMLINK_MODE)
355
+ throw new DraftPathError({ code: "ELOOP", path: filePath });
356
+ if (!isTreeMode(found.mode)) return null;
357
+ current = found.oid;
358
+ }
359
+ return null;
360
+ }
361
+
362
+ /**
363
+ * Whether a path the tree does not track is ignored: under a folder no
364
+ * project history contains, or matched by the `.gitignore` files of the
365
+ * tree along its way, as a checkout's commit would skip it.
366
+ */
367
+ async isIgnored(
368
+ treeOid: string | null,
369
+ filePath: string,
370
+ rules: IgnoreRules = new Map(),
371
+ ): Promise<boolean> {
372
+ const segments = filePath.split("/");
373
+ if (segments.slice(0, -1).some((segment) => ALWAYS_IGNORED.has(segment)))
374
+ return true;
375
+ if (!treeOid) return false;
376
+ if (await this.entry(treeOid, filePath)) return false;
377
+ let ignored = false;
378
+ for (let depth = 0; depth < segments.length; depth++) {
379
+ const directory = segments.slice(0, depth).join("/");
380
+ const base = directory ? `${directory}/` : "";
381
+ let matcher = rules.get(directory);
382
+ if (matcher === undefined) {
383
+ const entry = await this.entry(treeOid, `${base}.gitignore`).catch(
384
+ () => null,
385
+ );
386
+ matcher =
387
+ entry && !isTreeMode(entry.mode)
388
+ ? ignore().add(new TextDecoder().decode(await this.blob(entry.oid)))
389
+ : null;
390
+ rules.set(directory, matcher);
391
+ }
392
+ if (!matcher) continue;
393
+ const result = matcher.test(filePath.slice(base.length));
394
+ if (result.ignored) ignored = true;
395
+ if (result.unignored) ignored = false;
396
+ }
397
+ return ignored;
398
+ }
399
+
400
+ /**
401
+ * `treeOid` with `changes` applied (path to an existing blob, or `null`
402
+ * to delete), written to the origin. Returns the new tree id. With
403
+ * `skipMissingDeletes`, deleting a path the tree lacks is not an error.
404
+ */
405
+ async writeTree(
406
+ treeOid: string | null,
407
+ changes: ReadonlyMap<string, TreeChange>,
408
+ options?: { skipMissingDeletes?: boolean },
409
+ ): Promise<string> {
410
+ return (
411
+ (await this.rewrite(treeOid, changes, "", options?.skipMissingDeletes)) ??
412
+ this.write({ type: "tree", data: new Uint8Array() })
413
+ );
414
+ }
415
+
416
+ private async rewrite(
417
+ treeOid: string | null,
418
+ changes: ReadonlyMap<string, TreeChange>,
419
+ base: string,
420
+ skipMissingDeletes = false,
421
+ ): Promise<string | null> {
422
+ // Keyed by the stored bytes, so names that are not UTF-8 (and would
423
+ // decode alike) stay distinct entries.
424
+ const entries = new Map(
425
+ (treeOid ? await this.tree(treeOid) : []).map((entry) => [
426
+ nameKey(entry.nameBytes),
427
+ entry,
428
+ ]),
429
+ );
430
+ const keyed = (name: string) => nameKey(new TextEncoder().encode(name));
431
+ const nested = new Map<string, Map<string, TreeChange>>();
432
+ for (const [filePath, change] of changes) {
433
+ const slash = filePath.indexOf("/");
434
+ if (slash >= 0) {
435
+ const directory = filePath.slice(0, slash);
436
+ const inner = nested.get(directory) ?? new Map<string, TreeChange>();
437
+ inner.set(filePath.slice(slash + 1), change);
438
+ nested.set(directory, inner);
439
+ continue;
440
+ }
441
+ const existing = entries.get(keyed(filePath));
442
+ const fullPath = `${base}${filePath}`;
443
+ if (existing && isTreeMode(existing.mode))
444
+ throw new DraftPathError({ code: "EISDIR", path: fullPath });
445
+ if (existing?.mode === SYMLINK_MODE)
446
+ throw new DraftPathError({ code: "ELOOP", path: fullPath });
447
+ if (change === null) {
448
+ if (!existing) {
449
+ if (skipMissingDeletes) continue;
450
+ throw new DraftPathError({ code: "ENOENT", path: fullPath });
451
+ }
452
+ entries.delete(keyed(filePath));
453
+ continue;
454
+ }
455
+ entries.set(
456
+ keyed(filePath),
457
+ existing
458
+ ? { ...existing, oid: change.oid, mode: change.mode ?? existing.mode }
459
+ : entryNamed(filePath, change.mode ?? FILE_MODE, change.oid),
460
+ );
461
+ }
462
+ const children = await Promise.all(
463
+ [...nested].map(async ([directory, inner]) => {
464
+ const existing = entries.get(keyed(directory));
465
+ const fullPath = `${base}${directory}`;
466
+ if (existing?.mode === SYMLINK_MODE)
467
+ throw new DraftPathError({ code: "ELOOP", path: fullPath });
468
+ if (existing && !isTreeMode(existing.mode)) {
469
+ const deleting = [...inner.values()].every(
470
+ (change) => change === null,
471
+ );
472
+ if (deleting && skipMissingDeletes)
473
+ return { directory, oid: existing.oid, keep: true };
474
+ throw new DraftPathError({
475
+ code: deleting ? "ENOENT" : "ENOTDIR",
476
+ path: `${fullPath}/${[...inner.keys()][0] ?? ""}`,
477
+ });
478
+ }
479
+ const oid = await this.rewrite(
480
+ existing?.oid ?? null,
481
+ inner,
482
+ `${fullPath}/`,
483
+ skipMissingDeletes,
484
+ );
485
+ return { directory, oid, keep: false };
486
+ }),
487
+ );
488
+ for (const child of children) {
489
+ if (child.keep) continue;
490
+ const existing = entries.get(keyed(child.directory));
491
+ if (child.oid === null) entries.delete(keyed(child.directory));
492
+ else
493
+ entries.set(
494
+ keyed(child.directory),
495
+ existing
496
+ ? { ...existing, mode: "40000", oid: child.oid }
497
+ : entryNamed(child.directory, "40000", child.oid),
498
+ );
499
+ }
500
+ if (entries.size === 0) return null;
501
+ return this.write({
502
+ type: "tree",
503
+ data: serializeTree([...entries.values()]),
504
+ });
505
+ }
506
+
507
+ async writeCommit(input: {
508
+ tree: string;
509
+ parents: readonly string[];
510
+ author: { name: string; email: string };
511
+ message: string;
512
+ }): Promise<string> {
513
+ return this.write({ type: "commit", data: serializeCommit(input) });
514
+ }
515
+
516
+ /** Paths whose file differs between two trees; equal subtrees are skipped. */
517
+ async diffTrees(
518
+ before: string | null,
519
+ after: string | null,
520
+ ): Promise<TreeDifference[]> {
521
+ const changes: TreeDifference[] = [];
522
+ const fileOf = (entry: TreeEntry | undefined): TreeFile | null =>
523
+ entry && !isTreeMode(entry.mode) && entry.mode !== SUBMODULE_MODE
524
+ ? { oid: entry.oid, mode: entry.mode }
525
+ : null;
526
+ const walk = async (
527
+ a: string | null,
528
+ b: string | null,
529
+ base: string,
530
+ ): Promise<void> => {
531
+ if (a === b) return;
532
+ const left = new Map(
533
+ (a ? await this.tree(a) : []).map((entry) => [entry.name, entry]),
534
+ );
535
+ const right = new Map(
536
+ (b ? await this.tree(b) : []).map((entry) => [entry.name, entry]),
537
+ );
538
+ const names = [...new Set([...left.keys(), ...right.keys()])];
539
+ await Promise.all(
540
+ names.map(async (name) => {
541
+ const filePath = `${base}${name}`;
542
+ if (isPersonalFile(filePath)) return;
543
+ const l = left.get(name);
544
+ const r = right.get(name);
545
+ if (l?.oid === r?.oid && l?.mode === r?.mode) return;
546
+ const lTree = l && isTreeMode(l.mode) ? l.oid : null;
547
+ const rTree = r && isTreeMode(r.mode) ? r.oid : null;
548
+ if (lTree || rTree) await walk(lTree, rTree, `${filePath}/`);
549
+ const lFile = fileOf(l);
550
+ const rFile = fileOf(r);
551
+ if (lFile?.oid !== rFile?.oid || lFile?.mode !== rFile?.mode)
552
+ changes.push({ path: filePath, before: lFile, after: rFile });
553
+ }),
554
+ );
555
+ };
556
+ await walk(before, after, "");
557
+ return changes.sort((x, y) => x.path.localeCompare(y.path));
558
+ }
559
+
560
+ /**
561
+ * Where two commits' histories meet, and how many commits each has that
562
+ * the other lacks. Walks newest first from both tips and stops once only
563
+ * shared history is left, so the cost follows the divergence, not the
564
+ * project's age. The meeting point is a common ancestor that no other
565
+ * common ancestor descends from (the best merge base), chosen by the
566
+ * commit graph.
567
+ */
568
+ async compare(
569
+ left: string,
570
+ right: string,
571
+ ): Promise<{ base: string | null; ahead: number; behind: number }> {
572
+ if (left === right) return { base: left, ahead: 0, behind: 0 };
573
+ const LEFT = 1;
574
+ const RIGHT = 2;
575
+ const BOTH = 3;
576
+ const flags = new Map<string, number>();
577
+ const times = new Map<string, number>();
578
+ const parents = new Map<string, string[]>();
579
+ const queue: string[] = [];
580
+ const push = async (oid: string, flag: number) => {
581
+ const current = flags.get(oid) ?? 0;
582
+ const next = current | flag;
583
+ if (next === current) return;
584
+ flags.set(oid, next);
585
+ if (!times.has(oid)) {
586
+ const commit = await this.commit(oid);
587
+ times.set(oid, commit.author.timestamp);
588
+ parents.set(oid, commit.parents);
589
+ }
590
+ queue.push(oid);
591
+ };
592
+ await push(left, LEFT);
593
+ await push(right, RIGHT);
594
+ let steps = 0;
595
+ while (queue.some((oid) => flags.get(oid) !== BOTH)) {
596
+ if (++steps > 100_000)
597
+ throw new Error("Histories too far apart to compare");
598
+ queue.sort((a, b) => (times.get(a) ?? 0) - (times.get(b) ?? 0));
599
+ const oid = queue.pop();
600
+ if (!oid) break;
601
+ const flag = flags.get(oid) ?? 0;
602
+ for (const parent of parents.get(oid) ?? []) await push(parent, flag);
603
+ }
604
+ let ahead = 0;
605
+ let behind = 0;
606
+ const common: string[] = [];
607
+ for (const [oid, flag] of flags) {
608
+ if (flag === LEFT) ahead++;
609
+ else if (flag === RIGHT) behind++;
610
+ else if (flag === BOTH) common.push(oid);
611
+ }
612
+ // A common commit is not the best base when another common commit
613
+ // descends from it.
614
+ const beneath = new Set<string>();
615
+ for (const oid of common) {
616
+ const stack = [...(parents.get(oid) ?? [])];
617
+ while (stack.length > 0) {
618
+ const ancestor = stack.pop();
619
+ if (!ancestor || beneath.has(ancestor) || !flags.has(ancestor))
620
+ continue;
621
+ beneath.add(ancestor);
622
+ stack.push(...(parents.get(ancestor) ?? []));
623
+ }
624
+ }
625
+ const best = common
626
+ .filter((oid) => !beneath.has(oid))
627
+ .sort(
628
+ (a, b) => (times.get(b) ?? 0) - (times.get(a) ?? 0) || (a < b ? -1 : 1),
629
+ );
630
+ return { base: best[0] ?? null, ahead, behind };
631
+ }
632
+
633
+ /** Commits reachable from `tip`, newest first. */
634
+ /**
635
+ * Whether commit `sha` is one of `tips` or reachable from them. Walks
636
+ * newest first and stops at commits clearly older than `sha` (a day of
637
+ * clock skew allowed) or after `limit` commits, so a lookup costs the
638
+ * history since that commit, not the project's age. Anything it cannot
639
+ * prove reachable answers false.
640
+ */
641
+ async isReachable(input: {
642
+ sha: string;
643
+ tips: readonly string[];
644
+ limit?: number;
645
+ }): Promise<boolean> {
646
+ const object = await this.read(input.sha).catch(() => null);
647
+ if (object?.type !== "commit") return false;
648
+ const floor = parseCommit(object.data).author.timestamp - 86_400;
649
+ const limit = input.limit ?? 20_000;
650
+ const seen = new Set<string>();
651
+ const queue: Array<{ sha: string; time: number }> = [];
652
+ const enqueue = async (sha: string) => {
653
+ if (seen.has(sha)) return;
654
+ seen.add(sha);
655
+ const commit = await this.commit(sha).catch(() => null);
656
+ if (commit) queue.push({ sha, time: commit.author.timestamp });
657
+ };
658
+ for (const tip of input.tips) await enqueue(tip);
659
+ while (queue.length > 0 && seen.size <= limit) {
660
+ queue.sort((a, b) => a.time - b.time);
661
+ const next = queue.pop();
662
+ if (!next) break;
663
+ if (next.sha === input.sha) return true;
664
+ if (next.time < floor) continue;
665
+ for (const parent of (await this.commit(next.sha)).parents)
666
+ await enqueue(parent);
667
+ }
668
+ return false;
669
+ }
670
+
671
+ async log(
672
+ tip: string,
673
+ maxCount: number,
674
+ ): Promise<
675
+ Array<{
676
+ sha: string;
677
+ message: string;
678
+ author: { name: string; email: string };
679
+ timestamp: number;
680
+ }>
681
+ > {
682
+ const seen = new Set<string>();
683
+ const queue: Array<{ sha: string; commit: ParsedCommit }> = [];
684
+ const out: Array<{
685
+ sha: string;
686
+ message: string;
687
+ author: { name: string; email: string };
688
+ timestamp: number;
689
+ }> = [];
690
+ const enqueue = async (sha: string) => {
691
+ if (seen.has(sha)) return;
692
+ seen.add(sha);
693
+ queue.push({ sha, commit: await this.commit(sha) });
694
+ };
695
+ await enqueue(tip);
696
+ while (queue.length > 0 && out.length < maxCount) {
697
+ queue.sort(
698
+ (a, b) => a.commit.author.timestamp - b.commit.author.timestamp,
699
+ );
700
+ const next = queue.pop();
701
+ if (!next) break;
702
+ out.push({
703
+ sha: next.sha,
704
+ message: next.commit.message,
705
+ author: {
706
+ name: next.commit.author.name,
707
+ email: next.commit.author.email,
708
+ },
709
+ timestamp: next.commit.author.timestamp,
710
+ });
711
+ for (const parent of next.commit.parents) await enqueue(parent);
712
+ }
713
+ return out;
714
+ }
715
+ }
716
+
717
+ /**
718
+ * A three-way merge of trees in memory: every path only one side changed
719
+ * takes that side, a text file both changed merges line by line, and
720
+ * anything else both changed differently is a conflict. `resolutions`
721
+ * settle conflicted paths with the member's content. Ours is the member's
722
+ * side and theirs the published program, as in every conflict a member
723
+ * resolves.
724
+ */
725
+ export async function mergeTrees(input: {
726
+ objects: OriginObjects;
727
+ base: string | null;
728
+ ours: string;
729
+ theirs: string;
730
+ resolutions?: Record<string, string>;
731
+ }): Promise<
732
+ | { status: "merged"; tree: string }
733
+ | { status: "conflict"; conflicts: ConflictEntry[] }
734
+ > {
735
+ const { objects } = input;
736
+ const [oursChanges, theirsChanges] = await Promise.all([
737
+ objects.diffTrees(input.base, input.ours),
738
+ objects.diffTrees(input.base, input.theirs),
739
+ ]);
740
+ const theirsByPath = new Map(
741
+ theirsChanges.map((change) => [change.path, change]),
742
+ );
743
+ const blobOf = async (file: TreeFile | null) =>
744
+ file ? objects.blob(file.oid) : null;
745
+ const changes = new Map<string, TreeChange>();
746
+ const conflicts: ConflictEntry[] = [];
747
+ /** Modes a resolution keeps: from the side each conflicted file came from. */
748
+ const modes = new Map<string, string>();
749
+ const conflict = async (entry: {
750
+ path: string;
751
+ base: TreeFile | null;
752
+ ours: TreeFile | null;
753
+ theirs: TreeFile | null;
754
+ }) => {
755
+ const [base, ours, theirs] = await Promise.all([
756
+ blobOf(entry.base),
757
+ blobOf(entry.ours),
758
+ blobOf(entry.theirs),
759
+ ]);
760
+ const mode = entry.ours?.mode ?? entry.theirs?.mode ?? entry.base?.mode;
761
+ if (mode) modes.set(entry.path, mode);
762
+ // Binary contents are never decoded as text: the member sees which
763
+ // file clashed, not a corrupted rendering of it.
764
+ const binary = [base, ours, theirs].some((bytes) => bytes?.includes(0));
765
+ const text = (bytes: Uint8Array | null) =>
766
+ bytes && !binary ? new TextDecoder().decode(bytes) : null;
767
+ conflicts.push({
768
+ path: entry.path,
769
+ base: text(base),
770
+ ours: text(ours),
771
+ theirs: text(theirs),
772
+ ...(binary ? { binary: true } : {}),
773
+ });
774
+ };
775
+ for (const ours of oursChanges) {
776
+ const theirs = theirsByPath.get(ours.path);
777
+ if (!theirs) {
778
+ // A file on one side where the other made a folder, or the reverse.
779
+ if (
780
+ ours.after &&
781
+ (await clashesWithTree(objects, input.theirs, ours.path))
782
+ ) {
783
+ await conflict({
784
+ path: ours.path,
785
+ base: ours.before,
786
+ ours: ours.after,
787
+ theirs: null,
788
+ });
789
+ continue;
790
+ }
791
+ changes.set(
792
+ ours.path,
793
+ ours.after ? { oid: ours.after.oid, mode: ours.after.mode } : null,
794
+ );
795
+ continue;
796
+ }
797
+ if (
798
+ ours.after?.oid === theirs.after?.oid &&
799
+ ours.after?.mode === theirs.after?.mode
800
+ )
801
+ continue;
802
+ const merged = await mergeText({
803
+ objects,
804
+ base: ours.before,
805
+ ours: ours.after,
806
+ theirs: theirs.after,
807
+ });
808
+ if (merged !== null && ours.after) {
809
+ const [oid] = await objects.writeBlobs([merged]);
810
+ if (oid) changes.set(ours.path, { oid, mode: ours.after.mode });
811
+ continue;
812
+ }
813
+ await conflict({
814
+ path: ours.path,
815
+ base: ours.before,
816
+ ours: ours.after,
817
+ theirs: theirs.after,
818
+ });
819
+ }
820
+ const resolved = Object.entries(input.resolutions ?? {});
821
+ if (resolved.length > 0) {
822
+ const binary = resolved
823
+ .map(([file]) => file)
824
+ .filter((file) =>
825
+ conflicts.some((entry) => entry.path === file && entry.binary),
826
+ );
827
+ if (binary.length > 0) throw new DraftBinaryResolutionError(binary);
828
+ const rules: IgnoreRules = new Map();
829
+ const ignored: string[] = [];
830
+ for (const [file] of resolved)
831
+ if (
832
+ !modes.has(file) &&
833
+ (await objects.isIgnored(input.theirs, file, rules))
834
+ )
835
+ ignored.push(file);
836
+ if (ignored.length > 0) throw new DraftIgnoredPathError(ignored);
837
+ const oids = await objects.writeBlobs(
838
+ resolved.map(([, content]) => new TextEncoder().encode(content)),
839
+ );
840
+ resolved.forEach(([file], index) => {
841
+ const oid = oids[index];
842
+ const mode = modes.get(file);
843
+ if (oid) changes.set(file, mode ? { oid, mode } : { oid });
844
+ });
845
+ }
846
+ const unresolved = conflicts.filter(
847
+ (conflict) => input.resolutions?.[conflict.path] === undefined,
848
+ );
849
+ if (unresolved.length > 0)
850
+ return { status: "conflict", conflicts: unresolved };
851
+ return {
852
+ status: "merged",
853
+ tree: await objects.writeTree(input.theirs, changes, {
854
+ skipMissingDeletes: true,
855
+ }),
856
+ };
857
+ }
858
+
859
+ /**
860
+ * Whether writing a file at `filePath` would clash with `treeOid`: the
861
+ * path is a folder there, or one of its parents is a file.
862
+ */
863
+ async function clashesWithTree(
864
+ objects: OriginObjects,
865
+ treeOid: string,
866
+ filePath: string,
867
+ ): Promise<boolean> {
868
+ const at = await objects.entry(treeOid, filePath).catch(() => null);
869
+ if (at && isTreeMode(at.mode)) return true;
870
+ const segments = filePath.split("/");
871
+ for (let depth = 1; depth < segments.length; depth++) {
872
+ const parent = await objects
873
+ .entry(treeOid, segments.slice(0, depth).join("/"))
874
+ .catch(() => null);
875
+ if (!parent) return false;
876
+ if (!isTreeMode(parent.mode)) return true;
877
+ }
878
+ return false;
879
+ }
880
+
881
+ /** Both sides' edits to one text file, merged line by line, or null. */
882
+ async function mergeText(input: {
883
+ objects: OriginObjects;
884
+ base: TreeFile | null;
885
+ ours: TreeFile | null;
886
+ theirs: TreeFile | null;
887
+ }): Promise<Uint8Array | null> {
888
+ if (!input.base || !input.ours || !input.theirs) return null;
889
+ if (input.ours.mode !== input.theirs.mode) return null;
890
+ const [base, ours, theirs] = await Promise.all(
891
+ [input.base, input.ours, input.theirs].map((file) =>
892
+ input.objects.blob(file.oid),
893
+ ),
894
+ );
895
+ if (!base || !ours || !theirs) return null;
896
+ if ([base, ours, theirs].some((bytes) => bytes.includes(0))) return null;
897
+ const lines = (bytes: Uint8Array) =>
898
+ new TextDecoder().decode(bytes).match(/[^\n]*\n|[^\n]+$/g) ?? [];
899
+ const blocks = diff3Merge(lines(ours), lines(base), lines(theirs));
900
+ const merged: string[] = [];
901
+ for (const block of blocks) {
902
+ if (!("ok" in block)) return null;
903
+ merged.push(...block.ok);
904
+ }
905
+ return new TextEncoder().encode(merged.join(""));
906
+ }