@laoyuehanni/dsh-git-worktree 0.4.8 → 0.4.10
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 +5 -2
- package/README.zh.md +5 -2
- package/lib/client.js +2393 -205
- package/lib/git.d.ts +58 -11
- package/lib/git.js +197 -17
- package/lib/graph-preview/asciidoc-xKuVlNk6.js +5 -0
- package/lib/graph-preview/bat-Dx8nnxXE.js +5 -0
- package/lib/graph-preview/bibtex-BzgdqG3s.js +5 -0
- package/lib/graph-preview/c-BGpbtv2-.js +8 -0
- package/lib/graph-preview/clojure-DDsQ0FaV.js +5 -0
- package/lib/graph-preview/cmake-DPsCB_V6.js +5 -0
- package/lib/graph-preview/cpp-CBYrHpV9.js +27 -0
- package/lib/graph-preview/csharp-CFKaLbHg.js +5 -0
- package/lib/graph-preview/css-C6zsnaz5.js +8 -0
- package/lib/graph-preview/csv-DqIVFkK7.js +5 -0
- package/lib/graph-preview/dart-C6DUdjib.js +5 -0
- package/lib/graph-preview/diff-Blb4MjsC.js +5 -0
- package/lib/graph-preview/dotenv-Dkdv7Sm2.js +5 -0
- package/lib/graph-preview/elixir-D0Gskj1z.js +8 -0
- package/lib/graph-preview/erlang-BJwlUj8s.js +8 -0
- package/lib/graph-preview/fish-D7qAeWQz.js +5 -0
- package/lib/graph-preview/fsharp-MCvH12ek.js +8 -0
- package/lib/graph-preview/go-aXtTCanQ.js +5 -0
- package/lib/graph-preview/graphql-DBbDUzBC.js +19 -0
- package/lib/graph-preview/groovy-Bw2Ku4bU.js +5 -0
- package/lib/graph-preview/haskell-CfGsE1Cf.js +5 -0
- package/lib/graph-preview/hcl-DHg_Osgo.js +5 -0
- package/lib/graph-preview/html-DwZ-9Aol.js +15 -0
- package/lib/graph-preview/html-derivative-CdrGiVx_.js +8 -0
- package/lib/graph-preview/http-B769neBI.js +16 -0
- package/lib/graph-preview/ini-C24lZfdM.js +5 -0
- package/lib/graph-preview/java-B6HH4GJL.js +8 -0
- package/lib/graph-preview/javascript-BXA9Hfas.js +5 -0
- package/lib/graph-preview/julia--d6L9eAJ.js +19 -0
- package/lib/graph-preview/kotlin-BHE8CoV9.js +5 -0
- package/lib/graph-preview/latex-BsyjE6iS.js +12 -0
- package/lib/graph-preview/less-BzbdhFUi.js +5 -0
- package/lib/graph-preview/log-Dad54gsi.js +5 -0
- package/lib/graph-preview/lua-DL6V31K-.js +10 -0
- package/lib/graph-preview/make-B2ukzWs3.js +5 -0
- package/lib/graph-preview/markdown-CkmxmzqY.js +5 -0
- package/lib/graph-preview/mdx-BK9ZufRc.js +5 -0
- package/lib/graph-preview/nix-BRl3YduB.js +9 -0
- package/lib/graph-preview/perl-DJHPR3L5.js +19 -0
- package/lib/graph-preview/php-B74oGaLi.js +21 -0
- package/lib/graph-preview/powershell-DvOBVZPr.js +5 -0
- package/lib/graph-preview/preview.js +79431 -0
- package/lib/graph-preview/proto-ClkOcAW0.js +5 -0
- package/lib/graph-preview/python-BjnOIxPe.js +5 -0
- package/lib/graph-preview/r-BSNufAtJ.js +8 -0
- package/lib/graph-preview/rst-CDCHc-qO.js +25 -0
- package/lib/graph-preview/ruby-Dx4dTqam.js +40 -0
- package/lib/graph-preview/rust-COBzcmTx.js +5 -0
- package/lib/graph-preview/scala-pMGZAs9j.js +5 -0
- package/lib/graph-preview/scss-D2N2uO1z.js +8 -0
- package/lib/graph-preview/sql-DBa5L-Wg.js +8 -0
- package/lib/graph-preview/svelte-DQXUqa3J.js +18 -0
- package/lib/graph-preview/swift-DWmMn3lF.js +5 -0
- package/lib/graph-preview/system-verilog-DW0KSMVO.js +5 -0
- package/lib/graph-preview/toml-B7BHZIqX.js +5 -0
- package/lib/graph-preview/vb-eGVhCUXq.js +5 -0
- package/lib/graph-preview/verilog-Ma7yBE30.js +5 -0
- package/lib/graph-preview/vue-k6e1qQTO.js +32 -0
- package/lib/graph-preview/xml-DUa-g8pJ.js +10 -0
- package/lib/graph-preview/yaml-B81N8prR.js +5 -0
- package/lib/history.d.ts +7 -0
- package/lib/history.js +79 -0
- package/lib/index.js +28 -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 +48 -6
- package/lib/routes.js +149 -7
- package/lib/stream.d.ts +33 -0
- package/lib/stream.js +54 -0
- package/lib/wire.d.ts +131 -2
- package/lib/wire.js +18 -2
- package/package.json +12 -10
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,8 @@
|
|
|
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 {
|
|
7
|
+
import type { CommitHistory, CommitDetail } from './wire.js';
|
|
8
|
+
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
9
|
/** Everything the handlers need from the host half. */
|
|
9
10
|
export interface RouteDeps {
|
|
10
11
|
exec: Exec;
|
|
@@ -46,7 +47,7 @@ export declare function fsMkdirRecursive(path: string): Promise<void>;
|
|
|
46
47
|
/** One route outcome: HTTP status plus the JSON body. */
|
|
47
48
|
export interface RouteOutcome {
|
|
48
49
|
status: number;
|
|
49
|
-
body: RepoStatus | HeadStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | WorktreesAllResult | PurgeDirectoryResult | RouteError;
|
|
50
|
+
body: CommitHistory | CommitDetail | PushPlan | PushPreview | PushResult | RepoStatus | HeadStatus | CreateWorktreeResult | SwitchResult | CreateBranchResult | FetchResult | UpdateResult | GroupWorkspacesResult | InspectWorktreeResult | RemoveWorktreeResult | PathExistsResult | EnsureDirectoryResult | WorktreesAllResult | PurgeDirectoryResult | RouteError;
|
|
50
51
|
}
|
|
51
52
|
/**
|
|
52
53
|
* POST /group — git belonging facts for a batch of workspace directories.
|
|
@@ -110,6 +111,8 @@ export declare function handleStatus(deps: RouteDeps, path: string | undefined):
|
|
|
110
111
|
* @param path - absolute directory the workspace reports.
|
|
111
112
|
*/
|
|
112
113
|
export declare function handleHead(path: string | undefined): Promise<RouteOutcome>;
|
|
114
|
+
export declare function handleHistory(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
115
|
+
export declare function handleCommit(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
113
116
|
/**
|
|
114
117
|
* POST /worktree — create or reuse the worktree for a branch, then report the
|
|
115
118
|
* directory so the client can register it as a workspace. The worktree lands
|
|
@@ -165,23 +168,62 @@ export declare function handleRenameBranch(deps: RouteDeps, body: unknown): Prom
|
|
|
165
168
|
*/
|
|
166
169
|
export declare function handleDeleteBranch(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
167
170
|
/**
|
|
168
|
-
*
|
|
171
|
+
* The live side of a long route: events out while it runs, and a signal in
|
|
172
|
+
* when the caller leaves. The HTTP shell owns both ends (stream and socket);
|
|
173
|
+
* the handlers only emit and pass the signal on to git.
|
|
174
|
+
*/
|
|
175
|
+
export interface RouteLive {
|
|
176
|
+
/** Aborted when the caller goes away — git is killed and the route answers
|
|
177
|
+
* 499 to nobody. */
|
|
178
|
+
signal: AbortSignal;
|
|
179
|
+
/** Send one event to the caller. */
|
|
180
|
+
emit: (event: SyncEvent) => void;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* POST /fetch — sync remote-tracking refs for the repository: fetch every
|
|
169
184
|
* remote and prune tracking branches the remotes no longer carry. Pure
|
|
170
185
|
* metadata — the working tree and the current checkout are untouched; the
|
|
171
186
|
* client refetches /status afterwards for the fresh branch list.
|
|
172
187
|
* @param deps - host dependencies.
|
|
173
188
|
* @param body - parsed request body.
|
|
189
|
+
* @param live - the streaming channel (absent = the plain request).
|
|
190
|
+
*/
|
|
191
|
+
export declare function handleFetch(deps: RouteDeps, body: unknown, live?: RouteLive): Promise<RouteOutcome>;
|
|
192
|
+
/**
|
|
193
|
+
* POST /push-plan — read-only destination resolution for one local branch,
|
|
194
|
+
* bundled with a display-only local snapshot of what it would push (see
|
|
195
|
+
* `openPush`). Publishing is a separate explicit POST.
|
|
196
|
+
* @param deps - host dependencies.
|
|
197
|
+
* @param body - parsed request body: `{ repoPath, branch }`.
|
|
198
|
+
*/
|
|
199
|
+
export declare function handlePushPlan(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
200
|
+
/**
|
|
201
|
+
* POST /push — push one explicit local branch to an explicit destination
|
|
202
|
+
* (or, without one, to the confirmation-free default of `planPush`).
|
|
203
|
+
* @param deps - host dependencies.
|
|
204
|
+
* @param body - parsed request body.
|
|
205
|
+
* @param live - the streaming channel (absent = the plain request, which
|
|
206
|
+
* keeps its two-minute cap).
|
|
207
|
+
*/
|
|
208
|
+
export declare function handlePush(deps: RouteDeps, body: unknown, live?: RouteLive): Promise<RouteOutcome>;
|
|
209
|
+
/**
|
|
210
|
+
* POST /push-preview — the commits one explicit remote/target would receive,
|
|
211
|
+
* read from the real push destination (or from local tracking refs with
|
|
212
|
+
* `localOnly`, which never touches the network). Pushes nothing.
|
|
213
|
+
* @param deps - host dependencies.
|
|
214
|
+
* @param body - parsed request body.
|
|
174
215
|
*/
|
|
175
|
-
export declare function
|
|
216
|
+
export declare function handlePushPreview(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
176
217
|
/**
|
|
177
|
-
* POST /update
|
|
218
|
+
* POST /update — update the CURRENT checkout: fetch every remote, then
|
|
178
219
|
* fast-forward the branch checked out by the queried directory to its
|
|
179
220
|
* upstream. Divergence, a missing upstream, and conflicting working-tree
|
|
180
221
|
* changes all surface as 400 envelopes carrying git's own explanation.
|
|
181
222
|
* @param deps - host dependencies.
|
|
182
223
|
* @param body - parsed request body.
|
|
224
|
+
* @param live - the streaming channel (absent = the plain request).
|
|
183
225
|
*/
|
|
184
|
-
export declare function handleUpdate(deps: RouteDeps, body: unknown): Promise<RouteOutcome>;
|
|
226
|
+
export declare function handleUpdate(deps: RouteDeps, body: unknown, live?: RouteLive): Promise<RouteOutcome>;
|
|
185
227
|
/**
|
|
186
228
|
* POST /inspect — pre-delete facts for one worktree directory: the
|
|
187
229
|
* uncommitted-file count (those die with the folder) and the checked-out
|