@narumitw/pi-worktree 0.51.7 → 0.51.9

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 CHANGED
@@ -5,907 +5,896 @@ import type { ExecResult, ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
5
 
6
6
  const GIT_TIMEOUT_MS = 15_000;
7
7
  const GIT_MUTATION_TIMEOUT_MS = 60_000;
8
+ // Metadata is a path, ref, OID, or boolean; record queries need room for large repositories.
9
+ const GIT_METADATA_MAX_BUFFER = 64 * 1024;
10
+ const GIT_RECORDS_MAX_BUFFER = 8 * 1024 * 1024;
11
+ // Mutations can emit progress and hook diagnostics, but their output is not parsed as records.
12
+ const GIT_MUTATION_MAX_BUFFER = 1024 * 1024;
8
13
  const LOCAL_BRANCH_PREFIX = "refs/heads/";
9
14
 
10
15
  export interface WorktreeRecord {
11
- path: string;
12
- head?: string;
13
- branchRef?: string;
14
- branch?: string;
15
- isMain: boolean;
16
- bare: boolean;
17
- detached: boolean;
18
- lockedReason?: string;
19
- prunableReason?: string;
16
+ path: string;
17
+ head?: string;
18
+ branchRef?: string;
19
+ branch?: string;
20
+ isMain: boolean;
21
+ bare: boolean;
22
+ detached: boolean;
23
+ lockedReason?: string;
24
+ prunableReason?: string;
20
25
  }
21
26
 
22
27
  export interface AddArguments {
23
- path: string;
24
- branch: string;
25
- startOid?: string;
28
+ path: string;
29
+ branch: string;
30
+ startOid?: string;
26
31
  }
27
32
 
28
33
  export interface AdministrativePruneCandidate {
29
- id: string;
30
- administrativePath: string;
31
- head?: string;
32
- branchRef?: string;
33
- indexDirty: boolean;
34
+ id: string;
35
+ administrativePath: string;
36
+ head?: string;
37
+ branchRef?: string;
38
+ indexDirty: boolean;
34
39
  }
35
40
 
36
41
  export interface GitClient {
37
- exec(command: string, args: string[], options?: GitExecOptions): Promise<ExecResult>;
42
+ exec(command: string, args: string[], options?: GitExecOptions): Promise<ExecResult>;
38
43
  }
39
44
 
40
45
  interface GitExecOptions {
41
- cwd?: string;
42
- signal?: AbortSignal;
43
- timeout?: number;
46
+ cwd?: string;
47
+ signal?: AbortSignal;
48
+ timeout?: number;
49
+ maxBuffer?: number;
44
50
  }
45
51
 
46
52
  export class GitWorktreeError extends Error {
47
- readonly args?: readonly string[];
53
+ readonly args?: readonly string[];
48
54
 
49
- constructor(message: string, args?: readonly string[]) {
50
- super(message);
51
- this.name = "GitWorktreeError";
52
- this.args = args;
53
- }
55
+ constructor(message: string, args?: readonly string[]) {
56
+ super(message);
57
+ this.name = "GitWorktreeError";
58
+ this.args = args;
59
+ }
54
60
  }
55
61
 
56
62
  export function parseWorktreePorcelain(output: string): WorktreeRecord[] {
57
- const records: WorktreeRecord[] = [];
58
- let current: Omit<WorktreeRecord, "isMain"> | undefined;
59
-
60
- const finish = () => {
61
- if (!current) return;
62
- records.push({ ...current, isMain: records.length === 0 });
63
- current = undefined;
64
- };
65
-
66
- for (const field of output.split("\0")) {
67
- if (field === "") {
68
- finish();
69
- continue;
70
- }
71
- const separator = field.indexOf(" ");
72
- const key = separator < 0 ? field : field.slice(0, separator);
73
- const value = separator < 0 ? "" : field.slice(separator + 1);
74
-
75
- if (key === "worktree") {
76
- finish();
77
- if (!value) throw new GitWorktreeError("Worktree porcelain record is missing path.");
78
- current = { path: value, bare: false, detached: false };
79
- continue;
80
- }
81
- if (!current) {
82
- throw new GitWorktreeError(
83
- `Worktree porcelain field ${JSON.stringify(key)} appears before worktree.`,
84
- );
85
- }
86
-
87
- switch (key) {
88
- case "HEAD":
89
- current.head = value;
90
- break;
91
- case "branch":
92
- current.branchRef = value;
93
- current.branch = value.startsWith(LOCAL_BRANCH_PREFIX)
94
- ? value.slice(LOCAL_BRANCH_PREFIX.length)
95
- : undefined;
96
- break;
97
- case "bare":
98
- current.bare = true;
99
- break;
100
- case "detached":
101
- current.detached = true;
102
- break;
103
- case "locked":
104
- current.lockedReason = value;
105
- break;
106
- case "prunable":
107
- current.prunableReason = value;
108
- break;
109
- }
110
- }
111
- finish();
112
- return records;
113
- }
114
-
115
- export function worktreeForBranch(
116
- records: readonly WorktreeRecord[],
117
- branch: string,
118
- ): WorktreeRecord | undefined {
119
- const branchRef = `${LOCAL_BRANCH_PREFIX}${branch}`;
120
- return records.find((record) => record.branchRef === branchRef);
121
- }
122
-
123
- export function defaultWorktreePath(
124
- mainWorktreePath: string,
125
- branch: string,
126
- worktreeRoot: string,
127
- ): string {
128
- return resolve(worktreeRoot, basename(mainWorktreePath), branch.replaceAll("/", "-"));
63
+ const records: WorktreeRecord[] = [];
64
+ let current: Omit<WorktreeRecord, "isMain"> | undefined;
65
+
66
+ const finish = () => {
67
+ if (!current) return;
68
+ records.push({ ...current, isMain: records.length === 0 });
69
+ current = undefined;
70
+ };
71
+
72
+ for (const field of output.split("\0")) {
73
+ if (field === "") {
74
+ finish();
75
+ continue;
76
+ }
77
+ const separator = field.indexOf(" ");
78
+ const key = separator < 0 ? field : field.slice(0, separator);
79
+ const value = separator < 0 ? "" : field.slice(separator + 1);
80
+
81
+ if (key === "worktree") {
82
+ finish();
83
+ if (!value) throw new GitWorktreeError("Worktree porcelain record is missing path.");
84
+ current = { path: value, bare: false, detached: false };
85
+ continue;
86
+ }
87
+ if (!current) {
88
+ throw new GitWorktreeError(`Worktree porcelain field ${JSON.stringify(key)} appears before worktree.`);
89
+ }
90
+
91
+ switch (key) {
92
+ case "HEAD":
93
+ current.head = value;
94
+ break;
95
+ case "branch":
96
+ current.branchRef = value;
97
+ current.branch = value.startsWith(LOCAL_BRANCH_PREFIX) ? value.slice(LOCAL_BRANCH_PREFIX.length) : undefined;
98
+ break;
99
+ case "bare":
100
+ current.bare = true;
101
+ break;
102
+ case "detached":
103
+ current.detached = true;
104
+ break;
105
+ case "locked":
106
+ current.lockedReason = value;
107
+ break;
108
+ case "prunable":
109
+ current.prunableReason = value;
110
+ break;
111
+ }
112
+ }
113
+ finish();
114
+ return records;
115
+ }
116
+
117
+ export function worktreeForBranch(records: readonly WorktreeRecord[], branch: string): 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, worktreeRoot: string): string {
123
+ return resolve(worktreeRoot, basename(mainWorktreePath), branch.replaceAll("/", "-"));
129
124
  }
130
125
 
131
126
  export function buildAddArguments(input: AddArguments): string[] {
132
- return input.startOid
133
- ? ["worktree", "add", "-b", input.branch, input.path, input.startOid]
134
- : ["worktree", "add", input.path, input.branch];
127
+ return input.startOid
128
+ ? ["worktree", "add", "-b", input.branch, input.path, input.startOid]
129
+ : ["worktree", "add", input.path, input.branch];
135
130
  }
136
131
 
137
132
  export function pathIdentity(path: string): string {
138
- const absolute = resolve(path);
139
- if (!existsSync(absolute)) return absolute;
140
- try {
141
- return realpathSync.native(absolute);
142
- } catch {
143
- return absolute;
144
- }
133
+ const absolute = resolve(path);
134
+ if (!existsSync(absolute)) return absolute;
135
+ try {
136
+ return realpathSync.native(absolute);
137
+ } catch {
138
+ return absolute;
139
+ }
145
140
  }
146
141
 
147
142
  export function pathEntryExists(path: string): boolean {
148
- try {
149
- lstatSync(path);
150
- return true;
151
- } catch (error) {
152
- if (isNodeError(error) && error.code === "ENOENT") return false;
153
- throw new GitWorktreeError(`Cannot inspect filesystem path ${path}: ${formatError(error)}`);
154
- }
143
+ try {
144
+ lstatSync(path);
145
+ return true;
146
+ } catch (error) {
147
+ if (isNodeError(error) && error.code === "ENOENT") return false;
148
+ throw new GitWorktreeError(`Cannot inspect filesystem path ${path}: ${formatError(error)}`);
149
+ }
155
150
  }
156
151
 
157
152
  export function unresolvableSymlinkAncestor(path: string): string | undefined {
158
- let current = dirname(resolve(path));
159
- while (true) {
160
- try {
161
- const stat = lstatSync(current);
162
- if (!stat.isSymbolicLink()) return undefined;
163
- try {
164
- realpathSync.native(current);
165
- return undefined;
166
- } catch (error) {
167
- if (isNodeError(error) && (error.code === "ENOENT" || error.code === "ELOOP")) {
168
- return current;
169
- }
170
- throw new GitWorktreeError(
171
- `Cannot resolve filesystem ancestor ${current}: ${formatError(error)}`,
172
- );
173
- }
174
- } catch (error) {
175
- if (!isNodeError(error) || error.code !== "ENOENT") {
176
- if (error instanceof GitWorktreeError) throw error;
177
- throw new GitWorktreeError(
178
- `Cannot inspect filesystem ancestor ${current}: ${formatError(error)}`,
179
- );
180
- }
181
- const parent = dirname(current);
182
- if (parent === current) return undefined;
183
- current = parent;
184
- }
185
- }
153
+ let current = dirname(resolve(path));
154
+ while (true) {
155
+ try {
156
+ const stat = lstatSync(current);
157
+ if (!stat.isSymbolicLink()) return undefined;
158
+ try {
159
+ realpathSync.native(current);
160
+ return undefined;
161
+ } catch (error) {
162
+ if (isNodeError(error) && (error.code === "ENOENT" || error.code === "ELOOP")) {
163
+ return current;
164
+ }
165
+ throw new GitWorktreeError(`Cannot resolve filesystem ancestor ${current}: ${formatError(error)}`);
166
+ }
167
+ } catch (error) {
168
+ if (!isNodeError(error) || error.code !== "ENOENT") {
169
+ if (error instanceof GitWorktreeError) throw error;
170
+ throw new GitWorktreeError(`Cannot inspect filesystem ancestor ${current}: ${formatError(error)}`);
171
+ }
172
+ const parent = dirname(current);
173
+ if (parent === current) return undefined;
174
+ current = parent;
175
+ }
176
+ }
186
177
  }
187
178
 
188
179
  export function pathsEqual(left: string, right: string): boolean {
189
- return pathIdentity(left) === pathIdentity(right);
180
+ return pathIdentity(left) === pathIdentity(right);
190
181
  }
191
182
 
192
183
  export function sameWorktreeIdentity(left: WorktreeRecord, right: WorktreeRecord): boolean {
193
- return (
194
- pathsEqual(left.path, right.path) &&
195
- left.head === right.head &&
196
- left.branchRef === right.branchRef &&
197
- left.detached === right.detached &&
198
- left.isMain === right.isMain &&
199
- left.bare === right.bare
200
- );
184
+ return (
185
+ pathsEqual(left.path, right.path) &&
186
+ left.head === right.head &&
187
+ left.branchRef === right.branchRef &&
188
+ left.detached === right.detached &&
189
+ left.isMain === right.isMain &&
190
+ left.bare === right.bare
191
+ );
201
192
  }
202
193
 
203
194
  export async function listWorktrees(
204
- pi: Pick<ExtensionAPI, "exec">,
205
- cwd: string,
206
- signal?: AbortSignal,
195
+ pi: Pick<ExtensionAPI, "exec">,
196
+ cwd: string,
197
+ signal?: AbortSignal,
207
198
  ): Promise<WorktreeRecord[]> {
208
- const result = await runGit(pi, ["worktree", "list", "--porcelain", "-z"], cwd, signal);
209
- return parseWorktreePorcelain(result.stdout);
199
+ const result = await runGit(pi, ["worktree", "list", "--porcelain", "-z"], cwd, GIT_RECORDS_MAX_BUFFER, signal);
200
+ return parseWorktreePorcelain(result.stdout);
210
201
  }
211
202
 
212
203
  export async function currentWorktreePath(
213
- pi: Pick<ExtensionAPI, "exec">,
214
- cwd: string,
215
- signal?: AbortSignal,
204
+ pi: Pick<ExtensionAPI, "exec">,
205
+ cwd: string,
206
+ signal?: AbortSignal,
216
207
  ): Promise<string> {
217
- const result = await runGit(pi, ["rev-parse", "--show-toplevel"], cwd, signal);
218
- const path = removeLineEnding(result.stdout);
219
- if (!path) throw new GitWorktreeError("Git did not return the current worktree path.");
220
- return pathIdentity(path);
208
+ const result = await runGit(pi, ["rev-parse", "--show-toplevel"], cwd, GIT_METADATA_MAX_BUFFER, signal);
209
+ const path = removeLineEnding(result.stdout);
210
+ if (!path) throw new GitWorktreeError("Git did not return the current worktree path.");
211
+ return pathIdentity(path);
221
212
  }
222
213
 
223
214
  export async function symbolicBranch(
224
- pi: Pick<ExtensionAPI, "exec">,
225
- cwd: string,
226
- signal?: AbortSignal,
215
+ pi: Pick<ExtensionAPI, "exec">,
216
+ cwd: string,
217
+ signal?: AbortSignal,
227
218
  ): Promise<string | undefined> {
228
- const result = await runGitAllowFailure(
229
- pi,
230
- ["symbolic-ref", "--quiet", "--short", "HEAD"],
231
- cwd,
232
- signal,
233
- );
234
- if (result.killed) throw killedError(["symbolic-ref", "--quiet", "--short", "HEAD"]);
235
- if (result.code !== 0) return undefined;
236
- return result.stdout.trim() || undefined;
219
+ const result = await runGitAllowFailure(
220
+ pi,
221
+ ["symbolic-ref", "--quiet", "--short", "HEAD"],
222
+ cwd,
223
+ GIT_METADATA_MAX_BUFFER,
224
+ signal,
225
+ );
226
+ if (result.killed) throw killedError(["symbolic-ref", "--quiet", "--short", "HEAD"]);
227
+ if (result.code !== 0) return undefined;
228
+ return result.stdout.trim() || undefined;
237
229
  }
238
230
 
239
231
  export async function validateBranch(
240
- pi: Pick<ExtensionAPI, "exec">,
241
- cwd: string,
242
- branch: string,
243
- signal?: AbortSignal,
232
+ pi: Pick<ExtensionAPI, "exec">,
233
+ cwd: string,
234
+ branch: string,
235
+ signal?: AbortSignal,
244
236
  ): Promise<string> {
245
- const result = await runGit(pi, ["check-ref-format", "--branch", branch], cwd, signal);
246
- const normalized = result.stdout.trim();
247
- if (!normalized) throw new GitWorktreeError("Git returned an empty branch name.");
248
- return normalized;
237
+ const result = await runGit(pi, ["check-ref-format", "--branch", branch], cwd, GIT_METADATA_MAX_BUFFER, signal);
238
+ const normalized = result.stdout.trim();
239
+ if (!normalized) throw new GitWorktreeError("Git returned an empty branch name.");
240
+ return normalized;
249
241
  }
250
242
 
251
243
  export async function localBranchExists(
252
- pi: Pick<ExtensionAPI, "exec">,
253
- cwd: string,
254
- branch: string,
255
- signal?: AbortSignal,
244
+ pi: Pick<ExtensionAPI, "exec">,
245
+ cwd: string,
246
+ branch: string,
247
+ signal?: AbortSignal,
256
248
  ): Promise<boolean> {
257
- const result = await runGitAllowFailure(
258
- pi,
259
- ["show-ref", "--verify", "--quiet", `${LOCAL_BRANCH_PREFIX}${branch}`],
260
- cwd,
261
- signal,
262
- );
263
- if (result.killed) throw killedError(["show-ref", "--verify", "--quiet"]);
264
- if (result.code === 0) return true;
265
- if (result.code === 1) return false;
266
- throw gitFailure(["show-ref", "--verify", "--quiet"], result);
249
+ const result = await runGitAllowFailure(
250
+ pi,
251
+ ["show-ref", "--verify", "--quiet", `${LOCAL_BRANCH_PREFIX}${branch}`],
252
+ cwd,
253
+ GIT_METADATA_MAX_BUFFER,
254
+ signal,
255
+ );
256
+ if (result.killed) throw killedError(["show-ref", "--verify", "--quiet"]);
257
+ if (result.code === 0) return true;
258
+ if (result.code === 1) return false;
259
+ throw gitFailure(["show-ref", "--verify", "--quiet"], result);
267
260
  }
268
261
 
269
262
  export async function resolveCommit(
270
- pi: Pick<ExtensionAPI, "exec">,
271
- cwd: string,
272
- startPoint: string,
273
- signal?: AbortSignal,
263
+ pi: Pick<ExtensionAPI, "exec">,
264
+ cwd: string,
265
+ startPoint: string,
266
+ signal?: AbortSignal,
274
267
  ): Promise<string> {
275
- const result = await runGit(
276
- pi,
277
- ["rev-parse", "--verify", "--end-of-options", `${startPoint}^{commit}`],
278
- cwd,
279
- signal,
280
- );
281
- const oid = result.stdout.trim();
282
- if (!/^[0-9a-fA-F]{40,64}$/u.test(oid)) {
283
- throw new GitWorktreeError(`Git returned an invalid commit object for ${startPoint}.`);
284
- }
285
- return oid;
268
+ const result = await runGit(
269
+ pi,
270
+ ["rev-parse", "--verify", "--end-of-options", `${startPoint}^{commit}`],
271
+ cwd,
272
+ GIT_METADATA_MAX_BUFFER,
273
+ signal,
274
+ );
275
+ const oid = result.stdout.trim();
276
+ if (!/^[0-9a-fA-F]{40,64}$/u.test(oid)) {
277
+ throw new GitWorktreeError(`Git returned an invalid commit object for ${startPoint}.`);
278
+ }
279
+ return oid;
286
280
  }
287
281
 
288
282
  export async function addWorktree(
289
- pi: Pick<ExtensionAPI, "exec">,
290
- cwd: string,
291
- input: AddArguments,
292
- signal?: AbortSignal,
283
+ pi: Pick<ExtensionAPI, "exec">,
284
+ cwd: string,
285
+ input: AddArguments,
286
+ signal?: AbortSignal,
293
287
  ): Promise<void> {
294
- await runGit(pi, buildAddArguments(input), cwd, signal, GIT_MUTATION_TIMEOUT_MS);
288
+ await runGit(pi, buildAddArguments(input), cwd, GIT_MUTATION_MAX_BUFFER, signal, GIT_MUTATION_TIMEOUT_MS);
295
289
  }
296
290
 
297
291
  export async function removeWorktree(
298
- pi: Pick<ExtensionAPI, "exec">,
299
- cwd: string,
300
- path: string,
301
- signal?: AbortSignal,
292
+ pi: Pick<ExtensionAPI, "exec">,
293
+ cwd: string,
294
+ path: string,
295
+ signal?: AbortSignal,
302
296
  ): Promise<void> {
303
- await runGit(pi, ["worktree", "remove", path], cwd, signal, GIT_MUTATION_TIMEOUT_MS);
297
+ await runGit(pi, ["worktree", "remove", path], cwd, GIT_MUTATION_MAX_BUFFER, signal, GIT_MUTATION_TIMEOUT_MS);
304
298
  }
305
299
 
306
300
  export async function worktreeInventory(
307
- pi: Pick<ExtensionAPI, "exec">,
308
- path: string,
309
- signal?: AbortSignal,
301
+ pi: Pick<ExtensionAPI, "exec">,
302
+ path: string,
303
+ signal?: AbortSignal,
310
304
  ): Promise<string[]> {
311
- const statusArgs = [
312
- "status",
313
- "--porcelain=v1",
314
- "--untracked-files=all",
315
- "--ignored=matching",
316
- "--ignore-submodules=none",
317
- ];
318
- const status = await runGit(pi, statusArgs, path, signal);
319
- const indexFlags = await runGit(pi, ["ls-files", "-v", "-z"], path, signal);
320
- const indexInventory = await indexFlagInventory(pi, indexFlags.stdout, path, signal);
321
- const submoduleStatus = await runGit(pi, ["submodule", "status", "--recursive"], path, signal);
322
- const initializedSubmodules = nonEmptyLines(submoduleStatus.stdout)
323
- .filter((line) => !line.startsWith("-"))
324
- .map((line) => `initialized submodule: ${line.slice(1).trimStart()}`);
325
- const submodules = await runGit(
326
- pi,
327
- [
328
- "submodule",
329
- "foreach",
330
- "--recursive",
331
- "--quiet",
332
- "git status --porcelain=v1 --untracked-files=all --ignored=matching --ignore-submodules=none",
333
- ],
334
- path,
335
- signal,
336
- );
337
- return [
338
- ...nonEmptyLines(status.stdout),
339
- ...indexInventory,
340
- ...initializedSubmodules,
341
- ...nonEmptyLines(submodules.stdout),
342
- ];
305
+ const statusArgs = [
306
+ "status",
307
+ "--porcelain=v1",
308
+ "--untracked-files=all",
309
+ "--ignored=matching",
310
+ "--ignore-submodules=none",
311
+ ];
312
+ const status = await runGit(pi, statusArgs, path, GIT_RECORDS_MAX_BUFFER, signal);
313
+ const indexFlags = await runGit(pi, ["ls-files", "-v", "-z"], path, GIT_RECORDS_MAX_BUFFER, signal);
314
+ const indexInventory = await indexFlagInventory(pi, indexFlags.stdout, path, signal);
315
+ const submoduleStatus = await runGit(
316
+ pi,
317
+ ["submodule", "status", "--recursive"],
318
+ path,
319
+ GIT_RECORDS_MAX_BUFFER,
320
+ signal,
321
+ );
322
+ const initializedSubmodules = nonEmptyLines(submoduleStatus.stdout)
323
+ .filter((line) => !line.startsWith("-"))
324
+ .map((line) => `initialized submodule: ${line.slice(1).trimStart()}`);
325
+ const submodules = await runGit(
326
+ pi,
327
+ [
328
+ "submodule",
329
+ "foreach",
330
+ "--recursive",
331
+ "--quiet",
332
+ "git status --porcelain=v1 --untracked-files=all --ignored=matching --ignore-submodules=none",
333
+ ],
334
+ path,
335
+ GIT_RECORDS_MAX_BUFFER,
336
+ signal,
337
+ );
338
+ return [
339
+ ...nonEmptyLines(status.stdout),
340
+ ...indexInventory,
341
+ ...initializedSubmodules,
342
+ ...nonEmptyLines(submodules.stdout),
343
+ ];
343
344
  }
344
345
 
345
346
  export async function worktreeAdministrativeDirectory(
346
- pi: Pick<ExtensionAPI, "exec">,
347
- cwd: string,
348
- signal?: AbortSignal,
347
+ pi: Pick<ExtensionAPI, "exec">,
348
+ cwd: string,
349
+ signal?: AbortSignal,
349
350
  ): Promise<string> {
350
- const result = await runGit(
351
- pi,
352
- ["rev-parse", "--path-format=absolute", "--git-dir"],
353
- cwd,
354
- signal,
355
- );
356
- const value = removeLineEnding(result.stdout);
357
- if (!value) throw new GitWorktreeError("Git did not return its worktree administrative path.");
358
- return resolve(cwd, value);
351
+ const result = await runGit(
352
+ pi,
353
+ ["rev-parse", "--path-format=absolute", "--git-dir"],
354
+ cwd,
355
+ GIT_METADATA_MAX_BUFFER,
356
+ signal,
357
+ );
358
+ const value = removeLineEnding(result.stdout);
359
+ if (!value) throw new GitWorktreeError("Git did not return its worktree administrative path.");
360
+ return resolve(cwd, value);
359
361
  }
360
362
 
361
363
  export async function administrativeHistoryOids(
362
- pi: Pick<ExtensionAPI, "exec">,
363
- cwd: string,
364
- administrativePath: string,
365
- signal?: AbortSignal,
364
+ pi: Pick<ExtensionAPI, "exec">,
365
+ cwd: string,
366
+ administrativePath: string,
367
+ signal?: AbortSignal,
366
368
  ): Promise<string[]> {
367
- const gitDirArgument = `--git-dir=${administrativePath}`;
368
- const values = readAdministrativeReflogOids(resolve(administrativePath, "logs"));
369
-
370
- const refs = await runGit(
371
- pi,
372
- [gitDirArgument, "for-each-ref", "--format=%(objectname)", "refs/worktree", "refs/bisect"],
373
- cwd,
374
- signal,
375
- );
376
- values.push(...splitAdministrativeOids(refs.stdout, "per-worktree refs"));
377
-
378
- for (const name of [
379
- "ORIG_HEAD",
380
- "MERGE_HEAD",
381
- "REBASE_HEAD",
382
- "CHERRY_PICK_HEAD",
383
- "REVERT_HEAD",
384
- "BISECT_HEAD",
385
- ]) {
386
- const contents = readAdministrativeFile(administrativePath, name);
387
- if (contents === undefined) continue;
388
- values.push(...splitAdministrativeOids(contents, name));
389
- }
390
- const fetchHead = readAdministrativeFile(administrativePath, "FETCH_HEAD");
391
- if (fetchHead !== undefined) {
392
- values.push(...splitFetchHeadOids(fetchHead));
393
- }
394
- return [...new Set(values)];
369
+ const gitDirArgument = `--git-dir=${administrativePath}`;
370
+ const values = readAdministrativeReflogOids(resolve(administrativePath, "logs"));
371
+
372
+ const refs = await runGit(
373
+ pi,
374
+ [gitDirArgument, "for-each-ref", "--format=%(objectname)", "refs/worktree", "refs/bisect"],
375
+ cwd,
376
+ GIT_RECORDS_MAX_BUFFER,
377
+ signal,
378
+ );
379
+ values.push(...splitAdministrativeOids(refs.stdout, "per-worktree refs"));
380
+
381
+ for (const name of ["ORIG_HEAD", "MERGE_HEAD", "REBASE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "BISECT_HEAD"]) {
382
+ const contents = readAdministrativeFile(administrativePath, name);
383
+ if (contents === undefined) continue;
384
+ values.push(...splitAdministrativeOids(contents, name));
385
+ }
386
+ const fetchHead = readAdministrativeFile(administrativePath, "FETCH_HEAD");
387
+ if (fetchHead !== undefined) {
388
+ values.push(...splitFetchHeadOids(fetchHead));
389
+ }
390
+ return [...new Set(values)];
395
391
  }
396
392
 
397
393
  export async function administrativePruneCandidates(
398
- pi: Pick<ExtensionAPI, "exec">,
399
- cwd: string,
400
- signal?: AbortSignal,
394
+ pi: Pick<ExtensionAPI, "exec">,
395
+ cwd: string,
396
+ signal?: AbortSignal,
401
397
  ): Promise<AdministrativePruneCandidate[]> {
402
- const commonResult = await runGit(
403
- pi,
404
- ["rev-parse", "--path-format=absolute", "--git-common-dir"],
405
- cwd,
406
- signal,
407
- );
408
- const commonValue = removeLineEnding(commonResult.stdout);
409
- if (!commonValue) throw new GitWorktreeError("Git did not return its common directory.");
410
- const commonDirectory = resolve(cwd, commonValue);
411
- const administrativeRoot = resolve(commonDirectory, "worktrees");
412
- if (!existsSync(administrativeRoot)) return [];
413
-
414
- const candidates: AdministrativePruneCandidate[] = [];
415
- for (const entry of readdirSync(administrativeRoot, { withFileTypes: true })) {
416
- const administrativePath = resolve(administrativeRoot, entry.name);
417
- if (!entry.isDirectory() || entry.isSymbolicLink()) {
418
- throw new GitWorktreeError(
419
- `Unexpected Git worktree administrative entry: ${administrativePath}.`,
420
- );
421
- }
422
- if (existsSync(resolve(administrativePath, "locked"))) continue;
423
-
424
- const gitdirPath = resolve(administrativePath, "gitdir");
425
- let registeredGitFile: string | undefined;
426
- try {
427
- registeredGitFile = removeLineEnding(readFileSync(gitdirPath, "utf8"));
428
- } catch (error) {
429
- if (!isNodeError(error) || error.code !== "ENOENT") throw error;
430
- }
431
- if (registeredGitFile) {
432
- const targetGitFile = resolve(administrativePath, registeredGitFile);
433
- if (existsSync(targetGitFile)) continue;
434
- }
435
-
436
- const headPath = resolve(administrativePath, "HEAD");
437
- let headValue: string;
438
- try {
439
- if (!lstatSync(headPath).isFile()) {
440
- throw new GitWorktreeError(`Git worktree administrative HEAD is not a file: ${headPath}.`);
441
- }
442
- headValue = removeLineEnding(readFileSync(headPath, "utf8"));
443
- } catch (error) {
444
- if (error instanceof GitWorktreeError) throw error;
445
- throw new GitWorktreeError(
446
- `Cannot inspect Git worktree administrative HEAD ${headPath}: ${formatError(error)}`,
447
- );
448
- }
449
- const indexDirty = await administrativeIndexIsDirty(pi, cwd, administrativePath, signal);
450
- if (headValue.startsWith("ref: ")) {
451
- const branchRef = headValue.slice("ref: ".length);
452
- if (!branchRef) {
453
- throw new GitWorktreeError(
454
- `Git worktree administrative HEAD has an empty ref: ${headPath}.`,
455
- );
456
- }
457
- candidates.push({
458
- id: entry.name,
459
- administrativePath,
460
- branchRef,
461
- indexDirty,
462
- });
463
- continue;
464
- }
465
- if (!/^[0-9a-fA-F]{40,64}$/u.test(headValue)) {
466
- throw new GitWorktreeError(`Git worktree administrative HEAD is malformed: ${headPath}.`);
467
- }
468
- candidates.push({
469
- id: entry.name,
470
- administrativePath,
471
- head: headValue,
472
- indexDirty,
473
- });
474
- }
475
- return candidates;
398
+ const commonResult = await runGit(
399
+ pi,
400
+ ["rev-parse", "--path-format=absolute", "--git-common-dir"],
401
+ cwd,
402
+ GIT_METADATA_MAX_BUFFER,
403
+ signal,
404
+ );
405
+ const commonValue = removeLineEnding(commonResult.stdout);
406
+ if (!commonValue) throw new GitWorktreeError("Git did not return its common directory.");
407
+ const commonDirectory = resolve(cwd, commonValue);
408
+ const administrativeRoot = resolve(commonDirectory, "worktrees");
409
+ if (!existsSync(administrativeRoot)) return [];
410
+
411
+ const candidates: AdministrativePruneCandidate[] = [];
412
+ for (const entry of readdirSync(administrativeRoot, { withFileTypes: true })) {
413
+ const administrativePath = resolve(administrativeRoot, entry.name);
414
+ if (!entry.isDirectory() || entry.isSymbolicLink()) {
415
+ throw new GitWorktreeError(`Unexpected Git worktree administrative entry: ${administrativePath}.`);
416
+ }
417
+ if (existsSync(resolve(administrativePath, "locked"))) continue;
418
+
419
+ const gitdirPath = resolve(administrativePath, "gitdir");
420
+ let registeredGitFile: string | undefined;
421
+ try {
422
+ registeredGitFile = removeLineEnding(readFileSync(gitdirPath, "utf8"));
423
+ } catch (error) {
424
+ if (!isNodeError(error) || error.code !== "ENOENT") throw error;
425
+ }
426
+ if (registeredGitFile) {
427
+ const targetGitFile = resolve(administrativePath, registeredGitFile);
428
+ if (existsSync(targetGitFile)) continue;
429
+ }
430
+
431
+ const headPath = resolve(administrativePath, "HEAD");
432
+ let headValue: string;
433
+ try {
434
+ if (!lstatSync(headPath).isFile()) {
435
+ throw new GitWorktreeError(`Git worktree administrative HEAD is not a file: ${headPath}.`);
436
+ }
437
+ headValue = removeLineEnding(readFileSync(headPath, "utf8"));
438
+ } catch (error) {
439
+ if (error instanceof GitWorktreeError) throw error;
440
+ throw new GitWorktreeError(`Cannot inspect Git worktree administrative HEAD ${headPath}: ${formatError(error)}`);
441
+ }
442
+ const indexDirty = await administrativeIndexIsDirty(pi, cwd, administrativePath, signal);
443
+ if (headValue.startsWith("ref: ")) {
444
+ const branchRef = headValue.slice("ref: ".length);
445
+ if (!branchRef) {
446
+ throw new GitWorktreeError(`Git worktree administrative HEAD has an empty ref: ${headPath}.`);
447
+ }
448
+ candidates.push({
449
+ id: entry.name,
450
+ administrativePath,
451
+ branchRef,
452
+ indexDirty,
453
+ });
454
+ continue;
455
+ }
456
+ if (!/^[0-9a-fA-F]{40,64}$/u.test(headValue)) {
457
+ throw new GitWorktreeError(`Git worktree administrative HEAD is malformed: ${headPath}.`);
458
+ }
459
+ candidates.push({
460
+ id: entry.name,
461
+ administrativePath,
462
+ head: headValue,
463
+ indexDirty,
464
+ });
465
+ }
466
+ return candidates;
476
467
  }
477
468
 
478
469
  async function administrativeIndexIsDirty(
479
- pi: Pick<ExtensionAPI, "exec">,
480
- cwd: string,
481
- administrativePath: string,
482
- signal?: AbortSignal,
470
+ pi: Pick<ExtensionAPI, "exec">,
471
+ cwd: string,
472
+ administrativePath: string,
473
+ signal?: AbortSignal,
483
474
  ): Promise<boolean> {
484
- const args = [
485
- `--git-dir=${administrativePath}`,
486
- "diff",
487
- "--cached",
488
- "--quiet",
489
- "--no-ext-diff",
490
- "--no-textconv",
491
- "--ignore-submodules=none",
492
- "--",
493
- ];
494
- const result = await runGitAllowFailure(pi, args, cwd, signal);
495
- if (result.killed) throw killedError(args);
496
- if (result.code === 0) return false;
497
- if (result.code === 1) return true;
498
- throw gitFailure(args, result);
475
+ const args = [
476
+ `--git-dir=${administrativePath}`,
477
+ "diff",
478
+ "--cached",
479
+ "--quiet",
480
+ "--no-ext-diff",
481
+ "--no-textconv",
482
+ "--ignore-submodules=none",
483
+ "--",
484
+ ];
485
+ const result = await runGitAllowFailure(pi, args, cwd, GIT_METADATA_MAX_BUFFER, signal);
486
+ if (result.killed) throw killedError(args);
487
+ if (result.code === 0) return false;
488
+ if (result.code === 1) return true;
489
+ throw gitFailure(args, result);
499
490
  }
500
491
 
501
492
  export async function durableRefExists(
502
- pi: Pick<ExtensionAPI, "exec">,
503
- cwd: string,
504
- ref: string,
505
- signal?: AbortSignal,
493
+ pi: Pick<ExtensionAPI, "exec">,
494
+ cwd: string,
495
+ ref: string,
496
+ signal?: AbortSignal,
506
497
  ): Promise<boolean> {
507
- if (!ref.startsWith("refs/") || ref.includes("\0")) {
508
- throw new GitWorktreeError("Git worktree administrative HEAD contains an invalid ref.");
509
- }
510
- const result = await runGitAllowFailure(
511
- pi,
512
- ["show-ref", "--verify", "--quiet", ref],
513
- cwd,
514
- signal,
515
- );
516
- if (result.killed) throw killedError(["show-ref", "--verify", "--quiet"]);
517
- if (result.code === 0) return true;
518
- if (result.code === 1) return false;
519
- throw gitFailure(["show-ref", "--verify", "--quiet"], result);
498
+ if (!ref.startsWith("refs/") || ref.includes("\0")) {
499
+ throw new GitWorktreeError("Git worktree administrative HEAD contains an invalid ref.");
500
+ }
501
+ const result = await runGitAllowFailure(
502
+ pi,
503
+ ["show-ref", "--verify", "--quiet", ref],
504
+ cwd,
505
+ GIT_METADATA_MAX_BUFFER,
506
+ signal,
507
+ );
508
+ if (result.killed) throw killedError(["show-ref", "--verify", "--quiet"]);
509
+ if (result.code === 0) return true;
510
+ if (result.code === 1) return false;
511
+ throw gitFailure(["show-ref", "--verify", "--quiet"], result);
520
512
  }
521
513
 
522
514
  export async function durableRefsContaining(
523
- pi: Pick<ExtensionAPI, "exec">,
524
- cwd: string,
525
- head: string,
526
- signal?: AbortSignal,
515
+ pi: Pick<ExtensionAPI, "exec">,
516
+ cwd: string,
517
+ head: string,
518
+ signal?: AbortSignal,
527
519
  ): Promise<string[]> {
528
- if (!/^[0-9a-fA-F]{40,64}$/u.test(head)) {
529
- throw new GitWorktreeError("Detached worktree has an invalid HEAD object.");
530
- }
531
- const result = await runGit(
532
- pi,
533
- [
534
- "for-each-ref",
535
- "--format=%(refname)",
536
- `--contains=${head}`,
537
- "refs/heads",
538
- "refs/tags",
539
- "refs/remotes",
540
- ],
541
- cwd,
542
- signal,
543
- );
544
- return nonEmptyLines(result.stdout);
545
- }
546
-
547
- export async function prunePreview(
548
- pi: Pick<ExtensionAPI, "exec">,
549
- cwd: string,
550
- signal?: AbortSignal,
551
- ): Promise<string> {
552
- const result = await runGit(pi, ["worktree", "prune", "--dry-run", "--verbose"], cwd, signal);
553
- return combineOutput(result);
520
+ if (!/^[0-9a-fA-F]{40,64}$/u.test(head)) {
521
+ throw new GitWorktreeError("Detached worktree has an invalid HEAD object.");
522
+ }
523
+ const result = await runGit(
524
+ pi,
525
+ ["for-each-ref", "--format=%(refname)", `--contains=${head}`, "refs/heads", "refs/tags", "refs/remotes"],
526
+ cwd,
527
+ GIT_RECORDS_MAX_BUFFER,
528
+ signal,
529
+ );
530
+ return nonEmptyLines(result.stdout);
531
+ }
532
+
533
+ export async function prunePreview(pi: Pick<ExtensionAPI, "exec">, cwd: string, signal?: AbortSignal): Promise<string> {
534
+ const result = await runGit(pi, ["worktree", "prune", "--dry-run", "--verbose"], cwd, GIT_RECORDS_MAX_BUFFER, signal);
535
+ return combineOutput(result);
554
536
  }
555
537
 
556
538
  export async function pruneWorktrees(
557
- pi: Pick<ExtensionAPI, "exec">,
558
- cwd: string,
559
- signal?: AbortSignal,
539
+ pi: Pick<ExtensionAPI, "exec">,
540
+ cwd: string,
541
+ signal?: AbortSignal,
560
542
  ): Promise<string> {
561
- const result = await runGit(
562
- pi,
563
- ["worktree", "prune", "--verbose"],
564
- cwd,
565
- signal,
566
- GIT_MUTATION_TIMEOUT_MS,
567
- );
568
- return combineOutput(result);
543
+ const result = await runGit(
544
+ pi,
545
+ ["worktree", "prune", "--verbose"],
546
+ cwd,
547
+ GIT_MUTATION_MAX_BUFFER,
548
+ signal,
549
+ GIT_MUTATION_TIMEOUT_MS,
550
+ );
551
+ return combineOutput(result);
569
552
  }
570
553
 
571
554
  export function formatWorktree(record: WorktreeRecord, currentPath?: string): string {
572
- const labels = [
573
- currentPath && pathsEqual(record.path, currentPath) ? "current" : undefined,
574
- record.isMain ? "main" : undefined,
575
- record.bare ? "bare" : undefined,
576
- record.detached ? "detached" : record.branch,
577
- record.lockedReason !== undefined
578
- ? `locked${record.lockedReason ? `: ${record.lockedReason}` : ""}`
579
- : undefined,
580
- record.prunableReason !== undefined
581
- ? `prunable${record.prunableReason ? `: ${record.prunableReason}` : ""}`
582
- : undefined,
583
- ].filter((label): label is string => Boolean(label));
584
- const head = record.head ? record.head.slice(0, 8) : "no HEAD";
585
- return stripTerminalControls(`${record.path} [${labels.join(", ") || "unknown"}] ${head}`);
555
+ const labels = [
556
+ currentPath && pathsEqual(record.path, currentPath) ? "current" : undefined,
557
+ record.isMain ? "main" : undefined,
558
+ record.bare ? "bare" : undefined,
559
+ record.detached ? "detached" : record.branch,
560
+ record.lockedReason !== undefined ? `locked${record.lockedReason ? `: ${record.lockedReason}` : ""}` : undefined,
561
+ record.prunableReason !== undefined
562
+ ? `prunable${record.prunableReason ? `: ${record.prunableReason}` : ""}`
563
+ : undefined,
564
+ ].filter((label): label is string => Boolean(label));
565
+ const head = record.head ? record.head.slice(0, 8) : "no HEAD";
566
+ return stripTerminalControls(`${record.path} [${labels.join(", ") || "unknown"}] ${head}`);
586
567
  }
587
568
 
588
569
  export function stripTerminalControls(value: string): string {
589
- return [...value]
590
- .filter((character) => {
591
- const code = character.codePointAt(0) ?? 0;
592
- return code > 0x1f && (code < 0x7f || code > 0x9f);
593
- })
594
- .join("");
570
+ return [...value]
571
+ .filter((character) => {
572
+ const code = character.codePointAt(0) ?? 0;
573
+ return code > 0x1f && (code < 0x7f || code > 0x9f);
574
+ })
575
+ .join("");
595
576
  }
596
577
 
597
578
  async function runGit(
598
- pi: Pick<ExtensionAPI, "exec">,
599
- args: string[],
600
- cwd: string,
601
- signal?: AbortSignal,
602
- timeout = GIT_TIMEOUT_MS,
579
+ pi: Pick<ExtensionAPI, "exec">,
580
+ args: string[],
581
+ cwd: string,
582
+ maxBuffer: number,
583
+ signal?: AbortSignal,
584
+ timeout = GIT_TIMEOUT_MS,
603
585
  ): Promise<ExecResult> {
604
- const result = await runGitAllowFailure(pi, args, cwd, signal, timeout);
605
- if (result.killed) throw killedError(args);
606
- if (result.code !== 0) throw gitFailure(args, result);
607
- return result;
586
+ const result = await runGitAllowFailure(pi, args, cwd, maxBuffer, signal, timeout);
587
+ if (result.killed) throw killedError(args);
588
+ if (result.code !== 0) throw gitFailure(args, result);
589
+ return result;
608
590
  }
609
591
 
610
592
  async function runGitAllowFailure(
611
- pi: Pick<ExtensionAPI, "exec">,
612
- args: string[],
613
- cwd: string,
614
- signal?: AbortSignal,
615
- timeout = GIT_TIMEOUT_MS,
593
+ pi: Pick<ExtensionAPI, "exec">,
594
+ args: string[],
595
+ cwd: string,
596
+ maxBuffer: number,
597
+ signal?: AbortSignal,
598
+ timeout = GIT_TIMEOUT_MS,
616
599
  ): Promise<ExecResult> {
617
- try {
618
- return await pi.exec("git", args, { cwd, signal, timeout });
619
- } catch (error) {
620
- const message = formatError(error);
621
- if (/\bENOENT\b|not found/i.test(message)) {
622
- throw new GitWorktreeError("Git executable was not found. Install Git and retry.", args);
623
- }
624
- throw new GitWorktreeError(
625
- `Could not start git ${args.slice(0, 2).join(" ")}: ${message}`,
626
- args,
627
- );
628
- }
600
+ let result: ExecResult;
601
+ try {
602
+ result = await pi.exec("git", args, { cwd, signal, timeout, maxBuffer });
603
+ } catch (error) {
604
+ const message = formatError(error);
605
+ if (/\bENOENT\b|not found/i.test(message)) {
606
+ throw new GitWorktreeError("Git executable was not found. Install Git and retry.", args);
607
+ }
608
+ throw new GitWorktreeError(`Could not start git ${args.slice(0, 2).join(" ")}: ${message}`, args);
609
+ }
610
+ // Even injected executors must not let incomplete data reach parsing or nonzero-exit fallbacks.
611
+ if (result.truncated) throw outputLimitError(args, maxBuffer);
612
+ return result;
613
+ }
614
+
615
+ function outputLimitError(args: string[], maxBuffer: number): GitWorktreeError {
616
+ return new GitWorktreeError(
617
+ `git ${args.slice(0, 2).join(" ")} output exceeded the ${maxBuffer}-byte limit. Partial output was not used; inspect Git state before retrying.`,
618
+ args,
619
+ );
629
620
  }
630
621
 
631
622
  function gitFailure(args: string[], result: ExecResult): GitWorktreeError {
632
- const detail = stripTerminalControls(
633
- [result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n"),
634
- );
635
- const hint = /not a git repository/i.test(detail)
636
- ? "The current Pi workspace is not inside a Git repository."
637
- : detail || `Git exited with code ${result.code}.`;
638
- return new GitWorktreeError(`git ${args.slice(0, 2).join(" ")} failed: ${hint}`, args);
623
+ const detail = stripTerminalControls([result.stderr.trim(), result.stdout.trim()].filter(Boolean).join("\n"));
624
+ const hint = /not a git repository/i.test(detail)
625
+ ? "The current Pi workspace is not inside a Git repository."
626
+ : detail || `Git exited with code ${result.code}.`;
627
+ return new GitWorktreeError(`git ${args.slice(0, 2).join(" ")} failed: ${hint}`, args);
639
628
  }
640
629
 
641
630
  function killedError(args: string[]): GitWorktreeError {
642
- return new GitWorktreeError(
643
- `git ${args.slice(0, 2).join(" ")} timed out or was cancelled.`,
644
- args,
645
- );
631
+ return new GitWorktreeError(`git ${args.slice(0, 2).join(" ")} timed out or was cancelled.`, args);
646
632
  }
647
633
 
648
634
  function nonEmptyLines(value: string): string[] {
649
- return value.split(/\r?\n/u).filter((line) => line.length > 0);
635
+ return value.split(/\r?\n/u).filter((line) => line.length > 0);
650
636
  }
651
637
 
652
638
  interface IndexFlagEntry {
653
- path: string;
654
- skipWorktree: boolean;
655
- assumeUnchanged: boolean;
639
+ path: string;
640
+ skipWorktree: boolean;
641
+ assumeUnchanged: boolean;
656
642
  }
657
643
 
658
644
  async function indexFlagInventory(
659
- pi: Pick<ExtensionAPI, "exec">,
660
- value: string,
661
- cwd: string,
662
- signal?: AbortSignal,
645
+ pi: Pick<ExtensionAPI, "exec">,
646
+ value: string,
647
+ cwd: string,
648
+ signal?: AbortSignal,
663
649
  ): Promise<string[]> {
664
- const entries = parseIndexFlagEntries(value);
665
- const sparseManagedPaths = await sparseManagedSkipWorktreePaths(
666
- pi,
667
- cwd,
668
- entries.filter((entry) => entry.skipWorktree).map((entry) => entry.path),
669
- signal,
670
- );
671
- const inventory: string[] = [];
672
- for (const entry of entries) {
673
- const flags = [
674
- entry.skipWorktree && !sparseManagedPaths.has(entry.path) ? "skip-worktree" : undefined,
675
- entry.assumeUnchanged ? "assume-unchanged" : undefined,
676
- ].filter((flag): flag is string => flag !== undefined);
677
- if (flags.length > 0) inventory.push(`index flag ${flags.join("+")}: ${entry.path}`);
678
- }
679
- return inventory;
650
+ const entries = parseIndexFlagEntries(value);
651
+ const sparseManagedPaths = await sparseManagedSkipWorktreePaths(
652
+ pi,
653
+ cwd,
654
+ entries.filter((entry) => entry.skipWorktree).map((entry) => entry.path),
655
+ signal,
656
+ );
657
+ const inventory: string[] = [];
658
+ for (const entry of entries) {
659
+ const flags = [
660
+ entry.skipWorktree && !sparseManagedPaths.has(entry.path) ? "skip-worktree" : undefined,
661
+ entry.assumeUnchanged ? "assume-unchanged" : undefined,
662
+ ].filter((flag): flag is string => flag !== undefined);
663
+ if (flags.length > 0) inventory.push(`index flag ${flags.join("+")}: ${entry.path}`);
664
+ }
665
+ return inventory;
680
666
  }
681
667
 
682
668
  function parseIndexFlagEntries(value: string): IndexFlagEntry[] {
683
- const entries: IndexFlagEntry[] = [];
684
- for (const entry of value.split("\0")) {
685
- if (!entry) continue;
686
- if (entry.length < 3 || entry[1] !== " ") {
687
- throw new GitWorktreeError("Git returned malformed ls-files index-flag output.");
688
- }
689
- const tag = entry[0] ?? "";
690
- const skipWorktree = tag.toUpperCase() === "S";
691
- const assumeUnchanged = /[a-z]/u.test(tag);
692
- if (skipWorktree || assumeUnchanged) {
693
- entries.push({ path: entry.slice(2), skipWorktree, assumeUnchanged });
694
- }
695
- }
696
- return entries;
669
+ const entries: IndexFlagEntry[] = [];
670
+ for (const entry of value.split("\0")) {
671
+ if (!entry) continue;
672
+ if (entry.length < 3 || entry[1] !== " ") {
673
+ throw new GitWorktreeError("Git returned malformed ls-files index-flag output.");
674
+ }
675
+ const tag = entry[0] ?? "";
676
+ const skipWorktree = tag.toUpperCase() === "S";
677
+ const assumeUnchanged = /[a-z]/u.test(tag);
678
+ if (skipWorktree || assumeUnchanged) {
679
+ entries.push({ path: entry.slice(2), skipWorktree, assumeUnchanged });
680
+ }
681
+ }
682
+ return entries;
697
683
  }
698
684
 
699
685
  async function sparseManagedSkipWorktreePaths(
700
- pi: Pick<ExtensionAPI, "exec">,
701
- cwd: string,
702
- paths: readonly string[],
703
- signal?: AbortSignal,
686
+ pi: Pick<ExtensionAPI, "exec">,
687
+ cwd: string,
688
+ paths: readonly string[],
689
+ signal?: AbortSignal,
704
690
  ): Promise<ReadonlySet<string>> {
705
- if (paths.length === 0) return new Set();
706
- const configArgs = ["config", "--bool", "--get", "core.sparseCheckout"];
707
- const config = await runGitAllowFailure(pi, configArgs, cwd, signal);
708
- if (config.killed) throw killedError(configArgs);
709
- if (config.code !== 0 || config.stdout.trim() !== "true") return new Set();
710
-
711
- const candidates = new Set(paths);
712
- const checkArgs = ["sparse-checkout", "check-rules", "-z"];
713
- const checked = await runGitWithInputAllowFailure(
714
- checkArgs,
715
- cwd,
716
- `${[...candidates].join("\0")}\0`,
717
- signal,
718
- );
719
- if (checked.killed) throw killedError(checkArgs);
720
- // Older Git versions lack check-rules; retain every flag rather than guessing.
721
- if (checked.code !== 0) return new Set();
722
-
723
- const included = new Set(nulSeparatedPaths(checked.stdout, "sparse-checkout rules"));
724
- if ([...included].some((path) => !candidates.has(path))) {
725
- throw new GitWorktreeError("Git returned an unexpected sparse-checkout path.");
726
- }
727
- return new Set([...candidates].filter((path) => !included.has(path)));
691
+ if (paths.length === 0) return new Set();
692
+ const configArgs = ["config", "--bool", "--get", "core.sparseCheckout"];
693
+ const config = await runGitAllowFailure(pi, configArgs, cwd, GIT_METADATA_MAX_BUFFER, signal);
694
+ if (config.killed) throw killedError(configArgs);
695
+ if (config.code !== 0 || config.stdout.trim() !== "true") return new Set();
696
+
697
+ const candidates = new Set(paths);
698
+ const checkArgs = ["sparse-checkout", "check-rules", "-z"];
699
+ const checked = await runGitWithInputAllowFailure(checkArgs, cwd, `${[...candidates].join("\0")}\0`, signal);
700
+ if (checked.truncated) throw outputLimitError(checkArgs, GIT_RECORDS_MAX_BUFFER);
701
+ if (checked.killed) throw killedError(checkArgs);
702
+ // Older Git versions lack check-rules; retain every flag rather than guessing.
703
+ if (checked.code !== 0) return new Set();
704
+
705
+ const included = new Set(nulSeparatedPaths(checked.stdout, "sparse-checkout rules"));
706
+ if ([...included].some((path) => !candidates.has(path))) {
707
+ throw new GitWorktreeError("Git returned an unexpected sparse-checkout path.");
708
+ }
709
+ return new Set([...candidates].filter((path) => !included.has(path)));
728
710
  }
729
711
 
730
712
  function runGitWithInputAllowFailure(
731
- args: string[],
732
- cwd: string,
733
- input: string,
734
- signal?: AbortSignal,
735
- timeout = GIT_TIMEOUT_MS,
713
+ args: string[],
714
+ cwd: string,
715
+ input: string,
716
+ signal?: AbortSignal,
717
+ timeout = GIT_TIMEOUT_MS,
736
718
  ): Promise<ExecResult> {
737
- if (signal?.aborted) {
738
- return Promise.resolve({ stdout: "", stderr: "", code: 1, killed: true });
739
- }
740
- return new Promise((resolveResult, reject) => {
741
- // ExtensionAPI.exec has no stdin channel, so this read-only check uses an argv-only child.
742
- const child = spawn("git", args, { cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
743
- let stdout = "";
744
- let stderr = "";
745
- let killed = false;
746
- let settled = false;
747
- const finish = (result: ExecResult) => {
748
- if (settled) return;
749
- settled = true;
750
- clearTimeout(timeoutHandle);
751
- signal?.removeEventListener("abort", stop);
752
- resolveResult(result);
753
- };
754
- const fail = (error: unknown) => {
755
- if (settled) return;
756
- settled = true;
757
- clearTimeout(timeoutHandle);
758
- signal?.removeEventListener("abort", stop);
759
- child.kill();
760
- const message = formatError(error);
761
- reject(
762
- /\bENOENT\b|not found/i.test(message)
763
- ? new GitWorktreeError("Git executable was not found. Install Git and retry.", args)
764
- : new GitWorktreeError(
765
- `Could not start git ${args.slice(0, 2).join(" ")}: ${message}`,
766
- args,
767
- ),
768
- );
769
- };
770
- const stop = () => {
771
- killed = true;
772
- child.kill();
773
- };
774
- const timeoutHandle = setTimeout(stop, timeout);
775
- child.stdout.setEncoding("utf8");
776
- child.stderr.setEncoding("utf8");
777
- child.stdout.on("data", (chunk: string) => {
778
- stdout += chunk;
779
- });
780
- child.stderr.on("data", (chunk: string) => {
781
- stderr += chunk;
782
- });
783
- child.stdin.on("error", (error) => {
784
- if (!isNodeError(error) || error.code !== "EPIPE") fail(error);
785
- });
786
- child.once("error", fail);
787
- child.once("close", (code, closeSignal) => {
788
- finish({ stdout, stderr, code: code ?? 1, killed: killed || closeSignal !== null });
789
- });
790
- signal?.addEventListener("abort", stop, { once: true });
791
- if (signal?.aborted) stop();
792
- child.stdin.end(input);
793
- });
719
+ if (signal?.aborted) {
720
+ return Promise.resolve({ stdout: "", stderr: "", code: 1, killed: true, truncated: false });
721
+ }
722
+ return new Promise((resolveResult, reject) => {
723
+ // ExtensionAPI.exec has no stdin channel, so this read-only check uses an argv-only child.
724
+ const child = spawn("git", args, { cwd, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
725
+ let stdout = "";
726
+ let stderr = "";
727
+ let killed = false;
728
+ let truncated = false;
729
+ let outputBytes = 0;
730
+ let settled = false;
731
+ const finish = (result: ExecResult) => {
732
+ if (settled) return;
733
+ settled = true;
734
+ clearTimeout(timeoutHandle);
735
+ signal?.removeEventListener("abort", stop);
736
+ resolveResult(result);
737
+ };
738
+ const fail = (error: unknown) => {
739
+ if (settled) return;
740
+ settled = true;
741
+ clearTimeout(timeoutHandle);
742
+ signal?.removeEventListener("abort", stop);
743
+ child.kill();
744
+ const message = formatError(error);
745
+ reject(
746
+ /\bENOENT\b|not found/i.test(message)
747
+ ? new GitWorktreeError("Git executable was not found. Install Git and retry.", args)
748
+ : new GitWorktreeError(`Could not start git ${args.slice(0, 2).join(" ")}: ${message}`, args),
749
+ );
750
+ };
751
+ const stop = () => {
752
+ killed = true;
753
+ child.kill();
754
+ };
755
+ const timeoutHandle = setTimeout(stop, timeout);
756
+ const acceptChunk = (chunk: string): boolean => {
757
+ if (truncated) return false;
758
+ outputBytes += Buffer.byteLength(chunk);
759
+ if (outputBytes <= GIT_RECORDS_MAX_BUFFER) return true;
760
+ truncated = true;
761
+ child.stdout.destroy();
762
+ child.stderr.destroy();
763
+ stop();
764
+ return false;
765
+ };
766
+ child.stdout.setEncoding("utf8");
767
+ child.stderr.setEncoding("utf8");
768
+ child.stdout.on("data", (chunk: string) => {
769
+ if (acceptChunk(chunk)) stdout += chunk;
770
+ });
771
+ child.stderr.on("data", (chunk: string) => {
772
+ if (acceptChunk(chunk)) stderr += chunk;
773
+ });
774
+ child.stdin.on("error", (error) => {
775
+ if (!isNodeError(error) || error.code !== "EPIPE") fail(error);
776
+ });
777
+ child.once("error", fail);
778
+ child.once("close", (code, closeSignal) => {
779
+ finish({
780
+ stdout,
781
+ stderr,
782
+ code: truncated && code === 0 ? 1 : (code ?? 1),
783
+ killed: killed || closeSignal !== null,
784
+ truncated,
785
+ });
786
+ });
787
+ signal?.addEventListener("abort", stop, { once: true });
788
+ if (signal?.aborted) stop();
789
+ child.stdin.end(input);
790
+ });
794
791
  }
795
792
 
796
793
  function nulSeparatedPaths(value: string, source: string): string[] {
797
- if (value && !value.endsWith("\0")) {
798
- throw new GitWorktreeError(`Git returned malformed ${source} output.`);
799
- }
800
- return value.split("\0").filter(Boolean);
794
+ if (value && !value.endsWith("\0")) {
795
+ throw new GitWorktreeError(`Git returned malformed ${source} output.`);
796
+ }
797
+ return value.split("\0").filter(Boolean);
801
798
  }
802
799
 
803
800
  function combineOutput(result: ExecResult): string {
804
- return [result.stdout.trimEnd(), result.stderr.trimEnd()].filter(Boolean).join("\n");
801
+ return [result.stdout.trimEnd(), result.stderr.trimEnd()].filter(Boolean).join("\n");
805
802
  }
806
803
 
807
804
  function removeLineEnding(value: string): string {
808
- if (value.endsWith("\r\n")) return value.slice(0, -2);
809
- if (value.endsWith("\n")) return value.slice(0, -1);
810
- return value;
805
+ if (value.endsWith("\r\n")) return value.slice(0, -2);
806
+ if (value.endsWith("\n")) return value.slice(0, -1);
807
+ return value;
811
808
  }
812
809
 
813
810
  function splitAdministrativeOids(value: string, source: string): string[] {
814
- const normalized = value.endsWith("\n") ? value.slice(0, -1) : value;
815
- if (!normalized) return [];
816
- const values = normalized
817
- .split("\n")
818
- .map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line));
819
- if (values.some((oid) => !/^[0-9a-fA-F]{40,64}$/u.test(oid))) {
820
- throw new GitWorktreeError(`Git returned malformed object IDs for ${source}.`);
821
- }
822
- return values;
811
+ const normalized = value.endsWith("\n") ? value.slice(0, -1) : value;
812
+ if (!normalized) return [];
813
+ const values = normalized.split("\n").map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line));
814
+ if (values.some((oid) => !/^[0-9a-fA-F]{40,64}$/u.test(oid))) {
815
+ throw new GitWorktreeError(`Git returned malformed object IDs for ${source}.`);
816
+ }
817
+ return values;
823
818
  }
824
819
 
825
820
  function splitFetchHeadOids(value: string): string[] {
826
- const normalized = value.endsWith("\n") ? value.slice(0, -1) : value;
827
- if (!normalized) return [];
828
- return normalized.split("\n").map((line) => {
829
- const match = /^([0-9a-fA-F]{40,64})\t/u.exec(line);
830
- if (!match?.[1]) {
831
- throw new GitWorktreeError("Git worktree administrative FETCH_HEAD is malformed.");
832
- }
833
- return match[1];
834
- });
821
+ const normalized = value.endsWith("\n") ? value.slice(0, -1) : value;
822
+ if (!normalized) return [];
823
+ return normalized.split("\n").map((line) => {
824
+ const match = /^([0-9a-fA-F]{40,64})\t/u.exec(line);
825
+ if (!match?.[1]) {
826
+ throw new GitWorktreeError("Git worktree administrative FETCH_HEAD is malformed.");
827
+ }
828
+ return match[1];
829
+ });
835
830
  }
836
831
 
837
832
  function readAdministrativeFile(administrativePath: string, name: string): string | undefined {
838
- const path = resolve(administrativePath, name);
839
- let stat: ReturnType<typeof lstatSync>;
840
- try {
841
- stat = lstatSync(path);
842
- } catch (error) {
843
- if (isNodeError(error) && error.code === "ENOENT") return undefined;
844
- throw new GitWorktreeError(
845
- `Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`,
846
- );
847
- }
848
- if (stat.isSymbolicLink() || !stat.isFile()) {
849
- throw new GitWorktreeError(
850
- `Git worktree administrative ${name} must be a regular file: ${path}.`,
851
- );
852
- }
853
- try {
854
- return readFileSync(path, "utf8");
855
- } catch (error) {
856
- throw new GitWorktreeError(
857
- `Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`,
858
- );
859
- }
833
+ const path = resolve(administrativePath, name);
834
+ let stat: ReturnType<typeof lstatSync>;
835
+ try {
836
+ stat = lstatSync(path);
837
+ } catch (error) {
838
+ if (isNodeError(error) && error.code === "ENOENT") return undefined;
839
+ throw new GitWorktreeError(`Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`);
840
+ }
841
+ if (stat.isSymbolicLink() || !stat.isFile()) {
842
+ throw new GitWorktreeError(`Git worktree administrative ${name} must be a regular file: ${path}.`);
843
+ }
844
+ try {
845
+ return readFileSync(path, "utf8");
846
+ } catch (error) {
847
+ throw new GitWorktreeError(`Cannot inspect Git worktree administrative ${name}: ${formatError(error)}`);
848
+ }
860
849
  }
861
850
 
862
851
  function readAdministrativeReflogOids(logPath: string): string[] {
863
- if (!existsSync(logPath)) return [];
864
- let stat: ReturnType<typeof lstatSync>;
865
- try {
866
- stat = lstatSync(logPath);
867
- } catch (error) {
868
- throw new GitWorktreeError(`Cannot inspect Git reflog path ${logPath}: ${formatError(error)}`);
869
- }
870
- if (stat.isSymbolicLink()) {
871
- throw new GitWorktreeError(`Git reflog path must not be a symbolic link: ${logPath}.`);
872
- }
873
- if (stat.isDirectory()) {
874
- const values: string[] = [];
875
- for (const entry of readdirSync(logPath, { withFileTypes: true })) {
876
- values.push(...readAdministrativeReflogOids(resolve(logPath, entry.name)));
877
- }
878
- return values;
879
- }
880
- if (!stat.isFile()) {
881
- throw new GitWorktreeError(`Unexpected Git reflog entry type: ${logPath}.`);
882
- }
883
-
884
- let contents: string;
885
- try {
886
- contents = readFileSync(logPath, "utf8");
887
- } catch (error) {
888
- throw new GitWorktreeError(`Cannot read Git reflog ${logPath}: ${formatError(error)}`);
889
- }
890
- const normalized = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
891
- if (!normalized) return [];
892
- const values: string[] = [];
893
- for (const line of normalized.split("\n")) {
894
- const match = /^([0-9a-fA-F]{40,64}) ([0-9a-fA-F]{40,64}) /u.exec(line);
895
- if (!match?.[1] || !match[2] || match[1].length !== match[2].length) {
896
- throw new GitWorktreeError(`Git worktree reflog is malformed: ${logPath}.`);
897
- }
898
- for (const oid of [match[1], match[2]]) {
899
- if (!/^0+$/u.test(oid)) values.push(oid);
900
- }
901
- }
902
- return values;
852
+ if (!existsSync(logPath)) return [];
853
+ let stat: ReturnType<typeof lstatSync>;
854
+ try {
855
+ stat = lstatSync(logPath);
856
+ } catch (error) {
857
+ throw new GitWorktreeError(`Cannot inspect Git reflog path ${logPath}: ${formatError(error)}`);
858
+ }
859
+ if (stat.isSymbolicLink()) {
860
+ throw new GitWorktreeError(`Git reflog path must not be a symbolic link: ${logPath}.`);
861
+ }
862
+ if (stat.isDirectory()) {
863
+ const values: string[] = [];
864
+ for (const entry of readdirSync(logPath, { withFileTypes: true })) {
865
+ values.push(...readAdministrativeReflogOids(resolve(logPath, entry.name)));
866
+ }
867
+ return values;
868
+ }
869
+ if (!stat.isFile()) {
870
+ throw new GitWorktreeError(`Unexpected Git reflog entry type: ${logPath}.`);
871
+ }
872
+
873
+ let contents: string;
874
+ try {
875
+ contents = readFileSync(logPath, "utf8");
876
+ } catch (error) {
877
+ throw new GitWorktreeError(`Cannot read Git reflog ${logPath}: ${formatError(error)}`);
878
+ }
879
+ const normalized = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
880
+ if (!normalized) return [];
881
+ const values: string[] = [];
882
+ for (const line of normalized.split("\n")) {
883
+ const match = /^([0-9a-fA-F]{40,64}) ([0-9a-fA-F]{40,64}) /u.exec(line);
884
+ if (!match?.[1] || !match[2] || match[1].length !== match[2].length) {
885
+ throw new GitWorktreeError(`Git worktree reflog is malformed: ${logPath}.`);
886
+ }
887
+ for (const oid of [match[1], match[2]]) {
888
+ if (!/^0+$/u.test(oid)) values.push(oid);
889
+ }
890
+ }
891
+ return values;
903
892
  }
904
893
 
905
894
  function isNodeError(error: unknown): error is NodeJS.ErrnoException {
906
- return error instanceof Error && "code" in error;
895
+ return error instanceof Error && "code" in error;
907
896
  }
908
897
 
909
898
  function formatError(error: unknown): string {
910
- return error instanceof Error ? error.message : String(error);
899
+ return error instanceof Error ? error.message : String(error);
911
900
  }