@narumitw/pi-worktree 0.24.0

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/src/git.ts ADDED
@@ -0,0 +1,724 @@
1
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "node:fs";
2
+ import { basename, dirname, resolve } from "node:path";
3
+ import type { ExecResult, ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
+
5
+ const GIT_TIMEOUT_MS = 15_000;
6
+ const GIT_MUTATION_TIMEOUT_MS = 60_000;
7
+ const LOCAL_BRANCH_PREFIX = "refs/heads/";
8
+
9
+ export interface WorktreeRecord {
10
+ path: string;
11
+ head?: string;
12
+ branchRef?: string;
13
+ branch?: string;
14
+ isMain: boolean;
15
+ bare: boolean;
16
+ detached: boolean;
17
+ lockedReason?: string;
18
+ prunableReason?: string;
19
+ }
20
+
21
+ export interface AddArguments {
22
+ path: string;
23
+ branch: string;
24
+ startOid?: string;
25
+ }
26
+
27
+ export interface AdministrativePruneCandidate {
28
+ id: string;
29
+ administrativePath: string;
30
+ head?: string;
31
+ branchRef?: string;
32
+ indexDirty: boolean;
33
+ }
34
+
35
+ export interface GitClient {
36
+ exec(command: string, args: string[], options?: GitExecOptions): Promise<ExecResult>;
37
+ }
38
+
39
+ interface GitExecOptions {
40
+ cwd?: string;
41
+ signal?: AbortSignal;
42
+ timeout?: number;
43
+ }
44
+
45
+ export class GitWorktreeError extends Error {
46
+ readonly args?: readonly string[];
47
+
48
+ constructor(message: string, args?: readonly string[]) {
49
+ super(message);
50
+ this.name = "GitWorktreeError";
51
+ this.args = args;
52
+ }
53
+ }
54
+
55
+ export function parseWorktreePorcelain(output: string): WorktreeRecord[] {
56
+ const records: WorktreeRecord[] = [];
57
+ let current: Omit<WorktreeRecord, "isMain"> | undefined;
58
+
59
+ const finish = () => {
60
+ if (!current) return;
61
+ records.push({ ...current, isMain: records.length === 0 });
62
+ current = undefined;
63
+ };
64
+
65
+ for (const field of output.split("\0")) {
66
+ if (field === "") {
67
+ finish();
68
+ continue;
69
+ }
70
+ const separator = field.indexOf(" ");
71
+ const key = separator < 0 ? field : field.slice(0, separator);
72
+ const value = separator < 0 ? "" : field.slice(separator + 1);
73
+
74
+ if (key === "worktree") {
75
+ finish();
76
+ if (!value) throw new GitWorktreeError("Worktree porcelain record is missing path.");
77
+ current = { path: value, bare: false, detached: false };
78
+ continue;
79
+ }
80
+ if (!current) {
81
+ throw new GitWorktreeError(
82
+ `Worktree porcelain field ${JSON.stringify(key)} appears before worktree.`,
83
+ );
84
+ }
85
+
86
+ switch (key) {
87
+ case "HEAD":
88
+ current.head = value;
89
+ break;
90
+ case "branch":
91
+ current.branchRef = value;
92
+ current.branch = value.startsWith(LOCAL_BRANCH_PREFIX)
93
+ ? value.slice(LOCAL_BRANCH_PREFIX.length)
94
+ : undefined;
95
+ break;
96
+ case "bare":
97
+ current.bare = true;
98
+ break;
99
+ case "detached":
100
+ current.detached = true;
101
+ break;
102
+ case "locked":
103
+ current.lockedReason = value;
104
+ break;
105
+ case "prunable":
106
+ current.prunableReason = value;
107
+ break;
108
+ }
109
+ }
110
+ finish();
111
+ return records;
112
+ }
113
+
114
+ export function worktreeForBranch(
115
+ records: readonly WorktreeRecord[],
116
+ branch: string,
117
+ ): WorktreeRecord | undefined {
118
+ const branchRef = `${LOCAL_BRANCH_PREFIX}${branch}`;
119
+ return records.find((record) => record.branchRef === branchRef);
120
+ }
121
+
122
+ export function defaultWorktreePath(mainWorktreePath: string, branch: string): string {
123
+ return resolve(
124
+ dirname(mainWorktreePath),
125
+ `${basename(mainWorktreePath)}-${branch.replaceAll("/", "-")}`,
126
+ );
127
+ }
128
+
129
+ export function buildAddArguments(input: AddArguments): string[] {
130
+ return input.startOid
131
+ ? ["worktree", "add", "-b", input.branch, input.path, input.startOid]
132
+ : ["worktree", "add", input.path, input.branch];
133
+ }
134
+
135
+ export function pathIdentity(path: string): string {
136
+ const absolute = resolve(path);
137
+ if (!existsSync(absolute)) return absolute;
138
+ try {
139
+ return realpathSync.native(absolute);
140
+ } catch {
141
+ return absolute;
142
+ }
143
+ }
144
+
145
+ export function pathEntryExists(path: string): boolean {
146
+ try {
147
+ lstatSync(path);
148
+ return true;
149
+ } catch (error) {
150
+ if (isNodeError(error) && error.code === "ENOENT") return false;
151
+ throw new GitWorktreeError(`Cannot inspect filesystem path ${path}: ${formatError(error)}`);
152
+ }
153
+ }
154
+
155
+ export function pathsEqual(left: string, right: string): boolean {
156
+ return pathIdentity(left) === pathIdentity(right);
157
+ }
158
+
159
+ export function sameWorktreeIdentity(left: WorktreeRecord, right: WorktreeRecord): boolean {
160
+ return (
161
+ pathsEqual(left.path, right.path) &&
162
+ left.head === right.head &&
163
+ left.branchRef === right.branchRef &&
164
+ left.detached === right.detached &&
165
+ left.isMain === right.isMain &&
166
+ left.bare === right.bare
167
+ );
168
+ }
169
+
170
+ export async function listWorktrees(
171
+ pi: Pick<ExtensionAPI, "exec">,
172
+ cwd: string,
173
+ signal?: AbortSignal,
174
+ ): Promise<WorktreeRecord[]> {
175
+ const result = await runGit(pi, ["worktree", "list", "--porcelain", "-z"], cwd, signal);
176
+ return parseWorktreePorcelain(result.stdout);
177
+ }
178
+
179
+ export async function currentWorktreePath(
180
+ pi: Pick<ExtensionAPI, "exec">,
181
+ cwd: string,
182
+ signal?: AbortSignal,
183
+ ): Promise<string> {
184
+ const result = await runGit(pi, ["rev-parse", "--show-toplevel"], cwd, signal);
185
+ const path = removeLineEnding(result.stdout);
186
+ if (!path) throw new GitWorktreeError("Git did not return the current worktree path.");
187
+ return pathIdentity(path);
188
+ }
189
+
190
+ export async function symbolicBranch(
191
+ pi: Pick<ExtensionAPI, "exec">,
192
+ cwd: string,
193
+ signal?: AbortSignal,
194
+ ): Promise<string | undefined> {
195
+ const result = await runGitAllowFailure(
196
+ pi,
197
+ ["symbolic-ref", "--quiet", "--short", "HEAD"],
198
+ cwd,
199
+ signal,
200
+ );
201
+ if (result.killed) throw killedError(["symbolic-ref", "--quiet", "--short", "HEAD"]);
202
+ if (result.code !== 0) return undefined;
203
+ return result.stdout.trim() || undefined;
204
+ }
205
+
206
+ export async function validateBranch(
207
+ pi: Pick<ExtensionAPI, "exec">,
208
+ cwd: string,
209
+ branch: string,
210
+ signal?: AbortSignal,
211
+ ): Promise<string> {
212
+ const result = await runGit(pi, ["check-ref-format", "--branch", branch], cwd, signal);
213
+ const normalized = result.stdout.trim();
214
+ if (!normalized) throw new GitWorktreeError("Git returned an empty branch name.");
215
+ return normalized;
216
+ }
217
+
218
+ export async function localBranchExists(
219
+ pi: Pick<ExtensionAPI, "exec">,
220
+ cwd: string,
221
+ branch: string,
222
+ signal?: AbortSignal,
223
+ ): Promise<boolean> {
224
+ const result = await runGitAllowFailure(
225
+ pi,
226
+ ["show-ref", "--verify", "--quiet", `${LOCAL_BRANCH_PREFIX}${branch}`],
227
+ cwd,
228
+ signal,
229
+ );
230
+ if (result.killed) throw killedError(["show-ref", "--verify", "--quiet"]);
231
+ if (result.code === 0) return true;
232
+ if (result.code === 1) return false;
233
+ throw gitFailure(["show-ref", "--verify", "--quiet"], result);
234
+ }
235
+
236
+ export async function resolveCommit(
237
+ pi: Pick<ExtensionAPI, "exec">,
238
+ cwd: string,
239
+ startPoint: string,
240
+ signal?: AbortSignal,
241
+ ): Promise<string> {
242
+ const result = await runGit(
243
+ pi,
244
+ ["rev-parse", "--verify", "--end-of-options", `${startPoint}^{commit}`],
245
+ cwd,
246
+ signal,
247
+ );
248
+ const oid = result.stdout.trim();
249
+ if (!/^[0-9a-fA-F]{40,64}$/u.test(oid)) {
250
+ throw new GitWorktreeError(`Git returned an invalid commit object for ${startPoint}.`);
251
+ }
252
+ return oid;
253
+ }
254
+
255
+ export async function addWorktree(
256
+ pi: Pick<ExtensionAPI, "exec">,
257
+ cwd: string,
258
+ input: AddArguments,
259
+ signal?: AbortSignal,
260
+ ): Promise<void> {
261
+ await runGit(pi, buildAddArguments(input), cwd, signal, GIT_MUTATION_TIMEOUT_MS);
262
+ }
263
+
264
+ export async function removeWorktree(
265
+ pi: Pick<ExtensionAPI, "exec">,
266
+ cwd: string,
267
+ path: string,
268
+ signal?: AbortSignal,
269
+ ): Promise<void> {
270
+ await runGit(pi, ["worktree", "remove", path], cwd, signal, GIT_MUTATION_TIMEOUT_MS);
271
+ }
272
+
273
+ export async function worktreeInventory(
274
+ pi: Pick<ExtensionAPI, "exec">,
275
+ path: string,
276
+ signal?: AbortSignal,
277
+ ): Promise<string[]> {
278
+ const statusArgs = [
279
+ "status",
280
+ "--porcelain=v1",
281
+ "--untracked-files=all",
282
+ "--ignored=matching",
283
+ "--ignore-submodules=none",
284
+ ];
285
+ const status = await runGit(pi, statusArgs, path, signal);
286
+ const submoduleStatus = await runGit(pi, ["submodule", "status", "--recursive"], path, signal);
287
+ const initializedSubmodules = nonEmptyLines(submoduleStatus.stdout)
288
+ .filter((line) => !line.startsWith("-"))
289
+ .map((line) => `initialized submodule: ${line.slice(1).trimStart()}`);
290
+ const submodules = await runGit(
291
+ pi,
292
+ [
293
+ "submodule",
294
+ "foreach",
295
+ "--recursive",
296
+ "--quiet",
297
+ "git status --porcelain=v1 --untracked-files=all --ignored=matching --ignore-submodules=none",
298
+ ],
299
+ path,
300
+ signal,
301
+ );
302
+ return [
303
+ ...nonEmptyLines(status.stdout),
304
+ ...initializedSubmodules,
305
+ ...nonEmptyLines(submodules.stdout),
306
+ ];
307
+ }
308
+
309
+ export async function worktreeAdministrativeDirectory(
310
+ pi: Pick<ExtensionAPI, "exec">,
311
+ cwd: string,
312
+ signal?: AbortSignal,
313
+ ): Promise<string> {
314
+ const result = await runGit(
315
+ pi,
316
+ ["rev-parse", "--path-format=absolute", "--git-dir"],
317
+ cwd,
318
+ signal,
319
+ );
320
+ const value = removeLineEnding(result.stdout);
321
+ if (!value) throw new GitWorktreeError("Git did not return its worktree administrative path.");
322
+ return resolve(cwd, value);
323
+ }
324
+
325
+ export async function administrativeHistoryOids(
326
+ pi: Pick<ExtensionAPI, "exec">,
327
+ cwd: string,
328
+ administrativePath: string,
329
+ signal?: AbortSignal,
330
+ ): Promise<string[]> {
331
+ const gitDirArgument = `--git-dir=${administrativePath}`;
332
+ const values = readAdministrativeReflogOids(resolve(administrativePath, "logs"));
333
+
334
+ const refs = await runGit(
335
+ pi,
336
+ [gitDirArgument, "for-each-ref", "--format=%(objectname)", "refs/worktree", "refs/bisect"],
337
+ cwd,
338
+ signal,
339
+ );
340
+ values.push(...splitAdministrativeOids(refs.stdout, "per-worktree refs"));
341
+
342
+ for (const name of [
343
+ "ORIG_HEAD",
344
+ "MERGE_HEAD",
345
+ "REBASE_HEAD",
346
+ "CHERRY_PICK_HEAD",
347
+ "REVERT_HEAD",
348
+ "BISECT_HEAD",
349
+ ]) {
350
+ const contents = readAdministrativeFile(administrativePath, name);
351
+ if (contents === undefined) continue;
352
+ values.push(...splitAdministrativeOids(contents, name));
353
+ }
354
+ const fetchHead = readAdministrativeFile(administrativePath, "FETCH_HEAD");
355
+ if (fetchHead !== undefined) {
356
+ values.push(...splitFetchHeadOids(fetchHead));
357
+ }
358
+ return [...new Set(values)];
359
+ }
360
+
361
+ export async function administrativePruneCandidates(
362
+ pi: Pick<ExtensionAPI, "exec">,
363
+ cwd: string,
364
+ signal?: AbortSignal,
365
+ ): Promise<AdministrativePruneCandidate[]> {
366
+ const commonResult = await runGit(
367
+ pi,
368
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
369
+ cwd,
370
+ signal,
371
+ );
372
+ const commonValue = removeLineEnding(commonResult.stdout);
373
+ if (!commonValue) throw new GitWorktreeError("Git did not return its common directory.");
374
+ const commonDirectory = resolve(cwd, commonValue);
375
+ const administrativeRoot = resolve(commonDirectory, "worktrees");
376
+ if (!existsSync(administrativeRoot)) return [];
377
+
378
+ const candidates: AdministrativePruneCandidate[] = [];
379
+ for (const entry of readdirSync(administrativeRoot, { withFileTypes: true })) {
380
+ const administrativePath = resolve(administrativeRoot, entry.name);
381
+ if (!entry.isDirectory() || entry.isSymbolicLink()) {
382
+ throw new GitWorktreeError(
383
+ `Unexpected Git worktree administrative entry: ${administrativePath}.`,
384
+ );
385
+ }
386
+ if (existsSync(resolve(administrativePath, "locked"))) continue;
387
+
388
+ const gitdirPath = resolve(administrativePath, "gitdir");
389
+ let registeredGitFile: string | undefined;
390
+ try {
391
+ registeredGitFile = removeLineEnding(readFileSync(gitdirPath, "utf8"));
392
+ } catch (error) {
393
+ if (!isNodeError(error) || error.code !== "ENOENT") throw error;
394
+ }
395
+ if (registeredGitFile) {
396
+ const targetGitFile = resolve(administrativePath, registeredGitFile);
397
+ if (existsSync(targetGitFile)) continue;
398
+ }
399
+
400
+ const headPath = resolve(administrativePath, "HEAD");
401
+ let headValue: string;
402
+ try {
403
+ if (!lstatSync(headPath).isFile()) {
404
+ throw new GitWorktreeError(`Git worktree administrative HEAD is not a file: ${headPath}.`);
405
+ }
406
+ headValue = removeLineEnding(readFileSync(headPath, "utf8"));
407
+ } catch (error) {
408
+ if (error instanceof GitWorktreeError) throw error;
409
+ throw new GitWorktreeError(
410
+ `Cannot inspect Git worktree administrative HEAD ${headPath}: ${formatError(error)}`,
411
+ );
412
+ }
413
+ const indexDirty = await administrativeIndexIsDirty(pi, cwd, administrativePath, signal);
414
+ if (headValue.startsWith("ref: ")) {
415
+ const branchRef = headValue.slice("ref: ".length);
416
+ if (!branchRef) {
417
+ throw new GitWorktreeError(
418
+ `Git worktree administrative HEAD has an empty ref: ${headPath}.`,
419
+ );
420
+ }
421
+ candidates.push({
422
+ id: entry.name,
423
+ administrativePath,
424
+ branchRef,
425
+ indexDirty,
426
+ });
427
+ continue;
428
+ }
429
+ if (!/^[0-9a-fA-F]{40,64}$/u.test(headValue)) {
430
+ throw new GitWorktreeError(`Git worktree administrative HEAD is malformed: ${headPath}.`);
431
+ }
432
+ candidates.push({
433
+ id: entry.name,
434
+ administrativePath,
435
+ head: headValue,
436
+ indexDirty,
437
+ });
438
+ }
439
+ return candidates;
440
+ }
441
+
442
+ async function administrativeIndexIsDirty(
443
+ pi: Pick<ExtensionAPI, "exec">,
444
+ cwd: string,
445
+ administrativePath: string,
446
+ signal?: AbortSignal,
447
+ ): Promise<boolean> {
448
+ const args = [
449
+ `--git-dir=${administrativePath}`,
450
+ "diff",
451
+ "--cached",
452
+ "--quiet",
453
+ "--no-ext-diff",
454
+ "--no-textconv",
455
+ "--ignore-submodules=none",
456
+ "--",
457
+ ];
458
+ const result = await runGitAllowFailure(pi, args, cwd, signal);
459
+ if (result.killed) throw killedError(args);
460
+ if (result.code === 0) return false;
461
+ if (result.code === 1) return true;
462
+ throw gitFailure(args, result);
463
+ }
464
+
465
+ export async function durableRefExists(
466
+ pi: Pick<ExtensionAPI, "exec">,
467
+ cwd: string,
468
+ ref: string,
469
+ signal?: AbortSignal,
470
+ ): Promise<boolean> {
471
+ if (!ref.startsWith("refs/") || ref.includes("\0")) {
472
+ throw new GitWorktreeError("Git worktree administrative HEAD contains an invalid ref.");
473
+ }
474
+ const result = await runGitAllowFailure(
475
+ pi,
476
+ ["show-ref", "--verify", "--quiet", ref],
477
+ cwd,
478
+ signal,
479
+ );
480
+ if (result.killed) throw killedError(["show-ref", "--verify", "--quiet"]);
481
+ if (result.code === 0) return true;
482
+ if (result.code === 1) return false;
483
+ throw gitFailure(["show-ref", "--verify", "--quiet"], result);
484
+ }
485
+
486
+ export async function durableRefsContaining(
487
+ pi: Pick<ExtensionAPI, "exec">,
488
+ cwd: string,
489
+ head: string,
490
+ signal?: AbortSignal,
491
+ ): Promise<string[]> {
492
+ if (!/^[0-9a-fA-F]{40,64}$/u.test(head)) {
493
+ throw new GitWorktreeError("Detached worktree has an invalid HEAD object.");
494
+ }
495
+ const result = await runGit(
496
+ pi,
497
+ [
498
+ "for-each-ref",
499
+ "--format=%(refname)",
500
+ `--contains=${head}`,
501
+ "refs/heads",
502
+ "refs/tags",
503
+ "refs/remotes",
504
+ ],
505
+ cwd,
506
+ signal,
507
+ );
508
+ return nonEmptyLines(result.stdout);
509
+ }
510
+
511
+ export async function prunePreview(
512
+ pi: Pick<ExtensionAPI, "exec">,
513
+ cwd: string,
514
+ signal?: AbortSignal,
515
+ ): Promise<string> {
516
+ const result = await runGit(pi, ["worktree", "prune", "--dry-run", "--verbose"], cwd, signal);
517
+ return combineOutput(result);
518
+ }
519
+
520
+ export async function pruneWorktrees(
521
+ pi: Pick<ExtensionAPI, "exec">,
522
+ cwd: string,
523
+ signal?: AbortSignal,
524
+ ): Promise<string> {
525
+ const result = await runGit(
526
+ pi,
527
+ ["worktree", "prune", "--verbose"],
528
+ cwd,
529
+ signal,
530
+ GIT_MUTATION_TIMEOUT_MS,
531
+ );
532
+ return combineOutput(result);
533
+ }
534
+
535
+ export function formatWorktree(record: WorktreeRecord, currentPath?: string): string {
536
+ const labels = [
537
+ currentPath && pathsEqual(record.path, currentPath) ? "current" : undefined,
538
+ record.isMain ? "main" : undefined,
539
+ record.bare ? "bare" : undefined,
540
+ record.detached ? "detached" : record.branch,
541
+ record.lockedReason !== undefined
542
+ ? `locked${record.lockedReason ? `: ${record.lockedReason}` : ""}`
543
+ : undefined,
544
+ record.prunableReason !== undefined
545
+ ? `prunable${record.prunableReason ? `: ${record.prunableReason}` : ""}`
546
+ : undefined,
547
+ ].filter((label): label is string => Boolean(label));
548
+ const head = record.head ? record.head.slice(0, 8) : "no HEAD";
549
+ return stripTerminalControls(`${record.path} [${labels.join(", ") || "unknown"}] ${head}`);
550
+ }
551
+
552
+ export function stripTerminalControls(value: string): string {
553
+ return [...value]
554
+ .filter((character) => {
555
+ const code = character.codePointAt(0) ?? 0;
556
+ return code > 0x1f && (code < 0x7f || code > 0x9f);
557
+ })
558
+ .join("");
559
+ }
560
+
561
+ async function runGit(
562
+ pi: Pick<ExtensionAPI, "exec">,
563
+ args: string[],
564
+ cwd: string,
565
+ signal?: AbortSignal,
566
+ timeout = GIT_TIMEOUT_MS,
567
+ ): Promise<ExecResult> {
568
+ const result = await runGitAllowFailure(pi, args, cwd, signal, timeout);
569
+ if (result.killed) throw killedError(args);
570
+ if (result.code !== 0) throw gitFailure(args, result);
571
+ return result;
572
+ }
573
+
574
+ async function runGitAllowFailure(
575
+ pi: Pick<ExtensionAPI, "exec">,
576
+ args: string[],
577
+ cwd: string,
578
+ signal?: AbortSignal,
579
+ timeout = GIT_TIMEOUT_MS,
580
+ ): Promise<ExecResult> {
581
+ try {
582
+ return await pi.exec("git", args, { cwd, signal, timeout });
583
+ } catch (error) {
584
+ const message = formatError(error);
585
+ if (/\bENOENT\b|not found/i.test(message)) {
586
+ throw new GitWorktreeError("Git executable was not found. Install Git and retry.", args);
587
+ }
588
+ throw new GitWorktreeError(
589
+ `Could not start git ${args.slice(0, 2).join(" ")}: ${message}`,
590
+ args,
591
+ );
592
+ }
593
+ }
594
+
595
+ function gitFailure(args: string[], result: ExecResult): GitWorktreeError {
596
+ const detail = stripTerminalControls(
597
+ [result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n"),
598
+ );
599
+ const hint = /not a git repository/i.test(detail)
600
+ ? "The current Pi workspace is not inside a Git repository."
601
+ : detail || `Git exited with code ${result.code}.`;
602
+ return new GitWorktreeError(`git ${args.slice(0, 2).join(" ")} failed: ${hint}`, args);
603
+ }
604
+
605
+ function killedError(args: string[]): GitWorktreeError {
606
+ return new GitWorktreeError(
607
+ `git ${args.slice(0, 2).join(" ")} timed out or was cancelled.`,
608
+ args,
609
+ );
610
+ }
611
+
612
+ function nonEmptyLines(value: string): string[] {
613
+ return value.split(/\r?\n/u).filter((line) => line.length > 0);
614
+ }
615
+
616
+ function combineOutput(result: ExecResult): string {
617
+ return [result.stdout.trimEnd(), result.stderr.trimEnd()].filter(Boolean).join("\n");
618
+ }
619
+
620
+ function removeLineEnding(value: string): string {
621
+ if (value.endsWith("\r\n")) return value.slice(0, -2);
622
+ if (value.endsWith("\n")) return value.slice(0, -1);
623
+ return value;
624
+ }
625
+
626
+ function splitAdministrativeOids(value: string, source: string): string[] {
627
+ const normalized = value.endsWith("\n") ? value.slice(0, -1) : value;
628
+ if (!normalized) return [];
629
+ const values = normalized
630
+ .split("\n")
631
+ .map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line));
632
+ if (values.some((oid) => !/^[0-9a-fA-F]{40,64}$/u.test(oid))) {
633
+ throw new GitWorktreeError(`Git returned malformed object IDs for ${source}.`);
634
+ }
635
+ return values;
636
+ }
637
+
638
+ function splitFetchHeadOids(value: string): string[] {
639
+ const normalized = value.endsWith("\n") ? value.slice(0, -1) : value;
640
+ if (!normalized) return [];
641
+ return normalized.split("\n").map((line) => {
642
+ const match = /^([0-9a-fA-F]{40,64})\t/u.exec(line);
643
+ if (!match?.[1]) {
644
+ throw new GitWorktreeError("Git worktree administrative FETCH_HEAD is malformed.");
645
+ }
646
+ return match[1];
647
+ });
648
+ }
649
+
650
+ function readAdministrativeFile(administrativePath: string, name: string): string | undefined {
651
+ const path = resolve(administrativePath, name);
652
+ let stat: ReturnType<typeof lstatSync>;
653
+ try {
654
+ stat = lstatSync(path);
655
+ } catch (error) {
656
+ if (isNodeError(error) && error.code === "ENOENT") return undefined;
657
+ throw new GitWorktreeError(
658
+ `Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`,
659
+ );
660
+ }
661
+ if (stat.isSymbolicLink() || !stat.isFile()) {
662
+ throw new GitWorktreeError(
663
+ `Git worktree administrative ${name} must be a regular file: ${path}.`,
664
+ );
665
+ }
666
+ try {
667
+ return readFileSync(path, "utf8");
668
+ } catch (error) {
669
+ throw new GitWorktreeError(
670
+ `Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`,
671
+ );
672
+ }
673
+ }
674
+
675
+ function readAdministrativeReflogOids(logPath: string): string[] {
676
+ if (!existsSync(logPath)) return [];
677
+ let stat: ReturnType<typeof lstatSync>;
678
+ try {
679
+ stat = lstatSync(logPath);
680
+ } catch (error) {
681
+ throw new GitWorktreeError(`Cannot inspect Git reflog path ${logPath}: ${formatError(error)}`);
682
+ }
683
+ if (stat.isSymbolicLink()) {
684
+ throw new GitWorktreeError(`Git reflog path must not be a symbolic link: ${logPath}.`);
685
+ }
686
+ if (stat.isDirectory()) {
687
+ const values: string[] = [];
688
+ for (const entry of readdirSync(logPath, { withFileTypes: true })) {
689
+ values.push(...readAdministrativeReflogOids(resolve(logPath, entry.name)));
690
+ }
691
+ return values;
692
+ }
693
+ if (!stat.isFile()) {
694
+ throw new GitWorktreeError(`Unexpected Git reflog entry type: ${logPath}.`);
695
+ }
696
+
697
+ let contents: string;
698
+ try {
699
+ contents = readFileSync(logPath, "utf8");
700
+ } catch (error) {
701
+ throw new GitWorktreeError(`Cannot read Git reflog ${logPath}: ${formatError(error)}`);
702
+ }
703
+ const normalized = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
704
+ if (!normalized) return [];
705
+ const values: string[] = [];
706
+ for (const line of normalized.split("\n")) {
707
+ const match = /^([0-9a-fA-F]{40,64}) ([0-9a-fA-F]{40,64}) /u.exec(line);
708
+ if (!match?.[1] || !match[2] || match[1].length !== match[2].length) {
709
+ throw new GitWorktreeError(`Git worktree reflog is malformed: ${logPath}.`);
710
+ }
711
+ for (const oid of [match[1], match[2]]) {
712
+ if (!/^0+$/u.test(oid)) values.push(oid);
713
+ }
714
+ }
715
+ return values;
716
+ }
717
+
718
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
719
+ return error instanceof Error && "code" in error;
720
+ }
721
+
722
+ function formatError(error: unknown): string {
723
+ return error instanceof Error ? error.message : String(error);
724
+ }