@laoyuehanni/dsh-git-worktree 0.4.7 → 0.4.9
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 +4 -2
- package/README.zh.md +4 -2
- package/lib/client.js +1704 -104
- package/lib/git.d.ts +58 -11
- package/lib/git.js +197 -17
- package/lib/head.d.ts +33 -0
- package/lib/head.js +152 -0
- package/lib/index.js +30 -5
- package/lib/progress.d.ts +60 -0
- package/lib/progress.js +122 -0
- package/lib/push.d.ts +27 -0
- package/lib/push.js +215 -0
- package/lib/routes.d.ts +51 -6
- package/lib/routes.js +136 -7
- package/lib/stream.d.ts +33 -0
- package/lib/stream.js +54 -0
- package/lib/wire.d.ts +114 -2
- package/lib/wire.js +18 -2
- package/package.json +12 -10
package/lib/git.d.ts
CHANGED
|
@@ -9,14 +9,30 @@ export interface ExecResult {
|
|
|
9
9
|
code: number;
|
|
10
10
|
stdout: string;
|
|
11
11
|
stderr: string;
|
|
12
|
+
/** The run was stopped by its `signal` (set by a live run only). */
|
|
13
|
+
cancelled?: boolean;
|
|
14
|
+
}
|
|
15
|
+
/** Options of one {@link Exec} call. */
|
|
16
|
+
export interface ExecOptions {
|
|
17
|
+
cwd: string;
|
|
18
|
+
/** Hard cap on the whole run. Absent = 20 s for a plain run, none for a
|
|
19
|
+
* live one (which is bounded by `idleTimeoutMs` and its `signal`). */
|
|
20
|
+
timeoutMs?: number;
|
|
21
|
+
nonInteractive?: boolean;
|
|
22
|
+
/** Live run: git's stdout and stderr text, chunk by chunk as it is written.
|
|
23
|
+
* Any of the three live options moves the run onto a streaming spawn. */
|
|
24
|
+
onOutput?: (chunk: string) => void;
|
|
25
|
+
/** Live run: aborting kills git and its transport children and answers
|
|
26
|
+
* `cancelled`. */
|
|
27
|
+
signal?: AbortSignal;
|
|
28
|
+
/** Live run: kill git after this long without a byte of output. */
|
|
29
|
+
idleTimeoutMs?: number;
|
|
12
30
|
}
|
|
13
31
|
/**
|
|
14
32
|
* Process executor seam. Runs `file args` with cwd set, captures output as
|
|
15
33
|
* UTF-8 text, and never throws — a non-zero exit is a normal result.
|
|
16
34
|
*/
|
|
17
|
-
export type Exec = (file: string, args: readonly string[], options:
|
|
18
|
-
cwd: string;
|
|
19
|
-
}) => Promise<ExecResult>;
|
|
35
|
+
export type Exec = (file: string, args: readonly string[], options: ExecOptions) => Promise<ExecResult>;
|
|
20
36
|
/** Failure of one git invocation: non-zero exit with the stderr text. */
|
|
21
37
|
export declare class GitError extends Error {
|
|
22
38
|
readonly args: readonly string[];
|
|
@@ -48,10 +64,9 @@ export interface RepoFacts {
|
|
|
48
64
|
branches: BranchEntry[];
|
|
49
65
|
worktrees: WorktreeEntry[];
|
|
50
66
|
}
|
|
51
|
-
/** Real executor over node:child_process with a hard timeout
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}): Promise<ExecResult>;
|
|
67
|
+
/** Real executor over node:child_process: a buffered run with a hard timeout,
|
|
68
|
+
* or — when the caller asks for live output / cancellation — a streaming one. */
|
|
69
|
+
export declare function childProcessExec(file: string, args: readonly string[], options: ExecOptions): Promise<ExecResult>;
|
|
55
70
|
/** Directory-existence seam over the parsed worktree registrations. */
|
|
56
71
|
export type DirExists = (path: string) => boolean;
|
|
57
72
|
/** Real existence check. */
|
|
@@ -193,12 +208,43 @@ export declare function deleteBranch(exec: Exec, repoRoot: string, name: string)
|
|
|
193
208
|
* Sync remote-tracking refs: fetch every remote and prune tracking branches
|
|
194
209
|
* the remotes no longer carry (the CLI equivalent of IDEA's "synchronize
|
|
195
210
|
* remote branches"). Pure metadata — the working tree, local branches, and
|
|
196
|
-
* the current checkout are untouched
|
|
197
|
-
* executor's hard timeout
|
|
211
|
+
* the current checkout are untouched. A plain call is bounded by the
|
|
212
|
+
* executor's hard timeout; a {@link LiveRun} lifts that for a transfer the
|
|
213
|
+
* user can watch and cancel.
|
|
198
214
|
* @param exec - executor seam.
|
|
199
215
|
* @param repoRoot - main worktree directory (fetch is repository-wide).
|
|
216
|
+
* @param live - optional live output / cancellation of this run.
|
|
200
217
|
*/
|
|
201
|
-
export declare function fetchAll(exec: Exec, repoRoot: string): Promise<void>;
|
|
218
|
+
export declare function fetchAll(exec: Exec, repoRoot: string, live?: LiveRun): Promise<void>;
|
|
219
|
+
/** A live run's patience with a silent git: long enough for a remote that
|
|
220
|
+
* takes minutes to enumerate a huge repository (or a pre-push hook that runs
|
|
221
|
+
* the test suite), short enough that a stuck connection is not left spinning
|
|
222
|
+
* for good. */
|
|
223
|
+
export declare const LIVE_IDLE_TIMEOUT_MS: number;
|
|
224
|
+
/**
|
|
225
|
+
* The executor options that make one git run live: no whole-run cap, only
|
|
226
|
+
* {@link LIVE_IDLE_TIMEOUT_MS} of silence, plus the caller's output sink and
|
|
227
|
+
* cancellation signal.
|
|
228
|
+
* @param live - the run's live channel.
|
|
229
|
+
* @returns options to spread into an {@link Exec} call (next to `cwd`).
|
|
230
|
+
*/
|
|
231
|
+
export declare function liveExecOptions(live: LiveRun): Pick<ExecOptions, 'idleTimeoutMs' | 'onOutput' | 'signal'>;
|
|
232
|
+
/** Watching and stopping one long git run (a fetch the UI shows progress for). */
|
|
233
|
+
export interface LiveRun {
|
|
234
|
+
/** git's stdout and stderr text as it is written. */
|
|
235
|
+
onOutput?: (chunk: string) => void;
|
|
236
|
+
/** The fetch moves on to this remote; its output follows. */
|
|
237
|
+
onRemote?: (remote: string) => void;
|
|
238
|
+
/** Aborting kills git; the call then throws {@link CancelledError}. */
|
|
239
|
+
signal?: AbortSignal;
|
|
240
|
+
/** The fetch is over and the fast-forward begins — the last step, which
|
|
241
|
+
* is quick and not worth interrupting half way. */
|
|
242
|
+
onMerge?: () => void;
|
|
243
|
+
}
|
|
244
|
+
/** A live run its caller aborted — not a failure anyone needs to hear about. */
|
|
245
|
+
export declare class CancelledError extends Error {
|
|
246
|
+
constructor();
|
|
247
|
+
}
|
|
202
248
|
/** Outcome of {@link updateBranch}: the branch touched and whether it moved. */
|
|
203
249
|
export interface UpdateOutcome {
|
|
204
250
|
branch: string;
|
|
@@ -215,10 +261,11 @@ export interface UpdateOutcome {
|
|
|
215
261
|
* branch ITS worktree holds.
|
|
216
262
|
* @param exec - executor seam.
|
|
217
263
|
* @param cwd - directory whose checked-out branch is updated.
|
|
264
|
+
* @param live - optional live output / cancellation of the fetch step.
|
|
218
265
|
* @returns the branch name and whether HEAD actually moved (false = the
|
|
219
266
|
* upstream already contained it).
|
|
220
267
|
*/
|
|
221
|
-
export declare function updateBranch(exec: Exec, cwd: string): Promise<UpdateOutcome>;
|
|
268
|
+
export declare function updateBranch(exec: Exec, cwd: string, live?: LiveRun): Promise<UpdateOutcome>;
|
|
222
269
|
/** Guard for route inputs: a non-empty absolute directory path. */
|
|
223
270
|
export declare function isAbsoluteDir(value: string): boolean;
|
|
224
271
|
/** Pre-delete facts of one worktree directory, for the remove-confirm dialog. */
|
package/lib/git.js
CHANGED
|
@@ -3,11 +3,12 @@
|
|
|
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 { execFile } from 'node:child_process';
|
|
6
|
+
import { execFile, spawn } from 'node:child_process';
|
|
7
7
|
import { existsSync, readdirSync } from 'node:fs';
|
|
8
8
|
import { appendFile, mkdir, readFile, rm } from 'node:fs/promises';
|
|
9
9
|
import { basename, dirname, isAbsolute, join, normalize, resolve } from 'node:path';
|
|
10
10
|
import { localBranchName } from './normalize.js';
|
|
11
|
+
import { stripProgress } from './progress.js';
|
|
11
12
|
/** Failure of one git invocation: non-zero exit with the stderr text. */
|
|
12
13
|
export class GitError extends Error {
|
|
13
14
|
args;
|
|
@@ -21,17 +22,116 @@ export class GitError extends Error {
|
|
|
21
22
|
this.name = 'GitError';
|
|
22
23
|
}
|
|
23
24
|
}
|
|
24
|
-
/**
|
|
25
|
+
/** Appended to the stderr of a run that was killed for taking too long. */
|
|
26
|
+
const TIMED_OUT = 'Git command timed out; check the remote before retrying.';
|
|
27
|
+
/** Environment of one run: `nonInteractive` stops git (and its credential
|
|
28
|
+
* helper) from waiting on a prompt nobody can answer. */
|
|
29
|
+
function execEnv(options) {
|
|
30
|
+
return options.nonInteractive ? { env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never' } } : {};
|
|
31
|
+
}
|
|
32
|
+
/** Real executor over node:child_process: a buffered run with a hard timeout,
|
|
33
|
+
* or — when the caller asks for live output / cancellation — a streaming one. */
|
|
25
34
|
export function childProcessExec(file, args, options) {
|
|
35
|
+
if (options.onOutput !== undefined || options.signal !== undefined || options.idleTimeoutMs !== undefined) {
|
|
36
|
+
return liveProcessExec(file, args, options);
|
|
37
|
+
}
|
|
26
38
|
return new Promise((resolvePromise) => {
|
|
27
|
-
execFile(file, args, { cwd: options.cwd, encoding: 'utf8', timeout: 20_000, windowsHide: true, maxBuffer: 4 * 1024 * 1024
|
|
39
|
+
execFile(file, args, { cwd: options.cwd, encoding: 'utf8', timeout: options.timeoutMs ?? 20_000, windowsHide: true, maxBuffer: 4 * 1024 * 1024,
|
|
40
|
+
...execEnv(options),
|
|
41
|
+
}, (error, stdout, stderr) => {
|
|
28
42
|
// execFile reports any failure (non-zero exit, spawn error, timeout) as
|
|
29
43
|
// a truthy error; the specific exit code never carries signal here —
|
|
30
44
|
// stderr does — so every failure collapses to 1.
|
|
31
|
-
resolvePromise({ code: error !== null ? 1 : 0, stdout: stdout ?? '', stderr: stderr ?? '' });
|
|
45
|
+
resolvePromise({ code: error !== null ? 1 : 0, stdout: stdout ?? '', stderr: error?.killed ? `${stderr ?? ''}\n${TIMED_OUT}` : stderr || error?.message || '' });
|
|
32
46
|
});
|
|
33
47
|
});
|
|
34
48
|
}
|
|
49
|
+
/** What a live run keeps of each stream: git's progress redraws can run to
|
|
50
|
+
* megabytes, but only the head of stdout and the tail of stderr (where the
|
|
51
|
+
* failure is) are ever read back. */
|
|
52
|
+
const STDOUT_KEEP = 1024 * 1024;
|
|
53
|
+
const STDERR_KEEP = 256 * 1024;
|
|
54
|
+
/**
|
|
55
|
+
* Stop git AND the transport processes it started. `child.kill()` alone
|
|
56
|
+
* leaves them running on Windows (it is TerminateProcess on one pid), so a
|
|
57
|
+
* cancelled fetch would keep downloading in the background; POSIX git cleans
|
|
58
|
+
* up its own children on SIGTERM.
|
|
59
|
+
*/
|
|
60
|
+
function killProcessTree(child) {
|
|
61
|
+
if (child.pid === undefined || child.exitCode !== null)
|
|
62
|
+
return;
|
|
63
|
+
if (process.platform === 'win32') {
|
|
64
|
+
const killer = spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
|
|
65
|
+
killer.on('error', () => { child.kill(); });
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
child.kill('SIGTERM');
|
|
69
|
+
}
|
|
70
|
+
/** Streaming executor: reports output as it arrives and honours a signal. */
|
|
71
|
+
function liveProcessExec(file, args, options) {
|
|
72
|
+
return new Promise((resolvePromise) => {
|
|
73
|
+
if (options.signal?.aborted) {
|
|
74
|
+
resolvePromise({ code: 1, stdout: '', stderr: '', cancelled: true });
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const child = spawn(file, args, { cwd: options.cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], ...execEnv(options) });
|
|
78
|
+
let stdout = '';
|
|
79
|
+
let stderr = '';
|
|
80
|
+
let cancelled = false;
|
|
81
|
+
let timedOut = false;
|
|
82
|
+
let settled = false;
|
|
83
|
+
let idleTimer;
|
|
84
|
+
let hardTimer;
|
|
85
|
+
const result = (code) => ({
|
|
86
|
+
code: cancelled || timedOut ? 1 : code,
|
|
87
|
+
stdout,
|
|
88
|
+
stderr: timedOut ? `${stderr}\n${TIMED_OUT}` : stderr,
|
|
89
|
+
...cancelled ? { cancelled: true } : {},
|
|
90
|
+
});
|
|
91
|
+
const settle = (outcome) => {
|
|
92
|
+
if (settled)
|
|
93
|
+
return;
|
|
94
|
+
settled = true;
|
|
95
|
+
clearTimeout(idleTimer);
|
|
96
|
+
clearTimeout(hardTimer);
|
|
97
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
98
|
+
resolvePromise(outcome);
|
|
99
|
+
};
|
|
100
|
+
const stop = () => { killProcessTree(child); };
|
|
101
|
+
const onAbort = () => { cancelled = true; stop(); };
|
|
102
|
+
const armIdle = () => {
|
|
103
|
+
if (options.idleTimeoutMs === undefined)
|
|
104
|
+
return;
|
|
105
|
+
clearTimeout(idleTimer);
|
|
106
|
+
idleTimer = setTimeout(() => { timedOut = true; stop(); }, options.idleTimeoutMs);
|
|
107
|
+
};
|
|
108
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
109
|
+
if (options.timeoutMs !== undefined)
|
|
110
|
+
hardTimer = setTimeout(() => { timedOut = true; stop(); }, options.timeoutMs);
|
|
111
|
+
armIdle();
|
|
112
|
+
child.stdout.setEncoding('utf8');
|
|
113
|
+
child.stderr.setEncoding('utf8');
|
|
114
|
+
child.stdout.on('data', (chunk) => {
|
|
115
|
+
if (stdout.length < STDOUT_KEEP)
|
|
116
|
+
stdout += chunk;
|
|
117
|
+
armIdle();
|
|
118
|
+
options.onOutput?.(chunk);
|
|
119
|
+
});
|
|
120
|
+
child.stderr.on('data', (chunk) => {
|
|
121
|
+
stderr += chunk;
|
|
122
|
+
if (stderr.length > STDERR_KEEP * 2)
|
|
123
|
+
stderr = stderr.slice(-STDERR_KEEP);
|
|
124
|
+
armIdle();
|
|
125
|
+
options.onOutput?.(chunk);
|
|
126
|
+
});
|
|
127
|
+
child.on('error', (error) => { settle({ code: 1, stdout, stderr: stderr || error.message }); });
|
|
128
|
+
// A killed run settles on exit: a transport grandchild that outlived the
|
|
129
|
+
// kill could hold the pipes open and postpone `close` indefinitely.
|
|
130
|
+
child.on('exit', (code) => { if (cancelled || timedOut)
|
|
131
|
+
settle(result(code ?? 1)); });
|
|
132
|
+
child.on('close', (code) => { settle(result(code ?? 1)); });
|
|
133
|
+
});
|
|
134
|
+
}
|
|
35
135
|
/** Run one git command; a non-zero exit raises {@link GitError} with stderr. */
|
|
36
136
|
async function git(exec, cwd, args) {
|
|
37
137
|
const result = await exec('git', args, { cwd });
|
|
@@ -155,17 +255,16 @@ async function currentBranch(exec, cwd) {
|
|
|
155
255
|
* exists) plus remote-only branches across EVERY remote (`<remote>/HEAD`
|
|
156
256
|
* dropped).
|
|
157
257
|
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
161
|
-
* without a separator. `[gone]` (upstream deleted server-side) carries no
|
|
162
|
-
* counts and is dropped here; the UI renders no marker for it.
|
|
258
|
+
* Track follows the refname (`[` is forbidden in refs); a tab separates
|
|
259
|
+
* the configured upstream. Keeping the upstream and [gone] fact lets the
|
|
260
|
+
* UI distinguish unpublished branches from synchronized and deleted ones.
|
|
163
261
|
*/
|
|
164
262
|
async function listBranches(exec, repoRoot) {
|
|
165
|
-
const localOut = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)%(upstream:track)']);
|
|
263
|
+
const localOut = await git(exec, repoRoot, ['for-each-ref', 'refs/heads', '--format=%(refname:short)%(upstream:track)%09%(upstream:short)']);
|
|
166
264
|
const entries = [];
|
|
167
265
|
for (const line of localOut.split('\n')) {
|
|
168
|
-
const
|
|
266
|
+
const [label = '', upstream = ''] = line.split('\t');
|
|
267
|
+
const trimmed = label.trim();
|
|
169
268
|
if (trimmed === '')
|
|
170
269
|
continue;
|
|
171
270
|
const bracket = trimmed.indexOf('[');
|
|
@@ -176,6 +275,10 @@ async function listBranches(exec, repoRoot) {
|
|
|
176
275
|
const ahead = /\bahead (\d+)/.exec(track);
|
|
177
276
|
const behind = /\bbehind (\d+)/.exec(track);
|
|
178
277
|
const entry = { name, kind: 'local' };
|
|
278
|
+
if (upstream !== '')
|
|
279
|
+
entry.upstream = upstream.trim();
|
|
280
|
+
if (track === '[gone]')
|
|
281
|
+
entry.upstreamGone = true;
|
|
179
282
|
if (ahead !== null)
|
|
180
283
|
entry.ahead = Number(ahead[1]);
|
|
181
284
|
if (behind !== null)
|
|
@@ -442,13 +545,84 @@ export async function deleteBranch(exec, repoRoot, name) {
|
|
|
442
545
|
* Sync remote-tracking refs: fetch every remote and prune tracking branches
|
|
443
546
|
* the remotes no longer carry (the CLI equivalent of IDEA's "synchronize
|
|
444
547
|
* remote branches"). Pure metadata — the working tree, local branches, and
|
|
445
|
-
* the current checkout are untouched
|
|
446
|
-
* executor's hard timeout
|
|
548
|
+
* the current checkout are untouched. A plain call is bounded by the
|
|
549
|
+
* executor's hard timeout; a {@link LiveRun} lifts that for a transfer the
|
|
550
|
+
* user can watch and cancel.
|
|
447
551
|
* @param exec - executor seam.
|
|
448
552
|
* @param repoRoot - main worktree directory (fetch is repository-wide).
|
|
553
|
+
* @param live - optional live output / cancellation of this run.
|
|
554
|
+
*/
|
|
555
|
+
export async function fetchAll(exec, repoRoot, live) {
|
|
556
|
+
if (live === undefined) {
|
|
557
|
+
await git(exec, repoRoot, FETCH_ARGS);
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
// One fetch per remote instead of `--all --progress`: with several remotes
|
|
561
|
+
// git runs a child per remote and never hands it `--progress`, so the
|
|
562
|
+
// counters would silently vanish exactly in the fork setups that have them.
|
|
563
|
+
// Like `--all`, a failing remote does not stop the others.
|
|
564
|
+
let failure;
|
|
565
|
+
for (const remote of await fetchableRemotes(exec, repoRoot)) {
|
|
566
|
+
live.onRemote?.(remote);
|
|
567
|
+
// `--progress` because git only draws its counters on a terminal otherwise.
|
|
568
|
+
const result = await exec('git', ['fetch', remote, '--prune', '--progress'], { cwd: repoRoot, ...liveExecOptions(live) });
|
|
569
|
+
if (result.cancelled)
|
|
570
|
+
throw new CancelledError();
|
|
571
|
+
if (result.code !== 0) {
|
|
572
|
+
failure ??= { code: result.code, messages: [] };
|
|
573
|
+
// git's words without the thousand progress redraws before them.
|
|
574
|
+
failure.messages.push(stripProgress(result.stderr));
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
// The error names the command the user knows, not the per-remote plumbing.
|
|
578
|
+
if (failure !== undefined)
|
|
579
|
+
throw new GitError(FETCH_ARGS, failure.code, failure.messages.join('\n'));
|
|
580
|
+
}
|
|
581
|
+
/** The fetch every plain sync runs. */
|
|
582
|
+
const FETCH_ARGS = ['fetch', '--all', '--prune'];
|
|
583
|
+
/**
|
|
584
|
+
* The remotes `git fetch --all` would visit: all of them except those marked
|
|
585
|
+
* `remote.<name>.skipFetchAll` — a live run walks them itself.
|
|
586
|
+
* @param exec - executor seam.
|
|
587
|
+
* @param repoRoot - main worktree directory.
|
|
588
|
+
* @returns remote names, in git's order.
|
|
449
589
|
*/
|
|
450
|
-
|
|
451
|
-
await git(exec, repoRoot, ['
|
|
590
|
+
async function fetchableRemotes(exec, repoRoot) {
|
|
591
|
+
const names = (await git(exec, repoRoot, ['remote'])).split('\n').map(line => line.trim()).filter(line => line !== '');
|
|
592
|
+
const flags = await gitMaybe(exec, repoRoot, ['config', '--bool', '--get-regexp', '^remote\\..+\\.skipfetchall$']);
|
|
593
|
+
const skipped = new Set();
|
|
594
|
+
for (const line of (flags ?? '').split('\n')) {
|
|
595
|
+
const name = /^remote\.(.+)\.skipfetchall\s+true$/i.exec(line.trim())?.[1];
|
|
596
|
+
if (name !== undefined)
|
|
597
|
+
skipped.add(name);
|
|
598
|
+
}
|
|
599
|
+
return names.filter(name => !skipped.has(name));
|
|
600
|
+
}
|
|
601
|
+
/** A live run's patience with a silent git: long enough for a remote that
|
|
602
|
+
* takes minutes to enumerate a huge repository (or a pre-push hook that runs
|
|
603
|
+
* the test suite), short enough that a stuck connection is not left spinning
|
|
604
|
+
* for good. */
|
|
605
|
+
export const LIVE_IDLE_TIMEOUT_MS = 5 * 60_000;
|
|
606
|
+
/**
|
|
607
|
+
* The executor options that make one git run live: no whole-run cap, only
|
|
608
|
+
* {@link LIVE_IDLE_TIMEOUT_MS} of silence, plus the caller's output sink and
|
|
609
|
+
* cancellation signal.
|
|
610
|
+
* @param live - the run's live channel.
|
|
611
|
+
* @returns options to spread into an {@link Exec} call (next to `cwd`).
|
|
612
|
+
*/
|
|
613
|
+
export function liveExecOptions(live) {
|
|
614
|
+
return {
|
|
615
|
+
idleTimeoutMs: LIVE_IDLE_TIMEOUT_MS,
|
|
616
|
+
...live.onOutput === undefined ? {} : { onOutput: live.onOutput },
|
|
617
|
+
...live.signal === undefined ? {} : { signal: live.signal },
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
/** A live run its caller aborted — not a failure anyone needs to hear about. */
|
|
621
|
+
export class CancelledError extends Error {
|
|
622
|
+
constructor() {
|
|
623
|
+
super('Cancelled');
|
|
624
|
+
this.name = 'CancelledError';
|
|
625
|
+
}
|
|
452
626
|
}
|
|
453
627
|
/**
|
|
454
628
|
* Update the CURRENT checkout: fetch every remote, then fast-forward the
|
|
@@ -461,11 +635,17 @@ export async function fetchAll(exec, repoRoot) {
|
|
|
461
635
|
* branch ITS worktree holds.
|
|
462
636
|
* @param exec - executor seam.
|
|
463
637
|
* @param cwd - directory whose checked-out branch is updated.
|
|
638
|
+
* @param live - optional live output / cancellation of the fetch step.
|
|
464
639
|
* @returns the branch name and whether HEAD actually moved (false = the
|
|
465
640
|
* upstream already contained it).
|
|
466
641
|
*/
|
|
467
|
-
export async function updateBranch(exec, cwd) {
|
|
468
|
-
await fetchAll(exec, cwd);
|
|
642
|
+
export async function updateBranch(exec, cwd, live) {
|
|
643
|
+
await fetchAll(exec, cwd, live);
|
|
644
|
+
// Cancelled in the instant between the fetch ending and now: honour it,
|
|
645
|
+
// never move the user's branch after they said stop.
|
|
646
|
+
if (live?.signal?.aborted)
|
|
647
|
+
throw new CancelledError();
|
|
648
|
+
live?.onMerge?.();
|
|
469
649
|
const before = (await git(exec, cwd, ['rev-parse', 'HEAD'])).trim();
|
|
470
650
|
await git(exec, cwd, ['merge', '--ff-only', '@{u}']);
|
|
471
651
|
const after = (await git(exec, cwd, ['rev-parse', 'HEAD'])).trim();
|
package/lib/head.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checked-out branch by reading HEAD, not by spawning git.
|
|
3
|
+
*
|
|
4
|
+
* The branch label polls this while the page is visible. A full `git status`
|
|
5
|
+
* probe is several processes (and ahead/behind grows with the branch list);
|
|
6
|
+
* `git branch --show-current` is one process whose cost is mostly startup.
|
|
7
|
+
* HEAD is a single short text file, and the host process is already resident.
|
|
8
|
+
*
|
|
9
|
+
* Discovery follows git's own walk: from the directory upward until a `.git`
|
|
10
|
+
* entry. A directory is the git dir (main checkout). A file is a gitfile
|
|
11
|
+
* (`gitdir: <path>`, relative paths resolved against the file's directory) —
|
|
12
|
+
* linked worktrees and submodules. The branch name is whatever that git dir's
|
|
13
|
+
* HEAD says.
|
|
14
|
+
*
|
|
15
|
+
* This does not consult `GIT_DIR`. The full status route still goes through
|
|
16
|
+
* git, and that result is what the label actually renders; a disagreement
|
|
17
|
+
* here only decides whether to ask git again.
|
|
18
|
+
*/
|
|
19
|
+
/** What a directory's checkout looks like to the poll. */
|
|
20
|
+
export type CheckedOutBranch = {
|
|
21
|
+
kind: 'absent';
|
|
22
|
+
}
|
|
23
|
+
/** `.git` was found, but HEAD could not be read completely this tick. */
|
|
24
|
+
| {
|
|
25
|
+
kind: 'unread';
|
|
26
|
+
}
|
|
27
|
+
/** `name` is the branch, or `HEAD` when detached (the label's existing word). */
|
|
28
|
+
| {
|
|
29
|
+
kind: 'branch';
|
|
30
|
+
name: string;
|
|
31
|
+
};
|
|
32
|
+
/** Checked-out branch of `dir`, walking parent directories the way git does. */
|
|
33
|
+
export declare function readCheckedOutBranch(dir: string): Promise<CheckedOutBranch>;
|
package/lib/head.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checked-out branch by reading HEAD, not by spawning git.
|
|
3
|
+
*
|
|
4
|
+
* The branch label polls this while the page is visible. A full `git status`
|
|
5
|
+
* probe is several processes (and ahead/behind grows with the branch list);
|
|
6
|
+
* `git branch --show-current` is one process whose cost is mostly startup.
|
|
7
|
+
* HEAD is a single short text file, and the host process is already resident.
|
|
8
|
+
*
|
|
9
|
+
* Discovery follows git's own walk: from the directory upward until a `.git`
|
|
10
|
+
* entry. A directory is the git dir (main checkout). A file is a gitfile
|
|
11
|
+
* (`gitdir: <path>`, relative paths resolved against the file's directory) —
|
|
12
|
+
* linked worktrees and submodules. The branch name is whatever that git dir's
|
|
13
|
+
* HEAD says.
|
|
14
|
+
*
|
|
15
|
+
* This does not consult `GIT_DIR`. The full status route still goes through
|
|
16
|
+
* git, and that result is what the label actually renders; a disagreement
|
|
17
|
+
* here only decides whether to ask git again.
|
|
18
|
+
*/
|
|
19
|
+
import { open, realpath, stat } from 'node:fs/promises';
|
|
20
|
+
import { dirname, join, resolve } from 'node:path';
|
|
21
|
+
/** HEAD is one short line. A buffer that comes back full is a partial write
|
|
22
|
+
* or not a HEAD file — a prefix must not be treated as a branch name. */
|
|
23
|
+
const HEAD_READ_MAX = 1024;
|
|
24
|
+
/** A gitfile is one path. Same rule as {@link HEAD_READ_MAX}. */
|
|
25
|
+
const GITDIR_READ_MAX = 4096;
|
|
26
|
+
/** Checked-out branch of `dir`, walking parent directories the way git does. */
|
|
27
|
+
export async function readCheckedOutBranch(dir) {
|
|
28
|
+
try {
|
|
29
|
+
return await discover(dir);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
// A permission error or a path that vanishes mid-read is a skipped tick,
|
|
33
|
+
// not a reason to clear the label.
|
|
34
|
+
return { kind: 'unread' };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
async function discover(dir) {
|
|
38
|
+
let cursor;
|
|
39
|
+
try {
|
|
40
|
+
cursor = await realpath(dir);
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
return isEnoent(error) ? { kind: 'absent' } : { kind: 'unread' };
|
|
44
|
+
}
|
|
45
|
+
if (!(await stat(cursor)).isDirectory())
|
|
46
|
+
return { kind: 'absent' };
|
|
47
|
+
for (;;) {
|
|
48
|
+
const gitPath = join(cursor, '.git');
|
|
49
|
+
let info;
|
|
50
|
+
try {
|
|
51
|
+
info = await stat(gitPath);
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (!isEnoent(error))
|
|
55
|
+
return { kind: 'unread' };
|
|
56
|
+
const parent = dirname(cursor);
|
|
57
|
+
if (parent === cursor)
|
|
58
|
+
return { kind: 'absent' };
|
|
59
|
+
cursor = parent;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (info.isDirectory())
|
|
63
|
+
return readHeadFile(join(gitPath, 'HEAD'));
|
|
64
|
+
if (info.isFile())
|
|
65
|
+
return readGitfile(gitPath);
|
|
66
|
+
return { kind: 'unread' };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** Linked worktree / submodule: `.git` is a file pointing at the real git dir. */
|
|
70
|
+
async function readGitfile(gitFile) {
|
|
71
|
+
const text = await readBounded(gitFile, GITDIR_READ_MAX);
|
|
72
|
+
if (typeof text !== 'string')
|
|
73
|
+
return { kind: 'unread' };
|
|
74
|
+
const line = firstLine(text).trim();
|
|
75
|
+
if (!line.startsWith('gitdir:'))
|
|
76
|
+
return { kind: 'unread' };
|
|
77
|
+
const target = line.slice('gitdir:'.length).trim();
|
|
78
|
+
if (target === '')
|
|
79
|
+
return { kind: 'unread' };
|
|
80
|
+
// One hop. A gitfile points at a git dir that holds HEAD, not at another gitfile.
|
|
81
|
+
return readHeadFile(join(resolve(dirname(gitFile), target), 'HEAD'));
|
|
82
|
+
}
|
|
83
|
+
async function readHeadFile(headPath) {
|
|
84
|
+
const text = await readBounded(headPath, HEAD_READ_MAX);
|
|
85
|
+
if (typeof text !== 'string')
|
|
86
|
+
return { kind: 'unread' };
|
|
87
|
+
const name = parseHead(text);
|
|
88
|
+
if (name === undefined)
|
|
89
|
+
return { kind: 'unread' };
|
|
90
|
+
return { kind: 'branch', name };
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Read at most `max` bytes. `'missing'` is ENOENT; `'truncated'` means the
|
|
94
|
+
* file filled the cap (do not parse a prefix). Other IO errors throw.
|
|
95
|
+
*/
|
|
96
|
+
async function readBounded(path, max) {
|
|
97
|
+
let handle;
|
|
98
|
+
try {
|
|
99
|
+
handle = await open(path, 'r');
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (isEnoent(error))
|
|
103
|
+
return 'missing';
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
const buffer = Buffer.alloc(max);
|
|
108
|
+
const { bytesRead } = await handle.read(buffer, 0, max, 0);
|
|
109
|
+
if (bytesRead >= max)
|
|
110
|
+
return 'truncated';
|
|
111
|
+
return buffer.subarray(0, bytesRead).toString('utf8');
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
await handle.close();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The label's word for one HEAD file. `refs/heads/<name>` is that branch.
|
|
119
|
+
* Any other complete form git uses for "not on a branch" (a commit id, or a
|
|
120
|
+
* symbolic ref outside `refs/heads`) is `HEAD`, matching
|
|
121
|
+
* `git branch --show-current` printing nothing. A partial line is `undefined`
|
|
122
|
+
* so the tick is skipped.
|
|
123
|
+
*/
|
|
124
|
+
function parseHead(text) {
|
|
125
|
+
const line = firstLine(text).trim();
|
|
126
|
+
if (line === '')
|
|
127
|
+
return undefined;
|
|
128
|
+
if (line.startsWith('ref:')) {
|
|
129
|
+
const ref = line.slice('ref:'.length).trim();
|
|
130
|
+
const heads = 'refs/heads/';
|
|
131
|
+
if (ref.startsWith(heads)) {
|
|
132
|
+
const name = ref.slice(heads.length);
|
|
133
|
+
if (name === '' || name.endsWith('/') || /\s/.test(name))
|
|
134
|
+
return undefined;
|
|
135
|
+
return name;
|
|
136
|
+
}
|
|
137
|
+
// A finished non-branch symref is `refs/<namespace>/<name>`. A torn write
|
|
138
|
+
// (`ref: refs/hea`) never has that second slash, so it stays unread.
|
|
139
|
+
if (/^refs\/[A-Za-z0-9_-]+\/\S+$/.test(ref))
|
|
140
|
+
return 'HEAD';
|
|
141
|
+
return undefined;
|
|
142
|
+
}
|
|
143
|
+
if (/^[0-9a-f]{40}$/i.test(line) || /^[0-9a-f]{64}$/i.test(line))
|
|
144
|
+
return 'HEAD';
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
function firstLine(text) {
|
|
148
|
+
return text.split(/\r?\n/, 1)[0] ?? '';
|
|
149
|
+
}
|
|
150
|
+
function isEnoent(error) {
|
|
151
|
+
return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';
|
|
152
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -8,9 +8,10 @@
|
|
|
8
8
|
import { homedir } from 'node:os';
|
|
9
9
|
import z from '@deepseek-ai/schemastery';
|
|
10
10
|
import { childProcessExec } from './git.js';
|
|
11
|
-
import { handleCreateBranch, handleCreateWorktree, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleInspectWorktree, handlePathExists, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleStatus, handleSwitch, handleUpdate, handleWorktreesAll, } from './routes.js';
|
|
11
|
+
import { handleCreateBranch, handleCreateWorktree, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGroupWorktrees, handleHead, handleInspectWorktree, handlePathExists, handlePush, handlePushPlan, handlePushPreview, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleStatus, handleSwitch, handleUpdate, handleWorktreesAll, } from './routes.js';
|
|
12
12
|
import { validateRootDir } from './settings.js';
|
|
13
|
-
import {
|
|
13
|
+
import { streamRoute } from './stream.js';
|
|
14
|
+
import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_HEAD, ROUTE_INSPECT, ROUTE_PUSH, ROUTE_PUSH_PLAN, ROUTE_PUSH_PREVIEW, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
|
|
14
15
|
export const name = 'dsh-git-worktree';
|
|
15
16
|
export const inject = [];
|
|
16
17
|
/** Largest accepted request body (bytes) — these payloads are a few strings. */
|
|
@@ -174,20 +175,44 @@ export function apply(ctx, config = {}) {
|
|
|
174
175
|
}
|
|
175
176
|
} }), `git-worktree: ${label} route`);
|
|
176
177
|
};
|
|
177
|
-
|
|
178
|
+
/** Like {@link postRoute}, but the response is an NDJSON stream of live
|
|
179
|
+
* progress events ended by a `done` frame (see ./stream.ts). A body-level
|
|
180
|
+
* failure is still a plain 400 — the stream has not started yet. */
|
|
181
|
+
const streamPostRoute = (path, label, handle) => {
|
|
182
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path, handler: async (req, res) => {
|
|
183
|
+
let body;
|
|
184
|
+
try {
|
|
185
|
+
body = await readJson(req);
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
await streamRoute(res, live => handle(deps(), body, live));
|
|
192
|
+
} }), `git-worktree: ${label} route`);
|
|
193
|
+
};
|
|
194
|
+
// Query-driven reads. Every mutation is a POST body.
|
|
178
195
|
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_STATUS, handler: async (req, res) => {
|
|
179
196
|
/* v8 ignore next -- node:http always sets url on server requests. */
|
|
180
197
|
const query = new URL(req.url ?? '/', 'http://x').searchParams;
|
|
181
198
|
send(res, await handleStatus(deps(), query.get('path') ?? undefined));
|
|
182
199
|
} }), 'git-worktree: status route');
|
|
200
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_HEAD, handler: async (req, res) => {
|
|
201
|
+
/* v8 ignore next -- node:http always sets url on server requests. */
|
|
202
|
+
const query = new URL(req.url ?? '/', 'http://x').searchParams;
|
|
203
|
+
send(res, await handleHead(query.get('path') ?? undefined));
|
|
204
|
+
} }), 'git-worktree: head route');
|
|
183
205
|
postRoute(ROUTE_WORKTREE, 'worktree', handleCreateWorktree);
|
|
184
206
|
postRoute(ROUTE_SWITCH, 'switch', handleSwitch);
|
|
185
207
|
postRoute(ROUTE_BRANCH, 'branch', handleCreateBranch);
|
|
186
208
|
postRoute(ROUTE_BRANCH_RENAME, 'branch-rename', handleRenameBranch);
|
|
187
209
|
postRoute(ROUTE_BRANCH_DELETE, 'branch-delete', handleDeleteBranch);
|
|
188
|
-
|
|
210
|
+
streamPostRoute(ROUTE_FETCH, 'fetch', handleFetch);
|
|
189
211
|
postRoute(ROUTE_GROUP, 'group', handleGroupWorktrees);
|
|
190
|
-
|
|
212
|
+
streamPostRoute(ROUTE_UPDATE, 'update', handleUpdate);
|
|
213
|
+
postRoute(ROUTE_PUSH_PLAN, 'push-plan', handlePushPlan);
|
|
214
|
+
postRoute(ROUTE_PUSH_PREVIEW, 'push-preview', handlePushPreview);
|
|
215
|
+
streamPostRoute(ROUTE_PUSH, 'push', handlePush);
|
|
191
216
|
postRoute(ROUTE_INSPECT, 'inspect', handleInspectWorktree);
|
|
192
217
|
postRoute(ROUTE_REMOVE, 'remove', handleRemoveWorktree);
|
|
193
218
|
postRoute(ROUTE_EXISTS, 'exists', handlePathExists);
|