@invariantly/cli 0.0.0-stage → 0.0.3

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.
package/dist/git.js ADDED
@@ -0,0 +1,765 @@
1
+ // A minimal, read-only reader for SHA-1 git repositories (spec 2026-12-06-check-base-contract-change).
2
+ // It never spawns git, never writes a file and never fetches: every file is opened for reading only.
3
+ // Anything it does not understand (reftable, SHA-256, pack index v1, a multi-pack-index without
4
+ // `.idx` files, a missing object) is a GitError, so callers fail closed.
5
+ import { open, readdir, readFile, stat } from "node:fs/promises";
6
+ import { dirname, isAbsolute, join, resolve } from "node:path";
7
+ import { inflateSync } from "node:zlib";
8
+ /** Every unsupported or missing case; the message names the reason. */
9
+ export class GitError extends Error {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = "GitError";
13
+ }
14
+ }
15
+ const HEX40 = /^[0-9a-f]{40}$/;
16
+ const CACHE_LIMIT = 4096;
17
+ const states = new WeakMap();
18
+ const state = (repo) => {
19
+ let s = states.get(repo);
20
+ if (!s) {
21
+ s = { cache: new Map() };
22
+ states.set(repo, s);
23
+ }
24
+ return s;
25
+ };
26
+ const code = (err) => err?.code;
27
+ /** Reads a file, or undefined when it (or a directory on its path) does not exist. */
28
+ const readOptional = async (path) => {
29
+ try {
30
+ return await readFile(path);
31
+ }
32
+ catch (err) {
33
+ const c = code(err);
34
+ if (c === "ENOENT" || c === "ENOTDIR" || c === "EISDIR")
35
+ return undefined;
36
+ throw new GitError(`cannot read ${path}: ${err.message}`);
37
+ }
38
+ };
39
+ const kind = async (path) => {
40
+ try {
41
+ const s = await stat(path);
42
+ return s.isDirectory() ? "dir" : s.isFile() ? "file" : undefined;
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ };
48
+ // ---------------------------------------------------------------------------------------------
49
+ // Repository discovery and configuration
50
+ // ---------------------------------------------------------------------------------------------
51
+ /** Parses the git config entries that matter here: `section.key` (lower-case) → value. */
52
+ const parseConfig = (text) => {
53
+ const out = new Map();
54
+ let section = "";
55
+ for (const raw of text.split(/\r?\n/)) {
56
+ const line = raw.trim();
57
+ if (line === "" || line.startsWith("#") || line.startsWith(";"))
58
+ continue;
59
+ const header = /^\[\s*([A-Za-z0-9.-]+)(?:\s+"(?:[^"\\]|\\.)*")?\s*\](.*)$/.exec(line);
60
+ if (header) {
61
+ // A subsection (`[remote "origin"]`) never holds `core` or `extensions` keys we read.
62
+ section = /"/.test(line) ? `${header[1].toLowerCase()}."` : header[1].toLowerCase();
63
+ const rest = header[2].trim();
64
+ if (rest === "" || rest.startsWith("#") || rest.startsWith(";"))
65
+ continue;
66
+ parseEntry(rest, section, out);
67
+ continue;
68
+ }
69
+ parseEntry(line, section, out);
70
+ }
71
+ return out;
72
+ };
73
+ const parseEntry = (line, section, out) => {
74
+ const m = /^([A-Za-z][A-Za-z0-9-]*)\s*(?:=\s*(.*))?$/.exec(line);
75
+ if (!m)
76
+ return;
77
+ let value = (m[2] ?? "true").replace(/\s+[#;].*$/, "").trim();
78
+ if (value.startsWith('"') && value.endsWith('"') && value.length >= 2)
79
+ value = value.slice(1, -1);
80
+ out.set(`${section}.${m[1].toLowerCase()}`, value);
81
+ };
82
+ const KNOWN_EXTENSIONS = new Set(["noop", "noop-v1", "preciousobjects", "partialclone", "worktreeconfig", "objectformat", "refstorage", "relativeworktrees"]);
83
+ const checkConfig = async (commonDir) => {
84
+ const text = await readOptional(join(commonDir, "config"));
85
+ if (!text)
86
+ return;
87
+ const config = parseConfig(text.toString("utf8"));
88
+ const refStorage = config.get("extensions.refstorage");
89
+ if (refStorage !== undefined && refStorage.toLowerCase() !== "files")
90
+ throw new GitError(`unsupported repository: extensions.refStorage = ${refStorage} (reftable is not supported)`);
91
+ const objectFormat = config.get("extensions.objectformat");
92
+ if (objectFormat !== undefined && objectFormat.toLowerCase() !== "sha1")
93
+ throw new GitError(`unsupported repository: extensions.objectFormat = ${objectFormat} (only SHA-1 is supported)`);
94
+ const version = Number(config.get("core.repositoryformatversion") ?? "0");
95
+ if (!(version === 0 || version === 1))
96
+ throw new GitError(`unsupported repository: core.repositoryformatversion = ${config.get("core.repositoryformatversion")}`);
97
+ if (version === 1)
98
+ for (const key of config.keys())
99
+ if (key.startsWith("extensions.") && !KNOWN_EXTENSIONS.has(key.slice("extensions.".length)))
100
+ throw new GitError(`unsupported repository: unknown extension ${key}`);
101
+ };
102
+ /** Finds the repository that contains `startDir`, searching upwards. */
103
+ export async function openRepo(startDir) {
104
+ let dir = resolve(startDir);
105
+ for (;;) {
106
+ const dotGit = join(dir, ".git");
107
+ const k = await kind(dotGit);
108
+ let gitDir;
109
+ if (k === "dir")
110
+ gitDir = dotGit;
111
+ else if (k === "file") {
112
+ const text = (await readOptional(dotGit))?.toString("utf8") ?? "";
113
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(text);
114
+ if (!m)
115
+ throw new GitError(`${dotGit} is not a valid gitdir file`);
116
+ gitDir = resolve(dir, m[1]);
117
+ if ((await kind(gitDir)) !== "dir")
118
+ throw new GitError(`${dotGit} points to a missing git directory ${gitDir}`);
119
+ }
120
+ if (gitDir !== undefined) {
121
+ const common = (await readOptional(join(gitDir, "commondir")))?.toString("utf8").trim();
122
+ const commonDir = common ? resolve(gitDir, common) : gitDir;
123
+ if ((await kind(join(commonDir, "objects"))) !== "dir")
124
+ throw new GitError(`${gitDir} is not a git directory (no objects/)`);
125
+ await checkConfig(commonDir);
126
+ return { gitDir, commonDir, root: dir };
127
+ }
128
+ const parent = dirname(dir);
129
+ if (parent === dir)
130
+ throw new GitError(`no git repository found at or above ${resolve(startDir)}`);
131
+ dir = parent;
132
+ }
133
+ }
134
+ // ---------------------------------------------------------------------------------------------
135
+ // Refs
136
+ // ---------------------------------------------------------------------------------------------
137
+ /** Conservative ref-name check: also guarantees the name cannot leave the git directory. */
138
+ const validRefName = (name) => name.length > 0 &&
139
+ !name.startsWith("-") &&
140
+ !name.startsWith("/") &&
141
+ !name.endsWith("/") &&
142
+ !name.endsWith(".") &&
143
+ !name.endsWith(".lock") &&
144
+ !name.includes("..") &&
145
+ !name.includes("//") &&
146
+ !name.includes("@{") &&
147
+ !name.split("/").some((part) => part.startsWith(".")) &&
148
+ !/[\x00-\x20~^:?*[\\\x7f]/.test(name);
149
+ /** Per-worktree refs live in the worktree's git dir; the rest in the common dir. */
150
+ const refDir = (repo, name) => !name.startsWith("refs/") || /^refs\/(worktree|bisect|rewritten)\//.test(name) ? repo.gitDir : repo.commonDir;
151
+ const readPackedRefs = async (repo) => {
152
+ const out = new Map();
153
+ const text = (await readOptional(join(repo.commonDir, "packed-refs")))?.toString("utf8");
154
+ if (!text)
155
+ return out;
156
+ for (const line of text.split(/\r?\n/)) {
157
+ if (line === "" || line.startsWith("#") || line.startsWith("^"))
158
+ continue;
159
+ const m = /^([0-9a-f]{40}) (.+)$/.exec(line);
160
+ if (m)
161
+ out.set(m[2], m[1]);
162
+ }
163
+ return out;
164
+ };
165
+ const readRawRef = async (repo, name, packed) => {
166
+ const file = await readOptional(join(refDir(repo, name), name));
167
+ if (file) {
168
+ const text = file.toString("utf8");
169
+ const sym = /^ref:\s*(\S+)/.exec(text);
170
+ if (sym)
171
+ return { symbolic: sym[1] };
172
+ const id = /^([0-9a-f]{40})/.exec(text);
173
+ if (id)
174
+ return { id: id[1] };
175
+ throw new GitError(`ref ${name} is not readable (unexpected content)`);
176
+ }
177
+ if (name.startsWith("refs/")) {
178
+ const id = (await packed()).get(name);
179
+ if (id)
180
+ return { id };
181
+ }
182
+ return undefined;
183
+ };
184
+ /** Follows a ref to an object id; undefined when it (or the ref it points to) does not exist. */
185
+ const followRef = async (repo, name, packed) => {
186
+ let current = name;
187
+ for (let depth = 0; depth < 10; depth++) {
188
+ if (!validRefName(current))
189
+ throw new GitError(`invalid ref name: ${current}`);
190
+ const raw = await readRawRef(repo, current, packed);
191
+ if (!raw)
192
+ return undefined;
193
+ if ("id" in raw)
194
+ return raw.id;
195
+ current = raw.symbolic;
196
+ }
197
+ throw new GitError(`ref ${name}: symbolic ref chain is too deep`);
198
+ };
199
+ /** Peels tags until it reaches a commit. */
200
+ const peelToCommit = async (repo, id, ref) => {
201
+ let current = id;
202
+ for (let depth = 0; depth < 20; depth++) {
203
+ const obj = await readObject(repo, current);
204
+ if (obj.type === "commit")
205
+ return current;
206
+ if (obj.type !== "tag")
207
+ throw new GitError(`${ref} is not a commit (it names a ${obj.type})`);
208
+ const m = /^object ([0-9a-f]{40})$/m.exec(obj.data.toString("utf8"));
209
+ if (!m)
210
+ throw new GitError(`tag ${current} has no object line`);
211
+ current = m[1];
212
+ }
213
+ throw new GitError(`${ref}: tag chain is too deep`);
214
+ };
215
+ /** Resolves a ref (or a full 40-hex id) to a commit id, in git's documented order. */
216
+ export async function resolveRef(repo, ref) {
217
+ if (HEX40.test(ref))
218
+ return peelToCommit(repo, ref, ref);
219
+ if (!validRefName(ref))
220
+ throw new GitError(`invalid ref name: ${ref}`);
221
+ let packedCache;
222
+ const packed = () => (packedCache ??= readPackedRefs(repo));
223
+ if (ref === "HEAD") {
224
+ const raw = await readRawRef(repo, "HEAD", packed);
225
+ if (!raw)
226
+ throw new GitError(`HEAD not found in ${repo.gitDir}`);
227
+ const id = "id" in raw ? raw.id : await followRef(repo, raw.symbolic, packed);
228
+ if (!id)
229
+ throw new GitError(`HEAD is unborn: ${"symbolic" in raw ? raw.symbolic : "HEAD"} has no commit yet`);
230
+ return peelToCommit(repo, id, "HEAD");
231
+ }
232
+ const candidates = [
233
+ // `$GIT_DIR/<ref>` only for pseudo-refs (HEAD, ORIG_HEAD, FETCH_HEAD, …) and full names.
234
+ ...(/^[A-Z][A-Z0-9_]*$/.test(ref) || ref.startsWith("refs/") ? [ref] : []),
235
+ `refs/${ref}`,
236
+ `refs/tags/${ref}`,
237
+ `refs/heads/${ref}`,
238
+ `refs/remotes/${ref}`,
239
+ `refs/remotes/${ref}/HEAD`,
240
+ ];
241
+ for (const name of candidates) {
242
+ if (!validRefName(name))
243
+ continue;
244
+ const id = await followRef(repo, name, packed);
245
+ if (id)
246
+ return peelToCommit(repo, id, ref);
247
+ }
248
+ throw new GitError(`ref not found: ${ref}`);
249
+ }
250
+ // ---------------------------------------------------------------------------------------------
251
+ // Objects: loose, packs (v2 .idx, OFS_DELTA, REF_DELTA), alternates
252
+ // ---------------------------------------------------------------------------------------------
253
+ const objectDirs = (repo) => {
254
+ const s = state(repo);
255
+ return (s.objectDirs ??= (async () => {
256
+ const dirs = [];
257
+ const visit = async (dir, depth) => {
258
+ if (dirs.includes(dir))
259
+ return;
260
+ if (depth > 5)
261
+ throw new GitError(`objects/info/alternates nests too deeply at ${dir}`);
262
+ if ((await kind(dir)) !== "dir") {
263
+ if (depth === 0)
264
+ throw new GitError(`object directory not found: ${dir}`);
265
+ throw new GitError(`alternate object directory not found: ${dir}`);
266
+ }
267
+ dirs.push(dir);
268
+ const text = (await readOptional(join(dir, "info", "alternates")))?.toString("utf8");
269
+ if (!text)
270
+ return;
271
+ for (const raw of text.split(/\r?\n/)) {
272
+ const line = raw.trim();
273
+ if (line === "" || line.startsWith("#"))
274
+ continue;
275
+ if (line.startsWith('"'))
276
+ throw new GitError(`unsupported quoted path in ${join(dir, "info", "alternates")}`);
277
+ await visit(isAbsolute(line) ? resolve(line) : resolve(dir, line), depth + 1);
278
+ }
279
+ };
280
+ await visit(join(repo.commonDir, "objects"), 0);
281
+ return dirs;
282
+ })());
283
+ };
284
+ const listPacks = (repo) => {
285
+ const s = state(repo);
286
+ return (s.packs ??= (async () => {
287
+ const packs = [];
288
+ for (const dir of await objectDirs(repo)) {
289
+ const packDir = join(dir, "pack");
290
+ let names;
291
+ try {
292
+ names = await readdir(packDir);
293
+ }
294
+ catch {
295
+ continue;
296
+ }
297
+ const idx = new Set(names.filter((n) => n.endsWith(".idx")));
298
+ for (const name of names.filter((n) => n.endsWith(".pack")).sort()) {
299
+ const base = name.slice(0, -".pack".length);
300
+ if (!idx.has(`${base}.idx`)) {
301
+ const midx = names.includes("multi-pack-index") ? " (a multi-pack-index without .idx files is not supported)" : "";
302
+ throw new GitError(`pack ${join(packDir, name)} has no .idx${midx}`);
303
+ }
304
+ packs.push({ packPath: join(packDir, name), idxPath: join(packDir, `${base}.idx`) });
305
+ }
306
+ }
307
+ return packs;
308
+ })());
309
+ };
310
+ const loadIndex = async (pack) => {
311
+ if (pack.index)
312
+ return pack.index;
313
+ const buf = await readOptional(pack.idxPath);
314
+ if (!buf)
315
+ throw new GitError(`pack index missing: ${pack.idxPath}`);
316
+ if (buf.length < 8 || buf.readUInt32BE(0) !== 0xff744f63)
317
+ throw new GitError(`unsupported pack index v1: ${pack.idxPath} (only v2 is supported)`);
318
+ const version = buf.readUInt32BE(4);
319
+ if (version !== 2)
320
+ throw new GitError(`unsupported pack index version ${version}: ${pack.idxPath}`);
321
+ const fanout = new Uint32Array(256);
322
+ for (let i = 0; i < 256; i++)
323
+ fanout[i] = buf.readUInt32BE(8 + i * 4);
324
+ const count = fanout[255];
325
+ const namesAt = 8 + 256 * 4;
326
+ const offsetsAt = namesAt + count * 20 + count * 4;
327
+ const largeAt = offsetsAt + count * 4;
328
+ if (buf.length < largeAt + 40)
329
+ throw new GitError(`pack index is truncated: ${pack.idxPath}`);
330
+ const offsets = new Array(count);
331
+ for (let i = 0; i < count; i++) {
332
+ const o = buf.readUInt32BE(offsetsAt + i * 4);
333
+ if (o & 0x80000000) {
334
+ const at = largeAt + (o & 0x7fffffff) * 8;
335
+ if (at + 8 > buf.length - 40)
336
+ throw new GitError(`pack index is truncated: ${pack.idxPath}`);
337
+ offsets[i] = Number(buf.readBigUInt64BE(at));
338
+ }
339
+ else
340
+ offsets[i] = o;
341
+ }
342
+ let packSize;
343
+ try {
344
+ packSize = (await stat(pack.packPath)).size;
345
+ }
346
+ catch {
347
+ throw new GitError(`pack file missing: ${pack.packPath}`);
348
+ }
349
+ pack.index = { fanout, count, names: buf.subarray(namesAt, namesAt + count * 20), offsets, packSize };
350
+ return pack.index;
351
+ };
352
+ const findInIndex = (index, id) => {
353
+ const first = id[0];
354
+ let lo = first === 0 ? 0 : index.fanout[first - 1];
355
+ let hi = index.fanout[first];
356
+ while (lo < hi) {
357
+ const mid = (lo + hi) >>> 1;
358
+ const cmp = index.names.compare(id, 0, 20, mid * 20, mid * 20 + 20);
359
+ if (cmp === 0)
360
+ return index.offsets[mid];
361
+ if (cmp < 0)
362
+ lo = mid + 1;
363
+ else
364
+ hi = mid;
365
+ }
366
+ return undefined;
367
+ };
368
+ /** The offset where the entry at `offset` ends: the next entry, or the pack trailer. */
369
+ const entryEnd = (index, offset) => {
370
+ if (!index.sorted) {
371
+ const sorted = new Float64Array(index.count + 1);
372
+ for (let i = 0; i < index.count; i++)
373
+ sorted[i] = index.offsets[i];
374
+ sorted[index.count] = index.packSize - 20;
375
+ sorted.sort();
376
+ index.sorted = sorted;
377
+ }
378
+ const s = index.sorted;
379
+ let lo = 0;
380
+ let hi = s.length;
381
+ while (lo < hi) {
382
+ const mid = (lo + hi) >>> 1;
383
+ if (s[mid] <= offset)
384
+ lo = mid + 1;
385
+ else
386
+ hi = mid;
387
+ }
388
+ if (lo >= s.length)
389
+ throw new GitError("pack entry offset is out of range");
390
+ return s[lo];
391
+ };
392
+ /** Largest object the reader materializes (1 GiB); a larger one fails closed. */
393
+ const MAX_OBJECT_SIZE = 2 ** 30;
394
+ /** Longest delta chain followed across OFS_DELTA and REF_DELTA links; a cycle hits it and fails closed. */
395
+ const MAX_DELTA_DEPTH = 10000;
396
+ const TYPES = { 1: "commit", 2: "tree", 3: "blob", 4: "tag" };
397
+ const inflate = (data, expected, what) => {
398
+ let out;
399
+ try {
400
+ // Never inflate more than the header promises: a crafted object cannot grow without bound.
401
+ out = inflateSync(data, { maxOutputLength: Math.max(1, Math.min(expected + 1, MAX_OBJECT_SIZE)) });
402
+ }
403
+ catch (err) {
404
+ throw new GitError(`cannot inflate ${what}: ${err.message}`);
405
+ }
406
+ if (out.length !== expected)
407
+ throw new GitError(`corrupt ${what}: size ${out.length}, expected ${expected}`);
408
+ return out;
409
+ };
410
+ const applyDelta = (base, delta, what) => {
411
+ let pos = 0;
412
+ const varint = () => {
413
+ let value = 0;
414
+ let shift = 0;
415
+ let c;
416
+ do {
417
+ if (pos >= delta.length)
418
+ throw new GitError(`corrupt delta in ${what}`);
419
+ c = delta[pos++];
420
+ value += (c & 0x7f) * 2 ** shift;
421
+ shift += 7;
422
+ } while (c & 0x80);
423
+ return value;
424
+ };
425
+ if (varint() !== base.length)
426
+ throw new GitError(`corrupt delta in ${what}: base size mismatch`);
427
+ const size = varint();
428
+ if (size > MAX_OBJECT_SIZE)
429
+ throw new GitError(`delta in ${what} claims ${size} bytes, more than the ${MAX_OBJECT_SIZE} supported`);
430
+ const out = Buffer.allocUnsafe(size);
431
+ let o = 0;
432
+ while (pos < delta.length) {
433
+ const op = delta[pos++];
434
+ if (op & 0x80) {
435
+ let off = 0;
436
+ let len = 0;
437
+ for (let i = 0; i < 4; i++)
438
+ if (op & (1 << i))
439
+ off += delta[pos++] * 2 ** (8 * i);
440
+ for (let i = 0; i < 3; i++)
441
+ if (op & (1 << (4 + i)))
442
+ len += delta[pos++] * 2 ** (8 * i);
443
+ if (len === 0)
444
+ len = 0x10000;
445
+ if (off + len > base.length || o + len > size)
446
+ throw new GitError(`corrupt delta in ${what}: copy out of range`);
447
+ base.copy(out, o, off, off + len);
448
+ o += len;
449
+ }
450
+ else if (op > 0) {
451
+ if (pos + op > delta.length || o + op > size)
452
+ throw new GitError(`corrupt delta in ${what}: insert out of range`);
453
+ delta.copy(out, o, pos, pos + op);
454
+ pos += op;
455
+ o += op;
456
+ }
457
+ else
458
+ throw new GitError(`corrupt delta in ${what}: reserved opcode 0`);
459
+ }
460
+ if (o !== size)
461
+ throw new GitError(`corrupt delta in ${what}: result size mismatch`);
462
+ return out;
463
+ };
464
+ const readPacked = async (repo, pack, index, startOffset, startDepth, chain) => {
465
+ const fh = await open(pack.packPath, "r");
466
+ try {
467
+ const at = async (offset, depth) => {
468
+ if (depth > MAX_DELTA_DEPTH)
469
+ throw new GitError(`delta chain too deep (or a delta cycle) in ${pack.packPath}`);
470
+ const end = entryEnd(index, offset);
471
+ const buf = Buffer.allocUnsafe(end - offset);
472
+ const { bytesRead } = await fh.read(buf, 0, buf.length, offset);
473
+ if (bytesRead !== buf.length)
474
+ throw new GitError(`pack ${pack.packPath} is truncated`);
475
+ let pos = 0;
476
+ let c = buf[pos++];
477
+ const typeNo = (c >> 4) & 7;
478
+ let size = c & 0x0f;
479
+ let shift = 4;
480
+ while (c & 0x80) {
481
+ c = buf[pos++];
482
+ size += (c & 0x7f) * 2 ** shift;
483
+ shift += 7;
484
+ }
485
+ const what = `object at ${offset} in ${pack.packPath}`;
486
+ const type = TYPES[typeNo];
487
+ if (type)
488
+ return { type, data: inflate(buf.subarray(pos), size, what) };
489
+ if (typeNo === 6) {
490
+ c = buf[pos++];
491
+ let rel = c & 0x7f;
492
+ while (c & 0x80) {
493
+ c = buf[pos++];
494
+ rel = (rel + 1) * 128 + (c & 0x7f);
495
+ }
496
+ const baseOffset = offset - rel;
497
+ if (baseOffset < 12 || baseOffset >= offset)
498
+ throw new GitError(`corrupt OFS_DELTA base in ${what}`);
499
+ const base = await at(baseOffset, depth + 1);
500
+ return { type: base.type, data: applyDelta(base.data, inflate(buf.subarray(pos), size, what), what) };
501
+ }
502
+ if (typeNo === 7) {
503
+ const baseId = buf.subarray(pos, pos + 20).toString("hex");
504
+ pos += 20;
505
+ const base = await readObject(repo, baseId, depth + 1, chain);
506
+ return { type: base.type, data: applyDelta(base.data, inflate(buf.subarray(pos), size, what), what) };
507
+ }
508
+ throw new GitError(`unknown object type ${typeNo} in ${what}`);
509
+ };
510
+ return await at(startOffset, startDepth);
511
+ }
512
+ finally {
513
+ await fh.close();
514
+ }
515
+ };
516
+ const readLoose = async (dir, id) => {
517
+ const file = await readOptional(join(dir, id.slice(0, 2), id.slice(2)));
518
+ if (!file)
519
+ return undefined;
520
+ let raw;
521
+ try {
522
+ raw = inflateSync(file, { maxOutputLength: MAX_OBJECT_SIZE + 64 });
523
+ }
524
+ catch (err) {
525
+ throw new GitError(`cannot inflate loose object ${id}: ${err.message}`);
526
+ }
527
+ const nul = raw.indexOf(0);
528
+ const m = nul > 0 ? /^(commit|tree|blob|tag) (\d+)$/.exec(raw.subarray(0, nul).toString("latin1")) : null;
529
+ if (!m)
530
+ throw new GitError(`corrupt loose object ${id}: bad header`);
531
+ const data = raw.subarray(nul + 1);
532
+ if (data.length !== Number(m[2]))
533
+ throw new GitError(`corrupt loose object ${id}: size mismatch`);
534
+ return { type: m[1], data };
535
+ };
536
+ /** `chain` holds the ids being resolved through REF_DELTA links, so a delta cycle fails at once. */
537
+ const readObject = async (repo, id, depth = 0, chain = new Set()) => {
538
+ if (!HEX40.test(id))
539
+ throw new GitError(`invalid object id: ${id}`);
540
+ const s = state(repo);
541
+ const hit = s.cache.get(id);
542
+ if (hit)
543
+ return hit;
544
+ if (chain.has(id))
545
+ throw new GitError(`delta cycle at object ${id}`);
546
+ chain.add(id);
547
+ let obj;
548
+ const bin = Buffer.from(id, "hex");
549
+ for (const pack of await listPacks(repo)) {
550
+ const index = await loadIndex(pack);
551
+ const offset = findInIndex(index, bin);
552
+ if (offset !== undefined) {
553
+ obj = await readPacked(repo, pack, index, offset, depth, chain);
554
+ break;
555
+ }
556
+ }
557
+ if (!obj)
558
+ for (const dir of await objectDirs(repo)) {
559
+ obj = await readLoose(dir, id);
560
+ if (obj)
561
+ break;
562
+ }
563
+ if (!obj)
564
+ throw new GitError(`object not found: ${id} (it is never fetched)`);
565
+ if (s.cache.size >= CACHE_LIMIT)
566
+ s.cache.delete(s.cache.keys().next().value);
567
+ s.cache.set(id, obj);
568
+ return obj;
569
+ };
570
+ const readTyped = async (repo, id, type) => {
571
+ const obj = await readObject(repo, id);
572
+ if (obj.type !== type)
573
+ throw new GitError(`object ${id} is a ${obj.type}, not a ${type}`);
574
+ return obj.data;
575
+ };
576
+ // ---------------------------------------------------------------------------------------------
577
+ // Commits, history, trees and blobs
578
+ // ---------------------------------------------------------------------------------------------
579
+ const parseCommit = (data, id) => {
580
+ const end = data.indexOf("\n\n");
581
+ const header = data.subarray(0, end < 0 ? data.length : end).toString("utf8");
582
+ let tree;
583
+ const parents = [];
584
+ let time = 0;
585
+ for (const line of header.split("\n")) {
586
+ if (line.startsWith("tree "))
587
+ tree ??= line.slice(5);
588
+ else if (line.startsWith("parent "))
589
+ parents.push(line.slice(7));
590
+ else if (line.startsWith("committer "))
591
+ time = Number(/ (\d+) [+-]\d{4}$/.exec(line)?.[1] ?? 0);
592
+ }
593
+ if (!tree || !HEX40.test(tree) || parents.some((p) => !HEX40.test(p)))
594
+ throw new GitError(`corrupt commit ${id}`);
595
+ return { tree, parents, time };
596
+ };
597
+ /** Reads a commit's tree and parents. */
598
+ export async function readCommit(repo, id) {
599
+ const { tree, parents } = parseCommit(await readTyped(repo, id, "commit"), id);
600
+ return { tree, parents };
601
+ }
602
+ const shallowSet = (repo) => {
603
+ const s = state(repo);
604
+ return (s.shallow ??= (async () => {
605
+ const text = (await readOptional(join(repo.commonDir, "shallow")))?.toString("utf8") ?? "";
606
+ return new Set(text.split(/\r?\n/).filter((l) => HEX40.test(l)));
607
+ })());
608
+ };
609
+ /** Every ancestor of `start` (inclusive), not following the parents of shallow commits. */
610
+ const ancestors = async (repo, start, shallow) => {
611
+ const seen = new Map();
612
+ const queue = [start];
613
+ for (let i = 0; i < queue.length; i++) {
614
+ const id = queue[i];
615
+ if (seen.has(id))
616
+ continue;
617
+ let commit;
618
+ try {
619
+ commit = parseCommit(await readTyped(repo, id, "commit"), id);
620
+ }
621
+ catch (err) {
622
+ if (id !== start && err instanceof GitError && err.message.startsWith("object not found"))
623
+ throw new GitError(`merge base not found: commit ${id} is missing (shallow or incomplete history)`);
624
+ throw err;
625
+ }
626
+ const parents = shallow.has(id) ? [] : commit.parents;
627
+ seen.set(id, { parents, time: commit.time });
628
+ for (const p of parents)
629
+ if (!seen.has(p))
630
+ queue.push(p);
631
+ }
632
+ return seen;
633
+ };
634
+ /**
635
+ * A best common ancestor of two commits (breadth-first over parents). When several exist
636
+ * (criss-cross merges) the one with the newest committer date wins, ties broken by id.
637
+ */
638
+ export async function mergeBase(repo, a, b) {
639
+ const shallow = await shallowSet(repo);
640
+ const fromA = await ancestors(repo, a, shallow);
641
+ const fromB = await ancestors(repo, b, shallow);
642
+ const common = new Map();
643
+ for (const [id, c] of fromB)
644
+ if (fromA.has(id))
645
+ common.set(id, c);
646
+ // The common set is closed under ancestry, so a common commit is redundant exactly when it is
647
+ // a parent of another common commit.
648
+ const redundant = new Set();
649
+ for (const c of common.values())
650
+ for (const p of c.parents)
651
+ redundant.add(p);
652
+ const best = [...common].filter(([id]) => !redundant.has(id));
653
+ if (best.length === 0)
654
+ throw new GitError(`merge base not found for ${a} and ${b}`);
655
+ best.sort(([ia, ca], [ib, cb]) => cb.time - ca.time || (ia < ib ? -1 : ia > ib ? 1 : 0));
656
+ return best[0][0];
657
+ }
658
+ const readTree = async (repo, id) => {
659
+ const data = await readTyped(repo, id, "tree");
660
+ const entries = [];
661
+ let pos = 0;
662
+ while (pos < data.length) {
663
+ const space = data.indexOf(0x20, pos);
664
+ const nul = data.indexOf(0, space + 1);
665
+ if (space < 0 || nul < 0 || nul + 21 > data.length)
666
+ throw new GitError(`corrupt tree ${id}`);
667
+ entries.push({
668
+ mode: data.subarray(pos, space).toString("latin1"),
669
+ name: data.subarray(space + 1, nul).toString("utf8"),
670
+ id: data.subarray(nul + 1, nul + 21).toString("hex"),
671
+ });
672
+ pos = nul + 21;
673
+ }
674
+ return entries;
675
+ };
676
+ const isTree = (mode) => mode === "40000" || mode === "040000";
677
+ /** Every non-tree path under a tree (gitlinks are listed as a path, never entered). */
678
+ const allPaths = async (repo, id, prefix, out) => {
679
+ for (const e of await readTree(repo, id)) {
680
+ const path = `${prefix}${e.name}`;
681
+ if (isTree(e.mode))
682
+ await allPaths(repo, e.id, `${path}/`, out);
683
+ else
684
+ out.push(path);
685
+ }
686
+ };
687
+ /**
688
+ * Sorted repo-relative paths of every added, removed or modified non-tree entry between two
689
+ * trees. Compares entry id and mode; no rename detection.
690
+ */
691
+ export async function diffTrees(repo, a, b) {
692
+ const out = [];
693
+ const walk = async (ta, tb, prefix) => {
694
+ if (ta === tb)
695
+ return;
696
+ const ea = new Map((ta ? await readTree(repo, ta) : []).map((e) => [e.name, e]));
697
+ const eb = new Map((tb ? await readTree(repo, tb) : []).map((e) => [e.name, e]));
698
+ for (const name of new Set([...ea.keys(), ...eb.keys()])) {
699
+ const x = ea.get(name);
700
+ const y = eb.get(name);
701
+ const path = `${prefix}${name}`;
702
+ if (x && y && x.id === y.id && x.mode === y.mode)
703
+ continue;
704
+ const xTree = x !== undefined && isTree(x.mode);
705
+ const yTree = y !== undefined && isTree(y.mode);
706
+ if (xTree || yTree)
707
+ await walk(xTree ? x.id : undefined, yTree ? y.id : undefined, `${path}/`);
708
+ if ((x && !xTree) || (y && !yTree))
709
+ out.push(path);
710
+ }
711
+ };
712
+ await walk(a, b, "");
713
+ return out.sort();
714
+ }
715
+ /** Lists directories and regular files below a committed directory, relative to it. */
716
+ export async function listTreePaths(repo, treeId, directory, descend) {
717
+ let subtree = treeId;
718
+ for (const part of directory.split("/").filter(Boolean)) {
719
+ const entry = (await readTree(repo, subtree)).find((candidate) => candidate.name === part && isTree(candidate.mode));
720
+ if (!entry)
721
+ return new Set();
722
+ subtree = entry.id;
723
+ }
724
+ const paths = new Set();
725
+ const walk = async (tree, prefix) => {
726
+ for (const entry of await readTree(repo, tree)) {
727
+ const path = prefix + entry.name;
728
+ if (isTree(entry.mode) && descend(entry.name)) {
729
+ paths.add(path);
730
+ await walk(entry.id, path + "/");
731
+ }
732
+ else if (entry.mode === "100644" || entry.mode === "100755") {
733
+ paths.add(path);
734
+ }
735
+ }
736
+ };
737
+ await walk(subtree, "");
738
+ return paths;
739
+ }
740
+ /**
741
+ * The content of the blob at `path` ("/"-separated) in a tree, or undefined when the path is
742
+ * absent there or is not a blob (a tree or a gitlink). A symlink's blob is its target text.
743
+ */
744
+ export async function readBlob(repo, treeId, path) {
745
+ const parts = path.split("/");
746
+ if (parts.some((p) => p === "" || p === "." || p === ".."))
747
+ throw new GitError(`invalid path: ${path}`);
748
+ let tree = treeId;
749
+ for (let i = 0; i < parts.length; i++) {
750
+ const entry = (await readTree(repo, tree)).find((e) => e.name === parts[i]);
751
+ if (!entry)
752
+ return undefined;
753
+ if (i < parts.length - 1) {
754
+ if (!isTree(entry.mode))
755
+ return undefined;
756
+ tree = entry.id;
757
+ }
758
+ else {
759
+ if (isTree(entry.mode) || entry.mode === "160000")
760
+ return undefined;
761
+ return Buffer.from(await readTyped(repo, entry.id, "blob"));
762
+ }
763
+ }
764
+ return undefined;
765
+ }