@narumitw/pi-worktree 0.49.3 โ 0.50.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -9
- package/package.json +7 -4
- package/src/command.ts +124 -12
- package/src/status.ts +384 -0
package/README.md
CHANGED
|
@@ -9,7 +9,9 @@ Pi cannot change its parent process working directory with `cd`. This extension
|
|
|
9
9
|
## โจ Features
|
|
10
10
|
|
|
11
11
|
- Shows compact main, linked, current, detached, locked, and prunable state in worktree selectors.
|
|
12
|
+
- Provides an on-demand, searchable status snapshot with staged, unstaged, untracked, conflict, upstream, and last-commit details.
|
|
12
13
|
- Creates a new branch worktree or attaches an existing unoccupied local branch.
|
|
14
|
+
- Previews the exact local base source and full commit OID before creation.
|
|
13
15
|
- Rejects occupied targets and unresolvable symbolic-link ancestors before Git can create a branch.
|
|
14
16
|
- Suggests `~/.worktrees/<main-worktree-name>/<branch>` by default and lets the user configure the root interactively.
|
|
15
17
|
- Optionally switches Pi into a newly created worktree while continuing the current conversation.
|
|
@@ -36,8 +38,8 @@ pi -e npm:@narumitw/pi-worktree
|
|
|
36
38
|
Try this package locally from the repository root:
|
|
37
39
|
|
|
38
40
|
```bash
|
|
39
|
-
just try
|
|
40
|
-
# or: pi -e ./
|
|
41
|
+
just try worktree
|
|
42
|
+
# or: pi -e ./packages/pi-worktree
|
|
41
43
|
```
|
|
42
44
|
|
|
43
45
|
## ๐ฌ Usage
|
|
@@ -50,7 +52,8 @@ Run the command without arguments:
|
|
|
50
52
|
|
|
51
53
|
Choose one action:
|
|
52
54
|
|
|
53
|
-
- **
|
|
55
|
+
- **Worktree status** โ browse a local snapshot for every registered worktree without fetching remotes.
|
|
56
|
+
- **Add worktree** โ enter a branch, optional start point, and optional path; review exact base provenance, confirm creation, and optionally switch.
|
|
54
57
|
- **Switch worktree** โ select another existing worktree and continue this Pi conversation there.
|
|
55
58
|
- **Remove worktree** โ remove a linked worktree without deleting its branch; ignored-only data is listed for explicit confirmation.
|
|
56
59
|
- **Prune stale metadata** โ inspect Git's dry-run output, then optionally run the matching prune.
|
|
@@ -63,10 +66,20 @@ RPC dialogs; print and JSON modes reject the command observably. Operation-speci
|
|
|
63
66
|
inputs, worktree identity selectors, preflight previews, and destructive confirmations remain
|
|
64
67
|
extension-owned because they carry Git safety and commit-aware revalidation.
|
|
65
68
|
|
|
69
|
+
The status browser runs only when selected and has no watcher, timer, persistent cache, or network
|
|
70
|
+
fetch. Each card shows textual current/main/detached state, full snapshot HEAD, aggregate working-tree
|
|
71
|
+
counts, configured upstream ahead/behind, and the last commit timestamp and subject. A missing
|
|
72
|
+
upstream is reported as **not configured**; it is not treated as proof that no commits are unpushed.
|
|
73
|
+
Bare, missing, prunable, or individually failing worktrees remain visible with an unavailable reason.
|
|
74
|
+
The snapshot is informational and can become stale immediately, so Remove still performs its stricter
|
|
75
|
+
inventory and identity checks.
|
|
76
|
+
|
|
66
77
|
## ๐ฟ Add defaults
|
|
67
78
|
|
|
68
79
|
For a new branch, the current symbolic branch is the default start point. If Pi is running from detached HEAD, the command requires an explicit commit-ish. Git must resolve the start point to exactly one commit.
|
|
69
80
|
|
|
81
|
+
Before mutation, Add identifies whether the branch is new or existing and displays the provenance as the current branch, an explicit commit-ish, or an existing local branch together with its full resolved OID and target path. New branches are created from that approved OID even if the source ref later moves. Existing branches are checked again immediately before mutation and the created worktree HEAD is verified afterward. Git has no atomic compare-and-add operation for attaching an existing branch, so a post-add mismatch is retained for inspection rather than rolled back.
|
|
82
|
+
|
|
70
83
|
The default root is `~/.worktrees`, where `~` is Node's platform home directory. Suggestions use the registered main worktree's directory name, not the current linked-worktree cwd:
|
|
71
84
|
|
|
72
85
|
```text
|
|
@@ -129,9 +142,10 @@ A successfully created Git worktree is never rolled back merely because Pi sessi
|
|
|
129
142
|
- Removal never deletes a branch and never uses `--force`.
|
|
130
143
|
- Remove invokes only argv-based `git worktree remove <path>`; production runtime never invokes a shell, `rm`, `rm -rf`, or a Node filesystem directory-deletion API for worktrees.
|
|
131
144
|
- Prune always runs `git worktree prune --dry-run --verbose` before confirmation, inspects candidates omitted from porcelain, rechecks the exact preview and recovery-risk set after confirmation, and uses Git's default expiry. Remove likewise rechecks worktree identity, inventory, administrative path, and the approved recovery-risk set before mutation.
|
|
132
|
-
- The
|
|
145
|
+
- The status browser uses only local Git state and never fetches a remote; its cards never authorize Remove or Prune.
|
|
146
|
+
- The extension does not commit, push, fetch, rebase, repair, move, lock, or unlock worktrees.
|
|
133
147
|
|
|
134
|
-
Use Git directly when you intentionally need force removal, branch deletion, custom prune expiry, detach/orphan creation, move, repair, lock, or
|
|
148
|
+
Use Git directly when you intentionally need force removal, branch deletion, custom prune expiry, detach/orphan creation, move, repair, lock, unlock, or remote refresh behavior.
|
|
135
149
|
|
|
136
150
|
## Requirements and limits
|
|
137
151
|
|
|
@@ -140,31 +154,37 @@ Use Git directly when you intentionally need force removal, branch deletion, cus
|
|
|
140
154
|
- Project trust and cwd-bound extension/resource loading during a switch remain owned by Pi.
|
|
141
155
|
- The extension registers no LLM tool, background watcher, project settings, or statusline item.
|
|
142
156
|
|
|
143
|
-
##
|
|
157
|
+
## ๐๏ธ Package layout
|
|
144
158
|
|
|
145
159
|
```text
|
|
146
|
-
|
|
160
|
+
packages/pi-worktree/
|
|
147
161
|
โโโ src/
|
|
148
162
|
โ โโโ index.ts
|
|
149
163
|
โ โโโ command.ts
|
|
150
164
|
โ โโโ git.ts
|
|
151
165
|
โ โโโ session.ts
|
|
152
166
|
โ โโโ settings.ts
|
|
167
|
+
โ โโโ status.ts
|
|
153
168
|
โ โโโ worktree.ts
|
|
154
169
|
โโโ test/
|
|
170
|
+
โ โโโ add-command.test.ts
|
|
171
|
+
โ โโโ command-test-support.ts
|
|
155
172
|
โ โโโ command.test.ts
|
|
156
173
|
โ โโโ git.integration.test.ts
|
|
157
174
|
โ โโโ git.test.ts
|
|
158
175
|
โ โโโ remove-ignored-command.test.ts
|
|
159
176
|
โ โโโ session.test.ts
|
|
160
|
-
โ
|
|
177
|
+
โ โโโ settings-command.test.ts
|
|
178
|
+
โ โโโ settings.test.ts
|
|
179
|
+
โ โโโ status-command.test.ts
|
|
180
|
+
โ โโโ status.test.ts
|
|
161
181
|
โโโ package.json
|
|
162
182
|
โโโ README.md
|
|
163
183
|
โโโ LICENSE
|
|
164
184
|
โโโ tsconfig.json
|
|
165
185
|
```
|
|
166
186
|
|
|
167
|
-
##
|
|
187
|
+
## ๐ Keywords
|
|
168
188
|
|
|
169
189
|
`pi-package`, `pi-extension`, `git`, `worktree`, `workspace`, `session`
|
|
170
190
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@narumitw/pi-worktree",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.50.0",
|
|
4
4
|
"description": "Pi extension for safe interactive Git worktree management and workspace switching.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -23,6 +23,9 @@
|
|
|
23
23
|
"./src/index.ts"
|
|
24
24
|
]
|
|
25
25
|
},
|
|
26
|
+
"piExtension": {
|
|
27
|
+
"lifecycle": "stable"
|
|
28
|
+
},
|
|
26
29
|
"scripts": {
|
|
27
30
|
"check": "biome check --vcs-use-ignore-file=false src test package.json README.md tsconfig.json && npm run typecheck",
|
|
28
31
|
"format": "biome check --write --vcs-use-ignore-file=false src test package.json README.md tsconfig.json",
|
|
@@ -33,16 +36,16 @@
|
|
|
33
36
|
},
|
|
34
37
|
"devDependencies": {
|
|
35
38
|
"@biomejs/biome": "2.5.7",
|
|
36
|
-
"@earendil-works/pi-coding-agent": "0.
|
|
39
|
+
"@earendil-works/pi-coding-agent": "0.84.1",
|
|
37
40
|
"@types/node": "26.1.2",
|
|
38
41
|
"typescript": "7.0.2"
|
|
39
42
|
},
|
|
40
43
|
"repository": {
|
|
41
44
|
"type": "git",
|
|
42
45
|
"url": "https://github.com/narumiruna/pi-extensions",
|
|
43
|
-
"directory": "
|
|
46
|
+
"directory": "packages/pi-worktree"
|
|
44
47
|
},
|
|
45
48
|
"dependencies": {
|
|
46
|
-
"@narumitw/pi-tui-kit": "^0.
|
|
49
|
+
"@narumitw/pi-tui-kit": "^0.51.0"
|
|
47
50
|
}
|
|
48
51
|
}
|
package/src/command.ts
CHANGED
|
@@ -31,13 +31,16 @@ import {
|
|
|
31
31
|
} from "./git.js";
|
|
32
32
|
import { switchToWorktree } from "./session.js";
|
|
33
33
|
import type { WorktreeSettingsRuntime } from "./settings.js";
|
|
34
|
+
import { loadWorktreeStatusCards, type WorktreeStatusCard } from "./status.js";
|
|
34
35
|
|
|
36
|
+
const ACTION_STATUS = "Worktree status";
|
|
35
37
|
const ACTION_ADD = "Add worktree";
|
|
36
38
|
const ACTION_SWITCH = "Switch worktree";
|
|
37
39
|
const ACTION_REMOVE = "Remove worktree";
|
|
38
40
|
const ACTION_PRUNE = "Prune stale metadata";
|
|
39
41
|
const ACTION_CONFIGURE_ROOT = "Configure worktree root";
|
|
40
42
|
const ACTIONS = {
|
|
43
|
+
status: ACTION_STATUS,
|
|
41
44
|
add: ACTION_ADD,
|
|
42
45
|
switch: ACTION_SWITCH,
|
|
43
46
|
remove: ACTION_REMOVE,
|
|
@@ -45,6 +48,10 @@ const ACTIONS = {
|
|
|
45
48
|
configure: ACTION_CONFIGURE_ROOT,
|
|
46
49
|
} as const;
|
|
47
50
|
|
|
51
|
+
interface WorktreeMenuState {
|
|
52
|
+
statusCards: WorktreeStatusCard[];
|
|
53
|
+
}
|
|
54
|
+
|
|
48
55
|
interface WorktreeMenuOwner {
|
|
49
56
|
signal: AbortSignal;
|
|
50
57
|
isCurrent(): boolean;
|
|
@@ -55,6 +62,12 @@ interface AdministrativeHistoryRisk {
|
|
|
55
62
|
oids: string[];
|
|
56
63
|
}
|
|
57
64
|
|
|
65
|
+
interface AddBaseProvenance {
|
|
66
|
+
kind: "existing-local-branch" | "current-branch" | "explicit-commit-ish";
|
|
67
|
+
label: string;
|
|
68
|
+
oid: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
58
71
|
export function registerWorktreeCommand(
|
|
59
72
|
pi: ExtensionAPI,
|
|
60
73
|
settings: WorktreeSettingsRuntime,
|
|
@@ -93,9 +106,10 @@ export function registerWorktreeCommand(
|
|
|
93
106
|
}
|
|
94
107
|
return { kind: "close" } as const;
|
|
95
108
|
};
|
|
96
|
-
|
|
109
|
+
const state: WorktreeMenuState = { statusCards: [] };
|
|
110
|
+
type Screen = "main" | "status";
|
|
97
111
|
type Action = keyof typeof ACTIONS;
|
|
98
|
-
const menu = defineMenu<
|
|
112
|
+
const menu = defineMenu<WorktreeMenuState, Screen, Action, ExtensionCommandContext>({
|
|
99
113
|
start: "main",
|
|
100
114
|
screens: {
|
|
101
115
|
main: () => ({
|
|
@@ -110,11 +124,37 @@ export function registerWorktreeCommand(
|
|
|
110
124
|
id,
|
|
111
125
|
label,
|
|
112
126
|
action: id as Action,
|
|
127
|
+
busyLabel: id === "status" ? "Inspecting worktreesโฆ" : undefined,
|
|
113
128
|
})),
|
|
114
129
|
hint: "close",
|
|
115
130
|
}),
|
|
131
|
+
status: ({ state: currentState }) => ({
|
|
132
|
+
kind: "browse",
|
|
133
|
+
title: "Worktree status",
|
|
134
|
+
lines: ["Local Git snapshot; no fetch performed."],
|
|
135
|
+
items: currentState.statusCards,
|
|
136
|
+
viewportSize: "adaptive",
|
|
137
|
+
hint: "back",
|
|
138
|
+
}),
|
|
116
139
|
},
|
|
117
140
|
actions: {
|
|
141
|
+
status: async ({ signal }) => {
|
|
142
|
+
try {
|
|
143
|
+
const statusRecords = await listWorktrees(pi, ctx.cwd, signal);
|
|
144
|
+
state.statusCards = await loadWorktreeStatusCards(
|
|
145
|
+
pi,
|
|
146
|
+
statusRecords,
|
|
147
|
+
currentPath,
|
|
148
|
+
signal,
|
|
149
|
+
);
|
|
150
|
+
if (signal.aborted || !owner.isCurrent()) return { kind: "close" };
|
|
151
|
+
return { kind: "to", screen: "status" };
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (signal.aborted || !owner.isCurrent()) return { kind: "close" };
|
|
154
|
+
safeNotify(ctx, formatError(error), "error");
|
|
155
|
+
return { kind: "stay" };
|
|
156
|
+
}
|
|
157
|
+
},
|
|
118
158
|
add: async () => runFlow(() => addFlow(pi, ctx, records, root.effectiveRoot)),
|
|
119
159
|
switch: async ({ signal }) =>
|
|
120
160
|
runFlow(() => switchFlow(pi, ctx, records, currentPath, signal)),
|
|
@@ -125,7 +165,7 @@ export function registerWorktreeCommand(
|
|
|
125
165
|
},
|
|
126
166
|
});
|
|
127
167
|
await runMenu(ctx, menu, {
|
|
128
|
-
getState: () =>
|
|
168
|
+
getState: () => state,
|
|
129
169
|
signal: owner.signal,
|
|
130
170
|
isCurrent: owner.isCurrent,
|
|
131
171
|
});
|
|
@@ -191,8 +231,14 @@ async function addFlow(
|
|
|
191
231
|
}
|
|
192
232
|
|
|
193
233
|
let startOid: string | undefined;
|
|
194
|
-
let
|
|
195
|
-
if (
|
|
234
|
+
let provenance: AddBaseProvenance;
|
|
235
|
+
if (branchExists) {
|
|
236
|
+
provenance = {
|
|
237
|
+
kind: "existing-local-branch",
|
|
238
|
+
label: branch,
|
|
239
|
+
oid: await resolveCommit(pi, ctx.cwd, `refs/heads/${branch}`, ctx.signal),
|
|
240
|
+
};
|
|
241
|
+
} else {
|
|
196
242
|
const defaultStart = await symbolicBranch(pi, ctx.cwd, ctx.signal);
|
|
197
243
|
const requestedStart = await ctx.ui.input(
|
|
198
244
|
stripTerminalControls(
|
|
@@ -203,9 +249,15 @@ async function addFlow(
|
|
|
203
249
|
stripTerminalControls(defaultStart ?? "commit-ish"),
|
|
204
250
|
);
|
|
205
251
|
if (requestedStart === undefined) return;
|
|
206
|
-
|
|
252
|
+
const explicitStart = requestedStart.trim();
|
|
253
|
+
const startLabel = explicitStart || defaultStart;
|
|
207
254
|
if (!startLabel) throw new Error("An explicit start point is required from detached HEAD.");
|
|
208
255
|
startOid = await resolveCommit(pi, ctx.cwd, startLabel, ctx.signal);
|
|
256
|
+
provenance = {
|
|
257
|
+
kind: explicitStart ? "explicit-commit-ish" : "current-branch",
|
|
258
|
+
label: startLabel,
|
|
259
|
+
oid: startOid,
|
|
260
|
+
};
|
|
209
261
|
}
|
|
210
262
|
|
|
211
263
|
const suggestedPath = defaultWorktreePath(main.path, branch, worktreeRoot);
|
|
@@ -223,10 +275,33 @@ async function addFlow(
|
|
|
223
275
|
throw new Error(`The target path is already registered as a worktree: ${pathCollision.path}.`);
|
|
224
276
|
}
|
|
225
277
|
|
|
226
|
-
const summary = branchExists
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
278
|
+
const summary = formatAddPreview(branch, branchExists, provenance, targetPath);
|
|
279
|
+
if (!(await ctx.ui.confirm("Create Git worktree", summary))) return;
|
|
280
|
+
|
|
281
|
+
assertTargetFilesystemAvailable(targetPath);
|
|
282
|
+
const latestRecords = await listWorktrees(pi, ctx.cwd, ctx.signal);
|
|
283
|
+
const latestOccupied = worktreeForBranch(latestRecords, branch);
|
|
284
|
+
if (latestOccupied) {
|
|
285
|
+
throw new Error(
|
|
286
|
+
`Branch ${branch} is now checked out at ${latestOccupied.path}; select it again.`,
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
const latestPathCollision = latestRecords.find((record) => pathsEqual(record.path, targetPath));
|
|
290
|
+
if (latestPathCollision) {
|
|
291
|
+
throw new Error(
|
|
292
|
+
`The target path is now registered as a worktree: ${latestPathCollision.path}. Select it again.`,
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
const branchStillExists = await localBranchExists(pi, ctx.cwd, branch, ctx.signal);
|
|
296
|
+
if (branchStillExists !== branchExists) {
|
|
297
|
+
throw new Error(`Branch ${branch} changed after confirmation; select it again.`);
|
|
298
|
+
}
|
|
299
|
+
if (branchExists) {
|
|
300
|
+
const latestOid = await resolveCommit(pi, ctx.cwd, `refs/heads/${branch}`, ctx.signal);
|
|
301
|
+
if (latestOid !== provenance.oid) {
|
|
302
|
+
throw new Error(`Branch ${branch} moved after confirmation; select it again.`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
230
305
|
|
|
231
306
|
assertTargetFilesystemAvailable(targetPath);
|
|
232
307
|
await addWorktree(pi, ctx.cwd, { path: targetPath, branch, startOid }, ctx.signal);
|
|
@@ -234,8 +309,10 @@ async function addFlow(
|
|
|
234
309
|
try {
|
|
235
310
|
const updated = await listWorktrees(pi, ctx.cwd, ctx.signal);
|
|
236
311
|
const verified = updated.find((record) => pathsEqual(record.path, targetPath));
|
|
237
|
-
if (!verified || verified.branch !== branch) {
|
|
238
|
-
throw new Error(
|
|
312
|
+
if (!verified || verified.branch !== branch || verified.head !== provenance.oid) {
|
|
313
|
+
throw new Error(
|
|
314
|
+
"the expected path, branch, and approved HEAD were not present in Git porcelain output",
|
|
315
|
+
);
|
|
239
316
|
}
|
|
240
317
|
created = verified;
|
|
241
318
|
} catch (error) {
|
|
@@ -259,6 +336,41 @@ async function addFlow(
|
|
|
259
336
|
}
|
|
260
337
|
}
|
|
261
338
|
|
|
339
|
+
function formatAddPreview(
|
|
340
|
+
branch: string,
|
|
341
|
+
branchExists: boolean,
|
|
342
|
+
provenance: AddBaseProvenance,
|
|
343
|
+
targetPath: string,
|
|
344
|
+
): string {
|
|
345
|
+
const base =
|
|
346
|
+
provenance.kind === "existing-local-branch"
|
|
347
|
+
? `existing local branch ${quoteTerminalValue(provenance.label)}`
|
|
348
|
+
: provenance.kind === "current-branch"
|
|
349
|
+
? `current branch ${quoteTerminalValue(provenance.label)}`
|
|
350
|
+
: `explicit commit-ish ${quoteTerminalValue(provenance.label)}`;
|
|
351
|
+
return [
|
|
352
|
+
`Branch: ${quoteTerminalValue(branch)} (${branchExists ? "existing" : "new"} local branch)`,
|
|
353
|
+
`Base: ${base}`,
|
|
354
|
+
`Base commit: ${provenance.oid}`,
|
|
355
|
+
`Path: ${quoteTerminalValue(targetPath)}`,
|
|
356
|
+
].join("; ");
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function quoteTerminalValue(value: string): string {
|
|
360
|
+
let quoted = "";
|
|
361
|
+
for (const character of value) {
|
|
362
|
+
const code = character.codePointAt(0) ?? 0;
|
|
363
|
+
if (code <= 0x1f || (code >= 0x7f && code <= 0x9f)) {
|
|
364
|
+
quoted += `\\u${code.toString(16).padStart(4, "0")}`;
|
|
365
|
+
} else if (character === "\\" || character === '"') {
|
|
366
|
+
quoted += `\\${character}`;
|
|
367
|
+
} else {
|
|
368
|
+
quoted += character;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return `"${quoted}"`;
|
|
372
|
+
}
|
|
373
|
+
|
|
262
374
|
function assertTargetFilesystemAvailable(targetPath: string): void {
|
|
263
375
|
if (pathEntryExists(targetPath)) {
|
|
264
376
|
throw new Error(`The target path already exists: ${targetPath}.`);
|
package/src/status.ts
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import type { ExecResult, ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { pathsEqual, stripTerminalControls, type WorktreeRecord } from "./git.js";
|
|
4
|
+
|
|
5
|
+
const GIT_STATUS_TIMEOUT_MS = 15_000;
|
|
6
|
+
const DEFAULT_STATUS_CONCURRENCY = 4;
|
|
7
|
+
const OID_PATTERN = /^[0-9a-fA-F]{40,64}$/u;
|
|
8
|
+
const STATUS_XY_PATTERN = /^[.MADRCUT]{2}$/u;
|
|
9
|
+
|
|
10
|
+
export interface WorktreeStatusSnapshot {
|
|
11
|
+
headOid?: string;
|
|
12
|
+
branch?: string;
|
|
13
|
+
detached: boolean;
|
|
14
|
+
upstream?: string;
|
|
15
|
+
ahead?: number;
|
|
16
|
+
behind?: number;
|
|
17
|
+
staged: number;
|
|
18
|
+
unstaged: number;
|
|
19
|
+
untracked: number;
|
|
20
|
+
conflicts: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface LastCommitSummary {
|
|
24
|
+
committedAt: string;
|
|
25
|
+
subject: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export type WorktreeStatusResult =
|
|
29
|
+
| {
|
|
30
|
+
kind: "available";
|
|
31
|
+
snapshot: WorktreeStatusSnapshot;
|
|
32
|
+
lastCommit?: LastCommitSummary;
|
|
33
|
+
}
|
|
34
|
+
| { kind: "unavailable"; reason: string };
|
|
35
|
+
|
|
36
|
+
export interface WorktreeStatusCard {
|
|
37
|
+
id: string;
|
|
38
|
+
label: string;
|
|
39
|
+
description: string;
|
|
40
|
+
statusText: string;
|
|
41
|
+
searchText: string;
|
|
42
|
+
details: string[];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
interface LoadStatusOptions {
|
|
46
|
+
concurrency?: number;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function parseWorktreeStatusPorcelain(output: string): WorktreeStatusSnapshot {
|
|
50
|
+
if (output && !output.endsWith("\0")) {
|
|
51
|
+
throw new Error("Git status porcelain output is not NUL-terminated.");
|
|
52
|
+
}
|
|
53
|
+
const entries = output ? output.slice(0, -1).split("\0") : [];
|
|
54
|
+
const snapshot: WorktreeStatusSnapshot = {
|
|
55
|
+
detached: false,
|
|
56
|
+
staged: 0,
|
|
57
|
+
unstaged: 0,
|
|
58
|
+
untracked: 0,
|
|
59
|
+
conflicts: 0,
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
for (let index = 0; index < entries.length; index += 1) {
|
|
63
|
+
const entry = entries[index] ?? "";
|
|
64
|
+
if (entry.startsWith("# ")) {
|
|
65
|
+
parseBranchHeader(snapshot, entry);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (entry.startsWith("1 ")) {
|
|
69
|
+
assertFieldCount(entry, 9, "ordinary");
|
|
70
|
+
countTrackedState(snapshot, statusCode(entry));
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (entry.startsWith("2 ")) {
|
|
74
|
+
assertFieldCount(entry, 10, "renamed");
|
|
75
|
+
countTrackedState(snapshot, statusCode(entry));
|
|
76
|
+
const originalPath = entries[index + 1];
|
|
77
|
+
if (!originalPath) throw new Error("Git status returned a malformed renamed record.");
|
|
78
|
+
index += 1;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (entry.startsWith("u ")) {
|
|
82
|
+
assertFieldCount(entry, 11, "unmerged");
|
|
83
|
+
statusCode(entry);
|
|
84
|
+
snapshot.conflicts += 1;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (entry.startsWith("? ")) {
|
|
88
|
+
if (entry.length === 2) throw new Error("Git status returned a malformed untracked record.");
|
|
89
|
+
snapshot.untracked += 1;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (entry.startsWith("! ")) continue;
|
|
93
|
+
throw new Error("Git status returned an unknown porcelain-v2 record.");
|
|
94
|
+
}
|
|
95
|
+
return snapshot;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function formatWorktreeStatusCard(
|
|
99
|
+
record: WorktreeRecord,
|
|
100
|
+
currentPath: string,
|
|
101
|
+
result: WorktreeStatusResult,
|
|
102
|
+
): WorktreeStatusCard {
|
|
103
|
+
const path = safeDisplay(record.path);
|
|
104
|
+
const identity = [
|
|
105
|
+
pathsEqual(record.path, currentPath) ? "current" : undefined,
|
|
106
|
+
record.isMain ? "main" : undefined,
|
|
107
|
+
record.bare ? "bare" : undefined,
|
|
108
|
+
record.detached ? "detached" : undefined,
|
|
109
|
+
].filter((value): value is string => value !== undefined);
|
|
110
|
+
const label = safeDisplay(
|
|
111
|
+
record.branch ??
|
|
112
|
+
(record.detached
|
|
113
|
+
? `Detached ${record.head?.slice(0, 8) ?? "HEAD"}`
|
|
114
|
+
: record.bare
|
|
115
|
+
? "Bare worktree"
|
|
116
|
+
: "Unknown worktree"),
|
|
117
|
+
);
|
|
118
|
+
const statePrefix = identity.length > 0 ? `${identity.join(" ยท ")} ยท ` : "";
|
|
119
|
+
const baseDetails = [
|
|
120
|
+
`Path: ${path}`,
|
|
121
|
+
`Identity: ${identity.join(" ยท ") || "linked"}`,
|
|
122
|
+
`Registered HEAD: ${safeDisplay(record.head ?? "unavailable")}`,
|
|
123
|
+
];
|
|
124
|
+
if (record.lockedReason !== undefined) {
|
|
125
|
+
baseDetails.push(
|
|
126
|
+
record.lockedReason
|
|
127
|
+
? `Locked: ${safeDisplay(record.lockedReason)}`
|
|
128
|
+
: "Locked: no reason provided",
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
if (record.prunableReason !== undefined) {
|
|
132
|
+
baseDetails.push(
|
|
133
|
+
record.prunableReason
|
|
134
|
+
? `Prunable: ${safeDisplay(record.prunableReason)}`
|
|
135
|
+
: "Prunable: no reason provided",
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (result.kind === "unavailable") {
|
|
140
|
+
const reason = safeDisplay(result.reason);
|
|
141
|
+
return {
|
|
142
|
+
id: record.path,
|
|
143
|
+
label,
|
|
144
|
+
description: path,
|
|
145
|
+
statusText: `${statePrefix}unavailable`,
|
|
146
|
+
searchText: `${label} ${path} ${identity.join(" ")} unavailable ${reason}`,
|
|
147
|
+
details: [
|
|
148
|
+
...baseDetails,
|
|
149
|
+
`Status: ${reason}`,
|
|
150
|
+
"Snapshot: local Git state; no fetch performed.",
|
|
151
|
+
],
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const { snapshot, lastCommit } = result;
|
|
156
|
+
const workingState = formatWorkingState(snapshot);
|
|
157
|
+
const upstream = snapshot.upstream
|
|
158
|
+
? snapshot.ahead !== undefined && snapshot.behind !== undefined
|
|
159
|
+
? `${safeDisplay(snapshot.upstream)} ยท ahead ${snapshot.ahead} ยท behind ${snapshot.behind}`
|
|
160
|
+
: `${safeDisplay(snapshot.upstream)} ยท ahead/behind unavailable`
|
|
161
|
+
: "not configured; ahead/behind unavailable";
|
|
162
|
+
const details = [
|
|
163
|
+
...baseDetails,
|
|
164
|
+
`Snapshot HEAD: ${safeDisplay(snapshot.headOid ?? "unborn")}`,
|
|
165
|
+
`Working tree: ${workingState}`,
|
|
166
|
+
`Upstream: ${upstream}`,
|
|
167
|
+
lastCommit
|
|
168
|
+
? `Last commit: ${safeDisplay(lastCommit.committedAt)} ยท ${safeDisplay(lastCommit.subject || "(no subject)")}`
|
|
169
|
+
: "Last commit: unavailable",
|
|
170
|
+
"Snapshot: local Git state; no fetch performed; removal uses stricter checks.",
|
|
171
|
+
];
|
|
172
|
+
return {
|
|
173
|
+
id: record.path,
|
|
174
|
+
label,
|
|
175
|
+
description: path,
|
|
176
|
+
statusText: `${statePrefix}${workingState}`,
|
|
177
|
+
searchText: `${label} ${path} ${identity.join(" ")} ${workingState} ${safeDisplay(snapshot.upstream ?? "")}`,
|
|
178
|
+
details,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export async function loadWorktreeStatusCards(
|
|
183
|
+
pi: Pick<ExtensionAPI, "exec">,
|
|
184
|
+
records: readonly WorktreeRecord[],
|
|
185
|
+
currentPath: string,
|
|
186
|
+
signal?: AbortSignal,
|
|
187
|
+
options: LoadStatusOptions = {},
|
|
188
|
+
): Promise<WorktreeStatusCard[]> {
|
|
189
|
+
const concurrency = Math.max(
|
|
190
|
+
1,
|
|
191
|
+
Math.min(options.concurrency ?? DEFAULT_STATUS_CONCURRENCY, records.length || 1),
|
|
192
|
+
);
|
|
193
|
+
const cards = new Array<WorktreeStatusCard>(records.length);
|
|
194
|
+
let nextIndex = 0;
|
|
195
|
+
|
|
196
|
+
const worker = async () => {
|
|
197
|
+
while (true) {
|
|
198
|
+
throwIfAborted(signal);
|
|
199
|
+
const index = nextIndex;
|
|
200
|
+
if (index >= records.length) return;
|
|
201
|
+
nextIndex += 1;
|
|
202
|
+
const record = records[index];
|
|
203
|
+
if (!record) return;
|
|
204
|
+
const unavailable = unavailableReason(record);
|
|
205
|
+
if (unavailable) {
|
|
206
|
+
cards[index] = formatWorktreeStatusCard(record, currentPath, {
|
|
207
|
+
kind: "unavailable",
|
|
208
|
+
reason: unavailable,
|
|
209
|
+
});
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
const status = await runGit(
|
|
214
|
+
pi,
|
|
215
|
+
[
|
|
216
|
+
"status",
|
|
217
|
+
"--porcelain=v2",
|
|
218
|
+
"--branch",
|
|
219
|
+
"-z",
|
|
220
|
+
"--untracked-files=all",
|
|
221
|
+
"--ignore-submodules=none",
|
|
222
|
+
],
|
|
223
|
+
record.path,
|
|
224
|
+
signal,
|
|
225
|
+
);
|
|
226
|
+
const snapshot = parseWorktreeStatusPorcelain(status.stdout);
|
|
227
|
+
const lastCommit = snapshot.headOid
|
|
228
|
+
? parseLastCommit(
|
|
229
|
+
(
|
|
230
|
+
await runGit(
|
|
231
|
+
pi,
|
|
232
|
+
["show", "-s", "--format=%aI%x00%s", "--end-of-options", snapshot.headOid],
|
|
233
|
+
record.path,
|
|
234
|
+
signal,
|
|
235
|
+
)
|
|
236
|
+
).stdout,
|
|
237
|
+
)
|
|
238
|
+
: undefined;
|
|
239
|
+
cards[index] = formatWorktreeStatusCard(record, currentPath, {
|
|
240
|
+
kind: "available",
|
|
241
|
+
snapshot,
|
|
242
|
+
lastCommit,
|
|
243
|
+
});
|
|
244
|
+
} catch (error) {
|
|
245
|
+
throwIfAborted(signal);
|
|
246
|
+
cards[index] = formatWorktreeStatusCard(record, currentPath, {
|
|
247
|
+
kind: "unavailable",
|
|
248
|
+
reason: `Status failed: ${formatError(error)}`,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
await Promise.all(Array.from({ length: concurrency }, worker));
|
|
255
|
+
throwIfAborted(signal);
|
|
256
|
+
return cards;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function parseBranchHeader(snapshot: WorktreeStatusSnapshot, entry: string): void {
|
|
260
|
+
if (entry.startsWith("# branch.oid ")) {
|
|
261
|
+
const oid = entry.slice("# branch.oid ".length);
|
|
262
|
+
if (oid === "(initial)") {
|
|
263
|
+
snapshot.headOid = undefined;
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
if (!OID_PATTERN.test(oid)) throw new Error("Git status returned a malformed branch OID.");
|
|
267
|
+
snapshot.headOid = oid;
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
if (entry.startsWith("# branch.head ")) {
|
|
271
|
+
const branch = entry.slice("# branch.head ".length);
|
|
272
|
+
if (!branch) throw new Error("Git status returned a malformed branch head.");
|
|
273
|
+
snapshot.detached = branch === "(detached)";
|
|
274
|
+
snapshot.branch = snapshot.detached || branch === "(unknown)" ? undefined : branch;
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
if (entry.startsWith("# branch.upstream ")) {
|
|
278
|
+
const upstream = entry.slice("# branch.upstream ".length);
|
|
279
|
+
if (!upstream) throw new Error("Git status returned a malformed upstream.");
|
|
280
|
+
snapshot.upstream = upstream;
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
if (entry.startsWith("# branch.ab ")) {
|
|
284
|
+
const match = /^# branch\.ab \+(\d+) -(\d+)$/u.exec(entry);
|
|
285
|
+
if (!match?.[1] || !match[2]) {
|
|
286
|
+
throw new Error("Git status returned malformed ahead/behind counts.");
|
|
287
|
+
}
|
|
288
|
+
snapshot.ahead = Number.parseInt(match[1], 10);
|
|
289
|
+
snapshot.behind = Number.parseInt(match[2], 10);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function statusCode(entry: string): string {
|
|
294
|
+
const code = entry.slice(2, 4);
|
|
295
|
+
if (!STATUS_XY_PATTERN.test(code)) {
|
|
296
|
+
throw new Error("Git status returned a malformed tracked status code.");
|
|
297
|
+
}
|
|
298
|
+
return code;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function countTrackedState(snapshot: WorktreeStatusSnapshot, code: string): void {
|
|
302
|
+
if (code[0] !== ".") snapshot.staged += 1;
|
|
303
|
+
if (code[1] !== ".") snapshot.unstaged += 1;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function assertFieldCount(entry: string, minimum: number, kind: string): void {
|
|
307
|
+
if (entry.split(" ").length < minimum) {
|
|
308
|
+
throw new Error(`Git status returned a malformed ${kind} record.`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function formatWorkingState(snapshot: WorktreeStatusSnapshot): string {
|
|
313
|
+
const values = [
|
|
314
|
+
snapshot.conflicts > 0
|
|
315
|
+
? `${snapshot.conflicts} conflict${snapshot.conflicts === 1 ? "" : "s"}`
|
|
316
|
+
: undefined,
|
|
317
|
+
snapshot.staged > 0 ? `${snapshot.staged} staged` : undefined,
|
|
318
|
+
snapshot.unstaged > 0 ? `${snapshot.unstaged} unstaged` : undefined,
|
|
319
|
+
snapshot.untracked > 0 ? `${snapshot.untracked} untracked` : undefined,
|
|
320
|
+
].filter((value): value is string => value !== undefined);
|
|
321
|
+
return values.join(" ยท ") || "clean";
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function unavailableReason(record: WorktreeRecord): string | undefined {
|
|
325
|
+
if (record.bare) return "Bare worktree cannot be inspected";
|
|
326
|
+
if (record.prunableReason !== undefined) {
|
|
327
|
+
return record.prunableReason
|
|
328
|
+
? `Prunable: ${record.prunableReason}`
|
|
329
|
+
: "Prunable worktree metadata";
|
|
330
|
+
}
|
|
331
|
+
if (!existsSync(record.path)) return "Worktree path is missing";
|
|
332
|
+
return undefined;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async function runGit(
|
|
336
|
+
pi: Pick<ExtensionAPI, "exec">,
|
|
337
|
+
args: string[],
|
|
338
|
+
cwd: string,
|
|
339
|
+
signal?: AbortSignal,
|
|
340
|
+
): Promise<ExecResult> {
|
|
341
|
+
throwIfAborted(signal);
|
|
342
|
+
const result = await pi.exec("git", args, { cwd, signal, timeout: GIT_STATUS_TIMEOUT_MS });
|
|
343
|
+
if (result.killed) {
|
|
344
|
+
throwIfAborted(signal);
|
|
345
|
+
throw new Error(`git ${args.slice(0, 2).join(" ")} timed out.`);
|
|
346
|
+
}
|
|
347
|
+
if (result.code !== 0) {
|
|
348
|
+
const detail = [result.stderr.trim(), result.stdout.trim()].filter(Boolean).join(" ");
|
|
349
|
+
throw new Error(detail || `git ${args.slice(0, 2).join(" ")} exited with code ${result.code}.`);
|
|
350
|
+
}
|
|
351
|
+
return result;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function parseLastCommit(output: string): LastCommitSummary {
|
|
355
|
+
const separator = output.indexOf("\0");
|
|
356
|
+
if (separator <= 0 || output.indexOf("\0", separator + 1) >= 0) {
|
|
357
|
+
throw new Error("Git returned malformed last-commit details.");
|
|
358
|
+
}
|
|
359
|
+
const committedAt = output.slice(0, separator);
|
|
360
|
+
const subject = removeLineEnding(output.slice(separator + 1));
|
|
361
|
+
if (!committedAt) throw new Error("Git returned an empty last-commit timestamp.");
|
|
362
|
+
return { committedAt, subject };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function safeDisplay(value: string): string {
|
|
366
|
+
return stripTerminalControls(value);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function throwIfAborted(signal?: AbortSignal): void {
|
|
370
|
+
if (signal?.aborted) {
|
|
371
|
+
throw new DOMException("Worktree status loading was aborted.", "AbortError");
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function removeLineEnding(value: string): string {
|
|
376
|
+
if (value.endsWith("\r\n")) return value.slice(0, -2);
|
|
377
|
+
if (value.endsWith("\n")) return value.slice(0, -1);
|
|
378
|
+
return value;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function formatError(error: unknown): string {
|
|
382
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
383
|
+
return safeDisplay(message).slice(0, 500);
|
|
384
|
+
}
|