@laoyuehanni/dsh-git-worktree 0.4.8 → 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/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
- export declare function childProcessExec(file: string, args: readonly string[], options: {
53
- cwd: string;
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; a slow network surfaces through the
197
- * executor's hard timeout as a GitError.
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
- /** Real executor over node:child_process with a hard timeout. */
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 }, (error, stdout, stderr) => {
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
- * The upstream track comes from `%(upstream:track)`, which renders
159
- * `[ahead N, behind M]` (or a bare `[gone]`) directly after the refname —
160
- * `[` is illegal in refnames, so `indexOf('[')` splits name from track
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 trimmed = line.trim();
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; a slow network surfaces through the
446
- * executor's hard timeout as a GitError.
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
- export async function fetchAll(exec, repoRoot) {
451
- await git(exec, repoRoot, ['fetch', '--all', '--prune']);
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/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, handleHead, 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 { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_HEAD, ROUTE_INSPECT, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
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,6 +175,22 @@ export function apply(ctx, config = {}) {
174
175
  }
175
176
  } }), `git-worktree: ${label} route`);
176
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
+ };
177
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. */
@@ -190,9 +207,12 @@ export function apply(ctx, config = {}) {
190
207
  postRoute(ROUTE_BRANCH, 'branch', handleCreateBranch);
191
208
  postRoute(ROUTE_BRANCH_RENAME, 'branch-rename', handleRenameBranch);
192
209
  postRoute(ROUTE_BRANCH_DELETE, 'branch-delete', handleDeleteBranch);
193
- postRoute(ROUTE_FETCH, 'fetch', handleFetch);
210
+ streamPostRoute(ROUTE_FETCH, 'fetch', handleFetch);
194
211
  postRoute(ROUTE_GROUP, 'group', handleGroupWorktrees);
195
- postRoute(ROUTE_UPDATE, 'update', handleUpdate);
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);
196
216
  postRoute(ROUTE_INSPECT, 'inspect', handleInspectWorktree);
197
217
  postRoute(ROUTE_REMOVE, 'remove', handleRemoveWorktree);
198
218
  postRoute(ROUTE_EXISTS, 'exists', handlePathExists);
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Reader for git's progress output, the host half of the live fetch/update
3
+ * feedback.
4
+ *
5
+ * `git fetch <remote> --progress` writes one line per observation to stderr,
6
+ * ended by `\r` while a phase is still counting and by `\n` once it is done:
7
+ *
8
+ * remote: Compressing objects: 50% (101/202)\r
9
+ * Receiving objects: 3% (2147/58680), 708.01 KiB | 128.00 KiB/s\r
10
+ *
11
+ * (`fetch --all` over several remotes would not do: git starts a child per
12
+ * remote that never gets `--progress`, so the caller fetches them one by one
13
+ * and names each through {@link ProgressReader.remote}.)
14
+ *
15
+ * This turns that stream into structured, throttled events and nothing else:
16
+ * no localisation (the line is git's own words, shown as is, like IDEA's task
17
+ * popup) and no arithmetic on the numbers (the percentage git already
18
+ * computed is the percentage shown). Pure, with the clock injectable, so the
19
+ * parsing is testable without a process.
20
+ *
21
+ * @module git-worktree/progress
22
+ */
23
+ /** One progress observation, in the shape of the wire's `progress` event. */
24
+ export interface GitProgress {
25
+ /** The line as git wrote it, minus terminal control sequences. */
26
+ text: string;
27
+ /** The `NN%` git reported, when the line has one. */
28
+ percent?: number;
29
+ /** The remote being fetched, once the caller has named it. */
30
+ remote?: string;
31
+ }
32
+ /** Feed stderr chunks in, receive throttled events out. */
33
+ export interface ProgressReader {
34
+ /** The caller starts fetching another remote: every observation from here
35
+ * on carries its name, and `Fetching <name>` is shown at once. */
36
+ remote(name: string): void;
37
+ /** Add the next stderr chunk (any split; lines may straddle chunks). */
38
+ feed(chunk: string): void;
39
+ /** The stream ended: read a final unterminated line and flush the newest
40
+ * observation the throttle was still holding back. */
41
+ end(): void;
42
+ }
43
+ /**
44
+ * Create a reader.
45
+ * @param emit - receives each observation that passes the throttle.
46
+ * @param options - `intervalMs` throttle window, `now` clock (for tests).
47
+ * @returns the reader.
48
+ */
49
+ export declare function createProgressReader(emit: (progress: GitProgress) => void, options?: {
50
+ intervalMs?: number;
51
+ now?: () => number;
52
+ }): ProgressReader;
53
+ /**
54
+ * Remove git's counted progress lines and the transfer chatter around them from
55
+ * a captured stderr, so an error built from it names the failure instead of
56
+ * burying it under a thousand `Receiving objects: 41% …` redraws.
57
+ * @param text - the full stderr of a `--progress` run.
58
+ * @returns the remaining lines, `\r` redraws unrolled.
59
+ */
60
+ export declare function stripProgress(text: string): string;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Reader for git's progress output, the host half of the live fetch/update
3
+ * feedback.
4
+ *
5
+ * `git fetch <remote> --progress` writes one line per observation to stderr,
6
+ * ended by `\r` while a phase is still counting and by `\n` once it is done:
7
+ *
8
+ * remote: Compressing objects: 50% (101/202)\r
9
+ * Receiving objects: 3% (2147/58680), 708.01 KiB | 128.00 KiB/s\r
10
+ *
11
+ * (`fetch --all` over several remotes would not do: git starts a child per
12
+ * remote that never gets `--progress`, so the caller fetches them one by one
13
+ * and names each through {@link ProgressReader.remote}.)
14
+ *
15
+ * This turns that stream into structured, throttled events and nothing else:
16
+ * no localisation (the line is git's own words, shown as is, like IDEA's task
17
+ * popup) and no arithmetic on the numbers (the percentage git already
18
+ * computed is the percentage shown). Pure, with the clock injectable, so the
19
+ * parsing is testable without a process.
20
+ *
21
+ * @module git-worktree/progress
22
+ */
23
+ /** Terminal control sequences (`ESC [ … K` is how a server asks a terminal to
24
+ * erase the rest of a `remote:` line). Never wanted in a UI string. */
25
+ const CONTROL = /\u001b\[[0-9;?]*[ -/]*[@-~]/g;
26
+ /** A counted phase line: `<phase>: NN% …`, optionally behind `remote: `. The
27
+ * percentage must sit right after the phase name, or a ref name like
28
+ * `feat/50%-done` in an update line (or a porcelain push line) would be read
29
+ * as progress. */
30
+ const PERCENT = /^(?:remote: )?[A-Za-z][A-Za-z ]*:\s+(\d{1,3})%/;
31
+ /** The phase name in front of the first colon (`Receiving objects`). */
32
+ const PHASE = /^(?:remote: )?([^:]+):/;
33
+ /** A counted phase line, the only kind that is noise inside an error text. */
34
+ const COUNTED = /^(?:remote: )?[A-Za-z][A-Za-z ]*:\s+\d{1,3}% \(\d+\/\d+\)/;
35
+ /** The transfer chatter `--progress` also turns on, none of it a reason for a
36
+ * failure: `Enumerating objects: 204, done.`, `Delta compression using up to 20
37
+ * threads` and the `Total 203 (delta 1), reused 0 (delta 0), pack-reused 0 (from
38
+ * 0)` summary. Left in, a rejected push opens with four lines of it and the one
39
+ * `remote:` line that says why sits below the fold of the short error box. */
40
+ const CHATTER = /^(?:remote: )?(?:[A-Za-z][A-Za-z ]*: \d+, done\.|Delta compression using up to \d+ threads|Total \d+ \(delta \d+\), reused \d+ \(delta \d+\)(?:, pack-reused \d+(?: \(from \d+\))?)?)$/;
41
+ /** Fewest milliseconds between two events of the same phase. Git redraws on
42
+ * every percent step, which a card cannot show faster than it can be read. */
43
+ const DEFAULT_INTERVAL_MS = 150;
44
+ /**
45
+ * Create a reader.
46
+ * @param emit - receives each observation that passes the throttle.
47
+ * @param options - `intervalMs` throttle window, `now` clock (for tests).
48
+ * @returns the reader.
49
+ */
50
+ export function createProgressReader(emit, options = {}) {
51
+ const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
52
+ const now = options.now ?? Date.now;
53
+ let buffer = '';
54
+ let remote;
55
+ let phase;
56
+ let lastSentAt = Number.NEGATIVE_INFINITY;
57
+ let held;
58
+ const send = (progress) => {
59
+ held = undefined;
60
+ lastSentAt = now();
61
+ emit(progress);
62
+ };
63
+ const read = (raw) => {
64
+ const line = raw.replace(CONTROL, '').trim();
65
+ if (line === '')
66
+ return;
67
+ const percent = PERCENT.exec(line)?.[1];
68
+ // `From …`, ref updates and `remote: Total …` are not progress.
69
+ if (percent === undefined)
70
+ return;
71
+ const progress = { text: line, percent: Math.min(100, Number(percent)), ...remote === undefined ? {} : { remote } };
72
+ const name = PHASE.exec(line)?.[1];
73
+ // A new phase is always worth showing at once; only repeats are throttled.
74
+ if (name !== phase || now() - lastSentAt >= intervalMs) {
75
+ phase = name;
76
+ send(progress);
77
+ }
78
+ else {
79
+ held = progress;
80
+ }
81
+ };
82
+ const flush = () => {
83
+ if (buffer !== '')
84
+ read(buffer);
85
+ buffer = '';
86
+ if (held !== undefined)
87
+ send(held);
88
+ };
89
+ return {
90
+ remote(name) {
91
+ // What the previous remote still held back is its last word: say it
92
+ // before moving on, still under its own name.
93
+ flush();
94
+ remote = name;
95
+ phase = undefined;
96
+ send({ text: `Fetching ${name}`, remote: name });
97
+ },
98
+ feed(chunk) {
99
+ buffer += chunk;
100
+ const lines = buffer.split(/[\r\n]/);
101
+ buffer = lines.pop() ?? '';
102
+ for (const line of lines)
103
+ read(line);
104
+ },
105
+ end: flush,
106
+ };
107
+ }
108
+ /**
109
+ * Remove git's counted progress lines and the transfer chatter around them from
110
+ * a captured stderr, so an error built from it names the failure instead of
111
+ * burying it under a thousand `Receiving objects: 41% …` redraws.
112
+ * @param text - the full stderr of a `--progress` run.
113
+ * @returns the remaining lines, `\r` redraws unrolled.
114
+ */
115
+ export function stripProgress(text) {
116
+ return text
117
+ .split(/\r?\n/)
118
+ .flatMap(line => line.split('\r'))
119
+ .map(segment => segment.replace(CONTROL, '').trimEnd())
120
+ .filter(segment => segment.trim() !== '' && !COUNTED.test(segment.trim()) && !CHATTER.test(segment.trim()))
121
+ .join('\n');
122
+ }
package/lib/push.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /** Resolve and push explicit refs. Never infer the source from the executor's HEAD. */
2
+ import { type Exec, type LiveRun } from './git.js';
3
+ import type { PushBody, PushPlan, PushPreview, PushPreviewBody, PushResult } from './wire.js';
4
+ export declare function planPush(exec: Exec, cwd: string, branch: string): Promise<PushPlan>;
5
+ /**
6
+ * Opening the push window: the default destination plus a display-only
7
+ * snapshot of what it would push, computed from local refs. One request
8
+ * replaces a plan call followed by a separate local preview, and the two
9
+ * share their reads. The snapshot is a courtesy: a failure to build it
10
+ * leaves the plan intact, and the verified preview reports real problems.
11
+ */
12
+ export declare function openPush(exec: Exec, cwd: string, branch: string): Promise<PushPlan>;
13
+ /** Local snapshots are display-only; the verified preview reads the actual push destination. */
14
+ export declare function previewPush(exec: Exec, cwd: string, body: PushPreviewBody): Promise<PushPreview>;
15
+ /**
16
+ * Push one explicit local branch to an explicit (or default) destination.
17
+ * A plain call is one buffered `git push` under a two-minute cap; a
18
+ * {@link LiveRun} lifts the cap (a big push has no honest upper bound) for
19
+ * git's own progress, a cancel that kills the push, and five minutes of
20
+ * silence — a hung connection or hook — as the only limit.
21
+ * @param exec - executor seam.
22
+ * @param cwd - repository directory.
23
+ * @param body - what to push and where.
24
+ * @param live - optional live output / cancellation of the push itself.
25
+ * @returns the branch, remote and target that were pushed.
26
+ */
27
+ export declare function pushBranch(exec: Exec, cwd: string, body: PushBody, live?: LiveRun): Promise<PushResult>;