@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/README.md +4 -2
- package/README.zh.md +4 -2
- package/lib/client.js +1517 -102
- package/lib/git.d.ts +58 -11
- package/lib/git.js +197 -17
- package/lib/index.js +24 -4
- 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 +45 -6
- package/lib/routes.js +120 -7
- package/lib/stream.d.ts +33 -0
- package/lib/stream.js +54 -0
- package/lib/wire.d.ts +95 -2
- package/lib/wire.js +15 -2
- package/package.json +12 -10
package/lib/push.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/** Resolve and push explicit refs. Never infer the source from the executor's HEAD. */
|
|
2
|
+
import { CancelledError, GitError, liveExecOptions } from './git.js';
|
|
3
|
+
import { stripProgress } from './progress.js';
|
|
4
|
+
async function run(exec, cwd, args) {
|
|
5
|
+
const result = await exec('git', args, { cwd });
|
|
6
|
+
if (result.code !== 0)
|
|
7
|
+
throw new GitError(args, result.code, result.stderr);
|
|
8
|
+
return result.stdout.trim();
|
|
9
|
+
}
|
|
10
|
+
/** Only the two keys that can name a push remote: one process instead of one per key. */
|
|
11
|
+
const PUSH_REMOTE_KEYS = '^(remote\\.pushdefault|branch\\..*\\.pushremote)$';
|
|
12
|
+
/** `branch.<name>.pushRemote`, else `remote.pushDefault`, else '' (neither configured). */
|
|
13
|
+
async function configuredPushRemote(exec, cwd, branch) {
|
|
14
|
+
const args = ['config', '--get-regexp', PUSH_REMOTE_KEYS];
|
|
15
|
+
const result = await exec('git', args, { cwd });
|
|
16
|
+
if (result.code === 1)
|
|
17
|
+
return ''; // no match, not a failure
|
|
18
|
+
if (result.code !== 0)
|
|
19
|
+
throw new GitError(args, result.code, result.stderr);
|
|
20
|
+
const wanted = `branch.${branch}.pushremote`; // git lowercases section and variable, never the branch
|
|
21
|
+
let pushDefault = '';
|
|
22
|
+
let branchRemote = '';
|
|
23
|
+
for (const line of result.stdout.split('\n')) {
|
|
24
|
+
const space = line.indexOf(' ');
|
|
25
|
+
if (space === -1)
|
|
26
|
+
continue;
|
|
27
|
+
const key = line.slice(0, space);
|
|
28
|
+
// Later entries win, as in git's own resolution.
|
|
29
|
+
if (key === 'remote.pushdefault')
|
|
30
|
+
pushDefault = line.slice(space + 1).trim();
|
|
31
|
+
else if (key === wanted)
|
|
32
|
+
branchRemote = line.slice(space + 1).trim();
|
|
33
|
+
}
|
|
34
|
+
return branchRemote || pushDefault;
|
|
35
|
+
}
|
|
36
|
+
async function pushUrl(exec, cwd, remote) {
|
|
37
|
+
const result = await exec('git', ['remote', 'get-url', '--push', '--all', '--', remote], { cwd });
|
|
38
|
+
// Doubles as the "is this remote configured?" check, saving a `git remote` process.
|
|
39
|
+
if (result.code !== 0)
|
|
40
|
+
throw new Error(`Remote "${remote}" is not configured. ${result.stderr.trim()}`.trim());
|
|
41
|
+
const urls = result.stdout.trim().split('\n').filter(Boolean);
|
|
42
|
+
if (urls.length !== 1)
|
|
43
|
+
throw new Error(`Remote "${remote}" needs exactly one push URL for a branch push preview.`);
|
|
44
|
+
return urls[0];
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Everything the plan needs comes from three independent reads (the exact
|
|
48
|
+
* ref with its tracking facts, the remote list, the push-remote keys), run
|
|
49
|
+
* together rather than one process after another.
|
|
50
|
+
*/
|
|
51
|
+
async function resolvePlan(exec, cwd, branch) {
|
|
52
|
+
const [refs, remoteList, configured] = await Promise.all([
|
|
53
|
+
run(exec, cwd, ['for-each-ref', `refs/heads/${branch}`, '--format=%(refname)%09%(objectname)%09%(upstream:short)%09%(upstream:remotename)%09%(upstream:remoteref)%09%(upstream:track)']),
|
|
54
|
+
run(exec, cwd, ['remote']),
|
|
55
|
+
configuredPushRemote(exec, cwd, branch),
|
|
56
|
+
]);
|
|
57
|
+
const fields = refs.split('\n').map(line => line.split('\t')).find(parts => parts[0] === `refs/heads/${branch}`);
|
|
58
|
+
if (fields === undefined)
|
|
59
|
+
throw new Error(`Local branch "${branch}" no longer exists; refresh the branch list.`);
|
|
60
|
+
const [, sourceOid = '', upstream = '', upstreamRemote = '', upstreamRef = '', track = ''] = fields;
|
|
61
|
+
const remotes = remoteList.split('\n').filter(Boolean);
|
|
62
|
+
if (remotes.length === 0)
|
|
63
|
+
throw new Error('No Git remote configured. Add a remote before pushing a branch.');
|
|
64
|
+
const remote = configured || (remotes.includes(upstreamRemote) ? upstreamRemote : remotes.includes('origin') ? 'origin' : remotes[0]);
|
|
65
|
+
if (!remotes.includes(remote))
|
|
66
|
+
throw new Error(`Push remote "${remote}" is not configured; correct the Git push configuration.`);
|
|
67
|
+
// A branch cut from origin/main may automatically track main. Publishing
|
|
68
|
+
// it must suggest its OWN name, not silently send new feature commits to main.
|
|
69
|
+
const gone = track === '[gone]';
|
|
70
|
+
const sameNameCounterpart = upstream !== '' && !gone && upstreamRef === `refs/heads/${branch}`;
|
|
71
|
+
const confirm = upstream === '' || gone || remote !== upstreamRemote || upstreamRef !== `refs/heads/${branch}`;
|
|
72
|
+
return {
|
|
73
|
+
plan: { branch, remotes, remote, target: branch, confirm, ...(upstream === '' ? {} : { upstream }) },
|
|
74
|
+
sourceOid,
|
|
75
|
+
// A same-named upstream is the branch's real counterpart, possibly on a
|
|
76
|
+
// different remote than the one pushed to (a fork workflow). Only a
|
|
77
|
+
// missing, vanished or inherited-base upstream is replaced.
|
|
78
|
+
adoptUpstream: !sameNameCounterpart,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
export async function planPush(exec, cwd, branch) {
|
|
82
|
+
return (await resolvePlan(exec, cwd, branch)).plan;
|
|
83
|
+
}
|
|
84
|
+
/** Local tip of `refs/remotes/<remote>/<target>`, or null when it is not tracked. */
|
|
85
|
+
async function trackingOid(exec, cwd, remote, target) {
|
|
86
|
+
const trackingRef = `refs/remotes/${remote}/${target}`;
|
|
87
|
+
const refs = await run(exec, cwd, ['for-each-ref', '--format=%(refname)%09%(objectname)', trackingRef]);
|
|
88
|
+
// for-each-ref can include prefix descendants. Only the exact target counts.
|
|
89
|
+
return refs.split('\n').map(line => line.split('\t')).find(parts => parts[0] === trackingRef)?.[1] ?? null;
|
|
90
|
+
}
|
|
91
|
+
/** The commits `sourceOid` would add to the target, one subject line each. */
|
|
92
|
+
async function commitsToPush(exec, cwd, sourceOid, remote, targetOid) {
|
|
93
|
+
// A new branch excludes commits already known on this remote's other branches.
|
|
94
|
+
const range = [sourceOid, ...(targetOid === null ? ['--not', `--remotes=${remote}`] : [`^${targetOid}`]), '--'];
|
|
95
|
+
// Most pushes fit in the visible payload. Read one extra subject to detect
|
|
96
|
+
// truncation; avoid recounting history when the message list is complete.
|
|
97
|
+
const log = await run(exec, cwd, ['log', '-n', '201', '--format=%H%x09%s', ...range]);
|
|
98
|
+
const all = log === '' ? [] : log.split('\n').map(line => {
|
|
99
|
+
const tab = line.indexOf('\t');
|
|
100
|
+
return { oid: line.slice(0, tab), subject: line.slice(tab + 1) };
|
|
101
|
+
});
|
|
102
|
+
const truncated = all.length > 200;
|
|
103
|
+
const commits = all.slice(0, 200);
|
|
104
|
+
const total = truncated ? Number(await run(exec, cwd, ['rev-list', '--count', ...range])) : commits.length;
|
|
105
|
+
return { commits, total, truncated };
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Opening the push window: the default destination plus a display-only
|
|
109
|
+
* snapshot of what it would push, computed from local refs. One request
|
|
110
|
+
* replaces a plan call followed by a separate local preview, and the two
|
|
111
|
+
* share their reads. The snapshot is a courtesy: a failure to build it
|
|
112
|
+
* leaves the plan intact, and the verified preview reports real problems.
|
|
113
|
+
*/
|
|
114
|
+
export async function openPush(exec, cwd, branch) {
|
|
115
|
+
const { plan, sourceOid } = await resolvePlan(exec, cwd, branch);
|
|
116
|
+
try {
|
|
117
|
+
const targetOid = await trackingOid(exec, cwd, plan.remote, plan.target);
|
|
118
|
+
return { ...plan, local: { sourceOid, targetOid, ...await commitsToPush(exec, cwd, sourceOid, plan.remote, targetOid) } };
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
return plan;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** Local snapshots are display-only; the verified preview reads the actual push destination. */
|
|
125
|
+
export async function previewPush(exec, cwd, body) {
|
|
126
|
+
const targetRef = `refs/heads/${body.target}`;
|
|
127
|
+
// The reads below do not depend on one another. Run them as one stage so
|
|
128
|
+
// Windows process startup does not serialize the preview.
|
|
129
|
+
const checkTarget = run(exec, cwd, ['check-ref-format', targetRef]);
|
|
130
|
+
const readSource = run(exec, cwd, ['rev-parse', '--verify', `refs/heads/${body.branch}^{commit}`]);
|
|
131
|
+
if (body.localOnly === true) {
|
|
132
|
+
const [, sourceOid, remotes, targetOid] = await Promise.all([
|
|
133
|
+
checkTarget, readSource, run(exec, cwd, ['remote']), trackingOid(exec, cwd, body.remote, body.target),
|
|
134
|
+
]);
|
|
135
|
+
if (!remotes.split('\n').includes(body.remote))
|
|
136
|
+
throw new Error(`Remote "${body.remote}" is not configured.`);
|
|
137
|
+
return { sourceOid, targetOid, ...await commitsToPush(exec, cwd, sourceOid, body.remote, targetOid) };
|
|
138
|
+
}
|
|
139
|
+
const [, sourceOid, url] = await Promise.all([checkTarget, readSource, pushUrl(exec, cwd, body.remote)]);
|
|
140
|
+
const read = await exec('git', ['ls-remote', '--heads', '--refs', '--', url, targetRef], { cwd, timeoutMs: 20_000, nonInteractive: true });
|
|
141
|
+
if (read.code !== 0)
|
|
142
|
+
throw new GitError(['ls-remote', body.remote, targetRef], read.code, read.stderr);
|
|
143
|
+
const targetOid = read.stdout.trim().split('\n').map(line => line.split('\t')).find(parts => parts[1] === targetRef)?.[0] ?? null;
|
|
144
|
+
let list;
|
|
145
|
+
try {
|
|
146
|
+
list = await commitsToPush(exec, cwd, sourceOid, body.remote, targetOid);
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
// The common case needs no probe: the target tip is usually already
|
|
150
|
+
// local. Only when the walk failed do we check for a missing object.
|
|
151
|
+
if (targetOid === null)
|
|
152
|
+
throw error;
|
|
153
|
+
if ((await exec('git', ['cat-file', '-e', `${targetOid}^{commit}`], { cwd })).code === 0)
|
|
154
|
+
throw error;
|
|
155
|
+
// Empty refmap and no FETCH_HEAD avoid moving tracking refs during a preview.
|
|
156
|
+
const args = ['fetch', '--no-tags', '--no-recurse-submodules', '--no-write-fetch-head', '--no-auto-maintenance', '--refmap=', '--', url, targetRef];
|
|
157
|
+
const fetched = await exec('git', args, { cwd, timeoutMs: 120_000, nonInteractive: true });
|
|
158
|
+
if (fetched.code !== 0)
|
|
159
|
+
throw new GitError(['fetch', body.remote, targetRef], fetched.code, fetched.stderr);
|
|
160
|
+
await run(exec, cwd, ['cat-file', '-e', `${targetOid}^{commit}`]);
|
|
161
|
+
list = await commitsToPush(exec, cwd, sourceOid, body.remote, targetOid);
|
|
162
|
+
}
|
|
163
|
+
return { sourceOid, targetOid, ...list };
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Push one explicit local branch to an explicit (or default) destination.
|
|
167
|
+
* A plain call is one buffered `git push` under a two-minute cap; a
|
|
168
|
+
* {@link LiveRun} lifts the cap (a big push has no honest upper bound) for
|
|
169
|
+
* git's own progress, a cancel that kills the push, and five minutes of
|
|
170
|
+
* silence — a hung connection or hook — as the only limit.
|
|
171
|
+
* @param exec - executor seam.
|
|
172
|
+
* @param cwd - repository directory.
|
|
173
|
+
* @param body - what to push and where.
|
|
174
|
+
* @param live - optional live output / cancellation of the push itself.
|
|
175
|
+
* @returns the branch, remote and target that were pushed.
|
|
176
|
+
*/
|
|
177
|
+
export async function pushBranch(exec, cwd, body, live) {
|
|
178
|
+
const { plan, sourceOid: current, adoptUpstream } = await resolvePlan(exec, cwd, body.branch);
|
|
179
|
+
const publishing = body.remote !== undefined && body.target !== undefined;
|
|
180
|
+
if (!publishing && plan.confirm)
|
|
181
|
+
throw new Error('The push destination needs confirmation. Reopen Push to choose a remote and branch.');
|
|
182
|
+
const remote = publishing ? body.remote : plan.remote;
|
|
183
|
+
const target = publishing ? body.target : plan.target;
|
|
184
|
+
if (!plan.remotes.includes(remote))
|
|
185
|
+
throw new Error(`Remote "${remote}" is not configured.`);
|
|
186
|
+
await run(exec, cwd, ['check-ref-format', `refs/heads/${target}`]);
|
|
187
|
+
if (body.sourceOid !== undefined) {
|
|
188
|
+
await pushUrl(exec, cwd, remote);
|
|
189
|
+
if (current !== body.sourceOid)
|
|
190
|
+
throw new Error('The local branch changed after preview. Refresh the push preview before retrying.');
|
|
191
|
+
}
|
|
192
|
+
if (body.force === true && (!publishing || body.sourceOid === undefined || body.expectedTarget === undefined
|
|
193
|
+
|| !/^(?:[a-f0-9]{40}|[a-f0-9]{64})?$/.test(body.expectedTarget))) {
|
|
194
|
+
throw new Error('Force push requires an explicit destination and its previewed revision. Refresh the push preview.');
|
|
195
|
+
}
|
|
196
|
+
// Git applies remote.<name>.mirror after parsing --no-mirror. Override it
|
|
197
|
+
// for this invocation too; never edit the repository's persistent config.
|
|
198
|
+
const args = ['-c', `remote.${remote}.mirror=false`, 'push', '--porcelain', '--no-force', '--no-mirror', '--no-follow-tags', '--recurse-submodules=no',
|
|
199
|
+
// git draws its counters (`Writing objects: 45% …`) only on a terminal otherwise.
|
|
200
|
+
...(live === undefined ? [] : ['--progress']),
|
|
201
|
+
...(body.force === true ? [`--force-with-lease=refs/heads/${target}:${body.expectedTarget}`] : []),
|
|
202
|
+
...(body.tags === 'all' ? ['--tags'] : body.tags === 'follow' ? ['--follow-tags'] : []),
|
|
203
|
+
// Tracking follows the push only when the branch has no real counterpart
|
|
204
|
+
// yet. A one-off push to another remote or name must not rewrite it.
|
|
205
|
+
...(publishing && adoptUpstream ? ['--set-upstream'] : []), '--', remote, `refs/heads/${body.branch}:refs/heads/${target}`];
|
|
206
|
+
const result = live === undefined
|
|
207
|
+
? await exec('git', args, { cwd, timeoutMs: 120_000, nonInteractive: true })
|
|
208
|
+
: await exec('git', args, { cwd, nonInteractive: true, ...liveExecOptions(live) });
|
|
209
|
+
if (result.cancelled)
|
|
210
|
+
throw new CancelledError();
|
|
211
|
+
// A live run's stderr carries every counter redraw; the failure is what is left.
|
|
212
|
+
if (result.code !== 0)
|
|
213
|
+
throw new GitError(args, result.code, [live === undefined ? result.stderr : stripProgress(result.stderr), result.stdout].filter(Boolean).join('\n'));
|
|
214
|
+
return { branch: body.branch, remote, target };
|
|
215
|
+
}
|
package/lib/routes.d.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { type CopyFilesSeams } from './copy-files.js';
|
|
6
6
|
import { type DirExists, type ExcludeSeams, type Exec } from './git.js';
|
|
7
|
-
import type { CreateBranchResult, CreateWorktreeResult, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, HeadStatus, InspectWorktreeResult, PathExistsResult, PurgeDirectoryResult, RemoveWorktreeResult, RepoStatus, RouteError, SwitchResult, UpdateResult, WorktreesAllResult } from './wire.js';
|
|
7
|
+
import type { CreateBranchResult, CreateWorktreeResult, EnsureDirectoryResult, FetchResult, GroupWorkspacesResult, HeadStatus, InspectWorktreeResult, PathExistsResult, PushPlan, PushPreview, PushResult, PurgeDirectoryResult, RemoveWorktreeResult, RepoStatus, RouteError, SwitchResult, SyncEvent, UpdateResult, WorktreesAllResult } from './wire.js';
|
|
8
8
|
/** Everything the handlers need from the host half. */
|
|
9
9
|
export interface RouteDeps {
|
|
10
10
|
exec: Exec;
|
|
@@ -46,7 +46,7 @@ export declare function fsMkdirRecursive(path: string): Promise<void>;
|
|
|
46
46
|
/** One route outcome: HTTP status plus the JSON body. */
|
|
47
47
|
export interface RouteOutcome {
|
|
48
48
|
status: number;
|
|
49
|
-
body: RepoStatus | HeadStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | WorktreesAllResult | PurgeDirectoryResult | RouteError;
|
|
49
|
+
body: PushPlan | PushPreview | PushResult | RepoStatus | HeadStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | WorktreesAllResult | PurgeDirectoryResult | RouteError;
|
|
50
50
|
}
|
|
51
51
|
/**
|
|
52
52
|
* POST /group — git belonging facts for a batch of workspace directories.
|
|
@@ -165,23 +165,62 @@ export declare function handleRenameBranch(deps: RouteDeps, body: unknown): Prom
|
|
|
165
165
|
*/
|
|
166
166
|
export declare function handleDeleteBranch(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
167
167
|
/**
|
|
168
|
-
*
|
|
168
|
+
* The live side of a long route: events out while it runs, and a signal in
|
|
169
|
+
* when the caller leaves. The HTTP shell owns both ends (stream and socket);
|
|
170
|
+
* the handlers only emit and pass the signal on to git.
|
|
171
|
+
*/
|
|
172
|
+
export interface RouteLive {
|
|
173
|
+
/** Aborted when the caller goes away — git is killed and the route answers
|
|
174
|
+
* 499 to nobody. */
|
|
175
|
+
signal: AbortSignal;
|
|
176
|
+
/** Send one event to the caller. */
|
|
177
|
+
emit: (event: SyncEvent) => void;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* POST /fetch — sync remote-tracking refs for the repository: fetch every
|
|
169
181
|
* remote and prune tracking branches the remotes no longer carry. Pure
|
|
170
182
|
* metadata — the working tree and the current checkout are untouched; the
|
|
171
183
|
* client refetches /status afterwards for the fresh branch list.
|
|
172
184
|
* @param deps - host dependencies.
|
|
173
185
|
* @param body - parsed request body.
|
|
186
|
+
* @param live - the streaming channel (absent = the plain request).
|
|
187
|
+
*/
|
|
188
|
+
export declare function handleFetch(deps: RouteDeps, body: unknown, live?: RouteLive): Promise<RouteOutcome>;
|
|
189
|
+
/**
|
|
190
|
+
* POST /push-plan — read-only destination resolution for one local branch,
|
|
191
|
+
* bundled with a display-only local snapshot of what it would push (see
|
|
192
|
+
* `openPush`). Publishing is a separate explicit POST.
|
|
193
|
+
* @param deps - host dependencies.
|
|
194
|
+
* @param body - parsed request body: `{ repoPath, branch }`.
|
|
195
|
+
*/
|
|
196
|
+
export declare function handlePushPlan(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
197
|
+
/**
|
|
198
|
+
* POST /push — push one explicit local branch to an explicit destination
|
|
199
|
+
* (or, without one, to the confirmation-free default of `planPush`).
|
|
200
|
+
* @param deps - host dependencies.
|
|
201
|
+
* @param body - parsed request body.
|
|
202
|
+
* @param live - the streaming channel (absent = the plain request, which
|
|
203
|
+
* keeps its two-minute cap).
|
|
204
|
+
*/
|
|
205
|
+
export declare function handlePush(deps: RouteDeps, body: unknown, live?: RouteLive): Promise<RouteOutcome>;
|
|
206
|
+
/**
|
|
207
|
+
* POST /push-preview — the commits one explicit remote/target would receive,
|
|
208
|
+
* read from the real push destination (or from local tracking refs with
|
|
209
|
+
* `localOnly`, which never touches the network). Pushes nothing.
|
|
210
|
+
* @param deps - host dependencies.
|
|
211
|
+
* @param body - parsed request body.
|
|
174
212
|
*/
|
|
175
|
-
export declare function
|
|
213
|
+
export declare function handlePushPreview(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
176
214
|
/**
|
|
177
|
-
* POST /update
|
|
215
|
+
* POST /update — update the CURRENT checkout: fetch every remote, then
|
|
178
216
|
* fast-forward the branch checked out by the queried directory to its
|
|
179
217
|
* upstream. Divergence, a missing upstream, and conflicting working-tree
|
|
180
218
|
* changes all surface as 400 envelopes carrying git's own explanation.
|
|
181
219
|
* @param deps - host dependencies.
|
|
182
220
|
* @param body - parsed request body.
|
|
221
|
+
* @param live - the streaming channel (absent = the plain request).
|
|
183
222
|
*/
|
|
184
|
-
export declare function handleUpdate(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
223
|
+
export declare function handleUpdate(deps: RouteDeps, body: unknown, live?: RouteLive): Promise<RouteOutcome>;
|
|
185
224
|
/**
|
|
186
225
|
* POST /inspect — pre-delete facts for one worktree directory: the
|
|
187
226
|
* uncommitted-file count (those die with the folder) and the checked-out
|
package/lib/routes.js
CHANGED
|
@@ -5,9 +5,11 @@
|
|
|
5
5
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
6
6
|
import { mkdir, readdir, rm, stat } from 'node:fs/promises';
|
|
7
7
|
import { runPostCreateCopy } from './copy-files.js';
|
|
8
|
-
import { appendWorktreeExclude, fsExcludeSeams, GitError, addWorktree, addWorktreeCutout, createBranch, cutoutBranchName, deleteBranch, fetchAll, fsDirExists, inspectWorktree, isAbsoluteDir, probeRepo, probeWorkspaceGit, removeWorktree, renameBranch, resolveBranch, switchBranch, updateBranch } from './git.js';
|
|
8
|
+
import { appendWorktreeExclude, fsExcludeSeams, CancelledError, GitError, addWorktree, addWorktreeCutout, createBranch, cutoutBranchName, deleteBranch, fetchAll, fsDirExists, inspectWorktree, isAbsoluteDir, probeRepo, probeWorkspaceGit, removeWorktree, renameBranch, resolveBranch, switchBranch, updateBranch } from './git.js';
|
|
9
9
|
import { readCheckedOutBranch } from './head.js';
|
|
10
|
+
import { openPush, previewPush, pushBranch } from './push.js';
|
|
10
11
|
import { isAbsoluteConfigPath, sanitizeBranchDir } from './normalize.js';
|
|
12
|
+
import { createProgressReader } from './progress.js';
|
|
11
13
|
import { resolveRootDir } from './settings.js';
|
|
12
14
|
/** Real fs-backed one-level directory listing (names only). Plain FILES are
|
|
13
15
|
* filtered out — the storage root can carry strays (a legacy settings.json
|
|
@@ -634,49 +636,155 @@ export async function handleDeleteBranch(deps, body) {
|
|
|
634
636
|
}
|
|
635
637
|
}
|
|
636
638
|
/**
|
|
637
|
-
*
|
|
639
|
+
* Translate a route's live channel into a git {@link LiveRun}: git's raw
|
|
640
|
+
* output goes through the progress reader, so the caller sees structured,
|
|
641
|
+
* throttled events instead of a thousand `\r` redraws.
|
|
642
|
+
* @param live - the route's channel; absent for a plain, non-streamed call.
|
|
643
|
+
* @returns the run to hand to git (undefined = no live behaviour) and `end`,
|
|
644
|
+
* which flushes the reader's last held observation.
|
|
645
|
+
*/
|
|
646
|
+
function startLive(live) {
|
|
647
|
+
if (live === undefined)
|
|
648
|
+
return { run: undefined, end: () => undefined };
|
|
649
|
+
const reader = createProgressReader(progress => { live.emit({ type: 'progress', ...progress }); });
|
|
650
|
+
return {
|
|
651
|
+
run: {
|
|
652
|
+
onOutput: (chunk) => { reader.feed(chunk); },
|
|
653
|
+
onRemote: (remote) => { reader.remote(remote); },
|
|
654
|
+
signal: live.signal,
|
|
655
|
+
// The merge event must come after the last progress line, not before.
|
|
656
|
+
onMerge: () => { reader.end(); live.emit({ type: 'merge' }); },
|
|
657
|
+
},
|
|
658
|
+
end: () => { reader.end(); },
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* POST /fetch — sync remote-tracking refs for the repository: fetch every
|
|
638
663
|
* remote and prune tracking branches the remotes no longer carry. Pure
|
|
639
664
|
* metadata — the working tree and the current checkout are untouched; the
|
|
640
665
|
* client refetches /status afterwards for the fresh branch list.
|
|
641
666
|
* @param deps - host dependencies.
|
|
642
667
|
* @param body - parsed request body.
|
|
668
|
+
* @param live - the streaming channel (absent = the plain request).
|
|
643
669
|
*/
|
|
644
|
-
export async function handleFetch(deps, body) {
|
|
670
|
+
export async function handleFetch(deps, body, live) {
|
|
645
671
|
const parsed = readBody(body, ['repoPath']);
|
|
646
672
|
if (isOutcome(parsed))
|
|
647
673
|
return parsed;
|
|
648
674
|
const { repoPath } = parsed;
|
|
649
675
|
if (!isAbsoluteDir(repoPath))
|
|
650
676
|
return fail(400, '"repoPath" must be an absolute directory');
|
|
677
|
+
const { run, end } = startLive(live);
|
|
651
678
|
try {
|
|
652
679
|
const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
|
|
653
680
|
if (facts === undefined)
|
|
654
681
|
return fail(400, `"${repoPath}" is not inside a git repository`);
|
|
655
|
-
await fetchAll(deps.exec, facts.repoRoot);
|
|
682
|
+
await fetchAll(deps.exec, facts.repoRoot, run);
|
|
656
683
|
const result = { remote: 'all' };
|
|
657
684
|
return { status: 200, body: result };
|
|
658
685
|
}
|
|
659
686
|
catch (error) {
|
|
687
|
+
if (error instanceof CancelledError)
|
|
688
|
+
return fail(499, error.message);
|
|
660
689
|
if (error instanceof GitError)
|
|
661
690
|
return gitFailure(error);
|
|
662
691
|
return fail(500, error instanceof Error ? error.message : String(error));
|
|
663
692
|
}
|
|
693
|
+
finally {
|
|
694
|
+
end();
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
/**
|
|
698
|
+
* POST /push-plan — read-only destination resolution for one local branch,
|
|
699
|
+
* bundled with a display-only local snapshot of what it would push (see
|
|
700
|
+
* `openPush`). Publishing is a separate explicit POST.
|
|
701
|
+
* @param deps - host dependencies.
|
|
702
|
+
* @param body - parsed request body: `{ repoPath, branch }`.
|
|
703
|
+
*/
|
|
704
|
+
export async function handlePushPlan(deps, body) {
|
|
705
|
+
return handlePushAction(deps, body, false);
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* POST /push — push one explicit local branch to an explicit destination
|
|
709
|
+
* (or, without one, to the confirmation-free default of `planPush`).
|
|
710
|
+
* @param deps - host dependencies.
|
|
711
|
+
* @param body - parsed request body.
|
|
712
|
+
* @param live - the streaming channel (absent = the plain request, which
|
|
713
|
+
* keeps its two-minute cap).
|
|
714
|
+
*/
|
|
715
|
+
export async function handlePush(deps, body, live) {
|
|
716
|
+
return handlePushAction(deps, body, true, live);
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* POST /push-preview — the commits one explicit remote/target would receive,
|
|
720
|
+
* read from the real push destination (or from local tracking refs with
|
|
721
|
+
* `localOnly`, which never touches the network). Pushes nothing.
|
|
722
|
+
* @param deps - host dependencies.
|
|
723
|
+
* @param body - parsed request body.
|
|
724
|
+
*/
|
|
725
|
+
export async function handlePushPreview(deps, body) {
|
|
726
|
+
const parsed = readBody(body, ['repoPath', 'branch', 'remote', 'target'], ['localOnly']);
|
|
727
|
+
if (isOutcome(parsed))
|
|
728
|
+
return parsed;
|
|
729
|
+
if (!isAbsoluteDir(parsed.repoPath) || !parsed.branch.trim() || !parsed.remote?.trim() || !parsed.target?.trim())
|
|
730
|
+
return fail(400, 'An absolute repoPath, branch, remote and target are required');
|
|
731
|
+
try {
|
|
732
|
+
return { status: 200, body: await previewPush(deps.exec, parsed.repoPath, { ...parsed, remote: parsed.remote, target: parsed.target }) };
|
|
733
|
+
}
|
|
734
|
+
catch (error) {
|
|
735
|
+
return fail(400, error instanceof Error ? error.message : String(error));
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
async function handlePushAction(deps, body, execute, live) {
|
|
739
|
+
const parsed = readBody(body, ['repoPath', 'branch'], execute ? ['force'] : [], execute ? ['remote', 'target', 'tags', 'expectedTarget', 'sourceOid'] : []);
|
|
740
|
+
if (isOutcome(parsed))
|
|
741
|
+
return parsed;
|
|
742
|
+
if (!isAbsoluteDir(parsed.repoPath))
|
|
743
|
+
return fail(400, '"repoPath" must be an absolute directory');
|
|
744
|
+
if (parsed.branch.trim() === '')
|
|
745
|
+
return fail(400, '"branch" must be non-empty');
|
|
746
|
+
if (parsed.tags !== undefined && !['none', 'all', 'follow'].includes(parsed.tags))
|
|
747
|
+
return fail(400, '"tags" must be none, all or follow');
|
|
748
|
+
if (parsed.sourceOid !== undefined && !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(parsed.sourceOid))
|
|
749
|
+
return fail(400, '"sourceOid" must be a full object ID');
|
|
750
|
+
if ((parsed.remote === undefined) !== (parsed.target === undefined))
|
|
751
|
+
return fail(400, '"remote" and "target" must be provided together');
|
|
752
|
+
if (parsed.remote !== undefined && (typeof parsed.remote !== 'string' || parsed.remote.trim() === ''
|
|
753
|
+
|| typeof parsed.target !== 'string' || parsed.target.trim() === ''))
|
|
754
|
+
return fail(400, '"remote" and "target" must be non-empty strings');
|
|
755
|
+
const { run, end } = startLive(execute ? live : undefined);
|
|
756
|
+
try {
|
|
757
|
+
return { status: 200, body: execute
|
|
758
|
+
? await pushBranch(deps.exec, parsed.repoPath, parsed, run)
|
|
759
|
+
: await openPush(deps.exec, parsed.repoPath, parsed.branch) };
|
|
760
|
+
}
|
|
761
|
+
catch (error) {
|
|
762
|
+
// Stopped by the caller: not a failure, and nobody is left to read it.
|
|
763
|
+
if (error instanceof CancelledError)
|
|
764
|
+
return fail(499, error.message);
|
|
765
|
+
return fail(400, error instanceof Error ? error.message : String(error));
|
|
766
|
+
}
|
|
767
|
+
finally {
|
|
768
|
+
end();
|
|
769
|
+
}
|
|
664
770
|
}
|
|
665
771
|
/**
|
|
666
|
-
* POST /update
|
|
772
|
+
* POST /update — update the CURRENT checkout: fetch every remote, then
|
|
667
773
|
* fast-forward the branch checked out by the queried directory to its
|
|
668
774
|
* upstream. Divergence, a missing upstream, and conflicting working-tree
|
|
669
775
|
* changes all surface as 400 envelopes carrying git's own explanation.
|
|
670
776
|
* @param deps - host dependencies.
|
|
671
777
|
* @param body - parsed request body.
|
|
778
|
+
* @param live - the streaming channel (absent = the plain request).
|
|
672
779
|
*/
|
|
673
|
-
export async function handleUpdate(deps, body) {
|
|
780
|
+
export async function handleUpdate(deps, body, live) {
|
|
674
781
|
const parsed = readBody(body, ['repoPath']);
|
|
675
782
|
if (isOutcome(parsed))
|
|
676
783
|
return parsed;
|
|
677
784
|
const { repoPath } = parsed;
|
|
678
785
|
if (!isAbsoluteDir(repoPath))
|
|
679
786
|
return fail(400, '"repoPath" must be an absolute directory');
|
|
787
|
+
const { run, end } = startLive(live);
|
|
680
788
|
try {
|
|
681
789
|
const facts = await probeRepo(deps.exec, repoPath, deps.dirExists);
|
|
682
790
|
if (facts === undefined)
|
|
@@ -685,15 +793,20 @@ export async function handleUpdate(deps, body) {
|
|
|
685
793
|
// session "update current branch" means the branch that worktree holds.
|
|
686
794
|
// `repoRoot` would fast-forward the main checkout behind the user's back
|
|
687
795
|
// (both are the same directory when the session IS the main checkout).
|
|
688
|
-
const outcome = await updateBranch(deps.exec, facts.toplevel);
|
|
796
|
+
const outcome = await updateBranch(deps.exec, facts.toplevel, run);
|
|
689
797
|
const result = { branch: outcome.branch, updated: outcome.updated };
|
|
690
798
|
return { status: 200, body: result };
|
|
691
799
|
}
|
|
692
800
|
catch (error) {
|
|
801
|
+
if (error instanceof CancelledError)
|
|
802
|
+
return fail(499, error.message);
|
|
693
803
|
if (error instanceof GitError)
|
|
694
804
|
return gitFailure(error);
|
|
695
805
|
return fail(500, error instanceof Error ? error.message : String(error));
|
|
696
806
|
}
|
|
807
|
+
finally {
|
|
808
|
+
end();
|
|
809
|
+
}
|
|
697
810
|
}
|
|
698
811
|
/**
|
|
699
812
|
* POST /inspect — pre-delete facts for one worktree directory: the
|
package/lib/stream.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streamed route responses: the HTTP half of the live fetch/update progress.
|
|
3
|
+
*
|
|
4
|
+
* A streamed route answers `200` at once and then writes one JSON
|
|
5
|
+
* {@link SyncFrame} per line while the handler works; the last line is `done`
|
|
6
|
+
* and carries the status and body the same route would have answered in one
|
|
7
|
+
* piece. The status line is therefore no longer the verdict — the `done`
|
|
8
|
+
* frame is — which is what lets a failure that happens after minutes of
|
|
9
|
+
* transfer still be reported.
|
|
10
|
+
*
|
|
11
|
+
* The caller cancels by closing the connection. A response that is not yet
|
|
12
|
+
* finished when its socket closes aborts the handler's signal, which kills
|
|
13
|
+
* git. (`res`'s `close`, not `req`'s: a request body that was fully read
|
|
14
|
+
* closes early on modern Node whether or not the client is still there.)
|
|
15
|
+
*
|
|
16
|
+
* @module git-worktree/stream
|
|
17
|
+
*/
|
|
18
|
+
import type { RouteLive, RouteOutcome } from './routes.js';
|
|
19
|
+
/** The slice of `http.ServerResponse` a stream needs — a fake in tests. */
|
|
20
|
+
export interface StreamTarget {
|
|
21
|
+
writeHead: (status: number, headers: Record<string, string>) => unknown;
|
|
22
|
+
write: (chunk: string) => unknown;
|
|
23
|
+
end: () => unknown;
|
|
24
|
+
on: (event: 'close', listener: () => void) => unknown;
|
|
25
|
+
readonly writableEnded: boolean;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Run one handler as an NDJSON stream.
|
|
29
|
+
* @param res - the response to stream into.
|
|
30
|
+
* @param handle - the route logic; emits events through `live` and resolves
|
|
31
|
+
* with the outcome that becomes the `done` frame.
|
|
32
|
+
*/
|
|
33
|
+
export declare function streamRoute(res: StreamTarget, handle: (live: RouteLive) => Promise<RouteOutcome>): Promise<void>;
|
package/lib/stream.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streamed route responses: the HTTP half of the live fetch/update progress.
|
|
3
|
+
*
|
|
4
|
+
* A streamed route answers `200` at once and then writes one JSON
|
|
5
|
+
* {@link SyncFrame} per line while the handler works; the last line is `done`
|
|
6
|
+
* and carries the status and body the same route would have answered in one
|
|
7
|
+
* piece. The status line is therefore no longer the verdict — the `done`
|
|
8
|
+
* frame is — which is what lets a failure that happens after minutes of
|
|
9
|
+
* transfer still be reported.
|
|
10
|
+
*
|
|
11
|
+
* The caller cancels by closing the connection. A response that is not yet
|
|
12
|
+
* finished when its socket closes aborts the handler's signal, which kills
|
|
13
|
+
* git. (`res`'s `close`, not `req`'s: a request body that was fully read
|
|
14
|
+
* closes early on modern Node whether or not the client is still there.)
|
|
15
|
+
*
|
|
16
|
+
* @module git-worktree/stream
|
|
17
|
+
*/
|
|
18
|
+
import { NDJSON_TYPE } from './wire.js';
|
|
19
|
+
/**
|
|
20
|
+
* Run one handler as an NDJSON stream.
|
|
21
|
+
* @param res - the response to stream into.
|
|
22
|
+
* @param handle - the route logic; emits events through `live` and resolves
|
|
23
|
+
* with the outcome that becomes the `done` frame.
|
|
24
|
+
*/
|
|
25
|
+
export async function streamRoute(res, handle) {
|
|
26
|
+
const controller = new AbortController();
|
|
27
|
+
res.on('close', () => {
|
|
28
|
+
if (!res.writableEnded)
|
|
29
|
+
controller.abort();
|
|
30
|
+
});
|
|
31
|
+
res.writeHead(200, {
|
|
32
|
+
'content-type': `${NDJSON_TYPE}; charset=utf-8`,
|
|
33
|
+
'cache-control': 'no-store',
|
|
34
|
+
// Tell a reverse proxy not to hold the lines back until the stream ends.
|
|
35
|
+
'x-accel-buffering': 'no',
|
|
36
|
+
});
|
|
37
|
+
const write = (frame) => {
|
|
38
|
+
// Nobody is listening after an abort; writing would only raise EPIPE.
|
|
39
|
+
if (controller.signal.aborted || res.writableEnded)
|
|
40
|
+
return;
|
|
41
|
+
res.write(`${JSON.stringify(frame)}\n`);
|
|
42
|
+
};
|
|
43
|
+
let outcome;
|
|
44
|
+
try {
|
|
45
|
+
outcome = await handle({ signal: controller.signal, emit: write });
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
// Handlers answer their own failures; this is the backstop for a bug.
|
|
49
|
+
outcome = { status: 500, body: { error: error instanceof Error ? error.message : String(error) } };
|
|
50
|
+
}
|
|
51
|
+
write({ type: 'done', status: outcome.status, body: outcome.body });
|
|
52
|
+
if (!res.writableEnded)
|
|
53
|
+
res.end();
|
|
54
|
+
}
|