@laoyuehanni/dsh-git-worktree 0.4.0 → 0.4.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 +29 -9
- package/README.zh.md +30 -10
- package/lib/client.js +3456 -305
- package/lib/client.js.map +1 -1
- package/lib/git.d.ts +64 -1
- package/lib/git.js +135 -10
- package/lib/index.d.ts +5 -1
- package/lib/index.js +51 -5
- package/lib/normalize.d.ts +14 -0
- package/lib/normalize.js +32 -0
- package/lib/routes.d.ts +39 -2
- package/lib/routes.js +189 -6
- package/lib/wire.d.ts +78 -1
- package/lib/wire.js +8 -0
- package/package.json +4 -1
package/lib/git.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* injectable `exec` seam (tests substitute it); every method is plain
|
|
4
4
|
* argument assembly plus porcelain parsing, no ambient state.
|
|
5
5
|
*/
|
|
6
|
-
import type { BranchEntry, WorktreeEntry } from './wire.js';
|
|
6
|
+
import type { BranchEntry, WorktreeEntry, WorkspaceGitFacts } from './wire.js';
|
|
7
7
|
/** One process result as the seam reports it. */
|
|
8
8
|
export interface ExecResult {
|
|
9
9
|
code: number;
|
|
@@ -107,5 +107,68 @@ export declare function addWorktreeCutout(exec: Exec, repoRoot: string, base: st
|
|
|
107
107
|
* @returns the local branch name now checked out.
|
|
108
108
|
*/
|
|
109
109
|
export declare function switchBranch(exec: Exec, repoRoot: string, branch: string): Promise<string>;
|
|
110
|
+
/**
|
|
111
|
+
* Create a NEW branch from the current checkout and check it out in place
|
|
112
|
+
* (`git switch -c`): the cut point is whatever the queried directory's HEAD
|
|
113
|
+
* points at, so a detached or unborn checkout cuts from the current commit
|
|
114
|
+
* too. Runs at the queried directory's own toplevel — a session inside a
|
|
115
|
+
* linked worktree creates and checks out within that worktree, never the
|
|
116
|
+
* main checkout (the same semantics as {@link switchBranch}).
|
|
117
|
+
* @param exec - executor seam.
|
|
118
|
+
* @param cwd - directory whose HEAD the branch is cut from (worktree toplevel).
|
|
119
|
+
* @param name - new branch name (git validates; failures raise GitError).
|
|
120
|
+
* @returns the branch name now created and checked out.
|
|
121
|
+
*/
|
|
122
|
+
export declare function createBranch(exec: Exec, cwd: string, name: string): Promise<string>;
|
|
123
|
+
/**
|
|
124
|
+
* Sync remote-tracking refs: fetch every remote and prune tracking branches
|
|
125
|
+
* the remotes no longer carry (the CLI equivalent of IDEA's "synchronize
|
|
126
|
+
* remote branches"). Pure metadata — the working tree, local branches, and
|
|
127
|
+
* the current checkout are untouched; a slow network surfaces through the
|
|
128
|
+
* executor's hard timeout as a GitError.
|
|
129
|
+
* @param exec - executor seam.
|
|
130
|
+
* @param repoRoot - main worktree directory (fetch is repository-wide).
|
|
131
|
+
*/
|
|
132
|
+
export declare function fetchAll(exec: Exec, repoRoot: string): Promise<void>;
|
|
133
|
+
/** Outcome of {@link updateBranch}: the branch touched and whether it moved. */
|
|
134
|
+
export interface UpdateOutcome {
|
|
135
|
+
branch: string;
|
|
136
|
+
updated: boolean;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Update the CURRENT checkout: fetch every remote, then fast-forward the
|
|
140
|
+
* branch checked out by `cwd` to its upstream (`@{u}`) — IDEA's "update
|
|
141
|
+
* selected branch" in its default merge mode. Deliberately `--ff-only`:
|
|
142
|
+
* a diverged local branch refuses rather than silently rebase/merge, and
|
|
143
|
+
* uncommitted working-tree changes are git's own call to reject — the
|
|
144
|
+
* plugin never stashes behind the user's back. Runs at the queried
|
|
145
|
+
* directory's own toplevel, so a linked-worktree session updates the
|
|
146
|
+
* branch ITS worktree holds.
|
|
147
|
+
* @param exec - executor seam.
|
|
148
|
+
* @param cwd - directory whose checked-out branch is updated.
|
|
149
|
+
* @returns the branch name and whether HEAD actually moved (false = the
|
|
150
|
+
* upstream already contained it).
|
|
151
|
+
*/
|
|
152
|
+
export declare function updateBranch(exec: Exec, cwd: string): Promise<UpdateOutcome>;
|
|
110
153
|
/** Guard for route inputs: a non-empty absolute directory path. */
|
|
111
154
|
export declare function isAbsoluteDir(value: string): boolean;
|
|
155
|
+
/**
|
|
156
|
+
* Lightweight git belonging probe for ONE workspace directory: the three
|
|
157
|
+
* facts the sidebar grouping needs and nothing else (no branch list, no
|
|
158
|
+
* worktree list — {@link probeRepo} stays the full-facts path for the chip).
|
|
159
|
+
*
|
|
160
|
+
* `repoRoot` — the grouping key — is derived from `--git-common-dir`, which
|
|
161
|
+
* names the SHARED `<repo>/.git` from every worktree of the repository: the
|
|
162
|
+
* main checkout reports it directly, a linked worktree reports the path back
|
|
163
|
+
* to it. Both therefore resolve to the same repository root and group
|
|
164
|
+
* together, wherever the linked folder physically lives.
|
|
165
|
+
* `main` is decided without `worktree list`: a directory is the main worktree
|
|
166
|
+
* exactly when its own toplevel holds that shared .git.
|
|
167
|
+
* `branch` normalizes detached/unborn HEAD to null HERE so no consumer
|
|
168
|
+
* downstream ever string-compares against git's synthetic `'HEAD'`.
|
|
169
|
+
* @param exec - executor seam.
|
|
170
|
+
* @param path - absolute directory the workspace reports.
|
|
171
|
+
* @returns the facts, or undefined outside any git repository (a missing git
|
|
172
|
+
* binary surfaces the same way — a non-zero exit through the seam).
|
|
173
|
+
*/
|
|
174
|
+
export declare function probeWorkspaceGit(exec: Exec, path: string): Promise<WorkspaceGitFacts | undefined>;
|
package/lib/git.js
CHANGED
|
@@ -82,26 +82,58 @@ async function currentBranch(exec, cwd) {
|
|
|
82
82
|
const trimmed = name?.trim() ?? '';
|
|
83
83
|
return trimmed === '' ? 'HEAD' : trimmed;
|
|
84
84
|
}
|
|
85
|
-
/**
|
|
85
|
+
/**
|
|
86
|
+
* Local branches (each carrying its ahead/behind vs the upstream when one
|
|
87
|
+
* exists) plus remote-only branches across EVERY remote (`<remote>/HEAD`
|
|
88
|
+
* dropped).
|
|
89
|
+
*
|
|
90
|
+
* The upstream track comes from `%(upstream:track)`, which renders
|
|
91
|
+
* `[ahead N, behind M]` (or a bare `[gone]`) directly after the refname —
|
|
92
|
+
* `[` is illegal in refnames, so `indexOf('[')` splits name from track
|
|
93
|
+
* without a separator. `[gone]` (upstream deleted server-side) carries no
|
|
94
|
+
* counts and is dropped here; the UI renders no marker for it.
|
|
95
|
+
*/
|
|
86
96
|
async function listBranches(exec, repoRoot) {
|
|
87
|
-
const localOut = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)']);
|
|
88
|
-
const
|
|
89
|
-
const
|
|
97
|
+
const localOut = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)%(upstream:track)']);
|
|
98
|
+
const entries = [];
|
|
99
|
+
for (const line of localOut.split('\n')) {
|
|
100
|
+
const trimmed = line.trim();
|
|
101
|
+
if (trimmed === '')
|
|
102
|
+
continue;
|
|
103
|
+
const bracket = trimmed.indexOf('[');
|
|
104
|
+
const name = (bracket === -1 ? trimmed : trimmed.slice(0, bracket)).trim();
|
|
105
|
+
if (name === '')
|
|
106
|
+
continue;
|
|
107
|
+
const track = bracket === -1 ? '' : trimmed.slice(bracket);
|
|
108
|
+
const ahead = /\bahead (\d+)/.exec(track);
|
|
109
|
+
const behind = /\bbehind (\d+)/.exec(track);
|
|
110
|
+
const entry = { name, kind: 'local' };
|
|
111
|
+
if (ahead !== null)
|
|
112
|
+
entry.ahead = Number(ahead[1]);
|
|
113
|
+
if (behind !== null)
|
|
114
|
+
entry.behind = Number(behind[1]);
|
|
115
|
+
entries.push(entry);
|
|
116
|
+
}
|
|
90
117
|
const remoteOut = await gitMaybe(exec, repoRoot, ['for-each-ref', 'refs/remotes', '--format=%(refname:short)']);
|
|
91
118
|
if (remoteOut !== undefined) {
|
|
92
|
-
|
|
119
|
+
// Local names as a Set: the twin lookup runs once per remote row, and a
|
|
120
|
+
// linear scan over the assembled list would make the loop quadratic —
|
|
121
|
+
// felt at thousand-branch repos, free to avoid.
|
|
122
|
+
const localNames = new Set(entries.filter(e => e.kind === 'local').map(e => e.name));
|
|
93
123
|
for (const line of remoteOut.split('\n')) {
|
|
94
124
|
const name = line.trim();
|
|
95
125
|
if (name === '')
|
|
96
126
|
continue;
|
|
97
127
|
const localName = localBranchName(name);
|
|
98
|
-
|
|
128
|
+
// A bare ref directly under refs/remotes (shortname without `/`, like
|
|
129
|
+
// a leftover `refs/remotes/origin`) is not a remote branch — git
|
|
130
|
+
// branch -r hides it, the menu must not offer it either.
|
|
131
|
+
if (localName === name)
|
|
99
132
|
continue;
|
|
100
|
-
|
|
101
|
-
//
|
|
102
|
-
if (
|
|
133
|
+
// A remote branch with a local twin stays hidden: the twin is the
|
|
134
|
+
// actionable row, showing both would duplicate it in the menu.
|
|
135
|
+
if (localName === 'HEAD' || localNames.has(localName))
|
|
103
136
|
continue;
|
|
104
|
-
seenRemotes.add(remote);
|
|
105
137
|
entries.push({ name, kind: 'remote' });
|
|
106
138
|
}
|
|
107
139
|
}
|
|
@@ -150,6 +182,11 @@ async function resolveBranch(exec, repoRoot, branch) {
|
|
|
150
182
|
const locals = localsOut.split('\n').map(l => l.trim()).filter(l => l !== '');
|
|
151
183
|
if (locals.includes(branch))
|
|
152
184
|
return { local: branch, remote: undefined };
|
|
185
|
+
// A name without `/` can never name a remote branch — `<remote>/<name>`
|
|
186
|
+
// always carries the slash. This guards the leftover bare `refs/remotes/<x>`
|
|
187
|
+
// ref too: matching it would compute a garbage remote part.
|
|
188
|
+
if (!branch.includes('/'))
|
|
189
|
+
return undefined;
|
|
153
190
|
const local = localBranchName(branch);
|
|
154
191
|
if (local !== branch && locals.includes(local))
|
|
155
192
|
return undefined; // the display names a remote, but the local twin exists: use the twin
|
|
@@ -269,7 +306,95 @@ export async function switchBranch(exec, repoRoot, branch) {
|
|
|
269
306
|
}
|
|
270
307
|
return resolved.local;
|
|
271
308
|
}
|
|
309
|
+
/**
|
|
310
|
+
* Create a NEW branch from the current checkout and check it out in place
|
|
311
|
+
* (`git switch -c`): the cut point is whatever the queried directory's HEAD
|
|
312
|
+
* points at, so a detached or unborn checkout cuts from the current commit
|
|
313
|
+
* too. Runs at the queried directory's own toplevel — a session inside a
|
|
314
|
+
* linked worktree creates and checks out within that worktree, never the
|
|
315
|
+
* main checkout (the same semantics as {@link switchBranch}).
|
|
316
|
+
* @param exec - executor seam.
|
|
317
|
+
* @param cwd - directory whose HEAD the branch is cut from (worktree toplevel).
|
|
318
|
+
* @param name - new branch name (git validates; failures raise GitError).
|
|
319
|
+
* @returns the branch name now created and checked out.
|
|
320
|
+
*/
|
|
321
|
+
export async function createBranch(exec, cwd, name) {
|
|
322
|
+
await git(exec, cwd, ['switch', '-c', name]);
|
|
323
|
+
return name;
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Sync remote-tracking refs: fetch every remote and prune tracking branches
|
|
327
|
+
* the remotes no longer carry (the CLI equivalent of IDEA's "synchronize
|
|
328
|
+
* remote branches"). Pure metadata — the working tree, local branches, and
|
|
329
|
+
* the current checkout are untouched; a slow network surfaces through the
|
|
330
|
+
* executor's hard timeout as a GitError.
|
|
331
|
+
* @param exec - executor seam.
|
|
332
|
+
* @param repoRoot - main worktree directory (fetch is repository-wide).
|
|
333
|
+
*/
|
|
334
|
+
export async function fetchAll(exec, repoRoot) {
|
|
335
|
+
await git(exec, repoRoot, ['fetch', '--all', '--prune']);
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Update the CURRENT checkout: fetch every remote, then fast-forward the
|
|
339
|
+
* branch checked out by `cwd` to its upstream (`@{u}`) — IDEA's "update
|
|
340
|
+
* selected branch" in its default merge mode. Deliberately `--ff-only`:
|
|
341
|
+
* a diverged local branch refuses rather than silently rebase/merge, and
|
|
342
|
+
* uncommitted working-tree changes are git's own call to reject — the
|
|
343
|
+
* plugin never stashes behind the user's back. Runs at the queried
|
|
344
|
+
* directory's own toplevel, so a linked-worktree session updates the
|
|
345
|
+
* branch ITS worktree holds.
|
|
346
|
+
* @param exec - executor seam.
|
|
347
|
+
* @param cwd - directory whose checked-out branch is updated.
|
|
348
|
+
* @returns the branch name and whether HEAD actually moved (false = the
|
|
349
|
+
* upstream already contained it).
|
|
350
|
+
*/
|
|
351
|
+
export async function updateBranch(exec, cwd) {
|
|
352
|
+
await fetchAll(exec, cwd);
|
|
353
|
+
const before = (await git(exec, cwd, ['rev-parse', 'HEAD'])).trim();
|
|
354
|
+
await git(exec, cwd, ['merge', '--ff-only', '@{u}']);
|
|
355
|
+
const after = (await git(exec, cwd, ['rev-parse', 'HEAD'])).trim();
|
|
356
|
+
const branch = (await gitMaybe(exec, cwd, ['branch', '--show-current']))?.trim() ?? '';
|
|
357
|
+
return { branch, updated: before !== after };
|
|
358
|
+
}
|
|
272
359
|
/** Guard for route inputs: a non-empty absolute directory path. */
|
|
273
360
|
export function isAbsoluteDir(value) {
|
|
274
361
|
return value.trim() !== '' && isAbsolute(value);
|
|
275
362
|
}
|
|
363
|
+
/**
|
|
364
|
+
* Lightweight git belonging probe for ONE workspace directory: the three
|
|
365
|
+
* facts the sidebar grouping needs and nothing else (no branch list, no
|
|
366
|
+
* worktree list — {@link probeRepo} stays the full-facts path for the chip).
|
|
367
|
+
*
|
|
368
|
+
* `repoRoot` — the grouping key — is derived from `--git-common-dir`, which
|
|
369
|
+
* names the SHARED `<repo>/.git` from every worktree of the repository: the
|
|
370
|
+
* main checkout reports it directly, a linked worktree reports the path back
|
|
371
|
+
* to it. Both therefore resolve to the same repository root and group
|
|
372
|
+
* together, wherever the linked folder physically lives.
|
|
373
|
+
* `main` is decided without `worktree list`: a directory is the main worktree
|
|
374
|
+
* exactly when its own toplevel holds that shared .git.
|
|
375
|
+
* `branch` normalizes detached/unborn HEAD to null HERE so no consumer
|
|
376
|
+
* downstream ever string-compares against git's synthetic `'HEAD'`.
|
|
377
|
+
* @param exec - executor seam.
|
|
378
|
+
* @param path - absolute directory the workspace reports.
|
|
379
|
+
* @returns the facts, or undefined outside any git repository (a missing git
|
|
380
|
+
* binary surfaces the same way — a non-zero exit through the seam).
|
|
381
|
+
*/
|
|
382
|
+
export async function probeWorkspaceGit(exec, path) {
|
|
383
|
+
const top = await gitMaybe(exec, path, ['rev-parse', '--show-toplevel']);
|
|
384
|
+
if (top === undefined || top.trim() === '')
|
|
385
|
+
return undefined;
|
|
386
|
+
const toplevel = normalize(top.trim());
|
|
387
|
+
const commonDir = await gitMaybe(exec, path, ['rev-parse', '--git-common-dir']);
|
|
388
|
+
if (commonDir === undefined || commonDir.trim() === '')
|
|
389
|
+
return undefined;
|
|
390
|
+
// Git outputs carry forward slashes on Windows — normalize every derived
|
|
391
|
+
// path so consumers can compare against join()-built ones.
|
|
392
|
+
const gitDir = normalize(resolve(path, commonDir.trim()));
|
|
393
|
+
const branchName = (await gitMaybe(exec, path, ['branch', '--show-current']))?.trim() ?? '';
|
|
394
|
+
return {
|
|
395
|
+
repoRoot: dirname(gitDir),
|
|
396
|
+
repoName: basename(dirname(gitDir)),
|
|
397
|
+
branch: branchName === '' ? null : branchName,
|
|
398
|
+
main: normalize(resolve(toplevel, '.git')) === gitDir,
|
|
399
|
+
};
|
|
400
|
+
}
|
package/lib/index.d.ts
CHANGED
|
@@ -19,15 +19,19 @@ export declare const inject: never[];
|
|
|
19
19
|
export interface Config {
|
|
20
20
|
/** Worktree storage root; defaults to `$DSH_HOME/gitworktree` (`~/.dsh/gitworktree`). */
|
|
21
21
|
rootDir?: string;
|
|
22
|
+
/** Sidebar git grouping on/off; absent = on (the composition-entry layer's default). */
|
|
23
|
+
groupSidebar?: boolean;
|
|
22
24
|
}
|
|
23
25
|
/** Reject stale or misspelled config keys before defaults can hide them. */
|
|
24
26
|
export declare function validateConfig(config: Config): void;
|
|
25
27
|
/** The settings namespace this plugin serves; its browser card spells the same string. */
|
|
26
28
|
export declare const GIT_WORKTREE_NS: import("@deepseek-ai/dsh-settings").SettingsNamespace;
|
|
27
|
-
/** The settings-facing subset of the config: the worktree storage root. */
|
|
29
|
+
/** The settings-facing subset of the config: the worktree storage root and the sidebar grouping switch. */
|
|
28
30
|
export interface SectionConfig {
|
|
29
31
|
/** Worktree storage root; absent/blank selects `$DSH_HOME/gitworktree`. */
|
|
30
32
|
rootDir?: string;
|
|
33
|
+
/** Whether the sidebar groups same-repository workspaces; absent = on. */
|
|
34
|
+
groupSidebar?: boolean;
|
|
31
35
|
}
|
|
32
36
|
/** Schema resolving the `git-worktree` settings section. */
|
|
33
37
|
export declare const sectionSchema: z<SectionConfig>;
|
package/lib/index.js
CHANGED
|
@@ -17,22 +17,25 @@ import { rename } from 'node:fs/promises';
|
|
|
17
17
|
import { installSettingsSection, settingsNamespace } from '@deepseek-ai/dsh-settings';
|
|
18
18
|
import z from '@deepseek-ai/schemastery';
|
|
19
19
|
import { childProcessExec } from './git.js';
|
|
20
|
-
import { handleCreateWorktree, handleStatus, handleSwitch, } from './routes.js';
|
|
20
|
+
import { handleCreateBranch, handleCreateWorktree, handleFetch, handleGroupWorktrees, handleStatus, handleSwitch, handleUpdate, } from './routes.js';
|
|
21
21
|
import { loadLegacySettings, migratedFileOf, planLegacyMigration, settingsFileOf, validateRootDir, } from './settings.js';
|
|
22
|
-
import { ROUTE_STATUS, ROUTE_SWITCH, ROUTE_WORKTREE } from './wire.js';
|
|
22
|
+
import { ROUTE_BRANCH, ROUTE_FETCH, ROUTE_GROUP, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE } from './wire.js';
|
|
23
23
|
export const name = 'dsh-git-worktree';
|
|
24
24
|
export const inject = [];
|
|
25
25
|
/** Largest accepted request body (bytes) — these payloads are a few strings. */
|
|
26
26
|
const BODY_LIMIT = 64 * 1024;
|
|
27
27
|
/** Reject stale or misspelled config keys before defaults can hide them. */
|
|
28
28
|
export function validateConfig(config) {
|
|
29
|
-
const unknown = Object.keys(config).find(key => key !== 'rootDir');
|
|
29
|
+
const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar');
|
|
30
30
|
if (unknown !== undefined) {
|
|
31
31
|
throw new Error(`GitWorktreeConfig: unknown key "${unknown}"`);
|
|
32
32
|
}
|
|
33
33
|
if (config.rootDir !== undefined && (typeof config.rootDir !== 'string' || config.rootDir.length === 0)) {
|
|
34
34
|
throw new Error('GitWorktreeConfig: "rootDir" must be a non-empty string');
|
|
35
35
|
}
|
|
36
|
+
if (config.groupSidebar !== undefined && typeof config.groupSidebar !== 'boolean') {
|
|
37
|
+
throw new Error('GitWorktreeConfig: "groupSidebar" must be a boolean');
|
|
38
|
+
}
|
|
36
39
|
validateRootDir(config.rootDir);
|
|
37
40
|
}
|
|
38
41
|
/** The settings namespace this plugin serves; its browser card spells the same string. */
|
|
@@ -40,10 +43,16 @@ export const GIT_WORKTREE_NS = settingsNamespace('git-worktree');
|
|
|
40
43
|
/** Schema resolving the `git-worktree` settings section. */
|
|
41
44
|
export const sectionSchema = z.object({
|
|
42
45
|
rootDir: z.string(),
|
|
46
|
+
groupSidebar: z.boolean(),
|
|
43
47
|
});
|
|
44
48
|
/** The section-shaped view of a config: absent keys stay absent (`exactOptionalPropertyTypes`). */
|
|
45
49
|
export function sectionOf(config) {
|
|
46
|
-
return {
|
|
50
|
+
return {
|
|
51
|
+
...(config.rootDir === undefined ? {} : { rootDir: config.rootDir }),
|
|
52
|
+
// The composition layer spells the shipped default (grouping ON) so a
|
|
53
|
+
// user-layer unset can always fall back to it.
|
|
54
|
+
groupSidebar: config.groupSidebar ?? true,
|
|
55
|
+
};
|
|
47
56
|
}
|
|
48
57
|
/**
|
|
49
58
|
* Plugin apply: install the settings section, migrate any legacy stored root
|
|
@@ -65,7 +74,12 @@ export function apply(ctx, config = {}) {
|
|
|
65
74
|
envHome: () => process.env.DSH_HOME,
|
|
66
75
|
});
|
|
67
76
|
installSettingsSection(ctx, GIT_WORKTREE_NS, sectionSchema, sectionOf(config), {
|
|
68
|
-
validate: value =>
|
|
77
|
+
validate: value => {
|
|
78
|
+
validateRootDir(value.rootDir);
|
|
79
|
+
if (value.groupSidebar !== undefined && typeof value.groupSidebar !== 'boolean') {
|
|
80
|
+
throw new Error('groupSidebar must be a boolean');
|
|
81
|
+
}
|
|
82
|
+
},
|
|
69
83
|
setSource: (source) => { sectionSource = source; },
|
|
70
84
|
onChange: () => {
|
|
71
85
|
// The storage root takes effect live: the routes read the section
|
|
@@ -153,5 +167,37 @@ export function apply(ctx, config = {}) {
|
|
|
153
167
|
send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
154
168
|
}
|
|
155
169
|
} }), 'git-worktree: switch route');
|
|
170
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_BRANCH, handler: async (req, res) => {
|
|
171
|
+
try {
|
|
172
|
+
send(res, await handleCreateBranch(deps(), await readJson(req)));
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
176
|
+
}
|
|
177
|
+
} }), 'git-worktree: branch route');
|
|
178
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_FETCH, handler: async (req, res) => {
|
|
179
|
+
try {
|
|
180
|
+
send(res, await handleFetch(deps(), await readJson(req)));
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
184
|
+
}
|
|
185
|
+
} }), 'git-worktree: fetch route');
|
|
186
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_GROUP, handler: async (req, res) => {
|
|
187
|
+
try {
|
|
188
|
+
send(res, await handleGroupWorktrees(deps(), await readJson(req)));
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
192
|
+
}
|
|
193
|
+
} }), 'git-worktree: group route');
|
|
194
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_UPDATE, handler: async (req, res) => {
|
|
195
|
+
try {
|
|
196
|
+
send(res, await handleUpdate(deps(), await readJson(req)));
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
200
|
+
}
|
|
201
|
+
} }), 'git-worktree: update route');
|
|
156
202
|
});
|
|
157
203
|
}
|
package/lib/normalize.d.ts
CHANGED
|
@@ -42,3 +42,17 @@ export declare function splitRemoteBranch(branch: string): {
|
|
|
42
42
|
* @returns true when the value names an absolute path.
|
|
43
43
|
*/
|
|
44
44
|
export declare function isAbsoluteConfigPath(value: string): boolean;
|
|
45
|
+
/** Why a user-typed NEW branch name is not acceptable yet (null = fine). */
|
|
46
|
+
export type BranchNameIssue = 'empty' | 'leadingDash' | 'illegal';
|
|
47
|
+
/**
|
|
48
|
+
* Pre-flight check of a user-typed NEW branch name against git's ref-name
|
|
49
|
+
* rules (git check-ref-format's reject list, the subset typing can hit):
|
|
50
|
+
* non-empty; no leading `-` (git would parse it as a flag); no space, `~^:?*[\`
|
|
51
|
+
* or control character; no `..`, `@{`, `//`, leading/trailing `/`; no component
|
|
52
|
+
* starting with `.` or ending with `.lock`; no trailing `.`; not the lone `@`.
|
|
53
|
+
* `git switch -c` stays the authority — a miss here surfaces through the
|
|
54
|
+
* error envelope — this only feeds immediate form feedback.
|
|
55
|
+
* @param name - raw draft text (NOT trimmed: a space is a real issue).
|
|
56
|
+
* @returns the issue kind, or null when the name is acceptable.
|
|
57
|
+
*/
|
|
58
|
+
export declare function branchNameIssue(name: string): BranchNameIssue | null;
|
package/lib/normalize.js
CHANGED
|
@@ -59,3 +59,35 @@ export function isAbsoluteConfigPath(value) {
|
|
|
59
59
|
return true;
|
|
60
60
|
return /^[a-zA-Z]:[\\/]/.test(value);
|
|
61
61
|
}
|
|
62
|
+
/**
|
|
63
|
+
* Pre-flight check of a user-typed NEW branch name against git's ref-name
|
|
64
|
+
* rules (git check-ref-format's reject list, the subset typing can hit):
|
|
65
|
+
* non-empty; no leading `-` (git would parse it as a flag); no space, `~^:?*[\`
|
|
66
|
+
* or control character; no `..`, `@{`, `//`, leading/trailing `/`; no component
|
|
67
|
+
* starting with `.` or ending with `.lock`; no trailing `.`; not the lone `@`.
|
|
68
|
+
* `git switch -c` stays the authority — a miss here surfaces through the
|
|
69
|
+
* error envelope — this only feeds immediate form feedback.
|
|
70
|
+
* @param name - raw draft text (NOT trimmed: a space is a real issue).
|
|
71
|
+
* @returns the issue kind, or null when the name is acceptable.
|
|
72
|
+
*/
|
|
73
|
+
export function branchNameIssue(name) {
|
|
74
|
+
if (name.trim() === '')
|
|
75
|
+
return 'empty';
|
|
76
|
+
if (name.startsWith('-'))
|
|
77
|
+
return 'leadingDash';
|
|
78
|
+
if (name === '@')
|
|
79
|
+
return 'illegal';
|
|
80
|
+
if (/[\s~^:?*[\\\u0000-\u001f]/.test(name))
|
|
81
|
+
return 'illegal';
|
|
82
|
+
if (name.includes('..') || name.includes('@{') || name.includes('//'))
|
|
83
|
+
return 'illegal';
|
|
84
|
+
if (name.startsWith('/') || name.endsWith('/'))
|
|
85
|
+
return 'illegal';
|
|
86
|
+
if (name.endsWith('.'))
|
|
87
|
+
return 'illegal';
|
|
88
|
+
if (/(^|\/)\./.test(name))
|
|
89
|
+
return 'illegal';
|
|
90
|
+
if (/(^|\/)[^/]+\.lock($|\/)/.test(name))
|
|
91
|
+
return 'illegal';
|
|
92
|
+
return null;
|
|
93
|
+
}
|
package/lib/routes.d.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* shell (index.ts) owns req/res mechanics; everything testable lives here.
|
|
4
4
|
*/
|
|
5
5
|
import { type DirExists, type Exec } from './git.js';
|
|
6
|
-
import type { CreateWorktreeResult, RepoStatus, RouteError, SwitchResult } from './wire.js';
|
|
6
|
+
import type { CreateBranchResult, CreateWorktreeResult, FetchResult, GroupWorkspacesResult, RepoStatus, RouteError, SwitchResult, UpdateResult } from './wire.js';
|
|
7
7
|
/** Everything the handlers need from the host half. */
|
|
8
8
|
export interface RouteDeps {
|
|
9
9
|
exec: Exec;
|
|
@@ -19,8 +19,18 @@ export interface RouteDeps {
|
|
|
19
19
|
/** One route outcome: HTTP status plus the JSON body. */
|
|
20
20
|
export interface RouteOutcome {
|
|
21
21
|
status: number;
|
|
22
|
-
body: RepoStatus | CreateWorktreeResult | SwitchResult | RouteError;
|
|
22
|
+
body: RepoStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | RouteError;
|
|
23
23
|
}
|
|
24
|
+
/**
|
|
25
|
+
* POST /group — git belonging facts for a batch of workspace directories.
|
|
26
|
+
* Deduplicates, validates, probes in bounded batches, and answers 200 with
|
|
27
|
+
* per-path facts (null for non-repositories); a repository-wide git failure
|
|
28
|
+
* is a per-path null, never a 500 — the sidebar must degrade to flat, not
|
|
29
|
+
* error out.
|
|
30
|
+
* @param deps - host dependencies.
|
|
31
|
+
* @param body - parsed request body: `{ paths }`.
|
|
32
|
+
*/
|
|
33
|
+
export declare function handleGroupWorktrees(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
24
34
|
/**
|
|
25
35
|
* GET /status 鈥?repository facts for one directory.
|
|
26
36
|
* @param deps - host dependencies.
|
|
@@ -43,3 +53,30 @@ export declare function handleCreateWorktree(deps: RouteDeps, body: unknown): Pr
|
|
|
43
53
|
* @param body - parsed request body.
|
|
44
54
|
*/
|
|
45
55
|
export declare function handleSwitch(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
56
|
+
/**
|
|
57
|
+
* POST /branch 鈥?create a NEW branch from the queried directory's current
|
|
58
|
+
* checkout (whatever its HEAD points at, detached included) and check it out
|
|
59
|
+
* in place. Git validates the name; the client pre-flights the same rules
|
|
60
|
+
* and only sends names it already accepts.
|
|
61
|
+
* @param deps - host dependencies.
|
|
62
|
+
* @param body - parsed request body.
|
|
63
|
+
*/
|
|
64
|
+
export declare function handleCreateBranch(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
65
|
+
/**
|
|
66
|
+
* POST /fetch 鈥?sync remote-tracking refs for the repository: fetch every
|
|
67
|
+
* remote and prune tracking branches the remotes no longer carry. Pure
|
|
68
|
+
* metadata — the working tree and the current checkout are untouched; the
|
|
69
|
+
* client refetches /status afterwards for the fresh branch list.
|
|
70
|
+
* @param deps - host dependencies.
|
|
71
|
+
* @param body - parsed request body.
|
|
72
|
+
*/
|
|
73
|
+
export declare function handleFetch(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
74
|
+
/**
|
|
75
|
+
* POST /update 鈥?update the CURRENT checkout: fetch every remote, then
|
|
76
|
+
* fast-forward the branch checked out by the queried directory to its
|
|
77
|
+
* upstream. Divergence, a missing upstream, and conflicting working-tree
|
|
78
|
+
* changes all surface as 400 envelopes carrying git's own explanation.
|
|
79
|
+
* @param deps - host dependencies.
|
|
80
|
+
* @param body - parsed request body.
|
|
81
|
+
*/
|
|
82
|
+
export declare function handleUpdate(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|