@laoyuehanni/dsh-git-worktree 0.4.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/LICENSE +21 -0
- package/README.md +82 -0
- package/README.zh.md +82 -0
- package/cordis.patch.yml +5 -0
- package/lib/client.js +1766 -0
- package/lib/client.js.map +1 -0
- package/lib/git.d.ts +111 -0
- package/lib/git.js +275 -0
- package/lib/index.d.ts +42 -0
- package/lib/index.js +157 -0
- package/lib/normalize.d.ts +44 -0
- package/lib/normalize.js +61 -0
- package/lib/routes.d.ts +45 -0
- package/lib/routes.js +152 -0
- package/lib/settings.d.ts +51 -0
- package/lib/settings.js +91 -0
- package/lib/wire.d.ts +81 -0
- package/lib/wire.js +14 -0
- package/package.json +102 -0
package/lib/git.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Git command wrapper for the host half. All git access goes through one
|
|
3
|
+
* injectable `exec` seam (tests substitute it); every method is plain
|
|
4
|
+
* argument assembly plus porcelain parsing, no ambient state.
|
|
5
|
+
*/
|
|
6
|
+
import { execFile } from 'node:child_process';
|
|
7
|
+
import { existsSync } from 'node:fs';
|
|
8
|
+
import { basename, dirname, isAbsolute, normalize, resolve } from 'node:path';
|
|
9
|
+
import { localBranchName } from './normalize.js';
|
|
10
|
+
/** Failure of one git invocation: non-zero exit with the stderr text. */
|
|
11
|
+
export class GitError extends Error {
|
|
12
|
+
args;
|
|
13
|
+
code;
|
|
14
|
+
stderr;
|
|
15
|
+
constructor(args, code, stderr) {
|
|
16
|
+
super(`git ${args.join(' ')} failed (exit ${code}): ${stderr.trim()}`);
|
|
17
|
+
this.args = args;
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.stderr = stderr;
|
|
20
|
+
this.name = 'GitError';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Real executor over node:child_process with a hard timeout. */
|
|
24
|
+
export function childProcessExec(file, args, options) {
|
|
25
|
+
return new Promise((resolvePromise) => {
|
|
26
|
+
execFile(file, args, { cwd: options.cwd, encoding: 'utf8', timeout: 20_000, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
|
|
27
|
+
// execFile reports any failure (non-zero exit, spawn error, timeout) as
|
|
28
|
+
// a truthy error; the specific exit code never carries signal here —
|
|
29
|
+
// stderr does — so every failure collapses to 1.
|
|
30
|
+
resolvePromise({ code: error !== null ? 1 : 0, stdout: stdout ?? '', stderr: stderr ?? '' });
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/** Run one git command; a non-zero exit raises {@link GitError} with stderr. */
|
|
35
|
+
async function git(exec, cwd, args) {
|
|
36
|
+
const result = await exec('git', args, { cwd });
|
|
37
|
+
if (result.code !== 0)
|
|
38
|
+
throw new GitError(args, result.code, result.stderr);
|
|
39
|
+
return result.stdout;
|
|
40
|
+
}
|
|
41
|
+
/** Run one git command, mapping a non-zero exit to undefined instead of throwing. */
|
|
42
|
+
async function gitMaybe(exec, cwd, args) {
|
|
43
|
+
const result = await exec('git', args, { cwd });
|
|
44
|
+
return result.code === 0 ? result.stdout : undefined;
|
|
45
|
+
}
|
|
46
|
+
/** Real existence check. */
|
|
47
|
+
export const fsDirExists = path => existsSync(path);
|
|
48
|
+
/**
|
|
49
|
+
* Resolve a directory to repository facts, or undefined outside any git
|
|
50
|
+
* repository (including the `git` binary missing: ENOENT surfaces as a
|
|
51
|
+
* non-zero exit through the seam).
|
|
52
|
+
* @param exec - executor seam.
|
|
53
|
+
* @param path - absolute directory the workspace reports.
|
|
54
|
+
* @param dirExists - existence seam for stale-registration filtering.
|
|
55
|
+
*/
|
|
56
|
+
export async function probeRepo(exec, path, dirExists = fsDirExists) {
|
|
57
|
+
const top = await gitMaybe(exec, path, ['rev-parse', '--show-toplevel']);
|
|
58
|
+
if (top === undefined)
|
|
59
|
+
return undefined;
|
|
60
|
+
const commonDir = await gitMaybe(exec, path, ['rev-parse', '--git-common-dir']);
|
|
61
|
+
// repoName comes from the shared .git location: a linked worktree's own
|
|
62
|
+
// toplevel would name the branch folder, not the repository. Both git
|
|
63
|
+
// outputs carry forward slashes on Windows — normalize every derived path.
|
|
64
|
+
const repoRoot = normalize(top.trim());
|
|
65
|
+
const gitDir = commonDir !== undefined && commonDir.trim() !== ''
|
|
66
|
+
? normalize(resolve(path, commonDir.trim()))
|
|
67
|
+
: resolve(repoRoot, '.git');
|
|
68
|
+
return {
|
|
69
|
+
repoRoot,
|
|
70
|
+
repoName: basename(dirname(gitDir)),
|
|
71
|
+
currentBranch: await currentBranch(exec, path),
|
|
72
|
+
branches: await listBranches(exec, repoRoot),
|
|
73
|
+
// A stale registration (directory removed behind git's back) must not
|
|
74
|
+
// reach the UI as a real worktree — it would disable branch rows for a
|
|
75
|
+
// folder that no longer exists.
|
|
76
|
+
worktrees: (await listWorktrees(exec, repoRoot)).filter(w => dirExists(w.path)),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** Currently checked-out branch of a directory; `HEAD` when detached or unborn. */
|
|
80
|
+
async function currentBranch(exec, cwd) {
|
|
81
|
+
const name = await gitMaybe(exec, cwd, ['branch', '--show-current']);
|
|
82
|
+
const trimmed = name?.trim() ?? '';
|
|
83
|
+
return trimmed === '' ? 'HEAD' : trimmed;
|
|
84
|
+
}
|
|
85
|
+
/** Local branches plus remote-only branches (first remote only, `<remote>/HEAD` dropped). */
|
|
86
|
+
async function listBranches(exec, repoRoot) {
|
|
87
|
+
const localOut = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)']);
|
|
88
|
+
const locals = localOut.split('\n').map(l => l.trim()).filter(l => l !== '');
|
|
89
|
+
const entries = locals.map(name => ({ name, kind: 'local' }));
|
|
90
|
+
const remoteOut = await gitMaybe(exec, repoRoot, ['for-each-ref', 'refs/remotes', '--format=%(refname:short)']);
|
|
91
|
+
if (remoteOut !== undefined) {
|
|
92
|
+
const seenRemotes = new Set();
|
|
93
|
+
for (const line of remoteOut.split('\n')) {
|
|
94
|
+
const name = line.trim();
|
|
95
|
+
if (name === '')
|
|
96
|
+
continue;
|
|
97
|
+
const localName = localBranchName(name);
|
|
98
|
+
if (localName === 'HEAD' || locals.includes(localName))
|
|
99
|
+
continue;
|
|
100
|
+
const remote = name.slice(0, name.length - localName.length - 1);
|
|
101
|
+
// One remote only: a branch visible on several remotes collapses to the first.
|
|
102
|
+
if (seenRemotes.size === 1 && !seenRemotes.has(remote))
|
|
103
|
+
continue;
|
|
104
|
+
seenRemotes.add(remote);
|
|
105
|
+
entries.push({ name, kind: 'remote' });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return entries;
|
|
109
|
+
}
|
|
110
|
+
/** Parse `git worktree list --porcelain` into entries, main first. */
|
|
111
|
+
async function listWorktrees(exec, repoRoot) {
|
|
112
|
+
const out = await git(exec, repoRoot, ['worktree', 'list', '--porcelain']);
|
|
113
|
+
const entries = [];
|
|
114
|
+
let path;
|
|
115
|
+
let branch;
|
|
116
|
+
let detached = false;
|
|
117
|
+
const flush = () => {
|
|
118
|
+
if (path === undefined)
|
|
119
|
+
return;
|
|
120
|
+
// Porcelain reports forward slashes on Windows; normalize so consumers
|
|
121
|
+
// can compare against join()-built paths.
|
|
122
|
+
entries.push({ path: normalize(path), branch: detached || branch === undefined ? undefined : branch.replace('refs/heads/', ''), main: entries.length === 0 });
|
|
123
|
+
path = undefined;
|
|
124
|
+
branch = undefined;
|
|
125
|
+
detached = false;
|
|
126
|
+
};
|
|
127
|
+
for (const line of out.split('\n')) {
|
|
128
|
+
if (line.startsWith('worktree ')) {
|
|
129
|
+
flush();
|
|
130
|
+
path = line.slice('worktree '.length).trim();
|
|
131
|
+
}
|
|
132
|
+
else if (line.startsWith('branch ')) {
|
|
133
|
+
branch = line.slice('branch '.length).trim();
|
|
134
|
+
}
|
|
135
|
+
else if (line === 'detached') {
|
|
136
|
+
detached = true;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
flush();
|
|
140
|
+
return entries;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Resolve a branch display name against the authoritative branch list of the
|
|
144
|
+
* repository.
|
|
145
|
+
* @returns the local name plus the tracking remote when the display name is
|
|
146
|
+
* remote-only, or undefined when neither shape exists.
|
|
147
|
+
*/
|
|
148
|
+
async function resolveBranch(exec, repoRoot, branch) {
|
|
149
|
+
const localsOut = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)']);
|
|
150
|
+
const locals = localsOut.split('\n').map(l => l.trim()).filter(l => l !== '');
|
|
151
|
+
if (locals.includes(branch))
|
|
152
|
+
return { local: branch, remote: undefined };
|
|
153
|
+
const local = localBranchName(branch);
|
|
154
|
+
if (local !== branch && locals.includes(local))
|
|
155
|
+
return undefined; // the display names a remote, but the local twin exists: use the twin
|
|
156
|
+
const remoteOut = await gitMaybe(exec, repoRoot, ['for-each-ref', 'refs/remotes', `refs/remotes/${branch}`, '--format=%(refname:short)']);
|
|
157
|
+
if (remoteOut !== undefined && remoteOut.trim() !== '')
|
|
158
|
+
return { local, remote: branch.slice(0, branch.length - local.length - 1) };
|
|
159
|
+
return undefined;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Create (or reuse) the worktree for one branch.
|
|
163
|
+
*
|
|
164
|
+
* Idempotence: git allows one worktree per checked-out branch, so an existing
|
|
165
|
+
* worktree already on `branch` (compared by local name) is returned unreused.
|
|
166
|
+
* A local branch gets `git worktree add <path> <name>`; a remote-only branch
|
|
167
|
+
* gets a new local twin via `git worktree add <path> -b <name> <remoteRef>`.
|
|
168
|
+
* @param exec - executor seam.
|
|
169
|
+
* @param repoRoot - main worktree directory.
|
|
170
|
+
* @param branch - branch display name.
|
|
171
|
+
* @param targetPath - absolute directory to create.
|
|
172
|
+
* @returns the worktree path and whether this call created it.
|
|
173
|
+
*/
|
|
174
|
+
export async function addWorktree(exec, repoRoot, branch, targetPath, dirExists = fsDirExists) {
|
|
175
|
+
const resolved = await resolveBranch(exec, repoRoot, branch);
|
|
176
|
+
if (resolved === undefined)
|
|
177
|
+
throw new GitError(['worktree', 'add'], 1, `branch "${branch}" not found`);
|
|
178
|
+
let worktrees = await listWorktrees(exec, repoRoot);
|
|
179
|
+
const existing = worktrees.find(w => w.branch === resolved.local);
|
|
180
|
+
if (existing !== undefined && dirExists(existing.path))
|
|
181
|
+
return { path: existing.path, created: false };
|
|
182
|
+
if (existing !== undefined) {
|
|
183
|
+
// Stale registration: the directory is gone but git's administrative
|
|
184
|
+
// record still claims the branch. Prune (git-side no-op when clean) and
|
|
185
|
+
// re-read before creating, or `worktree add` would refuse the branch.
|
|
186
|
+
await git(exec, repoRoot, ['worktree', 'prune']);
|
|
187
|
+
worktrees = await listWorktrees(exec, repoRoot);
|
|
188
|
+
const afterPrune = worktrees.find(w => w.branch === resolved.local);
|
|
189
|
+
if (afterPrune !== undefined && dirExists(afterPrune.path))
|
|
190
|
+
return { path: afterPrune.path, created: false };
|
|
191
|
+
}
|
|
192
|
+
if (resolved.remote === undefined) {
|
|
193
|
+
await git(exec, repoRoot, ['worktree', 'add', targetPath, resolved.local]);
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
await git(exec, repoRoot, ['worktree', 'add', targetPath, '-b', resolved.local, branch]);
|
|
197
|
+
}
|
|
198
|
+
return { path: targetPath, created: true };
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Plan a new branch name to cut out of `base`: `<base>-wt`, or the first
|
|
202
|
+
* `-wt<N>` suffix not already taken (`main` → `main-wt`; if that exists,
|
|
203
|
+
* `main-wt2`, …). One `for-each-ref` pass decides; the worktree folder
|
|
204
|
+
* name derives from the returned name, so the caller should resolve it
|
|
205
|
+
* BEFORE computing the target path. With `folderTaken` given, a name is
|
|
206
|
+
* only free when its storage folder is free too: a leftover folder of a
|
|
207
|
+
* since-deleted branch would otherwise fail `worktree add` with a bare
|
|
208
|
+
* "already exists" — the suffix walk skips it the same way.
|
|
209
|
+
* @param exec - executor seam.
|
|
210
|
+
* @param repoRoot - main worktree directory.
|
|
211
|
+
* @param base - base branch local name (or `HEAD` when detached).
|
|
212
|
+
* @param folderTaken - storage-folder occupancy probe (branch name → taken).
|
|
213
|
+
* @returns the free cutout branch name.
|
|
214
|
+
*/
|
|
215
|
+
export async function cutoutBranchName(exec, repoRoot, base, folderTaken) {
|
|
216
|
+
const out = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)']);
|
|
217
|
+
const locals = new Set(out.split('\n').map(l => l.trim()).filter(l => l !== ''));
|
|
218
|
+
// `base` is the checked-out branch (`branch --show-current` output), which
|
|
219
|
+
// never carries a remote prefix — pass it through verbatim so a local name
|
|
220
|
+
// containing '/' survives.
|
|
221
|
+
const free = (candidate) => !locals.has(candidate) && !(folderTaken?.(candidate) ?? false);
|
|
222
|
+
const stem = `${base}-wt`;
|
|
223
|
+
if (free(stem))
|
|
224
|
+
return stem;
|
|
225
|
+
for (let i = 2;; i += 1) {
|
|
226
|
+
const candidate = `${stem}${i}`;
|
|
227
|
+
if (free(candidate))
|
|
228
|
+
return candidate;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Create a worktree on a brand-new branch cut out of `base`: the base is
|
|
233
|
+
* checked out by the main worktree (git forbids a second worktree on it),
|
|
234
|
+
* so the new branch is created from it and checked out in the fresh
|
|
235
|
+
* worktree instead.
|
|
236
|
+
* @param exec - executor seam.
|
|
237
|
+
* @param repoRoot - main worktree directory.
|
|
238
|
+
* @param base - base branch local name (`main` or `HEAD`).
|
|
239
|
+
* @param newBranch - the cutout branch name (see {@link cutoutBranchName}).
|
|
240
|
+
* @param targetPath - absolute directory to create.
|
|
241
|
+
*/
|
|
242
|
+
export async function addWorktreeCutout(exec, repoRoot, base, newBranch, targetPath) {
|
|
243
|
+
await git(exec, repoRoot, ['worktree', 'add', targetPath, '-b', newBranch, base]);
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* In-place branch switch of the main checkout. A remote display name relies
|
|
247
|
+
* on git's dwim: `git switch <local>` creates the tracking branch when
|
|
248
|
+
* exactly one remote has it.
|
|
249
|
+
* @param exec - executor seam.
|
|
250
|
+
* @param repoRoot - main worktree directory.
|
|
251
|
+
* @param branch - branch display name.
|
|
252
|
+
* @returns the local branch name now checked out.
|
|
253
|
+
*/
|
|
254
|
+
export async function switchBranch(exec, repoRoot, branch) {
|
|
255
|
+
const resolved = await resolveBranch(exec, repoRoot, branch);
|
|
256
|
+
if (resolved === undefined)
|
|
257
|
+
throw new GitError(['switch'], 1, `branch "${branch}" not found`);
|
|
258
|
+
try {
|
|
259
|
+
await git(exec, repoRoot, ['switch', resolved.local]);
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
// A stale worktree registration claims the branch; prune (no-op on a
|
|
263
|
+
// healthy repo) and retry once — a live worktree still refuses, as it must.
|
|
264
|
+
const stale = error instanceof GitError && error.stderr.includes('already used by worktree');
|
|
265
|
+
if (!stale)
|
|
266
|
+
throw error;
|
|
267
|
+
await git(exec, repoRoot, ['worktree', 'prune']);
|
|
268
|
+
await git(exec, repoRoot, ['switch', resolved.local]);
|
|
269
|
+
}
|
|
270
|
+
return resolved.local;
|
|
271
|
+
}
|
|
272
|
+
/** Guard for route inputs: a non-empty absolute directory path. */
|
|
273
|
+
export function isAbsoluteDir(value) {
|
|
274
|
+
return value.trim() !== '' && isAbsolute(value);
|
|
275
|
+
}
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-git-worktree host half. Owns the worktree storage-root settings section
|
|
3
|
+
* (the `git-worktree` namespace in the dsh settings document, registered
|
|
4
|
+
* through installSettingsSection with the composition entry as its base
|
|
5
|
+
* layer) and — while a webServer service exists — the HTTP routes the browser
|
|
6
|
+
* half fetches. A stored root edit takes effect live: the routes read the
|
|
7
|
+
* section source per request, so no restart and no route re-registration.
|
|
8
|
+
*
|
|
9
|
+
* The legacy ~/.dsh/git-worktree/settings.json value migrates into the
|
|
10
|
+
* namespace once, when a settings service first attaches and the user layer
|
|
11
|
+
* has recorded no choice of its own; the renamed file stays behind as a
|
|
12
|
+
* backup. Headless profiles lose only the routes: nothing else in the plugin
|
|
13
|
+
* has a browser dependency.
|
|
14
|
+
*/
|
|
15
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
16
|
+
import z from '@deepseek-ai/schemastery';
|
|
17
|
+
export declare const name = "dsh-git-worktree";
|
|
18
|
+
export declare const inject: never[];
|
|
19
|
+
export interface Config {
|
|
20
|
+
/** Worktree storage root; defaults to `$DSH_HOME/gitworktree` (`~/.dsh/gitworktree`). */
|
|
21
|
+
rootDir?: string;
|
|
22
|
+
}
|
|
23
|
+
/** Reject stale or misspelled config keys before defaults can hide them. */
|
|
24
|
+
export declare function validateConfig(config: Config): void;
|
|
25
|
+
/** The settings namespace this plugin serves; its browser card spells the same string. */
|
|
26
|
+
export declare const GIT_WORKTREE_NS: import("@deepseek-ai/dsh-settings").SettingsNamespace;
|
|
27
|
+
/** The settings-facing subset of the config: the worktree storage root. */
|
|
28
|
+
export interface SectionConfig {
|
|
29
|
+
/** Worktree storage root; absent/blank selects `$DSH_HOME/gitworktree`. */
|
|
30
|
+
rootDir?: string;
|
|
31
|
+
}
|
|
32
|
+
/** Schema resolving the `git-worktree` settings section. */
|
|
33
|
+
export declare const sectionSchema: z<SectionConfig>;
|
|
34
|
+
/** The section-shaped view of a config: absent keys stay absent (`exactOptionalPropertyTypes`). */
|
|
35
|
+
export declare function sectionOf(config: Config): SectionConfig;
|
|
36
|
+
/**
|
|
37
|
+
* Plugin apply: install the settings section, migrate any legacy stored root
|
|
38
|
+
* into it, then mount routes on any webServer that comes and goes.
|
|
39
|
+
* @param ctx - host cordis context.
|
|
40
|
+
* @param config - the composition entry config (the section's base layer).
|
|
41
|
+
*/
|
|
42
|
+
export declare function apply(ctx: Context, config?: Config): void;
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-git-worktree host half. Owns the worktree storage-root settings section
|
|
3
|
+
* (the `git-worktree` namespace in the dsh settings document, registered
|
|
4
|
+
* through installSettingsSection with the composition entry as its base
|
|
5
|
+
* layer) and — while a webServer service exists — the HTTP routes the browser
|
|
6
|
+
* half fetches. A stored root edit takes effect live: the routes read the
|
|
7
|
+
* section source per request, so no restart and no route re-registration.
|
|
8
|
+
*
|
|
9
|
+
* The legacy ~/.dsh/git-worktree/settings.json value migrates into the
|
|
10
|
+
* namespace once, when a settings service first attaches and the user layer
|
|
11
|
+
* has recorded no choice of its own; the renamed file stays behind as a
|
|
12
|
+
* backup. Headless profiles lose only the routes: nothing else in the plugin
|
|
13
|
+
* has a browser dependency.
|
|
14
|
+
*/
|
|
15
|
+
import { homedir } from 'node:os';
|
|
16
|
+
import { rename } from 'node:fs/promises';
|
|
17
|
+
import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings';
|
|
18
|
+
import z from '@deepseek-ai/schemastery';
|
|
19
|
+
import { childProcessExec } from './git.js';
|
|
20
|
+
import { handleCreateWorktree, handleStatus, handleSwitch, } from './routes.js';
|
|
21
|
+
import { loadLegacySettings, migratedFileOf, planLegacyMigration, settingsFileOf, validateRootDir, } from './settings.js';
|
|
22
|
+
import { ROUTE_STATUS, ROUTE_SWITCH, ROUTE_WORKTREE } from './wire.js';
|
|
23
|
+
export const name = 'dsh-git-worktree';
|
|
24
|
+
export const inject = [];
|
|
25
|
+
/** Largest accepted request body (bytes) — these payloads are a few strings. */
|
|
26
|
+
const BODY_LIMIT = 64 * 1024;
|
|
27
|
+
/** Reject stale or misspelled config keys before defaults can hide them. */
|
|
28
|
+
export function validateConfig(config) {
|
|
29
|
+
const unknown = Object.keys(config).find(key => key !== 'rootDir');
|
|
30
|
+
if (unknown !== undefined) {
|
|
31
|
+
throw new Error(`GitWorktreeConfig: unknown key "${unknown}"`);
|
|
32
|
+
}
|
|
33
|
+
if (config.rootDir !== undefined && (typeof config.rootDir !== 'string' || config.rootDir.length === 0)) {
|
|
34
|
+
throw new Error('GitWorktreeConfig: "rootDir" must be a non-empty string');
|
|
35
|
+
}
|
|
36
|
+
validateRootDir(config.rootDir);
|
|
37
|
+
}
|
|
38
|
+
/** The settings namespace this plugin serves; its browser card spells the same string. */
|
|
39
|
+
export const GIT_WORKTREE_NS = settingsNamespace('git-worktree');
|
|
40
|
+
/** Schema resolving the `git-worktree` settings section. */
|
|
41
|
+
export const sectionSchema = z.object({
|
|
42
|
+
rootDir: z.string(),
|
|
43
|
+
});
|
|
44
|
+
/** The section-shaped view of a config: absent keys stay absent (`exactOptionalPropertyTypes`). */
|
|
45
|
+
export function sectionOf(config) {
|
|
46
|
+
return { ...(config.rootDir === undefined ? {} : { rootDir: config.rootDir }) };
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Plugin apply: install the settings section, migrate any legacy stored root
|
|
50
|
+
* into it, then mount routes on any webServer that comes and goes.
|
|
51
|
+
* @param ctx - host cordis context.
|
|
52
|
+
* @param config - the composition entry config (the section's base layer).
|
|
53
|
+
*/
|
|
54
|
+
export function apply(ctx, config = {}) {
|
|
55
|
+
validateConfig(config);
|
|
56
|
+
// The section source: the composition entry until a settings service
|
|
57
|
+
// attaches, then `setSource` repoints it at the resolved settings scope.
|
|
58
|
+
// A thunk, not a snapshot — reads see the current resolution at call time,
|
|
59
|
+
// so the routes follow a stored edit without re-registering anything.
|
|
60
|
+
let sectionSource = () => sectionOf(config);
|
|
61
|
+
const deps = () => ({
|
|
62
|
+
exec: childProcessExec,
|
|
63
|
+
sectionRootDir: () => sectionSource().rootDir,
|
|
64
|
+
home: () => homedir(),
|
|
65
|
+
envHome: () => process.env.DSH_HOME,
|
|
66
|
+
});
|
|
67
|
+
installSettingsSection(ctx, GIT_WORKTREE_NS, sectionSchema, sectionOf(config), {
|
|
68
|
+
validate: value => validateRootDir(value.rootDir),
|
|
69
|
+
setSource: (source) => { sectionSource = source; },
|
|
70
|
+
onChange: () => {
|
|
71
|
+
// The storage root takes effect live: the routes read the section
|
|
72
|
+
// source per request, so a committed edit needs no action here.
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
// One-shot legacy migration: the pre-0.3 plugin persisted its own
|
|
76
|
+
// ~/.dsh/git-work-tree/settings.json. Registered after installSettingsSection
|
|
77
|
+
// so the namespace is on the ledger by the time this fiber runs; a failure
|
|
78
|
+
// (or a user layer that already chose) leaves both documents exactly as
|
|
79
|
+
// they are, and the next startup retries.
|
|
80
|
+
ctx.inject(['settings'], (sctx) => {
|
|
81
|
+
const file = settingsFileOf(homedir());
|
|
82
|
+
void (async () => {
|
|
83
|
+
const legacy = await loadLegacySettings(file);
|
|
84
|
+
const descriptor = sctx.settings.describe().find(d => d.ns === GIT_WORKTREE_NS);
|
|
85
|
+
if (descriptor === undefined)
|
|
86
|
+
return;
|
|
87
|
+
const user = descriptor.user;
|
|
88
|
+
const userLayer = typeof user === 'object' && user !== null ? user : undefined;
|
|
89
|
+
const planned = planLegacyMigration(legacy, userLayer);
|
|
90
|
+
if (planned === undefined)
|
|
91
|
+
return;
|
|
92
|
+
try {
|
|
93
|
+
await sctx.settings.update(GIT_WORKTREE_NS, { rootDir: planned });
|
|
94
|
+
await rename(file, migratedFileOf(file));
|
|
95
|
+
console.log(`[git-worktree] legacy settings migrated to the settings document (${planned})`);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
console.warn('[git-worktree] legacy settings migration failed:', error instanceof Error ? error.message : String(error));
|
|
99
|
+
}
|
|
100
|
+
})();
|
|
101
|
+
});
|
|
102
|
+
ctx.inject(['webServer'], (webCtx) => {
|
|
103
|
+
/** Send one outcome as JSON; no-store because repo facts are point-in-time. */
|
|
104
|
+
const send = (res, outcome) => {
|
|
105
|
+
res.writeHead(outcome.status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
106
|
+
res.end(JSON.stringify(outcome.body));
|
|
107
|
+
};
|
|
108
|
+
/** Read and JSON-parse one bounded request body. */
|
|
109
|
+
const readJson = (req) => new Promise((resolvePromise, rejectPromise) => {
|
|
110
|
+
const chunks = [];
|
|
111
|
+
let size = 0;
|
|
112
|
+
req.on('data', (chunk) => {
|
|
113
|
+
size += chunk.length;
|
|
114
|
+
if (size > BODY_LIMIT) {
|
|
115
|
+
req.destroy();
|
|
116
|
+
rejectPromise(new Error('request body too large'));
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
chunks.push(chunk);
|
|
120
|
+
});
|
|
121
|
+
req.on('end', () => {
|
|
122
|
+
if (chunks.length === 0) {
|
|
123
|
+
resolvePromise({});
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
try {
|
|
127
|
+
resolvePromise(JSON.parse(Buffer.concat(chunks).toString('utf8')));
|
|
128
|
+
}
|
|
129
|
+
catch (error) {
|
|
130
|
+
rejectPromise(new Error(`invalid JSON body: ${error instanceof Error ? error.message : String(error)}`));
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
req.on('error', rejectPromise);
|
|
134
|
+
});
|
|
135
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_STATUS, handler: async (req, res) => {
|
|
136
|
+
/* v8 ignore next -- node:http always sets url on server requests. */
|
|
137
|
+
const query = new URL(req.url ?? '/', 'http://x').searchParams;
|
|
138
|
+
send(res, await handleStatus(deps(), query.get('path') ?? undefined));
|
|
139
|
+
} }), 'git-worktree: status route');
|
|
140
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_WORKTREE, handler: async (req, res) => {
|
|
141
|
+
try {
|
|
142
|
+
send(res, await handleCreateWorktree(deps(), await readJson(req)));
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
146
|
+
}
|
|
147
|
+
} }), 'git-worktree: worktree route');
|
|
148
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_SWITCH, handler: async (req, res) => {
|
|
149
|
+
try {
|
|
150
|
+
send(res, await handleSwitch(deps(), await readJson(req)));
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
154
|
+
}
|
|
155
|
+
} }), 'git-worktree: switch route');
|
|
156
|
+
});
|
|
157
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure branch/path name normalization for worktree directory placement.
|
|
3
|
+
* Windows-forbidden characters are the governing constraint: a worktree
|
|
4
|
+
* folder name must survive on every platform the host runs on.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Turn a branch display name into a single safe directory segment.
|
|
8
|
+
* `feat/auth-login` → `feat-auth-login`; every Windows-forbidden character
|
|
9
|
+
* (`<>:"|?*`, control chars) and `/` become `-`; runs of separators (`-`,
|
|
10
|
+
* `.`, whitespace — so a `//` or a git-illegal `..` collapses too) merge to
|
|
11
|
+
* one `-`; a single interior `.` survives (`v1.2.3` stays readable); trailing
|
|
12
|
+
* dots and spaces (Windows-forbidden suffixes) are stripped; the result is
|
|
13
|
+
* clamped to 64 characters and never empty or dash-only.
|
|
14
|
+
* @param branch - branch display name (local or `remote/name` form).
|
|
15
|
+
* @returns a safe single path segment.
|
|
16
|
+
*/
|
|
17
|
+
export declare function sanitizeBranchDir(branch: string): string;
|
|
18
|
+
/**
|
|
19
|
+
* Local branch name for a display name: strip the leading `<remote>/` segment
|
|
20
|
+
* when one is present (`origin/feat/x` → `feat/x`). A local branch whose own
|
|
21
|
+
* name contains `/` (like `feat/x`) passes through unchanged — callers that
|
|
22
|
+
* need certainty compare against the authoritative branch list instead.
|
|
23
|
+
* @param branch - branch display name.
|
|
24
|
+
* @returns the candidate local branch name.
|
|
25
|
+
*/
|
|
26
|
+
export declare function localBranchName(branch: string): string;
|
|
27
|
+
/**
|
|
28
|
+
* Split a `<remote>/<name>` display name when it plausibly names a remote
|
|
29
|
+
* branch: the first `/`-separated segment is treated as the remote.
|
|
30
|
+
* @param branch - branch display name.
|
|
31
|
+
* @returns the remote part and the local-twin name, or undefined when the
|
|
32
|
+
* name has no `/` (a local branch or a bare word).
|
|
33
|
+
*/
|
|
34
|
+
export declare function splitRemoteBranch(branch: string): {
|
|
35
|
+
remote: string;
|
|
36
|
+
name: string;
|
|
37
|
+
} | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* Validate a user-configured worktree storage root: an absolute path on any
|
|
40
|
+
* platform (POSIX `/…`, Windows drive `C:\…`/`C:/…`, or UNC `\\…`).
|
|
41
|
+
* @param value - raw settings string.
|
|
42
|
+
* @returns true when the value names an absolute path.
|
|
43
|
+
*/
|
|
44
|
+
export declare function isAbsoluteConfigPath(value: string): boolean;
|
package/lib/normalize.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure branch/path name normalization for worktree directory placement.
|
|
3
|
+
* Windows-forbidden characters are the governing constraint: a worktree
|
|
4
|
+
* folder name must survive on every platform the host runs on.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Turn a branch display name into a single safe directory segment.
|
|
8
|
+
* `feat/auth-login` → `feat-auth-login`; every Windows-forbidden character
|
|
9
|
+
* (`<>:"|?*`, control chars) and `/` become `-`; runs of separators (`-`,
|
|
10
|
+
* `.`, whitespace — so a `//` or a git-illegal `..` collapses too) merge to
|
|
11
|
+
* one `-`; a single interior `.` survives (`v1.2.3` stays readable); trailing
|
|
12
|
+
* dots and spaces (Windows-forbidden suffixes) are stripped; the result is
|
|
13
|
+
* clamped to 64 characters and never empty or dash-only.
|
|
14
|
+
* @param branch - branch display name (local or `remote/name` form).
|
|
15
|
+
* @returns a safe single path segment.
|
|
16
|
+
*/
|
|
17
|
+
export function sanitizeBranchDir(branch) {
|
|
18
|
+
const replaced = branch.replace(/[<>:"/\\|?*\u0000-\u001f\s]/g, '-');
|
|
19
|
+
const merged = replaced.replace(/[-.]{2,}/g, '-');
|
|
20
|
+
const trimmed = merged.replace(/[.\s-]+$/, '');
|
|
21
|
+
const clamped = trimmed.slice(0, 64).replace(/[.\s-]+$/, '');
|
|
22
|
+
return clamped === '' || clamped.replaceAll('-', '') === '' ? 'branch' : clamped;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Local branch name for a display name: strip the leading `<remote>/` segment
|
|
26
|
+
* when one is present (`origin/feat/x` → `feat/x`). A local branch whose own
|
|
27
|
+
* name contains `/` (like `feat/x`) passes through unchanged — callers that
|
|
28
|
+
* need certainty compare against the authoritative branch list instead.
|
|
29
|
+
* @param branch - branch display name.
|
|
30
|
+
* @returns the candidate local branch name.
|
|
31
|
+
*/
|
|
32
|
+
export function localBranchName(branch) {
|
|
33
|
+
const at = branch.indexOf('/');
|
|
34
|
+
return at <= 0 ? branch : branch.slice(at + 1);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Split a `<remote>/<name>` display name when it plausibly names a remote
|
|
38
|
+
* branch: the first `/`-separated segment is treated as the remote.
|
|
39
|
+
* @param branch - branch display name.
|
|
40
|
+
* @returns the remote part and the local-twin name, or undefined when the
|
|
41
|
+
* name has no `/` (a local branch or a bare word).
|
|
42
|
+
*/
|
|
43
|
+
export function splitRemoteBranch(branch) {
|
|
44
|
+
const at = branch.indexOf('/');
|
|
45
|
+
if (at <= 0)
|
|
46
|
+
return undefined;
|
|
47
|
+
return { remote: branch.slice(0, at), name: branch.slice(at + 1) };
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Validate a user-configured worktree storage root: an absolute path on any
|
|
51
|
+
* platform (POSIX `/…`, Windows drive `C:\…`/`C:/…`, or UNC `\\…`).
|
|
52
|
+
* @param value - raw settings string.
|
|
53
|
+
* @returns true when the value names an absolute path.
|
|
54
|
+
*/
|
|
55
|
+
export function isAbsoluteConfigPath(value) {
|
|
56
|
+
if (value === '')
|
|
57
|
+
return false;
|
|
58
|
+
if (value.startsWith('/') || value.startsWith('\\'))
|
|
59
|
+
return true;
|
|
60
|
+
return /^[a-zA-Z]:[\\/]/.test(value);
|
|
61
|
+
}
|
package/lib/routes.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Route logic as pure functions: query/body in, status+body out. The HTTP
|
|
3
|
+
* shell (index.ts) owns req/res mechanics; everything testable lives here.
|
|
4
|
+
*/
|
|
5
|
+
import { type DirExists, type Exec } from './git.js';
|
|
6
|
+
import type { CreateWorktreeResult, RepoStatus, RouteError, SwitchResult } from './wire.js';
|
|
7
|
+
/** Everything the handlers need from the host half. */
|
|
8
|
+
export interface RouteDeps {
|
|
9
|
+
exec: Exec;
|
|
10
|
+
/** The settings-resolved rootDir (absent/blank = the default location). */
|
|
11
|
+
sectionRootDir: () => string | undefined;
|
|
12
|
+
/** User home directory seam. */
|
|
13
|
+
home: () => string;
|
|
14
|
+
/** `$DSH_HOME` environment value seam. */
|
|
15
|
+
envHome: () => string | undefined;
|
|
16
|
+
/** Worktree-registration existence seam (tests substitute). */
|
|
17
|
+
dirExists?: DirExists;
|
|
18
|
+
}
|
|
19
|
+
/** One route outcome: HTTP status plus the JSON body. */
|
|
20
|
+
export interface RouteOutcome {
|
|
21
|
+
status: number;
|
|
22
|
+
body: RepoStatus | CreateWorktreeResult | SwitchResult | RouteError;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* GET /status 鈥?repository facts for one directory.
|
|
26
|
+
* @param deps - host dependencies.
|
|
27
|
+
* @param path - absolute directory the workspace reports.
|
|
28
|
+
*/
|
|
29
|
+
export declare function handleStatus(deps: RouteDeps, path: string | undefined): Promise<RouteOutcome>;
|
|
30
|
+
/**
|
|
31
|
+
* POST /worktree 鈥?create or reuse the worktree for a branch, then report the
|
|
32
|
+
* directory so the client can register it as a workspace. With `cutout: true`
|
|
33
|
+
* the branch is the CURRENT checkout (occupied by the main worktree, so git
|
|
34
|
+
* refuses to add it): a new branch is cut out of it (`<branch>-wt`, first
|
|
35
|
+
* free `-wt<N>` suffix) and isolated in the fresh worktree instead.
|
|
36
|
+
* @param deps - host dependencies.
|
|
37
|
+
* @param body - parsed request body.
|
|
38
|
+
*/
|
|
39
|
+
export declare function handleCreateWorktree(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
40
|
+
/**
|
|
41
|
+
* POST /switch 鈥?in-place branch switch of the main checkout.
|
|
42
|
+
* @param deps - host dependencies.
|
|
43
|
+
* @param body - parsed request body.
|
|
44
|
+
*/
|
|
45
|
+
export declare function handleSwitch(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|