@catamorphic/git 0.1.0-alpha.39 → 0.1.0-alpha.42

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.
@@ -0,0 +1,999 @@
1
+ import {
2
+ type ChildProcess,
3
+ type ChildProcessWithoutNullStreams,
4
+ spawn,
5
+ } from "node:child_process";
6
+ import { randomUUID } from "node:crypto";
7
+ import { constants } from "node:fs";
8
+ import fs from "node:fs/promises";
9
+ import { tmpdir } from "node:os";
10
+ import path from "node:path";
11
+ import { nativeGit, nativeGitBytes } from "./native-git.js";
12
+ import type { DraftChange } from "./origin-draft.js";
13
+ import { isPersonalFile } from "./personal-files.js";
14
+
15
+ /**
16
+ * Saving a sandbox's workspace (ADRs 0343, 0344). The sandbox packs the
17
+ * files that changed since the last save, with a manifest naming each path,
18
+ * its Git mode and its blob, and the commits its branch gained, into one
19
+ * Git pack. Everything read here came from the sandbox and is treated as
20
+ * hostile: the pack is indexed in a repository of its own that is thrown
21
+ * away, every path and every tree entry is checked before anything is
22
+ * written, and no write ever follows a link.
23
+ */
24
+
25
+ /** A save that was refused, or whose pack or manifest could not be read. */
26
+ export class WorkspaceSaveError extends Error {
27
+ constructor(message: string, options?: ErrorOptions) {
28
+ super(message, options);
29
+ this.name = "WorkspaceSaveError";
30
+ }
31
+ }
32
+
33
+ /** One change of a save: a deletion, a file with its mode, or a link. */
34
+ export type SavedChange =
35
+ | { path: string; kind: "deleted" }
36
+ | { path: string; kind: "file"; mode: "100644" | "100755"; oid: string }
37
+ | { path: string; kind: "link"; oid: string };
38
+
39
+ const OBJECT_ID = /^[0-9a-f]{40}$|^[0-9a-f]{64}$/;
40
+ const RECORD =
41
+ /^:([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}|[0-9a-f]{64}) ([0-9a-f]{40}|[0-9a-f]{64}) ([AMTD])$/;
42
+ const GITLINK = "160000";
43
+ /** Code points HFS+ ignores in names, so `.g‌it` opens `.git`. */
44
+ const HFS_IGNORED = /[‌-‏‪-‮-]/g;
45
+ /** What a tree a saved commit holds may name: folders, files, links, nested repositories. */
46
+ const TREE_MODES = new Set(["40000", "100644", "100755", "120000", GITLINK]);
47
+ /** A tree larger than this names more entries than a commit may carry. */
48
+ const MAX_TREE_BYTES = 64 * 1024 * 1024;
49
+ /** The longest link target any supported filesystem takes. */
50
+ const MAX_LINK_BYTES = 4096;
51
+ /** A manifest larger than this names more paths than a save may carry. */
52
+ const MAX_MANIFEST_BYTES = 64 * 1024 * 1024;
53
+
54
+ /** Whether a path segment names a Git directory on any filesystem. */
55
+ function isGitDirectoryName(segment: string): boolean {
56
+ // NTFS drops trailing dots and spaces and reads `:stream` as the file.
57
+ const name = (segment.split(":")[0] ?? "")
58
+ .replace(HFS_IGNORED, "")
59
+ .replace(/[. ]+$/, "")
60
+ .toLowerCase();
61
+ return name === ".git" || name === "git~1";
62
+ }
63
+
64
+ /**
65
+ * Refuse a path a save may never name: one that is absolute, leaves the
66
+ * checkout, or passes through a Git directory. Git writes none of these
67
+ * into a tree, so a manifest holding one was not made by Git.
68
+ */
69
+ export function assertSavedPath(filePath: string): void {
70
+ const refuse = (why: string): never => {
71
+ throw new WorkspaceSaveError(
72
+ `the workspace names a path that ${why}: ${JSON.stringify(filePath.slice(0, 200))}`,
73
+ );
74
+ };
75
+ if (filePath.length === 0 || filePath.includes("\0")) refuse("is not a path");
76
+ if (filePath.startsWith("/")) refuse("is absolute");
77
+ // Where a backslash separates folders, it could leave the checkout.
78
+ if (
79
+ path.sep === "\\" &&
80
+ (filePath.includes("\\") || /^[A-Za-z]:/.test(filePath))
81
+ )
82
+ refuse("is not portable");
83
+ for (const segment of filePath.split("/")) {
84
+ if (segment === "" || segment === "." || segment === "..")
85
+ refuse("leaves the checkout");
86
+ if (isGitDirectoryName(segment)) refuse("is inside a Git directory");
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Read a save's manifest: the NUL-separated records of
92
+ * `git diff-tree -r --no-renames --raw --no-abbrev -z` between the last
93
+ * saved tree and the snapshot. Throws {@link WorkspaceSaveError} for a
94
+ * record Git would not write or a path a save may not name. Nested
95
+ * repositories (gitlinks) have no blob and are left out.
96
+ */
97
+ export function parseSavedChanges(manifest: Uint8Array): SavedChange[] {
98
+ const fields = splitOnNul(manifest);
99
+ if (fields.length % 2 !== 0)
100
+ throw new WorkspaceSaveError("the list of changed files was cut short");
101
+ const decoder = new TextDecoder("utf-8", { fatal: true });
102
+ const changes: SavedChange[] = [];
103
+ const seen = new Set<string>();
104
+ for (let index = 0; index < fields.length; index += 2) {
105
+ const record = RECORD.exec(
106
+ Buffer.from(fields[index] ?? new Uint8Array()).toString("latin1"),
107
+ );
108
+ if (!record)
109
+ throw new WorkspaceSaveError("the list of changed files was unreadable");
110
+ const [, before = "", after = "", , oid = "", status = ""] = record;
111
+ const name = decodePath(decoder, fields[index + 1] ?? new Uint8Array());
112
+ assertSavedPath(name);
113
+ if (seen.has(name))
114
+ throw new WorkspaceSaveError(
115
+ `the workspace names ${JSON.stringify(name)} twice`,
116
+ );
117
+ seen.add(name);
118
+ if ((status === "D") !== (after === "000000"))
119
+ throw new WorkspaceSaveError("the list of changed files was unreadable");
120
+ if (after === "000000" || after === GITLINK) {
121
+ // A nested repository that took a file's place: the file is gone.
122
+ if (before !== GITLINK && before !== "000000")
123
+ changes.push({ path: name, kind: "deleted" });
124
+ } else if (after === "100644" || after === "100755") {
125
+ changes.push({ path: name, kind: "file", mode: after, oid });
126
+ } else if (after === "120000") {
127
+ changes.push({ path: name, kind: "link", oid });
128
+ } else {
129
+ throw new WorkspaceSaveError(
130
+ `the workspace holds ${JSON.stringify(name)} with a mode (${after}) that cannot be saved`,
131
+ );
132
+ }
133
+ }
134
+ assertNoFileIsAFolder(changes);
135
+ return changes;
136
+ }
137
+
138
+ function splitOnNul(bytes: Uint8Array): Uint8Array[] {
139
+ const fields: Uint8Array[] = [];
140
+ let start = 0;
141
+ for (let index = 0; index < bytes.length; index += 1) {
142
+ if (bytes[index] !== 0) continue;
143
+ fields.push(bytes.subarray(start, index));
144
+ start = index + 1;
145
+ }
146
+ if (start !== bytes.length)
147
+ throw new WorkspaceSaveError("the list of changed files was cut short");
148
+ return fields;
149
+ }
150
+
151
+ function decodePath(decoder: TextDecoder, bytes: Uint8Array): string {
152
+ try {
153
+ return decoder.decode(bytes);
154
+ } catch {
155
+ throw new WorkspaceSaveError(
156
+ "the workspace holds a file whose name is not UTF-8; rename it so the workspace can be saved",
157
+ );
158
+ }
159
+ }
160
+
161
+ /** No written path may also be a folder of another: Git's trees never say so. */
162
+ function assertNoFileIsAFolder(changes: readonly SavedChange[]): void {
163
+ const written = new Set(
164
+ changes.flatMap((change) =>
165
+ change.kind === "deleted" ? [] : [change.path],
166
+ ),
167
+ );
168
+ for (const file of written) {
169
+ const segments = file.split("/");
170
+ for (let depth = 1; depth < segments.length; depth += 1)
171
+ if (written.has(segments.slice(0, depth).join("/")))
172
+ throw new WorkspaceSaveError(
173
+ `the workspace names ${JSON.stringify(file)} inside something that is not a folder`,
174
+ );
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Refuse a tree a saved commit may not hold: an entry whose name is not one
180
+ * path segment a checkout may contain, or whose mode is not a folder, a
181
+ * file, a link or a nested repository. Git's own trees never hold one.
182
+ */
183
+ export function assertSavedTree(input: {
184
+ /** The tree object's raw content: `<mode> <name>NUL<id>` per entry. */
185
+ tree: Uint8Array;
186
+ /** Bytes of each entry's id: 20 (SHA-1) or 32 (SHA-256). */
187
+ idBytes: 20 | 32;
188
+ }): void {
189
+ const { tree, idBytes } = input;
190
+ const decoder = new TextDecoder("utf-8", { fatal: true });
191
+ let offset = 0;
192
+ while (offset < tree.length) {
193
+ const space = tree.indexOf(0x20, offset);
194
+ const nul = space < 0 ? -1 : tree.indexOf(0, space + 1);
195
+ if (space < 0 || nul < 0 || nul + 1 + idBytes > tree.length)
196
+ throw new WorkspaceSaveError("the branch holds a folder Git cannot read");
197
+ const mode = Buffer.from(tree.subarray(offset, space)).toString("latin1");
198
+ const name = decodePath(decoder, tree.subarray(space + 1, nul));
199
+ if (!TREE_MODES.has(mode))
200
+ throw new WorkspaceSaveError(
201
+ `the branch holds ${JSON.stringify(name.slice(0, 200))} with a mode (${mode.slice(0, 12)}) that cannot be saved`,
202
+ );
203
+ if (name.includes("/"))
204
+ throw new WorkspaceSaveError(
205
+ `the branch names a path that is not one name: ${JSON.stringify(name.slice(0, 200))}`,
206
+ );
207
+ assertSavedPath(name);
208
+ offset = nul + 1 + idBytes;
209
+ }
210
+ }
211
+
212
+ /** Git with nothing inherited that could prompt or lock. */
213
+ function gitEnvironment(): NodeJS.ProcessEnv {
214
+ return { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_TERMINAL_PROMPT: "0" };
215
+ }
216
+
217
+ /**
218
+ * A pack a sandbox sent, indexed in a repository of its own under the
219
+ * host's temporary directory. Native Git verifies the pack's checksum and
220
+ * every object's id as it indexes, so bytes damaged or cut short on the
221
+ * way are refused, never saved. Dispose it when the save is done.
222
+ */
223
+ export class ReceivedPack {
224
+ private reader: BlobReader | undefined;
225
+
226
+ private constructor(
227
+ private readonly directory: string,
228
+ /** Bytes of an object id in the sandbox's repository. */
229
+ private readonly idBytes: 20 | 32,
230
+ ) {}
231
+
232
+ /** Index the pack arriving as `chunks`, in order. */
233
+ static async receive(input: {
234
+ /** The sandbox repository's object format, by its ids' length. */
235
+ objectFormat: "sha1" | "sha256";
236
+ chunks: AsyncIterable<Uint8Array>;
237
+ /**
238
+ * A repository on this machine whose objects the pack's commits may
239
+ * build on (the session's copy): read through, never written.
240
+ */
241
+ borrow?: string;
242
+ }): Promise<ReceivedPack> {
243
+ const directory = await fs.mkdtemp(path.join(tmpdir(), "work-save-"));
244
+ try {
245
+ await nativeGit(directory, [
246
+ "init",
247
+ "--bare",
248
+ "--quiet",
249
+ ...(input.objectFormat === "sha256" ? ["--object-format=sha256"] : []),
250
+ ]);
251
+ if (input.borrow) {
252
+ const objects = (
253
+ await nativeGit(input.borrow, [
254
+ "rev-parse",
255
+ "--path-format=absolute",
256
+ "--git-path",
257
+ "objects",
258
+ ])
259
+ ).trim();
260
+ if (/[\n"]/.test(objects))
261
+ throw new Error("The saved copy's path cannot be borrowed from");
262
+ await fs.writeFile(
263
+ path.join(directory, "objects", "info", "alternates"),
264
+ `${objects}\n`,
265
+ );
266
+ }
267
+ await indexPack({ directory, chunks: input.chunks });
268
+ return new ReceivedPack(
269
+ directory,
270
+ input.objectFormat === "sha256" ? 32 : 20,
271
+ );
272
+ } catch (error) {
273
+ await fs.rm(directory, { recursive: true, force: true });
274
+ throw error;
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Make sure every id names a file's content in the pack, and that
280
+ * together they hold at most `maxBytes`, before anything is written.
281
+ */
282
+ async assertBlobs(input: {
283
+ oids: readonly string[];
284
+ maxBytes: number;
285
+ }): Promise<void> {
286
+ const oids = [...new Set(input.oids)];
287
+ if (oids.length === 0) return;
288
+ for (const oid of oids)
289
+ if (!OBJECT_ID.test(oid))
290
+ throw new WorkspaceSaveError("the workspace names an invalid object");
291
+ const output = Buffer.from(
292
+ await nativeGitBytes(
293
+ this.directory,
294
+ ["cat-file", "--batch-check"],
295
+ new TextEncoder().encode(`${oids.join("\n")}\n`),
296
+ ),
297
+ ).toString("latin1");
298
+ const lines = output.split("\n").filter(Boolean);
299
+ if (lines.length !== oids.length)
300
+ throw new WorkspaceSaveError("the saved files could not be listed");
301
+ let total = 0;
302
+ for (const [index, line] of lines.entries()) {
303
+ const [oid, type, size] = line.split(" ");
304
+ if (oid !== oids[index] || type !== "blob" || !/^\d+$/.test(size ?? ""))
305
+ throw new WorkspaceSaveError(
306
+ "the workspace's pack lacks a file it names",
307
+ );
308
+ total += Number(size);
309
+ if (total > input.maxBytes)
310
+ throw new WorkspaceSaveError(
311
+ `the workspace changed more than ${Math.floor(input.maxBytes / (1024 * 1024))} MiB of files at once`,
312
+ );
313
+ }
314
+ }
315
+
316
+ /**
317
+ * Check the commits a save says its branch gained (ADR 0344), before any
318
+ * of them is kept: `head` and everything it reaches that `known` (the
319
+ * workspace's base and its last saved head) does not. Every commit must
320
+ * be here whole, with history that ends at `known`; every tree may name
321
+ * only what a checkout may hold; and together they are bounded. Returns
322
+ * the new commits, newest first.
323
+ */
324
+ async assertHistory(input: {
325
+ head: string;
326
+ known: readonly string[];
327
+ maxCommits: number;
328
+ maxBytes: number;
329
+ }): Promise<{ commits: string[] }> {
330
+ for (const oid of [input.head, ...input.known])
331
+ if (!OBJECT_ID.test(oid))
332
+ throw new WorkspaceSaveError("the workspace names an invalid commit");
333
+ const range = [input.head, "--not", ...input.known];
334
+ const walk = async (args: readonly string[]): Promise<string[]> => {
335
+ try {
336
+ return (
337
+ await nativeGit(this.directory, ["rev-list", ...args, ...range])
338
+ )
339
+ .split("\n")
340
+ .filter(Boolean);
341
+ } catch {
342
+ throw new WorkspaceSaveError(
343
+ "the branch's commits build on history that did not arrive with them; fetch that history (git fetch --unshallow) or go back to a branch that starts from this workspace's base",
344
+ );
345
+ }
346
+ };
347
+ const commits = await walk([
348
+ "--parents",
349
+ `--max-count=${input.maxCommits + 1}`,
350
+ ]);
351
+ if (commits.length > input.maxCommits)
352
+ throw new WorkspaceSaveError(
353
+ `the branch gained more than ${input.maxCommits} commits at once`,
354
+ );
355
+ for (const line of commits)
356
+ if (!line.includes(" "))
357
+ throw new WorkspaceSaveError(
358
+ "the branch holds a commit with no parent, so its history does not start from this workspace's base",
359
+ );
360
+ const objects = await walk(["--objects", "--no-object-names"]);
361
+ if (objects.length === 0) return { commits: [] };
362
+ const listed = Buffer.from(
363
+ await nativeGitBytes(
364
+ this.directory,
365
+ ["cat-file", "--batch-check"],
366
+ new TextEncoder().encode(`${objects.join("\n")}\n`),
367
+ ),
368
+ )
369
+ .toString("latin1")
370
+ .split("\n")
371
+ .filter(Boolean);
372
+ if (listed.length !== objects.length)
373
+ throw new WorkspaceSaveError("the branch's commits could not be listed");
374
+ let total = 0;
375
+ for (const [index, line] of listed.entries()) {
376
+ const [oid, type, size] = line.split(" ");
377
+ if (oid !== objects[index] || !/^\d+$/.test(size ?? ""))
378
+ throw new WorkspaceSaveError(
379
+ "the branch's commits name an object that did not arrive",
380
+ );
381
+ total += Number(size);
382
+ if (total > input.maxBytes)
383
+ throw new WorkspaceSaveError(
384
+ `the branch gained more than ${Math.floor(input.maxBytes / (1024 * 1024))} MiB of commits at once`,
385
+ );
386
+ if (type === "tree")
387
+ assertSavedTree({
388
+ tree: await this.readObject({ oid: oid ?? "", type: "tree" }),
389
+ idBytes: this.idBytes,
390
+ });
391
+ else if (type !== "commit" && type !== "blob")
392
+ throw new WorkspaceSaveError(
393
+ "the branch's commits hold something that is not a commit, a folder or a file",
394
+ );
395
+ }
396
+ return { commits: commits.map((line) => line.split(" ")[0] ?? "") };
397
+ }
398
+
399
+ /**
400
+ * Keep checked commits (ADR 0344): `head` and what it reaches beyond
401
+ * `known`, unpacked loose into the repository at `repoPath`, so no pack
402
+ * stays there. Git checks each object and its links again as it writes.
403
+ */
404
+ async unpackHistory(input: {
405
+ repoPath: string;
406
+ head: string;
407
+ known: readonly string[];
408
+ }): Promise<void> {
409
+ for (const oid of [input.head, ...input.known])
410
+ if (!OBJECT_ID.test(oid))
411
+ throw new WorkspaceSaveError("the workspace names an invalid commit");
412
+ await this.unpack({
413
+ repoPath: input.repoPath,
414
+ revisions: `${input.head}\n${input.known.map((oid) => `^${oid}\n`).join("")}`,
415
+ });
416
+ }
417
+
418
+ /**
419
+ * Build the checkpoint tree from its previous tree and checked file
420
+ * changes. Git's private index keeps paths, modes and bytes without
421
+ * re-reading a host working tree or applying a second set of filters.
422
+ */
423
+ async snapshotTree(input: {
424
+ repoPath: string;
425
+ previous: string;
426
+ changes: readonly SavedChange[];
427
+ containLinks: boolean;
428
+ }): Promise<string> {
429
+ const changes = withoutPersonalFiles(input.changes);
430
+ for (const change of changes) {
431
+ assertSavedPath(change.path);
432
+ if (change.kind === "link") {
433
+ const target = await readLinkTarget(this, change);
434
+ if (input.containLinks) assertLinkStaysInside(change.path, target);
435
+ }
436
+ }
437
+
438
+ const previousTree = (
439
+ await nativeGit(this.directory, ["rev-parse", `${input.previous}^{tree}`])
440
+ ).trim();
441
+ await nativeGit(this.directory, ["read-tree", previousTree]);
442
+ const zeros = "0".repeat(this.idBytes * 2);
443
+ const deleted: string[] = [];
444
+ const written: string[] = [];
445
+ for (const change of changes) {
446
+ if (change.kind === "deleted") {
447
+ deleted.push(`0 ${zeros}\t${change.path}\0`);
448
+ } else {
449
+ const mode = change.kind === "link" ? "120000" : change.mode;
450
+ written.push(`${mode} ${change.oid}\t${change.path}\0`);
451
+ }
452
+ }
453
+ if (deleted.length || written.length) {
454
+ try {
455
+ await nativeGitBytes(
456
+ this.directory,
457
+ ["update-index", "-z", "--index-info"],
458
+ Buffer.from(deleted.join("") + written.join("")),
459
+ );
460
+ } catch (error) {
461
+ throw new WorkspaceSaveError(
462
+ "the saved paths conflict with the checkpoint's files",
463
+ { cause: error },
464
+ );
465
+ }
466
+ }
467
+ const tree = (await nativeGit(this.directory, ["write-tree"])).trim();
468
+ if (tree !== previousTree) {
469
+ // Git can resolve a file/directory conflict by removing an existing
470
+ // index entry. Such a removal has to be explicit in the manifest
471
+ // (for example when a former symlink is replaced by a directory).
472
+ const claimed = new Set(changes.map((change) => change.path));
473
+ const changed = await nativeGitBytes(this.directory, [
474
+ "diff-tree",
475
+ "-r",
476
+ "-z",
477
+ "--no-renames",
478
+ "--name-only",
479
+ previousTree,
480
+ tree,
481
+ ]);
482
+ const decoder = new TextDecoder("utf-8", { fatal: true });
483
+ for (const name of splitOnNul(changed)) {
484
+ const filePath = decodePath(decoder, name);
485
+ if (!claimed.has(filePath))
486
+ throw new WorkspaceSaveError(
487
+ `the workspace tried to replace ${JSON.stringify(filePath)} without naming it in the save`,
488
+ );
489
+ }
490
+ await this.unpack({
491
+ repoPath: input.repoPath,
492
+ revisions: `${tree}\n^${previousTree}\n`,
493
+ });
494
+ }
495
+ return tree;
496
+ }
497
+
498
+ private async unpack(input: {
499
+ repoPath: string;
500
+ revisions: string;
501
+ }): Promise<void> {
502
+ const packer = spawn(
503
+ "git",
504
+ ["-C", this.directory, "pack-objects", "--revs", "--stdout", "--quiet"],
505
+ { env: gitEnvironment(), stdio: ["pipe", "pipe", "ignore"] },
506
+ );
507
+ const unpacker = spawn(
508
+ "git",
509
+ ["-C", input.repoPath, "unpack-objects", "--strict", "-q"],
510
+ { env: gitEnvironment(), stdio: ["pipe", "ignore", "pipe"] },
511
+ );
512
+ const stderr: Buffer[] = [];
513
+ unpacker.stderr.on("data", (chunk: Buffer) => {
514
+ if (stderr.length < 16) stderr.push(chunk);
515
+ });
516
+ packer.stdin.on("error", () => {});
517
+ unpacker.stdin.on("error", () => {});
518
+ const exit = (child: ChildProcess) =>
519
+ new Promise<number | null>((resolve, reject) => {
520
+ child.on("error", reject);
521
+ child.on("close", resolve);
522
+ });
523
+ const packed = exit(packer);
524
+ const unpacked = exit(unpacker);
525
+ packer.stdout.pipe(unpacker.stdin);
526
+ packer.stdin.end(input.revisions);
527
+ const [packCode, unpackCode] = await Promise.all([packed, unpacked]);
528
+ if (packCode !== 0 || unpackCode !== 0) {
529
+ const detail = Buffer.concat(stderr)
530
+ .toString("utf8")
531
+ .trim()
532
+ .split("\n")[0];
533
+ throw new WorkspaceSaveError(
534
+ `the workspace's objects could not be kept${detail ? ` (${detail.slice(0, 200)})` : ""}`,
535
+ );
536
+ }
537
+ }
538
+
539
+ /** One blob's bytes, refused when larger than `maxBytes`. */
540
+ async read(input: { oid: string; maxBytes: number }): Promise<Uint8Array> {
541
+ const parts: Uint8Array[] = [];
542
+ await this.stream({
543
+ oid: input.oid,
544
+ maxBytes: input.maxBytes,
545
+ write: async (chunk) => {
546
+ parts.push(Uint8Array.from(chunk));
547
+ },
548
+ });
549
+ return new Uint8Array(Buffer.concat(parts));
550
+ }
551
+
552
+ /** One object's bytes, refused when it is not of `type`. */
553
+ private async readObject(input: {
554
+ oid: string;
555
+ type: "tree";
556
+ }): Promise<Uint8Array> {
557
+ const parts: Uint8Array[] = [];
558
+ await this.stream({
559
+ oid: input.oid,
560
+ type: input.type,
561
+ maxBytes: MAX_TREE_BYTES,
562
+ write: async (chunk) => {
563
+ parts.push(Uint8Array.from(chunk));
564
+ },
565
+ });
566
+ return new Uint8Array(Buffer.concat(parts));
567
+ }
568
+
569
+ /** Stream one blob's bytes to `write`, in order. */
570
+ async copy(input: {
571
+ oid: string;
572
+ write: (chunk: Uint8Array) => Promise<void>;
573
+ }): Promise<void> {
574
+ await this.stream({ ...input, maxBytes: Number.MAX_SAFE_INTEGER });
575
+ }
576
+
577
+ private async stream(input: {
578
+ oid: string;
579
+ type?: "blob" | "tree";
580
+ maxBytes: number;
581
+ write: (chunk: Uint8Array) => Promise<void>;
582
+ }): Promise<void> {
583
+ this.reader ??= new BlobReader(this.directory);
584
+ const reader = this.reader;
585
+ try {
586
+ await reader.copy(input);
587
+ } catch (error) {
588
+ // A read that stopped part way leaves Git's answer half consumed.
589
+ reader.close();
590
+ if (this.reader === reader) this.reader = undefined;
591
+ throw error;
592
+ }
593
+ }
594
+
595
+ /** The manifest blob, parsed and checked. */
596
+ async changes(input: { manifest: string }): Promise<SavedChange[]> {
597
+ return parseSavedChanges(
598
+ await this.read({ oid: input.manifest, maxBytes: MAX_MANIFEST_BYTES }),
599
+ );
600
+ }
601
+
602
+ async dispose(): Promise<void> {
603
+ this.reader?.close();
604
+ this.reader = undefined;
605
+ await fs.rm(this.directory, { recursive: true, force: true });
606
+ }
607
+ }
608
+
609
+ /** Feed `chunks` to `git index-pack`, which checks the pack as it reads. */
610
+ async function indexPack(input: {
611
+ directory: string;
612
+ chunks: AsyncIterable<Uint8Array>;
613
+ }): Promise<void> {
614
+ const child = spawn(
615
+ "git",
616
+ // Git checks every object's form as it indexes, not only its checksum.
617
+ ["-C", input.directory, "index-pack", "--stdin", "--fsck-objects"],
618
+ { env: gitEnvironment(), stdio: ["pipe", "ignore", "pipe"] },
619
+ );
620
+ const stderr: Buffer[] = [];
621
+ child.stderr.on("data", (chunk: Buffer) => {
622
+ if (stderr.length < 16) stderr.push(chunk);
623
+ });
624
+ // Git that stopped reading reports why through its exit, not a pipe error.
625
+ child.stdin.on("error", () => {});
626
+ const exited = new Promise<number | null>((resolve, reject) => {
627
+ child.on("error", reject);
628
+ child.on("close", resolve);
629
+ });
630
+ try {
631
+ for await (const chunk of input.chunks) {
632
+ if (child.exitCode !== null || child.stdin.destroyed) break;
633
+ if (!child.stdin.write(chunk))
634
+ await new Promise<void>((resolve) => {
635
+ const done = () => {
636
+ child.stdin.off("drain", done);
637
+ child.off("close", done);
638
+ resolve();
639
+ };
640
+ child.stdin.once("drain", done);
641
+ child.once("close", done);
642
+ });
643
+ }
644
+ } catch (error) {
645
+ child.kill("SIGKILL");
646
+ await exited.catch(() => null);
647
+ throw error;
648
+ }
649
+ child.stdin.end();
650
+ const code = await exited;
651
+ if (code !== 0) {
652
+ const detail = Buffer.concat(stderr).toString("utf8").trim().split("\n")[0];
653
+ throw new WorkspaceSaveError(
654
+ `the workspace's files arrived damaged${detail ? ` (${detail.slice(0, 200)})` : ""}`,
655
+ );
656
+ }
657
+ }
658
+
659
+ /**
660
+ * One `git cat-file --batch` over a repository, asked for one object at a
661
+ * time. Its output is raw bytes with no conversion of any kind.
662
+ */
663
+ class BlobReader {
664
+ private readonly child: ChildProcessWithoutNullStreams;
665
+ private readonly output: AsyncIterator<Buffer>;
666
+ private pending: Buffer = Buffer.alloc(0);
667
+ /** Reads are answered in order: one waits for the one before it. */
668
+ private last: Promise<void> = Promise.resolve();
669
+
670
+ constructor(directory: string) {
671
+ this.child = spawn("git", ["-C", directory, "cat-file", "--batch"], {
672
+ env: gitEnvironment(),
673
+ stdio: ["pipe", "pipe", "pipe"],
674
+ });
675
+ this.child.on("error", () => {});
676
+ this.child.stdin.on("error", () => {});
677
+ this.child.stderr.resume();
678
+ this.output = this.child.stdout[Symbol.asyncIterator]();
679
+ }
680
+
681
+ copy(input: {
682
+ oid: string;
683
+ type?: "blob" | "tree";
684
+ maxBytes: number;
685
+ write: (chunk: Uint8Array) => Promise<void>;
686
+ }): Promise<void> {
687
+ const next = this.last.then(() => this.copyNow(input));
688
+ this.last = next.catch(() => {});
689
+ return next;
690
+ }
691
+
692
+ private async copyNow(input: {
693
+ oid: string;
694
+ type?: "blob" | "tree";
695
+ maxBytes: number;
696
+ write: (chunk: Uint8Array) => Promise<void>;
697
+ }): Promise<void> {
698
+ if (!OBJECT_ID.test(input.oid))
699
+ throw new WorkspaceSaveError("the workspace names an invalid object");
700
+ this.child.stdin.write(`${input.oid}\n`);
701
+ const [oid, type, size] = (await this.line()).split(" ");
702
+ if (
703
+ oid !== input.oid ||
704
+ type !== (input.type ?? "blob") ||
705
+ !/^\d+$/.test(size ?? "")
706
+ )
707
+ throw new WorkspaceSaveError(
708
+ "the workspace's pack lacks a file it names",
709
+ );
710
+ const length = Number(size);
711
+ if (length > input.maxBytes)
712
+ throw new WorkspaceSaveError("a saved file is larger than it may be");
713
+ let left = length;
714
+ while (left > 0) {
715
+ if (this.pending.length === 0 && !(await this.fill()))
716
+ throw new WorkspaceSaveError("a saved file was cut short");
717
+ const part = this.pending.subarray(
718
+ 0,
719
+ Math.min(left, this.pending.length),
720
+ );
721
+ this.pending = this.pending.subarray(part.length);
722
+ left -= part.length;
723
+ await input.write(part);
724
+ }
725
+ // Git ends every object with a line feed.
726
+ while (this.pending.length === 0)
727
+ if (!(await this.fill()))
728
+ throw new WorkspaceSaveError("a saved file was cut short");
729
+ this.pending = this.pending.subarray(1);
730
+ }
731
+
732
+ private async line(): Promise<string> {
733
+ for (;;) {
734
+ const end = this.pending.indexOf(10);
735
+ if (end >= 0) {
736
+ const line = this.pending.subarray(0, end).toString("latin1");
737
+ this.pending = this.pending.subarray(end + 1);
738
+ return line;
739
+ }
740
+ if (this.pending.length > 256 || !(await this.fill()))
741
+ throw new WorkspaceSaveError("the saved files could not be read");
742
+ }
743
+ }
744
+
745
+ private async fill(): Promise<boolean> {
746
+ const next = await this.output.next();
747
+ if (next.done) return false;
748
+ this.pending =
749
+ this.pending.length > 0
750
+ ? Buffer.concat([this.pending, next.value])
751
+ : next.value;
752
+ return true;
753
+ }
754
+
755
+ close(): void {
756
+ this.child.stdin.end();
757
+ this.child.kill("SIGKILL");
758
+ }
759
+ }
760
+
761
+ async function lstatOrNull(target: string) {
762
+ return fs.lstat(target).catch((error: unknown) => {
763
+ if (
764
+ error instanceof Error &&
765
+ "code" in error &&
766
+ (error.code === "ENOENT" || error.code === "ENOTDIR")
767
+ )
768
+ return null;
769
+ throw error;
770
+ });
771
+ }
772
+
773
+ /**
774
+ * The real folder a path's parent segments name under `root`, made when
775
+ * `create` says so. A link on the way is never followed: writing refuses
776
+ * it, and a deletion finds nothing of the checkout's there (null).
777
+ */
778
+ async function folderOf(input: {
779
+ root: string;
780
+ filePath: string;
781
+ create: boolean;
782
+ }): Promise<string | null> {
783
+ let current = input.root;
784
+ for (const segment of input.filePath.split("/").slice(0, -1)) {
785
+ current = path.join(current, segment);
786
+ const stat = await lstatOrNull(current);
787
+ if (!stat) {
788
+ if (!input.create) return null;
789
+ await fs.mkdir(current);
790
+ } else if (!stat.isDirectory()) {
791
+ if (!input.create) return null;
792
+ throw new WorkspaceSaveError(
793
+ stat.isSymbolicLink()
794
+ ? `${JSON.stringify(input.filePath)} would be written through a link, which a save never follows`
795
+ : `${JSON.stringify(input.filePath)} needs a folder where the saved copy holds a file`,
796
+ );
797
+ }
798
+ }
799
+ return current;
800
+ }
801
+
802
+ /** Remove a folder that holds nothing but empty folders; false otherwise. */
803
+ async function removeEmptyFolder(folder: string): Promise<boolean> {
804
+ for (const entry of await fs.readdir(folder, { withFileTypes: true })) {
805
+ if (!entry.isDirectory()) return false;
806
+ if (!(await removeEmptyFolder(path.join(folder, entry.name)))) return false;
807
+ }
808
+ await fs.rmdir(folder);
809
+ return true;
810
+ }
811
+
812
+ /** Take away what stands where a file or link is about to be written. */
813
+ async function clearTarget(target: string, filePath: string): Promise<void> {
814
+ const stat = await lstatOrNull(target);
815
+ if (!stat) return;
816
+ if (!stat.isDirectory()) {
817
+ // Unlinking removes a link itself, never what it points at.
818
+ await fs.unlink(target);
819
+ return;
820
+ }
821
+ if (!(await removeEmptyFolder(target)))
822
+ throw new WorkspaceSaveError(
823
+ `${JSON.stringify(filePath)} is a file in the workspace, and a folder that still holds files in the saved copy`,
824
+ );
825
+ }
826
+
827
+ /**
828
+ * Refuse a change the file APIs would refuse: a personal file is never
829
+ * written from a sandbox. Deleting one is skipped, as it always was.
830
+ */
831
+ function withoutPersonalFiles(changes: readonly SavedChange[]): SavedChange[] {
832
+ return changes.filter((change) => {
833
+ if (!isPersonalFile(change.path)) return true;
834
+ if (change.kind === "deleted") return false;
835
+ throw new WorkspaceSaveError(
836
+ `${JSON.stringify(change.path)} is a personal file, which is never saved from a workspace`,
837
+ );
838
+ });
839
+ }
840
+
841
+ /**
842
+ * Refuse a link that could lead outside the folder it is saved in. Its
843
+ * target must be relative: any `..` first, never above the folder, then
844
+ * names only, so no link the save itself wrote can be climbed out of, and
845
+ * never a Git directory.
846
+ */
847
+ function assertLinkStaysInside(filePath: string, target: Uint8Array): void {
848
+ const refuse = (): never => {
849
+ throw new WorkspaceSaveError(
850
+ `${JSON.stringify(filePath)} is a link that leads outside the project folder; a workspace's links are kept in a person's own folder only when they point inside it`,
851
+ );
852
+ };
853
+ const text = (() => {
854
+ try {
855
+ return new TextDecoder("utf-8", { fatal: true }).decode(target);
856
+ } catch {
857
+ return refuse();
858
+ }
859
+ })();
860
+ if (text.startsWith("/") || text.includes("\\") || /^[A-Za-z]:/.test(text))
861
+ refuse();
862
+ const segments = text
863
+ .split("/")
864
+ .filter((segment) => segment !== "" && segment !== ".");
865
+ const climbs = segments.findIndex((segment) => segment !== "..");
866
+ const up = climbs < 0 ? segments.length : climbs;
867
+ const names = segments.slice(up);
868
+ const depth = filePath.split("/").length - 1;
869
+ if (up > depth || names.includes("..") || names.some(isGitDirectoryName))
870
+ refuse();
871
+ }
872
+
873
+ /**
874
+ * Apply a save to a checkout on this machine, exactly: each file's bytes
875
+ * and executable bit, each link as a link, each deletion. Deletions go
876
+ * first, so a file may take a folder's place and a folder a file's. Nothing
877
+ * is written outside `repoPath`: parents are real folders or the save is
878
+ * refused, and what stands at a path is removed, never opened, so a link
879
+ * saved earlier cannot redirect a later write.
880
+ */
881
+ export async function writeSavedChanges(input: {
882
+ repoPath: string;
883
+ changes: readonly SavedChange[];
884
+ pack: ReceivedPack;
885
+ /**
886
+ * The checkout's file APIs follow links (a person's own folder): a link
887
+ * that could lead outside it is refused, so nothing read or written
888
+ * there later goes where the sandbox pointed.
889
+ */
890
+ containLinks?: boolean;
891
+ }): Promise<void> {
892
+ const changes = withoutPersonalFiles(input.changes);
893
+ for (const change of changes) assertSavedPath(change.path);
894
+ for (const change of changes) {
895
+ if (change.kind !== "deleted") continue;
896
+ const folder = await folderOf({
897
+ root: input.repoPath,
898
+ filePath: change.path,
899
+ create: false,
900
+ });
901
+ if (!folder) continue;
902
+ const target = path.join(folder, path.posix.basename(change.path));
903
+ const stat = await lstatOrNull(target);
904
+ if (stat && !stat.isDirectory()) await fs.unlink(target);
905
+ }
906
+ for (const change of changes) {
907
+ if (change.kind === "deleted") continue;
908
+ const folder = await folderOf({
909
+ root: input.repoPath,
910
+ filePath: change.path,
911
+ create: true,
912
+ });
913
+ if (!folder) continue;
914
+ const target = path.join(folder, path.posix.basename(change.path));
915
+ if (change.kind === "link") {
916
+ const link = Buffer.from(await readLinkTarget(input.pack, change));
917
+ if (input.containLinks) assertLinkStaysInside(change.path, link);
918
+ await clearTarget(target, change.path);
919
+ await fs.symlink(link, target);
920
+ continue;
921
+ }
922
+ // Written beside its place and moved in: a save that stops part way
923
+ // leaves the file as it was, and a rename replaces a link, never
924
+ // what the link points at.
925
+ const partial = path.join(folder, `.work-save-${randomUUID()}`);
926
+ try {
927
+ const handle = await fs.open(
928
+ partial,
929
+ constants.O_WRONLY |
930
+ constants.O_CREAT |
931
+ constants.O_EXCL |
932
+ (constants.O_NOFOLLOW ?? 0),
933
+ change.mode === "100755" ? 0o777 : 0o666,
934
+ );
935
+ try {
936
+ await input.pack.copy({
937
+ oid: change.oid,
938
+ write: async (chunk) => {
939
+ await handle.writeFile(chunk);
940
+ },
941
+ });
942
+ } finally {
943
+ await handle.close();
944
+ }
945
+ await clearTarget(target, change.path);
946
+ await fs.rename(partial, target);
947
+ } catch (error) {
948
+ await fs.rm(partial, { force: true });
949
+ throw error;
950
+ }
951
+ }
952
+ }
953
+
954
+ async function readLinkTarget(
955
+ pack: ReceivedPack,
956
+ change: { path: string; oid: string },
957
+ ): Promise<Uint8Array> {
958
+ const target = await pack.read({ oid: change.oid, maxBytes: MAX_LINK_BYTES });
959
+ if (target.length === 0 || target.includes(0))
960
+ throw new WorkspaceSaveError(
961
+ `${JSON.stringify(change.path)} is a link with no usable target`,
962
+ );
963
+ return target;
964
+ }
965
+
966
+ /**
967
+ * A save as changes to a member's draft in the origin (ADR 0191): the same
968
+ * bytes, modes and links, written as Git objects. Pass them to
969
+ * `OriginDraftRepo.write` with `replaceLinks`.
970
+ */
971
+ export async function savedDraftChanges(input: {
972
+ changes: readonly SavedChange[];
973
+ pack: ReceivedPack;
974
+ }): Promise<DraftChange[]> {
975
+ const changes = withoutPersonalFiles(input.changes);
976
+ for (const change of changes) assertSavedPath(change.path);
977
+ const draft: DraftChange[] = [];
978
+ for (const change of changes) {
979
+ if (change.kind === "deleted") {
980
+ draft.push({ path: change.path, delete: true });
981
+ } else if (change.kind === "link") {
982
+ draft.push({
983
+ path: change.path,
984
+ content: await readLinkTarget(input.pack, change),
985
+ mode: "120000",
986
+ });
987
+ } else {
988
+ draft.push({
989
+ path: change.path,
990
+ content: await input.pack.read({
991
+ oid: change.oid,
992
+ maxBytes: Number.MAX_SAFE_INTEGER,
993
+ }),
994
+ mode: change.mode,
995
+ });
996
+ }
997
+ }
998
+ return draft;
999
+ }