@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
|
@@ -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;
|
package/lib/progress.js
ADDED
|
@@ -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>;
|
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, 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 | 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.
|
|
@@ -104,6 +104,12 @@ export declare function handlePurgeDirectory(deps: RouteDeps, body: unknown): Pr
|
|
|
104
104
|
* @param path - absolute directory the workspace reports.
|
|
105
105
|
*/
|
|
106
106
|
export declare function handleStatus(deps: RouteDeps, path: string | undefined): Promise<RouteOutcome>;
|
|
107
|
+
/**
|
|
108
|
+
* GET /head — the checked-out branch of one directory, from the HEAD file.
|
|
109
|
+
* `pending` is a skipped tick: the caller keeps the label it already has.
|
|
110
|
+
* @param path - absolute directory the workspace reports.
|
|
111
|
+
*/
|
|
112
|
+
export declare function handleHead(path: string | undefined): Promise<RouteOutcome>;
|
|
107
113
|
/**
|
|
108
114
|
* POST /worktree — create or reuse the worktree for a branch, then report the
|
|
109
115
|
* directory so the client can register it as a workspace. The worktree lands
|
|
@@ -159,23 +165,62 @@ export declare function handleRenameBranch(deps: RouteDeps, body: unknown): Prom
|
|
|
159
165
|
*/
|
|
160
166
|
export declare function handleDeleteBranch(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
161
167
|
/**
|
|
162
|
-
*
|
|
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
|
|
163
181
|
* remote and prune tracking branches the remotes no longer carry. Pure
|
|
164
182
|
* metadata — the working tree and the current checkout are untouched; the
|
|
165
183
|
* client refetches /status afterwards for the fresh branch list.
|
|
166
184
|
* @param deps - host dependencies.
|
|
167
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.
|
|
168
212
|
*/
|
|
169
|
-
export declare function
|
|
213
|
+
export declare function handlePushPreview(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
170
214
|
/**
|
|
171
|
-
* POST /update
|
|
215
|
+
* POST /update — update the CURRENT checkout: fetch every remote, then
|
|
172
216
|
* fast-forward the branch checked out by the queried directory to its
|
|
173
217
|
* upstream. Divergence, a missing upstream, and conflicting working-tree
|
|
174
218
|
* changes all surface as 400 envelopes carrying git's own explanation.
|
|
175
219
|
* @param deps - host dependencies.
|
|
176
220
|
* @param body - parsed request body.
|
|
221
|
+
* @param live - the streaming channel (absent = the plain request).
|
|
177
222
|
*/
|
|
178
|
-
export declare function handleUpdate(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
223
|
+
export declare function handleUpdate(deps: RouteDeps, body: unknown, live?: RouteLive): Promise<RouteOutcome>;
|
|
179
224
|
/**
|
|
180
225
|
* POST /inspect — pre-delete facts for one worktree directory: the
|
|
181
226
|
* uncommitted-file count (those die with the folder) and the checked-out
|