@narumitw/pi-worktree 0.51.6 → 0.51.8

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