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

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 (66) hide show
  1. package/dist/checkout-remote-backend.d.ts.map +1 -1
  2. package/dist/fs-backend.d.ts +8 -0
  3. package/dist/fs-backend.d.ts.map +1 -1
  4. package/dist/fs-remote-backend.d.ts +43 -9
  5. package/dist/fs-remote-backend.d.ts.map +1 -1
  6. package/dist/git-objects.d.ts +77 -0
  7. package/dist/git-objects.d.ts.map +1 -0
  8. package/dist/git-sync.d.ts +16 -17
  9. package/dist/git-sync.d.ts.map +1 -1
  10. package/dist/index.d.ts +6 -5
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3912 -3059
  13. package/dist/index.js.map +23 -21
  14. package/dist/native-git.d.ts +114 -2
  15. package/dist/native-git.d.ts.map +1 -1
  16. package/dist/native-project-repo.d.ts +40 -5
  17. package/dist/native-project-repo.d.ts.map +1 -1
  18. package/dist/network-sync.d.ts.map +1 -1
  19. package/dist/network.d.ts +14 -9
  20. package/dist/network.d.ts.map +1 -1
  21. package/dist/object-origin-cache.d.ts +86 -0
  22. package/dist/object-origin-cache.d.ts.map +1 -0
  23. package/dist/object-remote-backend.d.ts +64 -10
  24. package/dist/object-remote-backend.d.ts.map +1 -1
  25. package/dist/origin-draft.d.ts.map +1 -1
  26. package/dist/origin-objects.d.ts +7 -2
  27. package/dist/origin-objects.d.ts.map +1 -1
  28. package/dist/project-manager.d.ts +22 -0
  29. package/dist/project-manager.d.ts.map +1 -1
  30. package/dist/project-paths.d.ts +20 -0
  31. package/dist/project-paths.d.ts.map +1 -0
  32. package/dist/ref-names.d.ts +35 -0
  33. package/dist/ref-names.d.ts.map +1 -1
  34. package/dist/types.d.ts +37 -4
  35. package/dist/types.d.ts.map +1 -1
  36. package/dist/workspace-checkout.d.ts +31 -0
  37. package/dist/workspace-checkout.d.ts.map +1 -0
  38. package/dist/workspace-mirror.d.ts +38 -5
  39. package/dist/workspace-mirror.d.ts.map +1 -1
  40. package/dist/workspace-save.d.ts +27 -2
  41. package/dist/workspace-save.d.ts.map +1 -1
  42. package/package.json +4 -4
  43. package/src/checkout-remote-backend.ts +77 -29
  44. package/src/fs-backend.ts +69 -7
  45. package/src/fs-remote-backend.ts +255 -133
  46. package/src/git-objects.ts +363 -0
  47. package/src/git-sync.ts +124 -453
  48. package/src/index.ts +17 -7
  49. package/src/native-git.ts +566 -25
  50. package/src/native-project-repo.ts +318 -99
  51. package/src/network-sync.ts +43 -35
  52. package/src/network.ts +177 -153
  53. package/src/object-origin-cache.ts +689 -0
  54. package/src/object-remote-backend.ts +277 -20
  55. package/src/origin-draft.ts +22 -15
  56. package/src/origin-objects.ts +21 -5
  57. package/src/project-manager.ts +261 -73
  58. package/src/project-paths.ts +142 -0
  59. package/src/ref-names.ts +56 -0
  60. package/src/types.ts +38 -4
  61. package/src/workspace-checkout.ts +192 -0
  62. package/src/workspace-mirror.ts +276 -68
  63. package/src/workspace-save.ts +99 -30
  64. package/dist/project-repo.d.ts +0 -81
  65. package/dist/project-repo.d.ts.map +0 -1
  66. package/src/project-repo.ts +0 -821
@@ -0,0 +1,363 @@
1
+ import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { deflate } from "node:zlib";
7
+ import { type GitObjectType, wrapObject } from "./git-object-codec.js";
8
+ import { nativeGitEnvironment } from "./native-git.js";
9
+
10
+ const deflateBytes = promisify(deflate);
11
+
12
+ const OBJECT_TYPES: readonly string[] = ["blob", "tree", "commit", "tag"];
13
+
14
+ function isObjectType(value: string): value is GitObjectType {
15
+ return OBJECT_TYPES.includes(value);
16
+ }
17
+
18
+ /** The first line of an answer that holds an object: its id, type and size. */
19
+ const ANSWER = /^([0-9a-f]{40}|[0-9a-f]{64}) (blob|tree|commit|tag) (\d+)$/;
20
+
21
+ /** What one `git cat-file --batch` answer says about an object. */
22
+ export interface ObjectAnswer {
23
+ oid: string;
24
+ type: GitObjectType;
25
+ size: number;
26
+ /** The object's content; empty when only its header was asked for. */
27
+ data: Uint8Array;
28
+ }
29
+
30
+ /**
31
+ * The most one object may weigh to be read into this process's memory
32
+ * where its reader names no limit of its own: a repository may hold files
33
+ * of any size, and reading one whole must never be what exhausts the host.
34
+ */
35
+ export const OBJECT_MAX_BYTES = 64 * 1024 * 1024;
36
+
37
+ /** An object is larger than its reader may hold in memory. */
38
+ export class ObjectTooLargeError extends Error {
39
+ constructor(
40
+ readonly oid: string,
41
+ readonly size: number | null,
42
+ readonly maxBytes: number,
43
+ ) {
44
+ super(
45
+ `Object ${oid.slice(0, 12)} is larger than the ${Math.floor(maxBytes / (1024 * 1024))} MiB that can be read here`,
46
+ );
47
+ this.name = "ObjectTooLargeError";
48
+ }
49
+ }
50
+
51
+ /** How long an idle reader keeps its Git process. */
52
+ const IDLE_MS = 5_000;
53
+
54
+ /**
55
+ * One long-lived `git cat-file` on a repository, answering object lookups
56
+ * in the order they are asked. Reading a tree at a time through a process
57
+ * each would cost more in process starts than in Git. The process sees
58
+ * objects and packs written after it started; it is stopped when idle and
59
+ * never keeps this process alive.
60
+ */
61
+ class ObjectReader {
62
+ private readonly child: ChildProcessWithoutNullStreams;
63
+ private readonly waiting: Array<{
64
+ resolve: (answer: ObjectAnswer | null) => void;
65
+ reject: (error: Error) => void;
66
+ }> = [];
67
+ private chunks: Buffer[] = [];
68
+ private buffered = 0;
69
+ private header: { oid: string; type: GitObjectType; size: number } | null =
70
+ null;
71
+ private failure: Error | null = null;
72
+ private idle: NodeJS.Timeout | undefined;
73
+
74
+ constructor(
75
+ gitdir: string,
76
+ private readonly contents: boolean,
77
+ private readonly closed: () => void,
78
+ env: NodeJS.ProcessEnv,
79
+ ) {
80
+ this.child = spawn(
81
+ "git",
82
+ ["-C", gitdir, "cat-file", contents ? "--batch" : "--batch-check"],
83
+ { env, stdio: ["pipe", "pipe", "pipe"] },
84
+ );
85
+ this.child.stdout.on("data", (chunk: Buffer) => this.receive(chunk));
86
+ this.child.stderr.on("data", () => {});
87
+ this.child.stdin.on("error", () => {});
88
+ this.child.once("error", (error) => this.fail(error));
89
+ this.child.once("close", () =>
90
+ this.fail(new Error("Git stopped while reading objects")),
91
+ );
92
+ this.hold(false);
93
+ this.touch();
94
+ }
95
+
96
+ /**
97
+ * Keep this process alive only while an answer is awaited: an idle
98
+ * reader must never hold a host open.
99
+ */
100
+ private hold(held: boolean): void {
101
+ for (const handle of [
102
+ this.child,
103
+ this.child.stdin,
104
+ this.child.stdout,
105
+ this.child.stderr,
106
+ ]) {
107
+ if (!("ref" in handle && "unref" in handle)) continue;
108
+ if (held) handle.ref();
109
+ else handle.unref();
110
+ }
111
+ }
112
+
113
+ private settle(answer: ObjectAnswer | null): void {
114
+ this.waiting.shift()?.resolve(answer);
115
+ if (this.waiting.length === 0) this.hold(false);
116
+ }
117
+
118
+ get usable(): boolean {
119
+ return this.failure === null;
120
+ }
121
+
122
+ ask(name: string): Promise<ObjectAnswer | null> {
123
+ if (this.failure) return Promise.reject(this.failure);
124
+ if (/[\n\0]/.test(name) || !name)
125
+ return Promise.reject(new Error("Invalid object name"));
126
+ this.touch();
127
+ return new Promise((resolve, reject) => {
128
+ if (this.waiting.length === 0) this.hold(true);
129
+ this.waiting.push({ resolve, reject });
130
+ this.child.stdin.write(`${name}\n`);
131
+ });
132
+ }
133
+
134
+ private touch(): void {
135
+ clearTimeout(this.idle);
136
+ this.idle = setTimeout(() => {
137
+ if (this.waiting.length > 0) return this.touch();
138
+ this.stop();
139
+ }, IDLE_MS);
140
+ this.idle.unref?.();
141
+ }
142
+
143
+ stop(): void {
144
+ clearTimeout(this.idle);
145
+ this.fail(new Error("The object reader was closed"));
146
+ this.child.stdin.end();
147
+ if (this.child.exitCode === null && this.child.signalCode === null)
148
+ this.child.kill();
149
+ }
150
+
151
+ private fail(error: Error): void {
152
+ if (this.failure) return;
153
+ this.failure = error;
154
+ this.closed();
155
+ for (const waiter of this.waiting.splice(0)) waiter.reject(error);
156
+ }
157
+
158
+ private receive(chunk: Buffer): void {
159
+ this.chunks.push(chunk);
160
+ this.buffered += chunk.byteLength;
161
+ while (this.advance()) {
162
+ // Each pass settles one answer.
163
+ }
164
+ }
165
+
166
+ /** Take `length` bytes off the front of what has arrived. */
167
+ private take(length: number): Buffer {
168
+ const all =
169
+ this.chunks.length === 1
170
+ ? (this.chunks[0] ?? Buffer.alloc(0))
171
+ : Buffer.concat(this.chunks);
172
+ const taken = all.subarray(0, length);
173
+ const rest = all.subarray(length);
174
+ this.chunks = rest.byteLength > 0 ? [rest] : [];
175
+ this.buffered = rest.byteLength;
176
+ return taken;
177
+ }
178
+
179
+ private advance(): boolean {
180
+ if (!this.header) {
181
+ // A header is short: look for its newline in what has arrived.
182
+ const all =
183
+ this.chunks.length === 1
184
+ ? (this.chunks[0] ?? Buffer.alloc(0))
185
+ : Buffer.concat(this.chunks);
186
+ this.chunks = all.byteLength > 0 ? [all] : [];
187
+ const end = all.indexOf(0x0a);
188
+ if (end < 0) return false;
189
+ const line = this.take(end + 1)
190
+ .subarray(0, end)
191
+ .toString("utf8");
192
+ // An answer is exactly `<id> <type> <size>`. Anything else says the
193
+ // name is not one object (`<name> missing`, `ambiguous`, a
194
+ // submodule), and nothing follows it. The name is the asker's: one
195
+ // such as `<commit>:notes/a blob 12` must never be read as a header
196
+ // whose content is then waited for.
197
+ const [, oid = "", type = "", size = ""] = ANSWER.exec(line) ?? [];
198
+ if (!isObjectType(type)) {
199
+ this.settle(null);
200
+ return true;
201
+ }
202
+ if (!this.contents) {
203
+ this.settle({ oid, type, size: Number(size), data: new Uint8Array() });
204
+ return true;
205
+ }
206
+ this.header = { oid, type, size: Number(size) };
207
+ }
208
+ // The content, then the newline Git ends every answer with.
209
+ if (this.buffered < this.header.size + 1) return false;
210
+ // One copy, off the stream's buffers.
211
+ const data = new Uint8Array(
212
+ this.take(this.header.size + 1).subarray(0, this.header.size),
213
+ );
214
+ const answer = { ...this.header, data };
215
+ this.header = null;
216
+ this.settle(answer);
217
+ return true;
218
+ }
219
+ }
220
+
221
+ const readers = new Map<string, ObjectReader>();
222
+ /** Readers being started, so two askers at once share one. */
223
+ const starting = new Map<string, Promise<ObjectReader>>();
224
+
225
+ function reader(gitdir: string, contents: boolean): Promise<ObjectReader> {
226
+ const key = `${contents ? "contents" : "headers"}\0${path.resolve(gitdir)}`;
227
+ const current = readers.get(key);
228
+ if (current?.usable) return Promise.resolve(current);
229
+ const pending = starting.get(key);
230
+ if (pending) return pending;
231
+ const started = nativeGitEnvironment({ cwd: gitdir })
232
+ .then((env) => {
233
+ const created: ObjectReader = new ObjectReader(
234
+ gitdir,
235
+ contents,
236
+ () => {
237
+ if (readers.get(key) === created) readers.delete(key);
238
+ },
239
+ env,
240
+ );
241
+ readers.set(key, created);
242
+ return created;
243
+ })
244
+ .finally(() => starting.delete(key));
245
+ starting.set(key, started);
246
+ return started;
247
+ }
248
+
249
+ /**
250
+ * A reader of its own on a repository, for one piece of work: it sees the
251
+ * repository as it is now (the objects it borrows included), and `stop`
252
+ * ends its Git process.
253
+ */
254
+ export async function openObjectReader(input: {
255
+ gitdir: string;
256
+ contents: boolean;
257
+ }): Promise<{
258
+ ask(name: string): Promise<ObjectAnswer | null>;
259
+ stop(): void;
260
+ }> {
261
+ const opened = new ObjectReader(
262
+ input.gitdir,
263
+ input.contents,
264
+ () => {},
265
+ await nativeGitEnvironment({ cwd: input.gitdir }),
266
+ );
267
+ return {
268
+ ask: (name) => opened.ask(name),
269
+ stop: () => opened.stop(),
270
+ };
271
+ }
272
+
273
+ /** An object's type and size in the repository at `gitdir`, or null when absent. */
274
+ export async function objectHeader(input: {
275
+ gitdir: string;
276
+ name: string;
277
+ }): Promise<ObjectAnswer | null> {
278
+ return (await reader(input.gitdir, false)).ask(input.name);
279
+ }
280
+
281
+ /**
282
+ * An object's content in the repository at `gitdir`, or null when absent.
283
+ * Its size is asked first: one over `maxBytes` (see
284
+ * {@link OBJECT_MAX_BYTES}) is refused before a byte of it is read. A
285
+ * caller that already has the size from Git (a tree's listing) passes it
286
+ * as `size`, and it is not asked again.
287
+ */
288
+ export async function objectContent(input: {
289
+ gitdir: string;
290
+ name: string;
291
+ maxBytes?: number;
292
+ size?: number;
293
+ }): Promise<ObjectAnswer | null> {
294
+ const maxBytes = input.maxBytes ?? OBJECT_MAX_BYTES;
295
+ if (input.size === undefined) {
296
+ const header = await objectHeader(input);
297
+ if (!header) return null;
298
+ if (header.size > maxBytes)
299
+ throw new ObjectTooLargeError(header.oid, header.size, maxBytes);
300
+ } else if (input.size > maxBytes)
301
+ throw new ObjectTooLargeError(input.name, input.size, maxBytes);
302
+ return (await reader(input.gitdir, true)).ask(input.name);
303
+ }
304
+
305
+ /**
306
+ * Stop the Git processes reading the repository at `folder`, and any under
307
+ * it, when the folder is about to be removed. Whoever is waiting for an
308
+ * answer from one is told it was closed, so this is never for a holder
309
+ * that is merely done with a repository others may be reading: readers are
310
+ * shared by everyone who reads a folder, and an idle one stops by itself.
311
+ */
312
+ export function closeObjectReaders(folder: string): void {
313
+ const resolved = path.resolve(folder);
314
+ for (const [key, entry] of readers) {
315
+ const read = key.slice(key.indexOf("\0") + 1);
316
+ if (read === resolved || read.startsWith(`${resolved}${path.sep}`))
317
+ entry.stop();
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Write one object as a loose file under `objects` (a repository's object
323
+ * folder), as Git itself stores a new object: deflated, under its id. One
324
+ * already there is left alone. Returns its id.
325
+ */
326
+ export async function writeLooseObject(input: {
327
+ objects: string;
328
+ type: GitObjectType;
329
+ data: Uint8Array;
330
+ }): Promise<string> {
331
+ const { wrapped, sha } = wrapObject(input);
332
+ await writeWrappedObject({ objects: input.objects, sha, wrapped });
333
+ return sha;
334
+ }
335
+
336
+ /** Write an object already in wrapped form (`<type> <length>\0<content>`). */
337
+ export async function writeWrappedObject(input: {
338
+ objects: string;
339
+ sha: string;
340
+ wrapped: Uint8Array;
341
+ }): Promise<void> {
342
+ const directory = path.join(input.objects, input.sha.slice(0, 2));
343
+ const target = path.join(directory, input.sha.slice(2));
344
+ if (
345
+ await fs.access(target).then(
346
+ () => true,
347
+ () => false,
348
+ )
349
+ )
350
+ return;
351
+ await fs.mkdir(directory, { recursive: true });
352
+ const staged = path.join(directory, `tmp_obj_${randomUUID()}`);
353
+ try {
354
+ await fs.writeFile(staged, await deflateBytes(input.wrapped), {
355
+ mode: 0o444,
356
+ });
357
+ // An object is immutable: whoever wrote this id first wrote these bytes.
358
+ await fs.rename(staged, target);
359
+ } catch (error) {
360
+ await fs.rm(staged, { force: true });
361
+ throw error;
362
+ }
363
+ }