dsh-devdock 2.5.0 → 3.0.0

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/src/host/git.js DELETED
@@ -1,1664 +0,0 @@
1
- /**
2
- * dsh-push — the git command runner.
3
- *
4
- * WHY THIS IS A STANDALONE MODULE: every function here imports nothing from
5
- * DSH. The plugin's Host half uses it, and a throwaway script can import it
6
- * directly against a temporary repository — which is exactly how this file is
7
- * verified. No cordis, no services, no plugin context.
8
- *
9
- * THE THREE NON-OBVIOUS CHOICES IN THIS FILE:
10
- *
11
- * 1. `LC_ALL=C` + `GIT_OPTIONAL_LOCKS=0` on EVERY child. The first keeps
12
- * stdout AND stderr in a stable, parseable language (the repository's own
13
- * safety refusals are matched as text); the second stops a read-only
14
- * status poll from taking write locks in a repository another process is
15
- * using.
16
- *
17
- * 2. Credentials are injected per invocation via
18
- * `http.extraheader=Authorization: Basic <token>` in the child ENVIRONMENT plus
19
- * `-c credential.helper=` — never written to `.git/config`, never put in a
20
- * shell, and never persisted anywhere. The extraheader works for
21
- * github.com over https; the emptied helper list means git can NEVER fall
22
- * back to an interactive prompt (which would hang a background server).
23
- *
24
- * 3. `GIT_TERMINAL_PROMPT=0` and a hard timeout on every spawn. A network
25
- * operation on a broken egress must fail in seconds with git's own stderr,
26
- * not wedge the plugin until the browser gives up.
27
- *
28
- * @module src/host/git.js
29
- */
30
-
31
- import { spawn } from 'node:child_process';
32
- import { randomBytes } from 'node:crypto';
33
- import { closeSync, openSync, statSync } from 'node:fs';
34
- import { mkdir, readFile, unlink } from 'node:fs/promises';
35
- import { isAbsolute, join, resolve } from 'node:path';
36
- import { tmpdir } from 'node:os';
37
-
38
- /** Cap on a write command's merged stdout+stderr (CONTRACT §3). */
39
- export const MAX_OUTPUT_CHARS = 20_000;
40
- /** Cap on a diff / patch body (CONTRACT §3 `/local/diff`). */
41
- export const MAX_PATCH_CHARS = 200_000;
42
- /** Cap on the file list returned by /local/status (CONTRACT §3). */
43
- export const MAX_STATUS_FILES = 2000;
44
-
45
- /** Default per-command ceiling for local (non-network) git commands. */
46
- const LOCAL_TIMEOUT_MS = 30_000;
47
- /** Ceiling for commands that talk to a remote. Long, but finite. */
48
- const NETWORK_TIMEOUT_MS = 180_000;
49
-
50
- /**
51
- * A full or abbreviated commit object name.
52
- *
53
- * Used to tell "this push source is a commit" (which needs a destination
54
- * refspec) apart from "this push source is a branch or tag" (which git can
55
- * push on its own). An abbreviated sha is 4-40 hex characters; a branch or tag
56
- * that happens to be all hex and at least 4 characters long is ambiguous, but
57
- * git resolves that same ambiguity the same way, and the destination-branch
58
- * requirement only ever adds clarity there.
59
- */
60
- const SHA_RE = /^[0-9a-f]{4,40}$/i;
61
-
62
- /**
63
- * The plugin's own error type.
64
- *
65
- * `code` uses the CONTRACT §0 vocabulary so the route layer can forward it
66
- * unchanged; `output` carries git's raw stderr for GIT_FAILED, which is what
67
- * makes a TLS/proxy/credential failure diagnosable instead of a generic
68
- * "command failed".
69
- */
70
- export class GitError extends Error {
71
- /**
72
- * @param {string} code one of GIT_MISSING, GIT_FAILED, NOT_A_REPO,
73
- * BAD_REQUEST, CONFLICT.
74
- * @param {string} message human-readable Chinese message.
75
- * @param {{output?: string, args?: string[], cause?: unknown}} [details]
76
- */
77
- constructor(code, message, details = {}) {
78
- super(message, details.cause === undefined ? undefined : { cause: details.cause });
79
- this.name = 'GitError';
80
- this.code = code;
81
- /** git's raw stdout/stderr, when the failure came from git itself. */
82
- this.output = details.output ?? '';
83
- /** The argv that failed (never contains a token — see #redact). */
84
- this.args = details.args ?? [];
85
- }
86
- }
87
-
88
- /**
89
- * Redact an Authorization header value out of any text we may return.
90
- *
91
- * git can echo a failed request's headers in some transport errors, so the
92
- * runner scrubs its own output before a caller ever sees it. Callers pass the
93
- * account tokens they know about as `secrets` for exact removal.
94
- *
95
- * @param {string} text
96
- * @param {Iterable<string>} [secrets]
97
- * @returns {string}
98
- */
99
- export function redact(text, secrets = []) {
100
- let out = String(text ?? '');
101
- for (const secret of secrets) {
102
- if (typeof secret === 'string' && secret.length >= 8) out = out.split(secret).join('***');
103
- }
104
- return out
105
- // Mask any auth scheme: Bearer was the old (wrong) one, Basic is current,
106
- // and a future scheme must not silently escape redaction either.
107
- .replace(/(Authorization:\s*\S+\s+)\S+/gi, '$1***')
108
- .replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}\b/g, '***')
109
- .replace(/\bgithub_pat_[A-Za-z0-9_]{20,}\b/g, '***')
110
- // A PEM block is a credential. Keep the BEGIN/END markers (useful for
111
- // diagnosis) and mask everything between them.
112
- .replace(/(-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----)[\s\S]*?(-----END [A-Z0-9 ]*PRIVATE KEY-----)/g, '$1\n***\n$2');
113
- }
114
-
115
- /** Truncate to `max` characters; the caller decides whether to flag it. */
116
- function truncate(text, max) {
117
- const value = String(text ?? '');
118
- return value.length > max ? value.slice(0, max) : value;
119
- }
120
-
121
- /**
122
- * Resolve the git executable to spawn.
123
- *
124
- * A `gitPath` setting may name a full executable or the directory holding one
125
- * (`C:\Program Files\Git\bin`), because a user who needs a different git
126
- * normally has the binary in mind, not its exact filename. An empty setting
127
- * means "whatever PATH resolves".
128
- *
129
- * @param {string} [gitPath]
130
- * @returns {string} the command to spawn.
131
- */
132
- export function resolveGitBinary(gitPath = '') {
133
- const configured = typeof gitPath === 'string' ? gitPath.trim() : '';
134
- if (configured === '') return 'git';
135
- let isDirectory = /[\\/]$/.test(configured);
136
- if (!isDirectory) {
137
- try {
138
- isDirectory = statSync(configured).isDirectory();
139
- } catch {
140
- // A path that does not exist yet is still spawned verbatim: git (or the
141
- // OS) produces the more useful ENOENT message for a typo.
142
- isDirectory = false;
143
- }
144
- }
145
- if (!isDirectory) return configured;
146
- return join(configured, process.platform === 'win32' ? 'git.exe' : 'git');
147
- }
148
-
149
- /**
150
- * Child environment for every git call.
151
- * @returns {NodeJS.ProcessEnv}
152
- */
153
- function baseEnv() {
154
- return {
155
- ...process.env,
156
- GIT_OPTIONAL_LOCKS: '0',
157
- LC_ALL: 'C',
158
- // A background server must never block on a credential prompt.
159
- GIT_TERMINAL_PROMPT: '0',
160
- GCM_INTERACTIVE: 'never',
161
- // A GUI askpass helper is the other way `git push` can try to ASK for a
162
- // credential — and in a headless host it either hangs or pops a window
163
- // nobody asked for. Blanking them makes the refusal immediate and lets the
164
- // error surface as a readable GIT_FAILED instead of a stuck request.
165
- GIT_ASKPASS: '',
166
- SSH_ASKPASS: '',
167
- };
168
- }
169
-
170
- /**
171
- * The username git should use when it has to talk to github.com over https.
172
- *
173
- * WHY A CONSTANT AND NOT THE ACCOUNT LOGIN: `http.extraheader` supplies the
174
- * Authorization header, but git's transport ALSO runs its credential flow
175
- * before/around that header, and with no terminal (this plugin always runs
176
- * `GIT_TERMINAL_PROMPT=0`) that flow can only fail with
177
- * `fatal: could not read Username for 'https://github.com': terminal prompts
178
- * disabled`. Supplying a username removes that failure mode without putting
179
- * anything secret on the command line — GitHub ignores the https username when
180
- * an Authorization header is present, and `x-access-token` is the value GitHub
181
- * documents for exactly this shape.
182
- */
183
- export const GITHUB_HTTPS_USERNAME = 'x-access-token';
184
-
185
- /** Certificate failures, quoted from git's own transport messages. */
186
- const TLS_FAILURE = /server certificate verification failed|SSL certificate problem|self[- ]signed certificate|certificate has expired|certificate verify failed/i;
187
-
188
- /**
189
- * The per-invocation environment that selects a credential for a network
190
- * command, WITHOUT writing anything to disk and WITHOUT touching argv.
191
- *
192
- * `credential.helper=` clears every configured helper for THIS command only,
193
- * so git cannot quietly use (or write) a stored credential; the extraheader is
194
- * then the only credential in play.
195
- *
196
- * `credential.username` is the second half of the fix described on
197
- * {@link GITHUB_HTTPS_USERNAME}: it answers the username half of the credential
198
- * flow from the command line (a public, non-secret literal) so git never has
199
- * to prompt. The PASSWORD half is deliberately NOT configured — the token
200
- * stays inside the Authorization header, never in argv and never in the
201
- * credential stack.
202
- *
203
- * The header uses HTTP BASIC, not Bearer: the git smart-HTTP endpoint rejects
204
- * Bearer with a 401 while the REST API accepts it. Getting this wrong made
205
- * every push fail with "could not read Password".
206
- *
207
- * @param {string|undefined} token the active account's token.
208
- * @param {{username?: string}} [options]
209
- * @returns {Record<string, string>} a CHILD-PROCESS ENVIRONMENT, not an argv
210
- * fragment: the credential travels as GIT_CONFIG_KEY_n / GIT_CONFIG_VALUE_n
211
- * so it never appears in a process command line. Do not "fix" this by
212
- * turning the return value back into `-c` arguments.
213
- */
214
- export function authEnv(token, options = {}) {
215
- const base = { GIT_TERMINAL_PROMPT: '0' };
216
- if (typeof token !== 'string' || token === '') return base;
217
- const username = typeof options.username === 'string' && options.username !== ''
218
- ? options.username
219
- : GITHUB_HTTPS_USERNAME;
220
- // HTTP Basic for the git transport: github.com rejects Bearer here even
221
- // though its REST API accepts it.
222
- const basic = Buffer.from(`${username}:${token}`, 'utf8').toString('base64');
223
- const pairs = [
224
- ['credential.helper', ''],
225
- ['credential.username', username],
226
- ['http.extraheader', `Authorization: Basic ${basic}`],
227
- ];
228
- // git >= 2.31 reads config from the environment. Passing it this way keeps
229
- // the credential OUT of argv: another local account can read a process
230
- // command line, but not its environment, and argv is what ends up in crash
231
- // dumps and audit logs.
232
- const env = { ...base };
233
- env.GIT_CONFIG_COUNT = String(pairs.length);
234
- pairs.forEach(([key, value], index) => {
235
- env[`GIT_CONFIG_KEY_${index}`] = key;
236
- env[`GIT_CONFIG_VALUE_${index}`] = value;
237
- });
238
- return env;
239
- }
240
-
241
- /**
242
- * Whether a remote URL points at github.com.
243
- * @param {string} url
244
- * @returns {boolean}
245
- */
246
- export function isGithubUrl(url) {
247
- return /^(?:https?:\/\/(?:[^@/]+@)?(?:www\.)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)/i.test(String(url ?? ''));
248
- }
249
-
250
- /**
251
- * Extract `{owner, repo}` from a GitHub https/ssh remote URL.
252
- *
253
- * Only used for display and for "open this repo's page" links; an unparseable
254
- * URL simply yields `null` rather than failing the whole status response.
255
- *
256
- * @param {string} url
257
- * @returns {{owner: string, repo: string}|null}
258
- */
259
- export function parseGithubRemote(url) {
260
- const value = String(url ?? '').trim();
261
- const match = /github\.com[/:]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/i.exec(value);
262
- if (!match) return null;
263
- const owner = match[1];
264
- const repo = match[2];
265
- if (!owner || !repo) return null;
266
- return { owner, repo };
267
- }
268
-
269
- /**
270
- * Build the HTTPS push URL for a GitHub repository the clone has no remote for
271
- * (CONTRACT §3b `target`).
272
- *
273
- * The URL carries NO credential: the token travels only as the per-invocation
274
- * `http.extraheader` (see {@link authEnv}), so it can never be read back
275
- * from `.git/config`, from argv, or from git's own error output. The literal
276
- * `x-access-token` is a public, documented placeholder.
277
- *
278
- * @param {string} owner
279
- * @param {string} repo
280
- * @returns {string} `https://github.com/<owner>/<repo>.git`
281
- */
282
- export function githubPushUrl(owner, repo) {
283
- const cleanOwner = String(owner ?? '').trim();
284
- const cleanRepo = String(repo ?? '').trim().replace(/\.git$/i, '');
285
- // The route layer already rejects empty values, but this function is exported
286
- // and `https://github.com//.git` is a URL nobody should ever be handed.
287
- if (cleanOwner === '' || cleanRepo === '') {
288
- throw new GitError('BAD_REQUEST', '推送目标必须是 owner/repo 两段,缺少 owner 或仓库名');
289
- }
290
- const safeOwner = encodeURIComponent(cleanOwner);
291
- const safeRepo = encodeURIComponent(cleanRepo);
292
- return `https://github.com/${safeOwner}/${safeRepo}.git`;
293
- }
294
-
295
- /**
296
- * Parse git's `## ...` branch header from `status --porcelain=v1 -z --branch`.
297
- *
298
- * Real shapes this must survive (all observed from git 2.54 on Windows):
299
- * `## main...origin/main [ahead 2, behind 1]`
300
- * `## main...origin/main [gone]`
301
- * `## main`
302
- * `## HEAD (no branch)` → detached
303
- * `## No commits yet on main` → unborn branch
304
- *
305
- * @param {string} header the first NUL-delimited token, header included.
306
- * @returns {{branch: string|null, upstream: string|null, ahead: number,
307
- * behind: number, detachedHead: boolean}}
308
- */
309
- export function parseBranchHeader(header) {
310
- const result = { branch: null, upstream: null, ahead: 0, behind: 0, detachedHead: false };
311
- const text = String(header ?? '').replace(/^##\s*/, '').trim();
312
- if (text === '') return result;
313
- if (/^HEAD\s*\(no branch\)$/i.test(text)) {
314
- result.detachedHead = true;
315
- return result;
316
- }
317
- const unborn = /^(?:No commits yet|Initial commit) on (.+)$/i.exec(text);
318
- if (unborn) {
319
- result.branch = unborn[1].trim();
320
- return result;
321
- }
322
- const [left, right] = text.split('...');
323
- result.branch = (left ?? '').trim() || null;
324
- if (right !== undefined) {
325
- const flags = /\[([^\]]*)\]\s*$/.exec(right);
326
- result.upstream = right.replace(/\s*\[[^\]]*\]\s*$/, '').trim() || null;
327
- if (flags) {
328
- const ahead = /ahead (\d+)/.exec(flags[1]);
329
- const behind = /behind (\d+)/.exec(flags[1]);
330
- result.ahead = ahead ? Number(ahead[1]) : 0;
331
- result.behind = behind ? Number(behind[1]) : 0;
332
- }
333
- }
334
- return result;
335
- }
336
-
337
- /** Two-letter porcelain codes that mean "this path has a merge conflict". */
338
- const CONFLICT_CODES = new Set(['DD', 'AU', 'UD', 'UA', 'DU', 'AA', 'UU']);
339
-
340
- /**
341
- * Parse `git status --porcelain=v1 -z --untracked-files=all --branch`.
342
- *
343
- * -z framing is why renames work at all: a rename emits `R <new>\0<old>\0`,
344
- * i.e. the ORIGINAL path is a bare extra token with no `XY` prefix, so the
345
- * parser consumes it explicitly instead of mistaking it for the next entry.
346
- *
347
- * @param {string} raw git's stdout (contains NUL bytes).
348
- * @returns {{header: object, files: object[], dirty: object}}
349
- */
350
- export function parseStatusPorcelainZ(raw) {
351
- const tokens = String(raw ?? '').split('\0');
352
- let header = { branch: null, upstream: null, ahead: 0, behind: 0, detachedHead: false };
353
- const files = [];
354
- const dirty = { changed: 0, staged: 0, untracked: 0, conflicted: 0 };
355
- let index = 0;
356
- // The branch header is always the first record when --branch is passed.
357
- if (tokens.length > 0 && tokens[0].startsWith('##')) {
358
- header = parseBranchHeader(tokens[0]);
359
- index = 1;
360
- }
361
- for (; index < tokens.length; index += 1) {
362
- const entry = tokens[index];
363
- if (entry === '') continue;
364
- if (entry.startsWith('##')) {
365
- header = parseBranchHeader(entry);
366
- continue;
367
- }
368
- if (entry.length < 3) continue;
369
- const indexStatus = entry[0];
370
- const worktreeStatus = entry[1];
371
- let path = entry.slice(3);
372
- const untracked = indexStatus === '?' && worktreeStatus === '?';
373
- // Rename/copy: the source path is the NEXT NUL token (already unquoted
374
- // because -z disables core.quotePath escaping).
375
- if (indexStatus === 'R' || indexStatus === 'C') {
376
- const source = tokens[index + 1];
377
- if (source !== undefined && source !== '') index += 1;
378
- }
379
- const conflicted = CONFLICT_CODES.has(`${indexStatus}${worktreeStatus}`);
380
- const staged = !untracked && indexStatus !== ' ' && indexStatus !== '?';
381
- // Each path is counted EXACTLY ONCE, in the same bucket the UI groups it
382
- // into (conflict → untracked → staged → unstaged). Counting a fully staged
383
- // file in `changed` too made the panel report "未暂存 1" for a tree whose
384
- // unstaged group was empty, and the two numbers stopped adding up to the
385
- // row count. Per-file detail (the `files` entries below) still carries both
386
- // index and worktree codes, so "staged and edited again" stays visible.
387
- if (untracked) dirty.untracked += 1;
388
- else if (conflicted) dirty.conflicted += 1;
389
- else if (staged) dirty.staged += 1;
390
- else dirty.changed += 1;
391
- if (files.length < MAX_STATUS_FILES) {
392
- files.push({ path, index: indexStatus, worktree: worktreeStatus, staged, untracked, conflicted });
393
- }
394
- }
395
- return { header, files, dirty };
396
- }
397
-
398
- /**
399
- * Parse `git log --pretty=format:%H%x1f%h%x1f%P%x1f%an%x1f%ae%x1f%aI%x1f%s%x1f%D`
400
- * rows. `\x1f` (unit separator) is used because a subject may contain any
401
- * printable character, including tabs and pipes.
402
- *
403
- * @param {string} raw
404
- * @returns {object[]} commits WITHOUT lanes.
405
- */
406
- export function parseLogRows(raw) {
407
- const commits = [];
408
- for (const line of String(raw ?? '').split('\n')) {
409
- if (line === '') continue;
410
- const fields = line.split('\x1f');
411
- if (fields.length < 8) continue;
412
- const [sha, shortSha, parents, author, authorEmail, date, subject, refs] = fields;
413
- commits.push({
414
- sha,
415
- shortSha,
416
- parents: parents.split(' ').filter(Boolean),
417
- author,
418
- authorEmail,
419
- date,
420
- subject,
421
- refs: refs.split(',').map((r) => r.trim()).filter(Boolean),
422
- });
423
- }
424
- return commits;
425
- }
426
-
427
- /**
428
- * Assign a graph lane to every commit in a `git log --topo-order` window.
429
- *
430
- * THE ALGORITHM (deterministic and stateless — same input, same lanes):
431
- * `lanes[i]` holds the commit sha lane `i` is currently waiting for. Walking
432
- * the topological (newest-first) order, each commit claims the lane already
433
- * waiting for it, or the first free lane. Its first parent inherits that lane;
434
- * each extra parent (a merge) claims another lane. Lanes that were waiting for
435
- * the same sha are closed when the commit arrives, and trailing free lanes are
436
- * trimmed so indices stay dense.
437
- *
438
- * WHY THE HOST DOES THIS: a client that computed lanes would have to re-derive
439
- * the same walk in a second place, and the sidebar draws a fixed 60-commit
440
- * window — the lanes are only stable relative to that window, which only the
441
- * Host knows.
442
- *
443
- * @param {object[]} commits topologically ordered, newest first.
444
- * @returns {object[]} the same commits with a numeric `lane`.
445
- */
446
- export function assignLanes(commits) {
447
- /** @type {Array<string|null>} */
448
- const lanes = [];
449
- const out = [];
450
- const freeLane = () => {
451
- const free = lanes.indexOf(null);
452
- return free === -1 ? lanes.length : free;
453
- };
454
- for (const commit of commits) {
455
- let lane = lanes.indexOf(commit.sha);
456
- if (lane === -1) lane = freeLane();
457
- // This commit fulfils every lane that was waiting for it (a merge base can
458
- // be awaited by two lanes); only the owning lane continues from here.
459
- for (let at = 0; at < lanes.length; at += 1) {
460
- if (at !== lane && lanes[at] === commit.sha) lanes[at] = null;
461
- }
462
- const [firstParent, ...otherParents] = commit.parents;
463
- lanes[lane] = firstParent ?? null;
464
- for (const parent of otherParents) {
465
- if (parent === undefined) continue;
466
- if (lanes.includes(parent)) continue;
467
- lanes[freeLane()] = parent;
468
- }
469
- while (lanes.length > 0 && lanes[lanes.length - 1] === null) lanes.pop();
470
- out.push({ ...commit, lane });
471
- }
472
- return out;
473
- }
474
-
475
- /**
476
- * Parse `git remote -v` into one row per remote name.
477
- *
478
- * The real line shape is `origin\thttps://github.com/o/r.git (fetch)` — the
479
- * `(fetch)`/`(push)` marker is appended to the URL after a SPACE, not as a
480
- * third tab-separated column, so it must be stripped from the URL rather than
481
- * read as a separate field. Only the fetch row is kept (they are identical for
482
- * the remote's identity), matching the contract's one-row-per-remote shape.
483
- *
484
- * @param {string} stdout
485
- * @returns {{name: string, url: string}[]}
486
- */
487
- export function parseRemotes(stdout) {
488
- const remotes = [];
489
- const seen = new Set();
490
- for (const line of String(stdout ?? '').split('\n')) {
491
- if (line.trim() === '') continue;
492
- const match = /^(\S+)\t(.+?)(?:\s+\((fetch|push)\))?\s*$/.exec(line);
493
- if (!match) continue;
494
- const name = match[1];
495
- const url = match[2].trim();
496
- if (name === '' || url === '' || seen.has(name)) continue;
497
- seen.add(name);
498
- remotes.push({ name, url });
499
- }
500
- return remotes;
501
- }
502
-
503
- /**
504
- * Parse `git show --numstat --format= -z` output.
505
- *
506
- * -z framing nests the rename pair: `0\t0\t\0<old>\0<new>\0`. A record whose
507
- * path column is empty therefore consumes the following two tokens.
508
- *
509
- * @param {string} raw
510
- * @returns {{path: string, additions: number, deletions: number}[]}
511
- */
512
- export function parseNumstatZ(raw) {
513
- const tokens = String(raw ?? '').split('\0');
514
- const files = [];
515
- for (let index = 0; index < tokens.length; index += 1) {
516
- const record = tokens[index];
517
- if (record === '') continue;
518
- const match = /^(-|\d+)\t(-|\d+)\t(.*)$/s.exec(record);
519
- if (!match) continue;
520
- let path = match[3];
521
- if (path === '') {
522
- const from = tokens[index + 1] ?? '';
523
- const to = tokens[index + 2] ?? '';
524
- index += 2;
525
- path = to !== '' ? to : from;
526
- }
527
- if (path === '') continue;
528
- files.push({
529
- path,
530
- additions: match[1] === '-' ? 0 : Number(match[1]),
531
- deletions: match[2] === '-' ? 0 : Number(match[2]),
532
- });
533
- }
534
- return files;
535
- }
536
-
537
- /**
538
- * A thin, reusable git runner bound to one `gitPath` setting.
539
- *
540
- * Instances are cheap and stateless; the plugin creates one per request-ish
541
- * (it reads the live settings) so a `gitPath` change takes effect without a
542
- * restart.
543
- */
544
- export class GitRunner {
545
- /** @type {string} the binary this runner spawns. */
546
- #binary;
547
- /** @type {number} default local timeout. */
548
- #timeoutMs;
549
-
550
- /**
551
- * @param {{gitPath?: string, timeoutMs?: number}} [options]
552
- */
553
- constructor(options = {}) {
554
- this.#binary = resolveGitBinary(options.gitPath ?? '');
555
- this.#timeoutMs = Number.isFinite(options.timeoutMs) ? Number(options.timeoutMs) : LOCAL_TIMEOUT_MS;
556
- }
557
-
558
- /** The resolved git command (diagnostics only). */
559
- get binary() {
560
- return this.#binary;
561
- }
562
-
563
- /**
564
- * Spawn one git command.
565
- *
566
- * @param {string[]} args arguments AFTER the global options.
567
- * @param {object} [options]
568
- * @param {string} [options.cwd] working directory (must exist).
569
- * @param {number} [options.timeoutMs]
570
- * @param {string[]} [options.config] flattened `-c key=value` pairs.
571
- * @param {Record<string,string>} [options.env] extra environment entries.
572
- * @param {boolean} [options.allowFailure] resolve instead of throwing on a
573
- * non-zero exit (the caller inspects `code`).
574
- * @param {Iterable<string>} [options.secrets] tokens to redact from output.
575
- * @returns {Promise<{stdout: string, stderr: string, code: number}>}
576
- */
577
- async run(args, options = {}) {
578
- const cwd = options.cwd ?? process.cwd();
579
- const timeoutMs = options.timeoutMs ?? this.#timeoutMs;
580
- const first = await this.#spawn(args, { ...options, cwd, timeoutMs });
581
- if (first.code === 0 || options.allowFailure) return first;
582
- // CVE-2022-24765: git refuses a repository owned by another user. The
583
- // refusal names the directory, so trusting exactly that directory for THIS
584
- // invocation (never `*`, never a config file) is the narrow answer.
585
- if (!/dubious ownership/i.test(first.stderr)) return first;
586
- const refused = /detected dubious ownership in repository at '([^']*)'/.exec(first.stderr)?.[1];
587
- const trusted = refused && refused !== '' ? [refused, cwd] : [cwd];
588
- const safeConfig = [...(options.config ?? [])];
589
- for (const dir of trusted) safeConfig.push('-c', `safe.directory=${dir}`);
590
- return await this.#spawn(args, { ...options, cwd, timeoutMs, config: safeConfig });
591
- }
592
-
593
- /**
594
- * Spawn-once primitive. Split from {@link run} so the safe.directory retry
595
- * re-spawns with the SAME framing and only an extra `-c`.
596
- *
597
- * TWO CAPTURE STRATEGIES. The normal one pipes stdout/stderr into listeners.
598
- * A sandboxed/restricted child-process environment can refuse to create those
599
- * pipes (`spawn EPERM`, which is what DSH's own Windows sandbox does to any
600
- * piped stdio); there the command is re-run with its streams redirected to
601
- * temp FILES and the files are read afterwards. That fallback is not just
602
- * test scaffolding: it is the difference between "this panel cannot show git
603
- * state at all" and "this panel works" on such a host. Output limits are
604
- * enforced by STATING the spool files, so the fallback cannot buffer more
605
- * than the pipe path would.
606
- * @private
607
- */
608
- #spawn(args, options) {
609
- return this.#spawnPiped(args, options).catch(async (error) => {
610
- if (error?.cause?.code !== 'EPERM' && error?.code !== 'EPERM') throw error;
611
- return await this.#spawnToFiles(args, options);
612
- });
613
- }
614
-
615
- /**
616
- * Assemble the argv: every global option that must precede the subcommand.
617
- * @private
618
- */
619
- #argv(args, options) {
620
- const cwd = options.cwd ?? process.cwd();
621
- return [
622
- '-C', cwd,
623
- '--no-pager',
624
- '-c', 'color.ui=false',
625
- // Chinese (and any non-ASCII) paths must come back as UTF-8, not as
626
- // `\u4e2d` escape sequences.
627
- '-c', 'core.quotePath=false',
628
- ...(process.platform === 'win32' ? ['--no-optional-locks'] : []),
629
- ...(options.config ?? []),
630
- ...args,
631
- ];
632
- }
633
-
634
- /**
635
- * The normal capture path: piped stdout/stderr.
636
- * @private
637
- */
638
- #spawnPiped(args, options) {
639
- const cwd = options.cwd ?? process.cwd();
640
- const timeoutMs = options.timeoutMs ?? this.#timeoutMs;
641
- const secrets = options.secrets ?? [];
642
- const argv = this.#argv(args, options);
643
- return new Promise((resolvePromise, reject) => {
644
- let child;
645
- try {
646
- child = spawn(this.#binary, argv, {
647
- cwd,
648
- windowsHide: true,
649
- stdio: ['ignore', 'pipe', 'pipe'],
650
- env: { ...baseEnv(), ...(options.env ?? {}) },
651
- });
652
- } catch (error) {
653
- reject(new GitError('GIT_MISSING', `无法启动 git(${this.#binary}):${error.message}`, { args: argv, cause: error }));
654
- return;
655
- }
656
- let stdout = '';
657
- let stderr = '';
658
- let settled = false;
659
- const finish = (fn, value) => {
660
- if (settled) return;
661
- settled = true;
662
- clearTimeout(timer);
663
- fn(value);
664
- };
665
- const timer = setTimeout(() => {
666
- try {
667
- child.kill('SIGKILL');
668
- } catch {
669
- // already gone
670
- }
671
- finish(reject, new GitError(
672
- 'GIT_FAILED',
673
- `git ${args[0] ?? ''} 超时(${timeoutMs}ms)已终止`,
674
- { output: redact(`${stdout}${stderr}`, secrets), args: argv },
675
- ));
676
- }, timeoutMs);
677
- child.stdout?.on('data', (chunk) => {
678
- stdout += chunk.toString('utf8');
679
- });
680
- child.stderr?.on('data', (chunk) => {
681
- stderr += chunk.toString('utf8');
682
- });
683
- child.on('error', (error) => {
684
- const missing = error?.code === 'ENOENT';
685
- finish(reject, new GitError(
686
- missing ? 'GIT_MISSING' : 'GIT_FAILED',
687
- missing
688
- ? `找不到 git 可执行文件(${this.#binary})。请安装 Git,或在插件设置里填写正确的「git 路径」。`
689
- : `无法运行 git(${this.#binary}):${error.message}`,
690
- { args: argv, cause: error },
691
- ));
692
- });
693
- child.on('close', (code) => {
694
- finish(resolvePromise, {
695
- stdout: redact(stdout, secrets),
696
- stderr: redact(stderr, secrets),
697
- code: typeof code === 'number' ? code : 1,
698
- });
699
- });
700
- });
701
- }
702
-
703
- /**
704
- * The restricted-host capture path: redirect both streams to spool files.
705
- *
706
- * Spool files are opened with `0o600` and removed in a `finally`, so no git
707
- * output (which can name private repository paths) is left behind.
708
- * @private
709
- */
710
- async #spawnToFiles(args, options) {
711
- const cwd = options.cwd ?? process.cwd();
712
- const timeoutMs = options.timeoutMs ?? this.#timeoutMs;
713
- const secrets = options.secrets ?? [];
714
- const argv = this.#argv(args, options);
715
- const token = randomBytes(8).toString('hex');
716
- const outPath = join(tmpdir(), `dsh-push-${token}.out`);
717
- const errPath = join(tmpdir(), `dsh-push-${token}.err`);
718
- let outFd;
719
- let errFd;
720
- try {
721
- outFd = openSync(outPath, 'w', 0o600);
722
- errFd = openSync(errPath, 'w', 0o600);
723
- } catch (error) {
724
- if (outFd !== undefined) closeSync(outFd);
725
- throw new GitError('GIT_FAILED', `无法创建 git 输出临时文件:${error.message}`, { args: argv, cause: error });
726
- }
727
- try {
728
- const code = await new Promise((resolvePromise, reject) => {
729
- let child;
730
- try {
731
- child = spawn(this.#binary, argv, {
732
- cwd,
733
- windowsHide: true,
734
- stdio: ['ignore', outFd, errFd],
735
- env: { ...baseEnv(), ...(options.env ?? {}) },
736
- });
737
- } catch (error) {
738
- reject(new GitError('GIT_MISSING', `无法启动 git(${this.#binary}):${error.message}`, { args: argv, cause: error }));
739
- return;
740
- }
741
- let settled = false;
742
- const finish = (fn, value) => {
743
- if (settled) return;
744
- settled = true;
745
- clearTimeout(timer);
746
- fn(value);
747
- };
748
- const timer = setTimeout(() => {
749
- try {
750
- child.kill('SIGKILL');
751
- } catch {
752
- // already gone
753
- }
754
- finish(reject, new GitError(
755
- 'GIT_FAILED',
756
- `git ${args[0] ?? ''} 超时(${timeoutMs}ms)已终止`,
757
- { args: argv },
758
- ));
759
- }, timeoutMs);
760
- child.on('error', (error) => {
761
- const missing = error?.code === 'ENOENT';
762
- finish(reject, new GitError(
763
- missing ? 'GIT_MISSING' : 'GIT_FAILED',
764
- missing
765
- ? `找不到 git 可执行文件(${this.#binary})。请安装 Git,或在插件设置里填写正确的「git 路径」。`
766
- : `无法运行 git(${this.#binary}):${error.message}`,
767
- { args: argv, cause: error },
768
- ));
769
- });
770
- child.on('close', (exitCode) => {
771
- finish(resolvePromise, typeof exitCode === 'number' ? exitCode : 1);
772
- });
773
- });
774
- const stdout = await readFile(outPath, 'utf8').catch(() => '');
775
- const stderr = await readFile(errPath, 'utf8').catch(() => '');
776
- return { stdout: redact(stdout, secrets), stderr: redact(stderr, secrets), code };
777
- } finally {
778
- try {
779
- closeSync(outFd);
780
- } catch {
781
- // already closed
782
- }
783
- try {
784
- closeSync(errFd);
785
- } catch {
786
- // already closed
787
- }
788
- await unlink(outPath).catch(() => {});
789
- await unlink(errPath).catch(() => {});
790
- }
791
- }
792
-
793
- /**
794
- * Run a command and reject with GIT_FAILED (carrying git's raw stderr) when
795
- * it exits non-zero.
796
- *
797
- * @param {string[]} args
798
- * @param {object} [options] see {@link run}; `label` names the operation in
799
- * the Chinese error message.
800
- * @returns {Promise<string>} stdout.
801
- */
802
- async must(args, options = {}) {
803
- const result = await this.run(args, options);
804
- if (result.code !== 0) {
805
- const output = `${result.stdout}${result.stderr}`.trim();
806
- throw new GitError(
807
- 'GIT_FAILED',
808
- `git ${options.label ?? args[0] ?? ''} 失败:${output !== '' ? output : `退出码 ${result.code}`}`,
809
- { output, args },
810
- );
811
- }
812
- return result.stdout;
813
- }
814
-
815
- /**
816
- * `git --version`, or `null` when git cannot run at all.
817
- * @returns {Promise<string|null>} e.g. `2.54.0.windows.1`.
818
- */
819
- async version() {
820
- try {
821
- const out = await this.run(['--version'], { timeoutMs: 10_000, allowFailure: true });
822
- if (out.code !== 0) return null;
823
- return /git version (\S+)/.exec(out.stdout.trim())?.[1] ?? out.stdout.trim() ?? null;
824
- } catch {
825
- return null;
826
- }
827
- }
828
-
829
- /**
830
- * Whether this machine has a runnable git.
831
- * @returns {Promise<{available: boolean, version: string|null}>}
832
- */
833
- async probe() {
834
- const version = await this.version();
835
- return { available: version !== null, version };
836
- }
837
-
838
- /**
839
- * Resolve a directory's repository root, or `null` when it is not inside a
840
- * git work tree.
841
- *
842
- * @param {string} path absolute (or resolvable) directory.
843
- * @param {{timeoutMs?: number, secrets?: Iterable<string>}} [options]
844
- * @returns {Promise<{root: string, gitDir: string}|null>}
845
- */
846
- async resolveRoot(path, options = {}) {
847
- const cwd = resolve(String(path ?? ''));
848
- // A missing working directory makes Node report `spawn ENOENT`, which is
849
- // indistinguishable from a missing git binary. Checking the directory first
850
- // keeps the two failures apart: a bad path is NOT_A_REPO, a bad gitPath is
851
- // GIT_MISSING, and the user is told to fix the right one.
852
- if (!isDirectory(cwd)) return null;
853
- const top = await this.run(['rev-parse', '--show-toplevel'], {
854
- cwd,
855
- timeoutMs: options.timeoutMs ?? 10_000,
856
- allowFailure: true,
857
- secrets: options.secrets,
858
- });
859
- if (top.code !== 0) return null;
860
- const root = top.stdout.trim();
861
- if (root === '') return null;
862
- const dir = await this.run(['rev-parse', '--absolute-git-dir'], {
863
- cwd,
864
- timeoutMs: options.timeoutMs ?? 10_000,
865
- allowFailure: true,
866
- secrets: options.secrets,
867
- });
868
- const gitDir = dir.code === 0 ? dir.stdout.trim() : '';
869
- return {
870
- // git prints forward slashes even on Windows; `resolve` restores the
871
- // platform's own separators so the value matches the cwd the client
872
- // already holds.
873
- root: resolve(root),
874
- gitDir: gitDir !== '' ? resolve(gitDir) : '',
875
- };
876
- }
877
-
878
- /**
879
- * Assert `path` is a directory inside a git work tree.
880
- *
881
- * EVERY mutating command goes through this: the contract requires an
882
- * absolute path whose toplevel has been verified before git is allowed to
883
- * change anything.
884
- *
885
- * @param {string} path
886
- * @param {object} [options]
887
- * @returns {Promise<{root: string, gitDir: string}>}
888
- * @throws {GitError} BAD_REQUEST for a relative/empty path, NOT_A_REPO when
889
- * the directory is not a repository.
890
- */
891
- async assertRepo(path, options = {}) {
892
- const raw = typeof path === 'string' ? path.trim() : '';
893
- if (raw === '') throw new GitError('BAD_REQUEST', '缺少仓库路径');
894
- if (!isAbsolute(raw)) {
895
- throw new GitError('BAD_REQUEST', `仓库路径必须是绝对路径:${raw}`);
896
- }
897
- const resolvedRoot = await this.resolveRoot(raw, options);
898
- if (!resolvedRoot) {
899
- throw new GitError('NOT_A_REPO', `${raw} 不是 Git 仓库(或不是仓库工作区内的目录)`);
900
- }
901
- return resolvedRoot;
902
- }
903
-
904
- /**
905
- * Read the full local status document of CONTRACT §3.
906
- *
907
- * @param {string} path
908
- * @param {{defaultRemote?: string, secrets?: Iterable<string>}} [options]
909
- * @returns {Promise<object>}
910
- */
911
- async status(path, options = {}) {
912
- const root = await this.assertRepo(path, options);
913
- const secrets = options.secrets;
914
- const [statusOut, remoteOut, tagOut, branchOut, stashOut, headOut] = await Promise.all([
915
- this.must(['status', '--porcelain=v1', '-z', '--untracked-files=all', '--branch'], {
916
- cwd: root.root, label: 'status', secrets,
917
- }),
918
- this.run(['remote', '-v'], { cwd: root.root, label: 'remote', allowFailure: true, secrets }),
919
- this.run(['tag', '--list'], { cwd: root.root, label: 'tag', allowFailure: true, secrets }),
920
- this.run(['for-each-ref', '--format=%(refname:short)', 'refs/heads'], {
921
- cwd: root.root, label: 'for-each-ref', allowFailure: true, secrets,
922
- }),
923
- this.run(['stash', 'list', '--format=%gd%x09%s'], {
924
- cwd: root.root, label: 'stash', allowFailure: true, secrets,
925
- }),
926
- this.run(['log', '-1', '--date=iso-strict', '--pretty=format:%H%x1f%h%x1f%s%x1f%an%x1f%aI'], {
927
- cwd: root.root, label: 'log', allowFailure: true, secrets,
928
- }),
929
- ]);
930
-
931
- const parsed = parseStatusPorcelainZ(statusOut);
932
- const remotes = parseRemotes(remoteOut.stdout);
933
-
934
- const githubRemote = pickGithubRemote(remotes, options.defaultRemote);
935
-
936
- const tags = tagOut.stdout.split('\n').map((t) => t.trim()).filter(Boolean);
937
- const branches = branchOut.stdout.split('\n').map((b) => b.trim()).filter(Boolean);
938
- const stashes = [];
939
- for (const line of stashOut.stdout.split('\n')) {
940
- if (line.trim() === '') continue;
941
- const [ref, message] = line.split('\t');
942
- const index = Number(/stash@\{(\d+)\}/.exec(ref ?? '')?.[1]);
943
- stashes.push({ index: Number.isFinite(index) ? index : stashes.length, message: message ?? '' });
944
- }
945
-
946
- let head = null;
947
- if (headOut.code === 0 && headOut.stdout.trim() !== '') {
948
- const [sha, shortSha, subject, author, date] = headOut.stdout.split('\x1f');
949
- if (sha) head = { sha, shortSha, subject, author, date };
950
- }
951
-
952
- return {
953
- isRepo: true,
954
- root: root.root,
955
- gitDir: root.gitDir || null,
956
- branch: parsed.header.branch,
957
- detachedHead: parsed.header.detachedHead,
958
- upstream: parsed.header.upstream,
959
- ahead: parsed.header.ahead,
960
- behind: parsed.header.behind,
961
- remotes,
962
- githubRemote,
963
- head,
964
- dirty: parsed.dirty,
965
- files: parsed.files,
966
- tags,
967
- branches,
968
- stashes,
969
- };
970
- }
971
-
972
- /**
973
- * Read a window of commits with lanes computed (CONTRACT §3 `Commit`).
974
- *
975
- * `--topo-order` is what makes the lane walk meaningful: parents always
976
- * appear after their children, so no lane is ever assigned to a commit whose
977
- * history has already been drawn.
978
- *
979
- * @param {string} path
980
- * @param {{limit?: number, ref?: string, secrets?: Iterable<string>}} [options]
981
- * @returns {Promise<{commits: object[], hasMore: boolean}>}
982
- */
983
- async log(path, options = {}) {
984
- const root = await this.assertRepo(path, options);
985
- const limit = clampInt(options.limit, 1, 500, 60);
986
- const ref = typeof options.ref === 'string' && options.ref.trim() !== '' ? options.ref.trim() : 'HEAD';
987
- const out = await this.run([
988
- 'log',
989
- '--topo-order',
990
- '--date=iso-strict',
991
- `-n`, String(limit + 1),
992
- '--pretty=format:%H%x1f%h%x1f%P%x1f%an%x1f%ae%x1f%aI%x1f%s%x1f%D',
993
- ref,
994
- '--',
995
- ], { cwd: root.root, label: 'log', allowFailure: true, secrets: options.secrets });
996
-
997
- // An unborn branch (`git log` on a repo with no commits) exits non-zero;
998
- // that is an empty history, not an error.
999
- if (out.code !== 0) return { commits: [], hasMore: false };
1000
- const rows = parseLogRows(out.stdout);
1001
- const hasMore = rows.length > limit;
1002
- const window = hasMore ? rows.slice(0, limit) : rows;
1003
- return { commits: assignLanes(window), hasMore };
1004
- }
1005
-
1006
- /**
1007
- * `git diff` for one file, truncated per CONTRACT §3.
1008
- *
1009
- * @param {string} path
1010
- * @param {{file: string, staged?: boolean, secrets?: Iterable<string>}} options
1011
- * @returns {Promise<{file: string, patch: string, truncated: boolean}>}
1012
- */
1013
- async diff(path, options) {
1014
- const root = await this.assertRepo(path, options);
1015
- const file = typeof options.file === 'string' ? options.file.trim() : '';
1016
- if (file === '') throw new GitError('BAD_REQUEST', '缺少文件路径');
1017
- const args = ['diff', '--no-color'];
1018
- if (options.staged === true) args.push('--cached');
1019
- args.push('--', file);
1020
- const out = await this.run(args, { cwd: root.root, label: 'diff', allowFailure: true, secrets: options.secrets });
1021
- const patch = out.stdout;
1022
- if (out.code !== 0) {
1023
- throw new GitError('GIT_FAILED', `git diff 失败:${`${out.stdout}${out.stderr}`.trim()}`, { output: out.stderr });
1024
- }
1025
- return {
1026
- file,
1027
- patch: truncate(patch, MAX_PATCH_CHARS),
1028
- truncated: patch.length > MAX_PATCH_CHARS,
1029
- };
1030
- }
1031
-
1032
- /**
1033
- * One commit in detail: metadata, per-file line counts and the patch.
1034
- *
1035
- * @param {string} path
1036
- * @param {{sha: string, secrets?: Iterable<string>}} options
1037
- * @returns {Promise<object>}
1038
- */
1039
- async commitDetail(path, options) {
1040
- const root = await this.assertRepo(path, options);
1041
- const sha = typeof options.sha === 'string' ? options.sha.trim() : '';
1042
- if (sha === '') throw new GitError('BAD_REQUEST', '缺少提交 SHA');
1043
- const meta = await this.run(['log', '-1', '--date=iso-strict', '--pretty=format:%H%x1f%s%x1f%b%x1f%an%x1f%aI', sha], {
1044
- cwd: root.root, label: 'log', allowFailure: true, secrets: options.secrets,
1045
- });
1046
- if (meta.code !== 0) {
1047
- throw new GitError('NOT_FOUND', `找不到提交 ${sha}`, { output: meta.stderr });
1048
- }
1049
- const [resolvedSha, subject, body, author, date] = meta.stdout.split('\x1f');
1050
- // `-m --first-parent` matters for MERGE commits: plain `git show` prints no
1051
- // diff at all for a merge, so a merge row in the graph would open an empty
1052
- // detail panel. Diffing against the first parent is what the user expects
1053
- // to see ("what did this merge bring into my branch"), and for an ordinary
1054
- // commit the flags change nothing.
1055
- const [numstat, patch] = await Promise.all([
1056
- this.run(['show', '--numstat', '--format=', '-z', '-m', '--first-parent', sha], {
1057
- cwd: root.root, label: 'show', allowFailure: true, secrets: options.secrets,
1058
- }),
1059
- this.run(['show', '--format=', '--patch', '--no-color', '-m', '--first-parent', sha], {
1060
- cwd: root.root, label: 'show', allowFailure: true, secrets: options.secrets,
1061
- }),
1062
- ]);
1063
- const patchText = patch.stdout;
1064
- return {
1065
- sha: resolvedSha ?? sha,
1066
- subject: subject ?? '',
1067
- body: (body ?? '').trim(),
1068
- author: author ?? '',
1069
- date: date ?? '',
1070
- files: parseNumstatZ(numstat.stdout),
1071
- patch: truncate(patchText, MAX_PATCH_CHARS),
1072
- };
1073
- }
1074
-
1075
- /**
1076
- * The branch HEAD points at, or `null` for a detached HEAD.
1077
- *
1078
- * `symbolic-ref` also answers for an UNBORN branch (a repository whose first
1079
- * commit has not been made yet), where `git status --branch` reports
1080
- * "No commits yet on main" instead. The push-target picker needs that case:
1081
- * the very first push of a new repository must still be remembered per
1082
- * branch.
1083
- *
1084
- * @param {string} path
1085
- * @param {{secrets?: Iterable<string>, root?: string}} [options] `root` skips
1086
- * the (three-spawn) repository probe when the caller already has it.
1087
- * @returns {Promise<string|null>}
1088
- */
1089
- async currentBranch(path, options = {}) {
1090
- const root = nonEmpty(options.root) ?? (await this.assertRepo(path, options)).root;
1091
- const out = await this.run(['symbolic-ref', '--short', '-q', 'HEAD'], {
1092
- cwd: root, label: 'symbolic-ref', allowFailure: true, secrets: options.secrets,
1093
- });
1094
- // A detached HEAD makes git exit 1 with no output.
1095
- const branch = out.code === 0 ? out.stdout.trim() : '';
1096
- return branch === '' ? null : branch;
1097
- }
1098
-
1099
- /**
1100
- * Read one file from the WORKING TREE as a unified diff against /dev/null.
1101
- *
1102
- * Used by the pre-push review for UNTRACKED files: such a file has no diff at
1103
- * all, so `git diff` says nothing about it — yet "a file I just wrote and
1104
- * never added" is exactly where a freshly pasted token lives. `--no-index`
1105
- * makes git treat the file as all-new, which also gives the review real line
1106
- * numbers to cite.
1107
- *
1108
- * `--no-index` exits 1 when the inputs differ (the normal case here), so a
1109
- * non-zero exit is not an error; only unreadable output is.
1110
- *
1111
- * @param {string} path repository path.
1112
- * @param {string} file repository-relative file path.
1113
- * @param {number} maxBytes refusal threshold (the diff is clipped past it).
1114
- * @param {{secrets?: Iterable<string>, root?: string}} [options]
1115
- * @returns {Promise<{text: string, binary?: boolean}>}
1116
- */
1117
- async readWorkingFile(path, file, maxBytes, options = {}) {
1118
- const root = nonEmpty(options.root) ?? (await this.assertRepo(path, options)).root;
1119
- const rel = nonEmpty(file);
1120
- if (!rel) throw new GitError('BAD_REQUEST', '缺少文件路径');
1121
- const limit = Number.isFinite(maxBytes) ? Math.max(1, Math.trunc(maxBytes)) : 200 * 1024;
1122
- const diff = await this.run(['diff', '--no-color', '--no-index', '--', '/dev/null', rel], {
1123
- cwd: root, label: 'diff', allowFailure: true, secrets: options.secrets,
1124
- });
1125
- const text = diff.stdout ?? '';
1126
- if (text === '') return { text: '' };
1127
- // git prints this instead of a patch for binary content.
1128
- if (/Binary files .* differ/.test(text)) return { text: '', binary: true };
1129
- return { text: text.slice(0, limit * 2) };
1130
- }
1131
-
1132
- /**
1133
- * `git remote -v` as an array, without the rest of the status document.
1134
- * @param {string} path
1135
- * @param {{secrets?: Iterable<string>}} [options]
1136
- * @returns {Promise<{remotes: {name: string, url: string}[]}>}
1137
- */
1138
- async remotes(path, options = {}) {
1139
- const root = await this.assertRepo(path, options);
1140
- const out = await this.run(['remote', '-v'], {
1141
- cwd: root.root, label: 'remote', allowFailure: true, secrets: options.secrets,
1142
- });
1143
- return { remotes: parseRemotes(out.stdout) };
1144
- }
1145
-
1146
- /* ---------------------------------------------------------------- */
1147
- /* Mutating operations */
1148
- /* ---------------------------------------------------------------- */
1149
-
1150
- /**
1151
- * `git init` in `path`, creating the directory when missing.
1152
- *
1153
- * @param {string} path
1154
- * @param {{secrets?: Iterable<string>}} [options]
1155
- * @returns {Promise<{root: string, gitDir: string, output: string}>}
1156
- */
1157
- async init(path, options = {}) {
1158
- const raw = typeof path === 'string' ? path.trim() : '';
1159
- if (raw === '') throw new GitError('BAD_REQUEST', '缺少仓库路径');
1160
- if (!isAbsolute(raw)) throw new GitError('BAD_REQUEST', `仓库路径必须是绝对路径:${raw}`);
1161
- const dir = resolve(raw);
1162
- await mkdir(dir, { recursive: true });
1163
- const out = await this.run(['init'], { cwd: dir, label: 'init', secrets: options.secrets });
1164
- if (out.code !== 0) {
1165
- throw new GitError('GIT_FAILED', `git init 失败:${`${out.stdout}${out.stderr}`.trim()}`, { output: out.stderr });
1166
- }
1167
- // Re-resolve AFTER init: the caller needs the verified toplevel, and a
1168
- // directory inside an existing repository initialises nothing new.
1169
- const root = await this.resolveRoot(dir, options);
1170
- return {
1171
- root: root?.root ?? dir,
1172
- gitDir: root?.gitDir ?? '',
1173
- output: merged(out),
1174
- };
1175
- }
1176
-
1177
- /**
1178
- * Add or update a remote.
1179
- * @param {string} path
1180
- * @param {{name?: string, url: string, secrets?: Iterable<string>}} options
1181
- * @returns {Promise<{output: string, remote: {name: string, url: string}}>}
1182
- */
1183
- async setRemote(path, options) {
1184
- const root = await this.assertRepo(path, options);
1185
- const name = nonEmpty(options.name) ?? 'origin';
1186
- const url = nonEmpty(options.url);
1187
- if (!url) throw new GitError('BAD_REQUEST', '缺少远端地址');
1188
- // `git remote get-url` exits 0 only when the remote already exists, which
1189
- // decides between "add" and "set-url" without parsing config.
1190
- const exists = await this.run(['remote', 'get-url', name], {
1191
- cwd: root.root, allowFailure: true, secrets: options.secrets,
1192
- });
1193
- const args = exists.code === 0 ? ['remote', 'set-url', name, url] : ['remote', 'add', name, url];
1194
- const out = await this.run(args, { cwd: root.root, label: 'remote', secrets: options.secrets });
1195
- if (out.code !== 0) {
1196
- throw new GitError('GIT_FAILED', `设置远端 ${name} 失败:${`${out.stdout}${out.stderr}`.trim()}`, { output: out.stderr });
1197
- }
1198
- return { output: merged(out), remote: { name, url } };
1199
- }
1200
-
1201
- /**
1202
- * `git add -A` (the init flow's "stage everything but do not commit").
1203
- * @param {string} path
1204
- * @param {{secrets?: Iterable<string>}} [options]
1205
- * @returns {Promise<{output: string}>}
1206
- */
1207
- async stageAll(path, options = {}) {
1208
- const root = await this.assertRepo(path, options);
1209
- const out = await this.run(['add', '-A'], { cwd: root.root, label: 'add', secrets: options.secrets });
1210
- if (out.code !== 0) {
1211
- throw new GitError('GIT_FAILED', `git add -A 失败:${`${out.stdout}${out.stderr}`.trim()}`, { output: out.stderr });
1212
- }
1213
- return { output: merged(out) };
1214
- }
1215
-
1216
- /**
1217
- * Fetch from a remote (with the active account's token when given).
1218
- *
1219
- * @param {string} path
1220
- * @param {{remote?: string, prune?: boolean, token?: string, secrets?: Iterable<string>}} [options]
1221
- * @returns {Promise<{output: string}>}
1222
- */
1223
- async fetch(path, options = {}) {
1224
- const root = await this.assertRepo(path, options);
1225
- const remote = nonEmpty(options.remote) ?? 'origin';
1226
- const args = ['fetch', remote];
1227
- if (options.prune === true) args.push('--prune');
1228
- return this.#network(root.root, args, 'fetch', options);
1229
- }
1230
-
1231
- /**
1232
- * Pull a remote branch.
1233
- *
1234
- * @param {string} path
1235
- * @param {{remote?: string, branch?: string, rebase?: boolean, token?: string,
1236
- * secrets?: Iterable<string>}} [options]
1237
- * @returns {Promise<{output: string}>}
1238
- */
1239
- async pull(path, options = {}) {
1240
- const root = await this.assertRepo(path, options);
1241
- const remote = nonEmpty(options.remote) ?? 'origin';
1242
- const branch = nonEmpty(options.branch);
1243
- const args = ['pull'];
1244
- if (options.rebase === true) args.push('--rebase');
1245
- args.push(remote);
1246
- if (branch) args.push(branch);
1247
- return this.#network(root.root, args, 'pull', options);
1248
- }
1249
-
1250
- /**
1251
- * Push the current (or named) branch.
1252
- *
1253
- * TWO DESTINATION FORMS, and both are the SAME command here:
1254
- *
1255
- * - `remote` names a configured remote (`origin`, `fork`, …).
1256
- * - `url` pushes to an ad-hoc URL (CONTRACT §3b: a `target` repository the
1257
- * local clone has no remote for). Passing the URL as the push destination
1258
- * is what keeps `.git/config` untouched.
1259
- *
1260
- * WHY `--set-upstream` IS NOT USED FOR A URL: `git push --set-upstream <url>`
1261
- * would write a `branch.<name>.remote=<url>` entry into `.git/config`, i.e.
1262
- * exactly the pollution the contract forbids. `--set-upstream` therefore only
1263
- * applies to a named remote, where it is what the user asked for.
1264
- *
1265
- * @param {string} path
1266
- * @param {{remote?: string, url?: string, branch?: string, force?: boolean,
1267
- * setUpstream?: boolean, tags?: boolean, token?: string, username?: string,
1268
- * secrets?: Iterable<string>}} [options]
1269
- * @returns {Promise<{output: string}>}
1270
- */
1271
- async push(path, options = {}) {
1272
- const root = await this.assertRepo(path, options);
1273
- const url = nonEmpty(options.url);
1274
- const remote = nonEmpty(options.remote) ?? 'origin';
1275
- // A URL and a named remote are mutually exclusive; the URL wins because it
1276
- // is the more specific instruction (the caller built it from `target`).
1277
- const destination = url ?? remote;
1278
- const branch = nonEmpty(options.branch);
1279
- // `source` is what actually leaves the local repository. It is a branch
1280
- // name by default, but a user picking a specific version in the panel may
1281
- // hand us a commit sha or a tag — git accepts all three as a push source
1282
- // (`<src>:<dst>`), and pinning it explicitly is what makes "push this
1283
- // exact version" possible without moving HEAD first.
1284
- const source = nonEmpty(options.source) ?? branch;
1285
- const args = ['push'];
1286
- // `--force-with-lease` rather than `--force`: the user asked for force, but
1287
- // refusing to clobber commits pushed by someone else is the behaviour that
1288
- // does not silently destroy their work.
1289
- if (options.force === true) args.push('--force-with-lease');
1290
- if (url === undefined && options.setUpstream !== false && source === branch) args.push('--set-upstream');
1291
- if (options.tags === true) args.push('--tags');
1292
- args.push(destination);
1293
- // An explicit refspec matters for URL pushes: the URL has no configured
1294
- // merge ref, so pushing the named branch is the only way to be sure WHICH
1295
- // local branch lands on the other side.
1296
- if (source) {
1297
- // A commit sha can NEVER be pushed without an explicit destination: git
1298
- // rejects `git push origin <sha>` outright ("cannot push a commit
1299
- // without a refspec"). Failing here, before the network handshake, says
1300
- // what to do instead of spending 20 s to reach a remote that then
1301
- // refuses. A branch or tag source is fine on its own.
1302
- const destinationBranch = branch;
1303
- if (destinationBranch) {
1304
- args.push(`${source}:${destinationBranch}`);
1305
- } else if (SHA_RE.test(source)) {
1306
- throw new GitError(
1307
- 'BAD_REQUEST',
1308
- `推送提交 ${source.slice(0, 8)} 必须同时指定目标分支(git 不接受没有 refspec 的提交推送)。`,
1309
- );
1310
- } else {
1311
- args.push(source);
1312
- }
1313
- }
1314
- return this.#network(root.root, args, 'push', options);
1315
- }
1316
-
1317
- /**
1318
- * Stage and commit.
1319
- *
1320
- * @param {string} path
1321
- * @param {{message: string, all?: boolean, files?: string[],
1322
- * secrets?: Iterable<string>}} options
1323
- * @returns {Promise<{output: string}>}
1324
- */
1325
- async commit(path, options) {
1326
- const root = await this.assertRepo(path, options);
1327
- const message = nonEmpty(options.message);
1328
- if (!message) throw new GitError('BAD_REQUEST', '提交信息不能为空');
1329
- const files = Array.isArray(options.files) ? options.files.filter((f) => typeof f === 'string' && f !== '') : [];
1330
- const addArgs = options.all !== false && files.length === 0 ? ['add', '-A'] : ['add', '--', ...files];
1331
- const add = await this.run(addArgs, { cwd: root.root, label: 'add', secrets: options.secrets });
1332
- if (add.code !== 0) {
1333
- throw new GitError('GIT_FAILED', `git add 失败:${`${add.stdout}${add.stderr}`.trim()}`, { output: add.stderr });
1334
- }
1335
- const out = await this.run(['commit', '-m', message], {
1336
- cwd: root.root, label: 'commit', secrets: options.secrets,
1337
- });
1338
- if (out.code !== 0) {
1339
- const raw = `${add.stdout}${add.stderr}${out.stdout}${out.stderr}`.trim();
1340
- // "nothing to commit" is a user-facing state, not a broken repository.
1341
- const nothing = /nothing to commit|no changes added to commit/i.test(raw);
1342
- throw new GitError(
1343
- nothing ? 'CONFLICT' : 'GIT_FAILED',
1344
- nothing ? '没有可提交的改动' : `git commit 失败:${raw}`,
1345
- { output: raw },
1346
- );
1347
- }
1348
- return { output: merged(add) + merged(out) };
1349
- }
1350
-
1351
- /**
1352
- * Checkout a branch, tag or sha.
1353
- *
1354
- * @param {string} path
1355
- * @param {{ref: string, create?: boolean, secrets?: Iterable<string>}} options
1356
- * @returns {Promise<{output: string}>}
1357
- */
1358
- async checkout(path, options) {
1359
- const root = await this.assertRepo(path, options);
1360
- const ref = nonEmpty(options.ref);
1361
- if (!ref) throw new GitError('BAD_REQUEST', '缺少要切换的分支或提交');
1362
- const args = ['checkout'];
1363
- if (options.create === true) args.push('-b');
1364
- args.push(ref);
1365
- return this.#write(root.root, args, 'checkout', options);
1366
- }
1367
-
1368
- /**
1369
- * Create a branch, optionally checking it out.
1370
- *
1371
- * @param {string} path
1372
- * @param {{name: string, from?: string, checkout?: boolean,
1373
- * secrets?: Iterable<string>}} options
1374
- * @returns {Promise<{output: string}>}
1375
- */
1376
- async createBranch(path, options) {
1377
- const root = await this.assertRepo(path, options);
1378
- const name = nonEmpty(options.name);
1379
- if (!name) throw new GitError('BAD_REQUEST', '分支名不能为空');
1380
- const from = nonEmpty(options.from);
1381
- const args = options.checkout === false
1382
- ? ['branch', name, ...(from ? [from] : [])]
1383
- : ['checkout', '-b', name, ...(from ? [from] : [])];
1384
- return this.#write(root.root, args, 'branch', options);
1385
- }
1386
-
1387
- /**
1388
- * Delete a branch.
1389
- * @param {string} path
1390
- * @param {{name: string, force?: boolean, secrets?: Iterable<string>}} options
1391
- * @returns {Promise<{output: string}>}
1392
- */
1393
- async deleteBranch(path, options) {
1394
- const root = await this.assertRepo(path, options);
1395
- const name = nonEmpty(options.name);
1396
- if (!name) throw new GitError('BAD_REQUEST', '分支名不能为空');
1397
- return this.#write(root.root, ['branch', options.force === true ? '-D' : '-d', name], 'branch', options);
1398
- }
1399
-
1400
- /**
1401
- * Merge a ref into the current branch.
1402
- * @param {string} path
1403
- * @param {{ref: string, secrets?: Iterable<string>}} options
1404
- * @returns {Promise<{output: string}>}
1405
- */
1406
- async merge(path, options) {
1407
- const root = await this.assertRepo(path, options);
1408
- const ref = nonEmpty(options.ref);
1409
- if (!ref) throw new GitError('BAD_REQUEST', '缺少要合并的分支或提交');
1410
- return this.#write(root.root, ['merge', '--no-edit', ref], 'merge', options);
1411
- }
1412
-
1413
- /**
1414
- * Reset to a ref.
1415
- *
1416
- * `mode: 'hard'` discards uncommitted work, which is why the ROUTE layer
1417
- * requires `confirm: true` before it calls this and why the message here says
1418
- * plainly what happened.
1419
- *
1420
- * @param {string} path
1421
- * @param {{ref?: string, mode?: 'soft'|'mixed'|'hard',
1422
- * secrets?: Iterable<string>}} [options]
1423
- * @returns {Promise<{output: string}>}
1424
- */
1425
- async reset(path, options = {}) {
1426
- const root = await this.assertRepo(path, options);
1427
- const ref = nonEmpty(options.ref) ?? 'HEAD';
1428
- const mode = options.mode === 'soft' || options.mode === 'hard' ? options.mode : 'mixed';
1429
- return this.#write(root.root, ['reset', `--${mode}`, ref], 'reset', options);
1430
- }
1431
-
1432
- /**
1433
- * Revert one commit by creating a new commit that undoes it.
1434
- *
1435
- * WHY THIS IS NON-DESTRUCTIVE: `/local/revert` and `/local/revert-commit`
1436
- * both mean "undo this commit" in the contract's route table, and reverting
1437
- * is the only undo that never rewrites history the user may already have
1438
- * pushed. Destructive rewinds belong to `/local/reset`.
1439
- *
1440
- * @param {string} path
1441
- * @param {{sha: string, secrets?: Iterable<string>}} options
1442
- * @returns {Promise<{output: string}>}
1443
- */
1444
- async revert(path, options) {
1445
- const root = await this.assertRepo(path, options);
1446
- const sha = nonEmpty(options.sha);
1447
- if (!sha) throw new GitError('BAD_REQUEST', '缺少提交 SHA');
1448
- return this.#write(root.root, ['revert', '--no-edit', sha], 'revert', options);
1449
- }
1450
-
1451
- /**
1452
- * Create a tag, optionally pushing it.
1453
- *
1454
- * @param {string} path
1455
- * @param {{name: string, ref?: string, push?: boolean, remote?: string,
1456
- * token?: string, secrets?: Iterable<string>}} options
1457
- * @returns {Promise<{output: string}>}
1458
- */
1459
- async tag(path, options) {
1460
- const root = await this.assertRepo(path, options);
1461
- const name = nonEmpty(options.name);
1462
- if (!name) throw new GitError('BAD_REQUEST', '标签名不能为空');
1463
- const ref = nonEmpty(options.ref) ?? 'HEAD';
1464
- const created = await this.#write(root.root, ['tag', name, ref], 'tag', options);
1465
- if (options.push !== true) return created;
1466
- const remote = nonEmpty(options.remote) ?? 'origin';
1467
- const pushed = await this.#network(
1468
- root.root,
1469
- ['push', remote, name],
1470
- 'push',
1471
- options,
1472
- );
1473
- return { output: `${created.output}${pushed.output}` };
1474
- }
1475
-
1476
- /**
1477
- * Stash the working tree.
1478
- * @param {string} path
1479
- * @param {{message?: string, includeUntracked?: boolean,
1480
- * secrets?: Iterable<string>}} [options]
1481
- * @returns {Promise<{output: string}>}
1482
- */
1483
- async stash(path, options = {}) {
1484
- const root = await this.assertRepo(path, options);
1485
- const args = ['stash', 'push'];
1486
- if (options.includeUntracked !== false) args.push('--include-untracked');
1487
- const message = nonEmpty(options.message);
1488
- if (message) args.push('-m', message);
1489
- return this.#write(root.root, args, 'stash', options);
1490
- }
1491
-
1492
- /**
1493
- * Pop one stash entry.
1494
- * @param {string} path
1495
- * @param {{index?: number, secrets?: Iterable<string>}} [options]
1496
- * @returns {Promise<{output: string}>}
1497
- */
1498
- async stashPop(path, options = {}) {
1499
- const root = await this.assertRepo(path, options);
1500
- const index = Number.isInteger(options.index) && options.index >= 0 ? options.index : 0;
1501
- return this.#write(root.root, ['stash', 'pop', `stash@{${index}}`], 'stash', options);
1502
- }
1503
-
1504
- /**
1505
- * Restore files from the index (or HEAD).
1506
- *
1507
- * `staged: true` discards BOTH the index and the worktree copy, which is what
1508
- * "撤回这个文件的全部改动" means in the panel; `staged: false` only rewrites
1509
- * the worktree file, leaving an already-staged version alone.
1510
- *
1511
- * @param {string} path
1512
- * @param {{files: string[], staged?: boolean, secrets?: Iterable<string>}} options
1513
- * @returns {Promise<{output: string}>}
1514
- */
1515
- async restore(path, options) {
1516
- const root = await this.assertRepo(path, options);
1517
- const files = Array.isArray(options.files) ? options.files.filter((f) => typeof f === 'string' && f !== '') : [];
1518
- if (files.length === 0) throw new GitError('BAD_REQUEST', '缺少要还原的文件');
1519
- const args = ['restore'];
1520
- if (options.staged === true) args.push('--staged', '--worktree');
1521
- args.push('--', ...files);
1522
- return this.#write(root.root, args, 'restore', options);
1523
- }
1524
-
1525
- /**
1526
- * Discard EVERYTHING uncommitted: `git reset --hard` plus removal of
1527
- * untracked files. Ignored files (node_modules, build output) are kept —
1528
- * `clean -x` would delete them, which is never what the button means.
1529
- *
1530
- * @param {string} path
1531
- * @param {{secrets?: Iterable<string>}} [options]
1532
- * @returns {Promise<{output: string}>}
1533
- */
1534
- async discardAll(path, options = {}) {
1535
- const root = await this.assertRepo(path, options);
1536
- const resetOut = await this.#write(root.root, ['reset', '--hard', 'HEAD'], 'reset', options);
1537
- const cleanOut = await this.#write(root.root, ['clean', '-fd'], 'clean', options);
1538
- return { output: resetOut.output + cleanOut.output };
1539
- }
1540
-
1541
- /**
1542
- * Run one mutating command and convert a non-zero exit into GIT_FAILED with
1543
- * git's raw output attached.
1544
- * @private
1545
- */
1546
- async #write(cwd, args, label, options = {}) {
1547
- const out = await this.run(args, { cwd, label, secrets: options.secrets });
1548
- if (out.code !== 0) {
1549
- const raw = `${out.stdout}${out.stderr}`.trim();
1550
- throw new GitError('GIT_FAILED', `git ${label} 失败:${raw}`, { output: raw, args });
1551
- }
1552
- return { output: merged(out) };
1553
- }
1554
-
1555
- /**
1556
- * Run one network command: long-but-finite timeout, no interactive prompt,
1557
- * token supplied per invocation only.
1558
- * @private
1559
- */
1560
- async #network(cwd, args, label, options = {}) {
1561
- const out = await this.run(args, {
1562
- cwd,
1563
- label,
1564
- timeoutMs: NETWORK_TIMEOUT_MS,
1565
- secrets: options.secrets,
1566
- // One place: the token becomes configuration in the CHILD ENVIRONMENT
1567
- // instead of an argv element, for every network command.
1568
- env: authEnv(options.token, { username: options.username }),
1569
- });
1570
- if (out.code !== 0) {
1571
- const raw = `${out.stdout}${out.stderr}`.trim();
1572
- throw new GitError('GIT_FAILED', `git ${label} 失败:${networkHint(raw, args)}`, { output: raw, args });
1573
- }
1574
- return { output: merged(out) };
1575
- }
1576
- }
1577
-
1578
- /**
1579
- * Turn the transport failures a user actually hits into an actionable Chinese
1580
- * sentence, PREPENDED to git's own (already redacted) output.
1581
- *
1582
- * The two failures this plugin can create by itself are the interesting ones:
1583
- *
1584
- * - `could not read Username/Password`: git's credential flow ran and had no
1585
- * terminal. Every network command here is started with
1586
- * `GIT_TERMINAL_PROMPT=0`, so this is a dead end for the request, not a
1587
- * transient hiccup — saying so (and naming the fix) beats leaving the user
1588
- * with a bare `fatal:` line.
1589
- * - certificate verification: the profile process may be behind an
1590
- * intercepting proxy. The panel already explains the gitPath workaround on
1591
- * API calls; the git path deserves the same hint.
1592
- *
1593
- * @param {string} raw merged git stdout+stderr.
1594
- * @param {string[]} args the argv (used to tell a URL push from a remote one).
1595
- * @returns {string} the message body.
1596
- */
1597
- function networkHint(raw, args) {
1598
- const text = String(raw ?? '');
1599
- if (/could not read (Username|Password)|terminal prompts disabled/i.test(text)) {
1600
- const urlPush = args.some((arg) => /^https?:\/\//i.test(arg));
1601
- return '需要凭据时无法弹出输入窗口(本插件的 git 不允许交互式提示)。'
1602
- + (urlPush
1603
- ? '请确认已登录 GitHub 账号且令牌有 repo 权限;如仍失败,可先在本地添加远端再推送。'
1604
- : '请确认远端地址正确、已登录 GitHub 账号且令牌有 repo 权限。')
1605
- + `\n${text}`;
1606
- }
1607
- if (TLS_FAILURE.test(text)) {
1608
- return 'git 无法校验 GitHub 的 TLS 证书(常见于企业代理、杀毒软件或系统时间错误)。'
1609
- + '请修复证书/代理,或在插件设置里填写可用的「git 路径」。'
1610
- + `\n${text}`;
1611
- }
1612
- return text;
1613
- }
1614
-
1615
- /** Merge stdout + stderr the way CONTRACT §3 defines a write command's output. */
1616
- function merged(result) {
1617
- return truncate(`${result.stdout}${result.stderr}`, MAX_OUTPUT_CHARS);
1618
- }
1619
-
1620
- /** A trimmed non-empty string, or undefined. */
1621
- function nonEmpty(value) {
1622
- return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
1623
- }
1624
-
1625
- /** True when `path` names an existing directory. */
1626
- function isDirectory(path) {
1627
- try {
1628
- return statSync(path).isDirectory();
1629
- } catch {
1630
- return false;
1631
- }
1632
- }
1633
-
1634
- /** Clamp an integer option into [min, max], falling back to `fallback`. */
1635
- function clampInt(value, min, max, fallback) {
1636
- const number = Number(value);
1637
- if (!Number.isFinite(number)) return fallback;
1638
- return Math.min(max, Math.max(min, Math.trunc(number)));
1639
- }
1640
-
1641
- /**
1642
- * Pick the remote that should be treated as "the GitHub remote".
1643
- *
1644
- * The configured `defaultRemote` wins when it IS a GitHub remote; otherwise the
1645
- * first GitHub remote in `git remote -v` order, which is stable per repository.
1646
- *
1647
- * @param {{name: string, url: string}[]} remotes
1648
- * @param {string} [defaultRemote]
1649
- * @returns {{name: string, owner: string, repo: string, url: string}|null}
1650
- */
1651
- function pickGithubRemote(remotes, defaultRemote) {
1652
- const preferred = typeof defaultRemote === 'string' && defaultRemote.trim() !== '' ? defaultRemote.trim() : 'origin';
1653
- const ordered = [
1654
- ...remotes.filter((remote) => remote.name === preferred),
1655
- ...remotes.filter((remote) => remote.name !== preferred),
1656
- ];
1657
- for (const remote of ordered) {
1658
- if (!isGithubUrl(remote.url)) continue;
1659
- const parsed = parseGithubRemote(remote.url);
1660
- if (!parsed) continue;
1661
- return { name: remote.name, owner: parsed.owner, repo: parsed.repo, url: remote.url };
1662
- }
1663
- return null;
1664
- }