dsh-worktree-switch 0.0.0-stage → 0.2.1
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 +159 -2
- package/cordis.patch.yml +19 -0
- package/icon.svg +8 -0
- package/lib/client.js +1068 -0
- package/lib/index.d.ts +25 -0
- package/lib/index.js +717 -0
- package/lib/index.js.map +1 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +133 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,717 @@
|
|
|
1
|
+
import Schema from "@deepseek-ai/schemastery";
|
|
2
|
+
import { lstat, realpath, stat } from "node:fs/promises";
|
|
3
|
+
import { basename, isAbsolute, relative, resolve } from "node:path";
|
|
4
|
+
/** Per-stream capture cap; worktree listings and status lines are small. */
|
|
5
|
+
const MAX_OUTPUT_BYTES = 1048576;
|
|
6
|
+
/**
|
|
7
|
+
* Clear inherited repository selectors and config so the command reads the
|
|
8
|
+
* checkout named by `cwd`, never one inherited from the Host's environment.
|
|
9
|
+
* One entry per key: `undefined` removes the variable for the child.
|
|
10
|
+
*/
|
|
11
|
+
const GIT_ENV = Object.fromEntries([
|
|
12
|
+
"GIT_DIR",
|
|
13
|
+
"GIT_WORK_TREE",
|
|
14
|
+
"GIT_COMMON_DIR",
|
|
15
|
+
"GIT_INDEX_FILE",
|
|
16
|
+
"GIT_OBJECT_DIRECTORY",
|
|
17
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
18
|
+
"GIT_CONFIG",
|
|
19
|
+
"GIT_CONFIG_PARAMETERS",
|
|
20
|
+
"GIT_CONFIG_COUNT",
|
|
21
|
+
"GIT_CEILING_DIRECTORIES",
|
|
22
|
+
"GIT_PREFIX",
|
|
23
|
+
"GIT_SHALLOW_FILE",
|
|
24
|
+
"GIT_GRAFT_FILE",
|
|
25
|
+
"GIT_REPLACE_REF_BASE",
|
|
26
|
+
"GIT_ATTR_SOURCE"
|
|
27
|
+
].map((key) => [key, void 0]));
|
|
28
|
+
/** A Git invocation that exited with a status the caller did not allow. */
|
|
29
|
+
var GitFailure = class extends Error {
|
|
30
|
+
args;
|
|
31
|
+
result;
|
|
32
|
+
/**
|
|
33
|
+
* @param args - arguments after the executable, for diagnostics.
|
|
34
|
+
* @param result - the captured outcome.
|
|
35
|
+
*/
|
|
36
|
+
constructor(args, result) {
|
|
37
|
+
const detail = result.stderr.trim() === "" ? result.stdout.trim() : result.stderr.trim();
|
|
38
|
+
super(`git ${args.join(" ")} failed (exit ${result.exitCode})${detail === "" ? "" : `: ${detail}`}`);
|
|
39
|
+
this.args = args;
|
|
40
|
+
this.result = result;
|
|
41
|
+
this.name = "GitFailure";
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Run one Git command without a shell and await its termination.
|
|
46
|
+
* @param ctx - Host context carrying the subprocess provider.
|
|
47
|
+
* @param cwd - absolute directory the command runs in.
|
|
48
|
+
* @param args - arguments after the executable.
|
|
49
|
+
* @param options - cancellation, accepted exit statuses, and deadline.
|
|
50
|
+
* @returns captured stdout, stderr, and exit status.
|
|
51
|
+
* @throws {GitFailure} when the exit status is not allowed or the command was killed.
|
|
52
|
+
*/
|
|
53
|
+
async function runGit(ctx, cwd, args, options = {}) {
|
|
54
|
+
const deadline = AbortSignal.timeout(options.timeoutMs ?? 2e4);
|
|
55
|
+
const signal = options.signal === void 0 ? deadline : AbortSignal.any([options.signal, deadline]);
|
|
56
|
+
const allowed = options.allowedExitCodes ?? [0];
|
|
57
|
+
const argv = [
|
|
58
|
+
await ctx.subprocess.resolveExecutable("git", void 0, signal),
|
|
59
|
+
"-c",
|
|
60
|
+
"core.hooksPath=/dev/null",
|
|
61
|
+
"-c",
|
|
62
|
+
"core.fsmonitor=false",
|
|
63
|
+
...args
|
|
64
|
+
];
|
|
65
|
+
const child = ctx.subprocess.spawn({
|
|
66
|
+
argv,
|
|
67
|
+
cwd,
|
|
68
|
+
env: {
|
|
69
|
+
...GIT_ENV,
|
|
70
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
71
|
+
GIT_LFS_SKIP_SMUDGE: "1",
|
|
72
|
+
GIT_NO_LAZY_FETCH: "1"
|
|
73
|
+
},
|
|
74
|
+
signal,
|
|
75
|
+
graceMs: 1500,
|
|
76
|
+
stdio: {
|
|
77
|
+
stdin: "ignore",
|
|
78
|
+
stdout: { maxBytes: MAX_OUTPUT_BYTES },
|
|
79
|
+
stderr: { maxBytes: MAX_OUTPUT_BYTES }
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
try {
|
|
83
|
+
const outcome = await child.done;
|
|
84
|
+
const result = {
|
|
85
|
+
stdout: child.collected.stdout?.readFrom(0).text ?? "",
|
|
86
|
+
stderr: child.collected.stderr?.readFrom(0).text ?? "",
|
|
87
|
+
exitCode: outcome.exitCode ?? -1
|
|
88
|
+
};
|
|
89
|
+
if (outcome.exitCode === null || !allowed.includes(outcome.exitCode)) throw new GitFailure(args, result);
|
|
90
|
+
return result;
|
|
91
|
+
} finally {
|
|
92
|
+
child.terminate();
|
|
93
|
+
await child.waitForExit();
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Resolve the repository root that contains `directory`.
|
|
98
|
+
* @param ctx - Host context carrying the subprocess provider.
|
|
99
|
+
* @param directory - absolute directory inside (or at) the checkout.
|
|
100
|
+
* @param signal - caller cancellation.
|
|
101
|
+
* @returns the canonical top-level directory Git reports.
|
|
102
|
+
* @throws {GitFailure} when the directory is not inside a Git working tree.
|
|
103
|
+
*/
|
|
104
|
+
async function repositoryRoot(ctx, directory, signal) {
|
|
105
|
+
const result = await runGit(ctx, directory, ["rev-parse", "--show-toplevel"], {
|
|
106
|
+
signal,
|
|
107
|
+
allowedExitCodes: [0, 128]
|
|
108
|
+
});
|
|
109
|
+
if (result.exitCode !== 0) throw new GitFailure(["rev-parse", "--show-toplevel"], result);
|
|
110
|
+
return result.stdout.replace(/\r?\n$/, "");
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Resolve symlinks in a path that exists, falling back to the path as given.
|
|
114
|
+
* @param path - absolute path.
|
|
115
|
+
* @returns the canonical spelling when the path exists.
|
|
116
|
+
*/
|
|
117
|
+
async function canonicalPath(path) {
|
|
118
|
+
try {
|
|
119
|
+
return await realpath(path);
|
|
120
|
+
} catch {
|
|
121
|
+
return path;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Parse `git worktree list --porcelain` output into its records.
|
|
126
|
+
* @param stdout - the command's stdout.
|
|
127
|
+
* @returns one record per reported checkout, in Git's order.
|
|
128
|
+
*/
|
|
129
|
+
function parseWorktreeList(stdout) {
|
|
130
|
+
const records = [];
|
|
131
|
+
let path;
|
|
132
|
+
let branch;
|
|
133
|
+
const flush = () => {
|
|
134
|
+
if (path === void 0) return;
|
|
135
|
+
records.push(branch === void 0 ? { path } : {
|
|
136
|
+
path,
|
|
137
|
+
branch
|
|
138
|
+
});
|
|
139
|
+
path = void 0;
|
|
140
|
+
branch = void 0;
|
|
141
|
+
};
|
|
142
|
+
for (const line of stdout.split("\n")) {
|
|
143
|
+
if (line === "") {
|
|
144
|
+
flush();
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (line.startsWith("worktree ")) path = line.slice(9);
|
|
148
|
+
else if (line.startsWith("branch refs/heads/")) branch = line.slice(18);
|
|
149
|
+
}
|
|
150
|
+
flush();
|
|
151
|
+
return records;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* List the worktree checkouts of one repository.
|
|
155
|
+
* @param ctx - Host context carrying the subprocess provider.
|
|
156
|
+
* @param root - repository root the command runs in.
|
|
157
|
+
* @param signal - caller cancellation.
|
|
158
|
+
* @returns every checkout Git reports for the repository.
|
|
159
|
+
*/
|
|
160
|
+
async function listWorktreeRecords(ctx, root, signal) {
|
|
161
|
+
return parseWorktreeList((await runGit(ctx, root, [
|
|
162
|
+
"worktree",
|
|
163
|
+
"list",
|
|
164
|
+
"--porcelain"
|
|
165
|
+
], { signal })).stdout);
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Count the changed and untracked files of one checkout.
|
|
169
|
+
* @param ctx - Host context carrying the subprocess provider.
|
|
170
|
+
* @param directory - checkout directory to inspect.
|
|
171
|
+
* @param signal - caller cancellation.
|
|
172
|
+
* @returns the number of `git status --porcelain` entries.
|
|
173
|
+
*/
|
|
174
|
+
async function changedFileCount(ctx, directory, signal) {
|
|
175
|
+
return (await runGit(ctx, directory, [
|
|
176
|
+
"status",
|
|
177
|
+
"--porcelain",
|
|
178
|
+
"--untracked-files=normal"
|
|
179
|
+
], { signal })).stdout.split("\n").filter((line) => line.trim() !== "").length;
|
|
180
|
+
}
|
|
181
|
+
// src/host/naming.ts
|
|
182
|
+
/**
|
|
183
|
+
* Names for the copy a session gets: lowercase words and a short suffix, so a
|
|
184
|
+
* branch, a directory, a `git branch` row and this plugin's UI all read the
|
|
185
|
+
* same. No prefix: the pool path already says where it lives.
|
|
186
|
+
* @module dsh-worktree-switch/host/naming
|
|
187
|
+
*/
|
|
188
|
+
/** First word of a generated name. */
|
|
189
|
+
const ADJECTIVES = [
|
|
190
|
+
"amber",
|
|
191
|
+
"brisk",
|
|
192
|
+
"calm",
|
|
193
|
+
"clever",
|
|
194
|
+
"crisp",
|
|
195
|
+
"eager",
|
|
196
|
+
"faint",
|
|
197
|
+
"fresh",
|
|
198
|
+
"gentle",
|
|
199
|
+
"happy",
|
|
200
|
+
"hollow",
|
|
201
|
+
"kind",
|
|
202
|
+
"lively",
|
|
203
|
+
"mellow",
|
|
204
|
+
"nimble",
|
|
205
|
+
"polite",
|
|
206
|
+
"quiet",
|
|
207
|
+
"rapid",
|
|
208
|
+
"ready",
|
|
209
|
+
"silent",
|
|
210
|
+
"soft",
|
|
211
|
+
"solid",
|
|
212
|
+
"steady",
|
|
213
|
+
"sunny",
|
|
214
|
+
"swift",
|
|
215
|
+
"tidy",
|
|
216
|
+
"vivid",
|
|
217
|
+
"warm",
|
|
218
|
+
"wise",
|
|
219
|
+
"young"
|
|
220
|
+
];
|
|
221
|
+
/** Second word of a generated name. */
|
|
222
|
+
const NOUNS = [
|
|
223
|
+
"anchor",
|
|
224
|
+
"atlas",
|
|
225
|
+
"badger",
|
|
226
|
+
"birch",
|
|
227
|
+
"brook",
|
|
228
|
+
"cedar",
|
|
229
|
+
"comet",
|
|
230
|
+
"coral",
|
|
231
|
+
"delta",
|
|
232
|
+
"ember",
|
|
233
|
+
"fern",
|
|
234
|
+
"field",
|
|
235
|
+
"finch",
|
|
236
|
+
"glade",
|
|
237
|
+
"harbor",
|
|
238
|
+
"heron",
|
|
239
|
+
"island",
|
|
240
|
+
"lark",
|
|
241
|
+
"ledge",
|
|
242
|
+
"maple",
|
|
243
|
+
"meadow",
|
|
244
|
+
"otter",
|
|
245
|
+
"pebble",
|
|
246
|
+
"pine",
|
|
247
|
+
"quartz",
|
|
248
|
+
"river",
|
|
249
|
+
"shore",
|
|
250
|
+
"stone",
|
|
251
|
+
"trail",
|
|
252
|
+
"willow"
|
|
253
|
+
];
|
|
254
|
+
/**
|
|
255
|
+
* Generate one candidate worktree name.
|
|
256
|
+
* @param random - uniform source in `[0, 1)`; injectable for deterministic tests.
|
|
257
|
+
* @returns a lowercase, hyphen-joined branch-safe name such as `quiet-harbor-3fa9`.
|
|
258
|
+
*/
|
|
259
|
+
function worktreeName(random = Math.random) {
|
|
260
|
+
const pick = (values) => {
|
|
261
|
+
return values[Math.min(values.length - 1, Math.floor(random() * values.length))] ?? values[0] ?? "copy";
|
|
262
|
+
};
|
|
263
|
+
const suffix = Math.min(65535, Math.floor(random() * 65536)).toString(16).padStart(4, "0");
|
|
264
|
+
return `${pick(ADJECTIVES)}-${pick(NOUNS)}-${suffix}`;
|
|
265
|
+
}
|
|
266
|
+
/** A pool entry name is exactly one path segment, as `git worktree` names it. */
|
|
267
|
+
const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
268
|
+
/**
|
|
269
|
+
* Validate a worktree name received from the browser before it reaches Git.
|
|
270
|
+
* @param value - candidate name.
|
|
271
|
+
* @returns true for one plain path segment that Git also accepts as a branch.
|
|
272
|
+
*/
|
|
273
|
+
function isWorktreeName(value) {
|
|
274
|
+
return NAME_PATTERN.test(value) && !value.endsWith(".lock");
|
|
275
|
+
}
|
|
276
|
+
// src/host/handlers.ts
|
|
277
|
+
/**
|
|
278
|
+
* The plugin's host Remote face: the four verbs the browser half can call,
|
|
279
|
+
* expressed against a live session and the checkouts on disk.
|
|
280
|
+
*
|
|
281
|
+
* This module is the seam the host tests drive directly. Everything below it —
|
|
282
|
+
* Git, the worktree service, the sandbox policy it applies, and session
|
|
283
|
+
* working-directory publication — belongs to the harness and is exercised by
|
|
284
|
+
* its own tests.
|
|
285
|
+
* @module dsh-worktree-switch/host/handlers
|
|
286
|
+
*/
|
|
287
|
+
/** Attempts at a fresh name before a creation failure becomes an error. */
|
|
288
|
+
const CREATE_ATTEMPTS = 3;
|
|
289
|
+
/** A failed verb, carrying the stable code the browser half switches on. */
|
|
290
|
+
var WorktreeToggleError = class extends Error {
|
|
291
|
+
code;
|
|
292
|
+
details;
|
|
293
|
+
/**
|
|
294
|
+
* @param code - stable failure code.
|
|
295
|
+
* @param message - human-readable explanation.
|
|
296
|
+
* @param details - extra machine-readable facts.
|
|
297
|
+
*/
|
|
298
|
+
constructor(code, message, details = {}) {
|
|
299
|
+
super(message);
|
|
300
|
+
this.code = code;
|
|
301
|
+
this.details = details;
|
|
302
|
+
this.name = "WorktreeToggleError";
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
/** Normalize a browser-supplied path before any filesystem work. */
|
|
306
|
+
function absolutePath(value) {
|
|
307
|
+
const trimmed = value.trim();
|
|
308
|
+
if (trimmed === "") throw new WorktreeToggleError("bad-request", "a project path is required");
|
|
309
|
+
return resolve(trimmed);
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* The copy a session already runs in.
|
|
313
|
+
*
|
|
314
|
+
* A linked worktree is recognised from the checkout itself — its `.git` is a
|
|
315
|
+
* file pointing back at the source repository, not a directory — rather than
|
|
316
|
+
* from any configured pool path. The pool belongs to the harness worktree
|
|
317
|
+
* service, so this plugin never needs a second copy of that setting: moving the
|
|
318
|
+
* pool in the service's row config keeps every verb working.
|
|
319
|
+
* @param current - the session's committed working directory.
|
|
320
|
+
* @param repositoryRoot - canonical root of the project's repository.
|
|
321
|
+
* @returns the copy's identity, or null when the directory is not one.
|
|
322
|
+
*/
|
|
323
|
+
async function worktreeAt(current, repositoryRoot) {
|
|
324
|
+
const path = await canonicalPath(current);
|
|
325
|
+
if (path === repositoryRoot) return null;
|
|
326
|
+
const inside = relative(repositoryRoot, path);
|
|
327
|
+
if (inside === "" || inside.startsWith("..") || isAbsolute(inside)) return null;
|
|
328
|
+
const name = basename(path);
|
|
329
|
+
if (!isWorktreeName(name)) return null;
|
|
330
|
+
try {
|
|
331
|
+
if (!(await lstat(`${path}/.git`)).isFile()) return null;
|
|
332
|
+
} catch {
|
|
333
|
+
return null;
|
|
334
|
+
}
|
|
335
|
+
return {
|
|
336
|
+
name,
|
|
337
|
+
path,
|
|
338
|
+
branch: name
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Build the host face.
|
|
343
|
+
* @param ctx - Host context with `agents`, `worktrees`, `workingDirectory`, and `subprocess`.
|
|
344
|
+
* @param options - resolved row config.
|
|
345
|
+
* @returns the four verbs.
|
|
346
|
+
*/
|
|
347
|
+
function createWorktreeToggle(ctx, options) {
|
|
348
|
+
/** One in-flight preparation per session, so a double mount cannot create twice. */
|
|
349
|
+
const pending = /* @__PURE__ */ new Map();
|
|
350
|
+
const sessionOf = async (sessionId, signal) => {
|
|
351
|
+
signal?.throwIfAborted();
|
|
352
|
+
if (sessionId === "") throw new WorktreeToggleError("bad-request", "a session id is required");
|
|
353
|
+
const controller = ctx.get("sessionController");
|
|
354
|
+
if (controller !== void 0) {
|
|
355
|
+
const resolved = await controller.resolveAgent(sessionId);
|
|
356
|
+
if ("error" in resolved) throw new WorktreeToggleError(resolved.error.code, resolved.error.message, { sessionId });
|
|
357
|
+
return resolved.agent;
|
|
358
|
+
}
|
|
359
|
+
const agent = ctx.agents.get(sessionId);
|
|
360
|
+
if (agent === void 0) throw new WorktreeToggleError("session-not-found", `no live agent for session ${sessionId}`, { sessionId });
|
|
361
|
+
return agent;
|
|
362
|
+
};
|
|
363
|
+
/**
|
|
364
|
+
* Resolve the canonical root of the repository that contains a directory.
|
|
365
|
+
* Git reports the spelling of the path it was given; the worktree service
|
|
366
|
+
* publishes canonical paths, so both halves must agree on one spelling.
|
|
367
|
+
* @param directory - absolute directory inside the project.
|
|
368
|
+
* @param signal - caller cancellation.
|
|
369
|
+
* @returns the canonical repository root.
|
|
370
|
+
*/
|
|
371
|
+
const repositoryOf = async (directory, signal) => canonicalPath(await repositoryRoot(ctx, directory, signal));
|
|
372
|
+
const status = async (request, signal) => {
|
|
373
|
+
const agent = await sessionOf(request.sessionId, signal);
|
|
374
|
+
const startDirectory = agent.session.header.cwd ?? ctx.workingDirectory.get(agent.session);
|
|
375
|
+
let root;
|
|
376
|
+
try {
|
|
377
|
+
root = await repositoryOf(startDirectory, signal);
|
|
378
|
+
} catch (error) {
|
|
379
|
+
if (error instanceof GitFailure) return {
|
|
380
|
+
supported: false,
|
|
381
|
+
reason: "not-a-git-repository",
|
|
382
|
+
defaultEnabled: options.defaultEnabled
|
|
383
|
+
};
|
|
384
|
+
throw error;
|
|
385
|
+
}
|
|
386
|
+
const current = ctx.workingDirectory.get(agent.session);
|
|
387
|
+
signal?.throwIfAborted();
|
|
388
|
+
const sourceDirty = await changedFileCount(ctx, root, signal);
|
|
389
|
+
return {
|
|
390
|
+
supported: true,
|
|
391
|
+
repositoryRoot: root,
|
|
392
|
+
sessionWorktree: await worktreeAt(current, root),
|
|
393
|
+
sourceDirty,
|
|
394
|
+
defaultEnabled: options.defaultEnabled
|
|
395
|
+
};
|
|
396
|
+
};
|
|
397
|
+
const prepareOnce = async (request, signal) => {
|
|
398
|
+
const agent = await sessionOf(request.sessionId, signal);
|
|
399
|
+
const current = await status(request, signal);
|
|
400
|
+
if (!current.supported) throw new WorktreeToggleError("not-a-git-repository", "the session project is not inside a Git working tree");
|
|
401
|
+
if (current.sessionWorktree !== null) return {
|
|
402
|
+
state: "existing",
|
|
403
|
+
worktree: current.sessionWorktree,
|
|
404
|
+
repositoryRoot: current.repositoryRoot,
|
|
405
|
+
sourceDirty: current.sourceDirty
|
|
406
|
+
};
|
|
407
|
+
const working = ctx.workingDirectory.get(agent.session);
|
|
408
|
+
const workingProject = await repositoryOf(working, signal);
|
|
409
|
+
if (workingProject !== current.repositoryRoot) throw new WorktreeToggleError("session-moved", `this session now works in ${workingProject}, not in its project ${current.repositoryRoot}`, {
|
|
410
|
+
repositoryRoot: current.repositoryRoot,
|
|
411
|
+
workingProject
|
|
412
|
+
});
|
|
413
|
+
let lastFailure;
|
|
414
|
+
for (let attempt = 0; attempt < CREATE_ATTEMPTS; attempt += 1) {
|
|
415
|
+
signal?.throwIfAborted();
|
|
416
|
+
const name = worktreeName();
|
|
417
|
+
try {
|
|
418
|
+
const created = await ctx.worktrees.create(agent, {
|
|
419
|
+
name,
|
|
420
|
+
from: "HEAD"
|
|
421
|
+
}, signal);
|
|
422
|
+
return {
|
|
423
|
+
state: "created",
|
|
424
|
+
worktree: {
|
|
425
|
+
name: created.branch,
|
|
426
|
+
path: created.path,
|
|
427
|
+
branch: created.branch
|
|
428
|
+
},
|
|
429
|
+
repositoryRoot: created.repositoryRoot,
|
|
430
|
+
sourceDirty: current.sourceDirty
|
|
431
|
+
};
|
|
432
|
+
} catch (error) {
|
|
433
|
+
lastFailure = error;
|
|
434
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
435
|
+
if (!/already exists|worktree branch already exists|worktree path already exists/i.test(message)) throw new WorktreeToggleError("worktree-create-failed", message, { name });
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
throw new WorktreeToggleError("worktree-create-failed", `could not allocate a free worktree name after ${CREATE_ATTEMPTS} attempts`, { cause: lastFailure instanceof Error ? lastFailure.message : String(lastFailure) });
|
|
439
|
+
};
|
|
440
|
+
const prepare = async (request, signal) => {
|
|
441
|
+
const running = pending.get(request.sessionId);
|
|
442
|
+
if (running !== void 0) return running;
|
|
443
|
+
const operation = prepareOnce(request, signal);
|
|
444
|
+
pending.set(request.sessionId, operation);
|
|
445
|
+
try {
|
|
446
|
+
return await operation;
|
|
447
|
+
} finally {
|
|
448
|
+
if (pending.get(request.sessionId) === operation) pending.delete(request.sessionId);
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
const list = async (request, signal) => {
|
|
452
|
+
const directory = absolutePath(request.path);
|
|
453
|
+
let root;
|
|
454
|
+
try {
|
|
455
|
+
root = await repositoryOf(directory, signal);
|
|
456
|
+
} catch (error) {
|
|
457
|
+
if (error instanceof GitFailure) return {
|
|
458
|
+
supported: false,
|
|
459
|
+
reason: "not-a-git-repository"
|
|
460
|
+
};
|
|
461
|
+
throw error;
|
|
462
|
+
}
|
|
463
|
+
const records = await listWorktreeRecords(ctx, root, signal);
|
|
464
|
+
const items = [];
|
|
465
|
+
for (const record of records) {
|
|
466
|
+
signal?.throwIfAborted();
|
|
467
|
+
const path = await canonicalPath(record.path);
|
|
468
|
+
if (path === root) continue;
|
|
469
|
+
const name = basename(path);
|
|
470
|
+
if (!isWorktreeName(name)) continue;
|
|
471
|
+
const branch = record.branch ?? name;
|
|
472
|
+
let createdAt = 0;
|
|
473
|
+
let prunable = true;
|
|
474
|
+
try {
|
|
475
|
+
const info = await stat(path);
|
|
476
|
+
createdAt = Math.trunc(info.birthtimeMs > 0 ? info.birthtimeMs : info.mtimeMs);
|
|
477
|
+
prunable = false;
|
|
478
|
+
} catch {}
|
|
479
|
+
const changedFiles = prunable ? 0 : await changedFileCount(ctx, path, signal);
|
|
480
|
+
items.push({
|
|
481
|
+
name,
|
|
482
|
+
path,
|
|
483
|
+
branch,
|
|
484
|
+
createdAt,
|
|
485
|
+
changedFiles,
|
|
486
|
+
prunable
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
items.sort((left, right) => right.createdAt - left.createdAt || left.name.localeCompare(right.name));
|
|
490
|
+
return {
|
|
491
|
+
supported: true,
|
|
492
|
+
repositoryRoot: root,
|
|
493
|
+
items
|
|
494
|
+
};
|
|
495
|
+
};
|
|
496
|
+
const discard = async (request, signal) => {
|
|
497
|
+
const directory = absolutePath(request.path);
|
|
498
|
+
if (!isWorktreeName(request.name)) throw new WorktreeToggleError("worktree-name-invalid", `not a worktree name: ${request.name}`);
|
|
499
|
+
const root = await repositoryOf(directory, signal);
|
|
500
|
+
const listed = await list({ path: directory }, signal);
|
|
501
|
+
if (!listed.supported) throw new WorktreeToggleError("not-a-git-repository", "the project is not inside a Git working tree");
|
|
502
|
+
const item = listed.items.find((entry) => entry.name === request.name);
|
|
503
|
+
if (item === void 0) throw new WorktreeToggleError("worktree-not-found", `no worktree named ${request.name} in ${root}`, {
|
|
504
|
+
name: request.name,
|
|
505
|
+
repositoryRoot: root
|
|
506
|
+
});
|
|
507
|
+
if (item.changedFiles > 0) throw new WorktreeToggleError("worktree-dirty", `${item.name} has ${item.changedFiles} uncommitted change(s); commit or discard them first`, {
|
|
508
|
+
name: item.name,
|
|
509
|
+
changedFiles: item.changedFiles
|
|
510
|
+
});
|
|
511
|
+
if (item.prunable) await runGit(ctx, root, ["worktree", "prune"], { signal });
|
|
512
|
+
else {
|
|
513
|
+
const removed = await runGit(ctx, root, [
|
|
514
|
+
"worktree",
|
|
515
|
+
"remove",
|
|
516
|
+
item.path
|
|
517
|
+
], {
|
|
518
|
+
signal,
|
|
519
|
+
allowedExitCodes: [0, 128]
|
|
520
|
+
});
|
|
521
|
+
if (removed.exitCode !== 0) throw new WorktreeToggleError("worktree-remove-failed", new GitFailure([
|
|
522
|
+
"worktree",
|
|
523
|
+
"remove",
|
|
524
|
+
item.path
|
|
525
|
+
], removed).message, {
|
|
526
|
+
name: item.name,
|
|
527
|
+
path: item.path
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
const deleted = await runGit(ctx, root, [
|
|
531
|
+
"branch",
|
|
532
|
+
"-D",
|
|
533
|
+
"--",
|
|
534
|
+
item.branch
|
|
535
|
+
], {
|
|
536
|
+
signal,
|
|
537
|
+
allowedExitCodes: [0, 1]
|
|
538
|
+
});
|
|
539
|
+
const branchGone = deleted.exitCode === 1 && /not found/i.test(deleted.stderr);
|
|
540
|
+
if (deleted.exitCode !== 0 && !branchGone) throw new WorktreeToggleError("worktree-remove-failed", new GitFailure([
|
|
541
|
+
"branch",
|
|
542
|
+
"-D",
|
|
543
|
+
item.branch
|
|
544
|
+
], deleted).message, {
|
|
545
|
+
name: item.name,
|
|
546
|
+
branch: item.branch
|
|
547
|
+
});
|
|
548
|
+
return {
|
|
549
|
+
removed: true,
|
|
550
|
+
name: item.name,
|
|
551
|
+
branch: item.branch,
|
|
552
|
+
path: item.path
|
|
553
|
+
};
|
|
554
|
+
};
|
|
555
|
+
return {
|
|
556
|
+
status,
|
|
557
|
+
prepare,
|
|
558
|
+
list,
|
|
559
|
+
discard
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
// src/host/routes.ts
|
|
563
|
+
/** Absolute prefix every route below lives under. */
|
|
564
|
+
const API_PREFIX = "/api/dsh-worktree-switch";
|
|
565
|
+
/** Plugin id; the wire method prefix and the package name are the same string. */
|
|
566
|
+
const PLUGIN_ID = "dsh-worktree-switch";
|
|
567
|
+
/** One route per verb. */
|
|
568
|
+
const ENDPOINTS = [
|
|
569
|
+
"status",
|
|
570
|
+
"prepare",
|
|
571
|
+
"list",
|
|
572
|
+
"discard"
|
|
573
|
+
];
|
|
574
|
+
/** A payload object with the named string field, or the failure to send back. */
|
|
575
|
+
function requiredString(payload, field) {
|
|
576
|
+
const value = payload[field];
|
|
577
|
+
if (typeof value !== "string" || value.trim() === "") return { failure: new WorktreeToggleError("bad-request", `payload.${field} must be a non-empty string`) };
|
|
578
|
+
return { value };
|
|
579
|
+
}
|
|
580
|
+
/**
|
|
581
|
+
* Decode the browser's `client-request` envelope.
|
|
582
|
+
* @param body - parsed JSON body.
|
|
583
|
+
* @returns the request, or null when the envelope is malformed.
|
|
584
|
+
*/
|
|
585
|
+
function readClientRequest(body) {
|
|
586
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) return null;
|
|
587
|
+
const record = body;
|
|
588
|
+
if (record.type !== "client-request") return null;
|
|
589
|
+
const { rpcId, method } = record;
|
|
590
|
+
if (typeof rpcId !== "string" || rpcId === "") return null;
|
|
591
|
+
if (typeof method !== "string" || method === "") return null;
|
|
592
|
+
const payload = record.payload;
|
|
593
|
+
return {
|
|
594
|
+
rpcId,
|
|
595
|
+
method,
|
|
596
|
+
payload: payload !== null && typeof payload === "object" && !Array.isArray(payload) ? payload : {}
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
/** A successful result. */
|
|
600
|
+
function ok(value) {
|
|
601
|
+
return {
|
|
602
|
+
ok: true,
|
|
603
|
+
value
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
/** A failed result carrying the stable code. */
|
|
607
|
+
function fail(code, message, details = {}) {
|
|
608
|
+
return {
|
|
609
|
+
ok: false,
|
|
610
|
+
error: {
|
|
611
|
+
code,
|
|
612
|
+
message,
|
|
613
|
+
details
|
|
614
|
+
}
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Dispatch one decoded verb.
|
|
619
|
+
* @param toggle - the host face.
|
|
620
|
+
* @param endpoint - the verb.
|
|
621
|
+
* @param payload - its decoded payload.
|
|
622
|
+
* @param signal - request cancellation.
|
|
623
|
+
* @returns the wire result.
|
|
624
|
+
*/
|
|
625
|
+
async function dispatch(toggle, endpoint, payload, signal) {
|
|
626
|
+
try {
|
|
627
|
+
if (endpoint === "status") {
|
|
628
|
+
const sessionId = requiredString(payload, "sessionId");
|
|
629
|
+
if ("failure" in sessionId) throw sessionId.failure;
|
|
630
|
+
return ok(await toggle.status({ sessionId: sessionId.value }, signal));
|
|
631
|
+
}
|
|
632
|
+
if (endpoint === "prepare") {
|
|
633
|
+
const sessionId = requiredString(payload, "sessionId");
|
|
634
|
+
if ("failure" in sessionId) throw sessionId.failure;
|
|
635
|
+
return ok(await toggle.prepare({ sessionId: sessionId.value }, signal));
|
|
636
|
+
}
|
|
637
|
+
if (endpoint === "list") {
|
|
638
|
+
const path = requiredString(payload, "path");
|
|
639
|
+
if ("failure" in path) throw path.failure;
|
|
640
|
+
return ok(await toggle.list({ path: path.value }, signal));
|
|
641
|
+
}
|
|
642
|
+
const path = requiredString(payload, "path");
|
|
643
|
+
if ("failure" in path) throw path.failure;
|
|
644
|
+
const name = requiredString(payload, "name");
|
|
645
|
+
if ("failure" in name) throw name.failure;
|
|
646
|
+
return ok(await toggle.discard({
|
|
647
|
+
path: path.value,
|
|
648
|
+
name: name.value
|
|
649
|
+
}, signal));
|
|
650
|
+
} catch (error) {
|
|
651
|
+
if (error instanceof WorktreeToggleError) return fail(error.code, error.message, { ...error.details });
|
|
652
|
+
return fail("internal", error instanceof Error ? error.message : String(error));
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Register one exact route per verb on the shared `/api` channel.
|
|
657
|
+
* @param ctx - Host context carrying `connection`.
|
|
658
|
+
* @param toggle - the host face the routes call.
|
|
659
|
+
*/
|
|
660
|
+
function registerWorktreeRoutes(ctx, toggle) {
|
|
661
|
+
for (const endpoint of ENDPOINTS) ctx.effect(() => ctx.connection.fetch.register({
|
|
662
|
+
path: `${API_PREFIX}/${endpoint}`,
|
|
663
|
+
methods: ["POST"],
|
|
664
|
+
requestBody: "buffered",
|
|
665
|
+
async fetch(request) {
|
|
666
|
+
if (request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") return new Response("content type must be application/json", { status: 415 });
|
|
667
|
+
let body;
|
|
668
|
+
try {
|
|
669
|
+
body = await request.json();
|
|
670
|
+
} catch {
|
|
671
|
+
return new Response("body is not JSON", { status: 400 });
|
|
672
|
+
}
|
|
673
|
+
const message = readClientRequest(body);
|
|
674
|
+
if (message === null) return new Response("invalid client-request message", { status: 400 });
|
|
675
|
+
if (message.method !== `dsh-worktree-switch/${endpoint}`) return Response.json({
|
|
676
|
+
type: "server-response",
|
|
677
|
+
rpcId: message.rpcId,
|
|
678
|
+
result: fail("bad-request", "RPC method does not match endpoint")
|
|
679
|
+
});
|
|
680
|
+
const result = await dispatch(toggle, endpoint, message.payload, request.signal);
|
|
681
|
+
return Response.json({
|
|
682
|
+
type: "server-response",
|
|
683
|
+
rpcId: message.rpcId,
|
|
684
|
+
result
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
}), `${PLUGIN_ID} ${endpoint} route`);
|
|
688
|
+
}
|
|
689
|
+
// src/index.ts
|
|
690
|
+
/** Plugin id: package name, bundle row id, browser module id. */
|
|
691
|
+
const name = "dsh-worktree-switch";
|
|
692
|
+
/**
|
|
693
|
+
* Services this plugin cannot work without.
|
|
694
|
+
*
|
|
695
|
+
* `worktrees` is provided by the row this bundle's patch inserts next to its
|
|
696
|
+
* own, so Cordis holds this plugin until that row has mounted.
|
|
697
|
+
*/
|
|
698
|
+
const inject = [
|
|
699
|
+
"agents",
|
|
700
|
+
"connection",
|
|
701
|
+
"subprocess",
|
|
702
|
+
"worktrees",
|
|
703
|
+
"workingDirectory"
|
|
704
|
+
];
|
|
705
|
+
/** Schemastery schema for {@link Config}. */
|
|
706
|
+
const Config = Schema.object({ defaultEnabled: Schema.boolean().default(true).description("Start a new session in a worktree copy until the user turns the switch off for that project.") });
|
|
707
|
+
/**
|
|
708
|
+
* Mount the host half.
|
|
709
|
+
* @param ctx - Host context.
|
|
710
|
+
* @param config - validated row config.
|
|
711
|
+
*/
|
|
712
|
+
function apply(ctx, config) {
|
|
713
|
+
registerWorktreeRoutes(ctx, createWorktreeToggle(ctx, { defaultEnabled: config.defaultEnabled }));
|
|
714
|
+
}
|
|
715
|
+
export { Config, apply, inject, name };
|
|
716
|
+
|
|
717
|
+
//# sourceMappingURL=index.js.map
|