dsh-git-scm 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +255 -2
- package/cordis.patch.yml +6 -0
- package/icon.svg +11 -0
- package/lib/client.js +6062 -0
- package/lib/client.js.map +1 -0
- package/lib/host/commit-message.d.ts +55 -0
- package/lib/host/git.d.ts +456 -0
- package/lib/host/types.d.ts +77 -0
- package/lib/index.d.ts +8 -0
- package/lib/index.js +2382 -0
- package/lib/index.js.map +1 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +77 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,2382 @@
|
|
|
1
|
+
import { readFile, stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, isAbsolute, join, normalize } from "node:path";
|
|
3
|
+
// src/host/git.ts
|
|
4
|
+
/**
|
|
5
|
+
* Git command layer of the source-control plugin.
|
|
6
|
+
*
|
|
7
|
+
* Pure Node ESM: this module knows Git's argument grammar and machine-readable
|
|
8
|
+
* output formats and nothing about Cordis, Sessions, or HTTP. Every invocation
|
|
9
|
+
* goes through the `exec` seam its caller supplies, so the caller owns process
|
|
10
|
+
* policy (executable resolution, confinement, cancellation, output caps) while
|
|
11
|
+
* this module owns what is asked and how the answer is read.
|
|
12
|
+
*
|
|
13
|
+
* Reading is lazy by design: the repository snapshot carries identity, branches,
|
|
14
|
+
* stashes, and tags, while a branch's commits and a commit's files are read only
|
|
15
|
+
* when the panel expands that node.
|
|
16
|
+
*
|
|
17
|
+
* Parsing follows Git's own stable formats: `status --porcelain=v2 -z`,
|
|
18
|
+
* `for-each-ref`, and `log --pretty=format:` with NUL separators. Human prose is
|
|
19
|
+
* never parsed.
|
|
20
|
+
*/
|
|
21
|
+
/** Environment every Git call must run with: no inherited repository selectors, no prompts, no lazy fetches. */
|
|
22
|
+
var GIT_ENV = Object.freeze({
|
|
23
|
+
...Object.fromEntries([
|
|
24
|
+
"GIT_DIR",
|
|
25
|
+
"GIT_WORK_TREE",
|
|
26
|
+
"GIT_COMMON_DIR",
|
|
27
|
+
"GIT_INDEX_FILE",
|
|
28
|
+
"GIT_OBJECT_DIRECTORY",
|
|
29
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
30
|
+
"GIT_CONFIG",
|
|
31
|
+
"GIT_CONFIG_PARAMETERS",
|
|
32
|
+
"GIT_CONFIG_COUNT",
|
|
33
|
+
"GIT_CEILING_DIRECTORIES",
|
|
34
|
+
"GIT_PREFIX",
|
|
35
|
+
"GIT_SHALLOW_FILE",
|
|
36
|
+
"GIT_GRAFT_FILE",
|
|
37
|
+
"GIT_REPLACE_REF_BASE",
|
|
38
|
+
"GIT_ATTR_SOURCE"
|
|
39
|
+
].map((key) => [key, void 0])),
|
|
40
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
41
|
+
GIT_OPTIONAL_LOCKS: "0",
|
|
42
|
+
GIT_NO_LAZY_FETCH: "1",
|
|
43
|
+
LC_ALL: "C"
|
|
44
|
+
});
|
|
45
|
+
/** A structured Git failure the Host route reports with its `code`. */
|
|
46
|
+
var GitError = class extends Error {
|
|
47
|
+
/** Stable code such as `NOT_A_REPO`, `INVALID`, or `GIT_FAILED`. */
|
|
48
|
+
code;
|
|
49
|
+
/** Raw output excerpt, when one exists. */
|
|
50
|
+
detail;
|
|
51
|
+
/**
|
|
52
|
+
* @param code - stable code such as `NOT_A_REPO`, `INVALID`, or `GIT_FAILED`.
|
|
53
|
+
* @param message - readable reason, usually Git's first diagnostic line.
|
|
54
|
+
* @param detail - raw output excerpt.
|
|
55
|
+
*/
|
|
56
|
+
constructor(code, message, detail = null) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = "GitError";
|
|
59
|
+
this.code = code;
|
|
60
|
+
this.detail = detail;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
/** Falls back to these bounds when the caller omits a limit. */
|
|
64
|
+
var DEFAULT_LIMITS = Object.freeze({
|
|
65
|
+
maxBranches: 500,
|
|
66
|
+
maxCommits: 40,
|
|
67
|
+
maxTags: 30,
|
|
68
|
+
maxFiles: 3e3,
|
|
69
|
+
maxDiffBytes: 409600
|
|
70
|
+
});
|
|
71
|
+
/** Names of {@link DEFAULT_LIMITS}, so an override map is read without string indexing. */
|
|
72
|
+
var LIMIT_KEYS = [
|
|
73
|
+
"maxBranches",
|
|
74
|
+
"maxCommits",
|
|
75
|
+
"maxTags",
|
|
76
|
+
"maxFiles",
|
|
77
|
+
"maxDiffBytes"
|
|
78
|
+
];
|
|
79
|
+
/** Deadline for operations that talk to a remote: large fetches take minutes. */
|
|
80
|
+
var NETWORK_TIMEOUT_MS = 3e5;
|
|
81
|
+
/** Deadline for one GitHub CLI probe that only reads the account. */
|
|
82
|
+
var GITHUB_PROBE_TIMEOUT_MS = 15e3;
|
|
83
|
+
/** Status letters `status --porcelain=v2` reports for one side of a change. */
|
|
84
|
+
var STATUS_OF_CODE = Object.freeze({
|
|
85
|
+
M: "modified",
|
|
86
|
+
A: "added",
|
|
87
|
+
D: "deleted",
|
|
88
|
+
R: "renamed",
|
|
89
|
+
C: "copied",
|
|
90
|
+
T: "typechange",
|
|
91
|
+
U: "conflicted"
|
|
92
|
+
});
|
|
93
|
+
/** Merge the caller's limits onto the defaults, ignoring invalid entries. */
|
|
94
|
+
function resolveLimits(limits = {}) {
|
|
95
|
+
const resolved = { ...DEFAULT_LIMITS };
|
|
96
|
+
for (const key of LIMIT_KEYS) {
|
|
97
|
+
const value = limits[key];
|
|
98
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) resolved[key] = value;
|
|
99
|
+
}
|
|
100
|
+
return resolved;
|
|
101
|
+
}
|
|
102
|
+
/** Build the argv this layer hands the seam: program name first, then the subcommand. */
|
|
103
|
+
function argvOf(args) {
|
|
104
|
+
return ["git", ...args];
|
|
105
|
+
}
|
|
106
|
+
/** The first non-empty line of Git output. */
|
|
107
|
+
function firstLine$1(text) {
|
|
108
|
+
return String(text ?? "").split(/\r?\n/).map((line) => line.trim()).find((line) => line.length > 0) ?? "no diagnostic";
|
|
109
|
+
}
|
|
110
|
+
/** At most `limit` characters of raw output, for a failure report. */
|
|
111
|
+
function excerpt$1(text, limit = 2e3) {
|
|
112
|
+
if (typeof text !== "string" || text.length === 0) return null;
|
|
113
|
+
return text.length <= limit ? text : `${text.slice(0, limit)}…`;
|
|
114
|
+
}
|
|
115
|
+
/** Whether an error is the layer's own structured failure. */
|
|
116
|
+
function isGitError(error) {
|
|
117
|
+
return error instanceof GitError;
|
|
118
|
+
}
|
|
119
|
+
/** Read the `code`, `message`, and `detail` fields a rejection from the `exec` seam may carry. */
|
|
120
|
+
function failureFieldsOf(error) {
|
|
121
|
+
if (typeof error !== "object" || error === null) return {};
|
|
122
|
+
return error;
|
|
123
|
+
}
|
|
124
|
+
/** Normalize a rejection from the `exec` seam into a structured failure. */
|
|
125
|
+
function failureOf(error, operation) {
|
|
126
|
+
if (isGitError(error)) return error;
|
|
127
|
+
const fields = failureFieldsOf(error);
|
|
128
|
+
return new GitError(typeof fields.code === "string" && fields.code.length > 0 ? fields.code : "GIT_FAILED", typeof fields.message === "string" && fields.message.length > 0 ? fields.message : `git ${operation} failed`, typeof fields.detail === "string" ? fields.detail : null);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Run one Git invocation that must succeed.
|
|
132
|
+
* @param exec - the caller's seam.
|
|
133
|
+
* @param args - subcommand arguments, without the program name.
|
|
134
|
+
* @param operation - name used in failure messages.
|
|
135
|
+
* @param options - `allowedExitCodes`, `timeoutMs`, and other exec options.
|
|
136
|
+
* @returns the output.
|
|
137
|
+
*/
|
|
138
|
+
async function run(exec, args, operation, options = {}) {
|
|
139
|
+
try {
|
|
140
|
+
return await exec(argvOf(args), options);
|
|
141
|
+
} catch (error) {
|
|
142
|
+
throw failureOf(error, operation);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** Whether a directory is inside a Git work tree, without throwing for the ordinary negative answer. */
|
|
146
|
+
async function repositoryRoot(exec, _cwd) {
|
|
147
|
+
let result;
|
|
148
|
+
try {
|
|
149
|
+
result = await exec(argvOf(["rev-parse", "--show-toplevel"]), { allowedExitCodes: [0, 128] });
|
|
150
|
+
} catch (error) {
|
|
151
|
+
throw failureOf(error, "rev-parse");
|
|
152
|
+
}
|
|
153
|
+
if (result.exitCode === 0) {
|
|
154
|
+
const root = firstLine$1(result.stdout);
|
|
155
|
+
if (root.length === 0) throw new GitError("GIT_FAILED", "git rev-parse printed no work tree root");
|
|
156
|
+
return root;
|
|
157
|
+
}
|
|
158
|
+
if (/not a git repository|must be run in a work tree/i.test(result.stderr)) return null;
|
|
159
|
+
throw new GitError("GIT_FAILED", `git rev-parse failed: ${firstLine$1(result.stderr)}`, excerpt$1(result.stderr));
|
|
160
|
+
}
|
|
161
|
+
/** Resolve the canonical Git directories of a checkout: shared and per-worktree. */
|
|
162
|
+
async function gitDirectories(exec, _cwd) {
|
|
163
|
+
const [common, own] = await Promise.all([run(exec, [
|
|
164
|
+
"rev-parse",
|
|
165
|
+
"--path-format=absolute",
|
|
166
|
+
"--git-common-dir"
|
|
167
|
+
], "rev-parse"), run(exec, [
|
|
168
|
+
"rev-parse",
|
|
169
|
+
"--path-format=absolute",
|
|
170
|
+
"--git-dir"
|
|
171
|
+
], "rev-parse")]);
|
|
172
|
+
return {
|
|
173
|
+
commonDir: firstLine$1(common.stdout),
|
|
174
|
+
gitDir: firstLine$1(own.stdout)
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
/** Read the mtime of `FETCH_HEAD`, the only durable record of the last fetch. */
|
|
178
|
+
async function lastFetchAt(commonDir) {
|
|
179
|
+
try {
|
|
180
|
+
const info = await stat(join(commonDir, "FETCH_HEAD"));
|
|
181
|
+
return Math.round(info.mtimeMs);
|
|
182
|
+
} catch {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/** Name the operation the checkout is in the middle of, or null when it is clean. */
|
|
187
|
+
async function pendingOperation(gitDir) {
|
|
188
|
+
for (const [kind, mark] of [
|
|
189
|
+
["cherry-pick", "CHERRY_PICK_HEAD"],
|
|
190
|
+
["revert", "REVERT_HEAD"],
|
|
191
|
+
["merge", "MERGE_HEAD"],
|
|
192
|
+
["rebase", "rebase-merge"],
|
|
193
|
+
["rebase", "rebase-apply"]
|
|
194
|
+
]) try {
|
|
195
|
+
await stat(join(gitDir, mark));
|
|
196
|
+
return kind;
|
|
197
|
+
} catch {}
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
/** The checked-out branch, or null when HEAD is detached. */
|
|
201
|
+
async function currentBranch(exec) {
|
|
202
|
+
const result = await exec(argvOf([
|
|
203
|
+
"symbolic-ref",
|
|
204
|
+
"--quiet",
|
|
205
|
+
"--short",
|
|
206
|
+
"HEAD"
|
|
207
|
+
]), { allowedExitCodes: [
|
|
208
|
+
0,
|
|
209
|
+
1,
|
|
210
|
+
128
|
|
211
|
+
] });
|
|
212
|
+
if (result.exitCode !== 0) return null;
|
|
213
|
+
const name = firstLine$1(result.stdout);
|
|
214
|
+
return name.length === 0 ? null : name;
|
|
215
|
+
}
|
|
216
|
+
/** HEAD facts: whether a commit exists and, if so, its identity. */
|
|
217
|
+
async function headCommit(exec) {
|
|
218
|
+
if ((await exec(argvOf([
|
|
219
|
+
"rev-parse",
|
|
220
|
+
"--verify",
|
|
221
|
+
"--quiet",
|
|
222
|
+
"HEAD"
|
|
223
|
+
]), { allowedExitCodes: [
|
|
224
|
+
0,
|
|
225
|
+
1,
|
|
226
|
+
128
|
|
227
|
+
] })).exitCode !== 0) return {
|
|
228
|
+
unborn: true,
|
|
229
|
+
head: null
|
|
230
|
+
};
|
|
231
|
+
const [hash, short, subject, author, date, body] = (await run(exec, [
|
|
232
|
+
"log",
|
|
233
|
+
"-1",
|
|
234
|
+
"--date=unix",
|
|
235
|
+
"--pretty=format:%H%x00%h%x00%s%x00%an%x00%at%x00%B"
|
|
236
|
+
], "log")).stdout.split("\0");
|
|
237
|
+
return {
|
|
238
|
+
unborn: false,
|
|
239
|
+
head: {
|
|
240
|
+
hash: hash ?? "",
|
|
241
|
+
short: short ?? "",
|
|
242
|
+
subject: subject ?? "",
|
|
243
|
+
author: author ?? "",
|
|
244
|
+
date: parseDate(date),
|
|
245
|
+
message: (body ?? "").trim()
|
|
246
|
+
}
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
/** Upstream branch name of HEAD, or null when none is configured. */
|
|
250
|
+
async function upstreamBranch(exec) {
|
|
251
|
+
const result = await exec(argvOf([
|
|
252
|
+
"rev-parse",
|
|
253
|
+
"--abbrev-ref",
|
|
254
|
+
"--symbolic-full-name",
|
|
255
|
+
"@{upstream}"
|
|
256
|
+
]), { allowedExitCodes: [0, 128] });
|
|
257
|
+
if (result.exitCode !== 0) return null;
|
|
258
|
+
const name = firstLine$1(result.stdout);
|
|
259
|
+
return name.length === 0 ? null : name;
|
|
260
|
+
}
|
|
261
|
+
/** Ahead/behind counts between HEAD and its upstream, or nulls without an upstream. */
|
|
262
|
+
async function aheadBehind(exec, upstream) {
|
|
263
|
+
if (upstream === null) return {
|
|
264
|
+
ahead: null,
|
|
265
|
+
behind: null
|
|
266
|
+
};
|
|
267
|
+
const result = await exec(argvOf([
|
|
268
|
+
"rev-list",
|
|
269
|
+
"--left-right",
|
|
270
|
+
"--count",
|
|
271
|
+
`HEAD...${upstream}`
|
|
272
|
+
]), { allowedExitCodes: [0, 128] });
|
|
273
|
+
if (result.exitCode !== 0) return {
|
|
274
|
+
ahead: null,
|
|
275
|
+
behind: null
|
|
276
|
+
};
|
|
277
|
+
const [aheadText, behindText] = firstLine$1(result.stdout).split(/\s+/);
|
|
278
|
+
return {
|
|
279
|
+
ahead: parseCount(aheadText),
|
|
280
|
+
behind: parseCount(behindText)
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
/** One line of `status --porcelain=v2 -z` as one side of a change. */
|
|
284
|
+
function changeEntry(path, code, origPath) {
|
|
285
|
+
return {
|
|
286
|
+
path,
|
|
287
|
+
origPath: origPath ?? null,
|
|
288
|
+
status: STATUS_OF_CODE[code] ?? "modified",
|
|
289
|
+
code,
|
|
290
|
+
staged: false
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Parse `git status --porcelain=v2 -z` into the four change lists.
|
|
295
|
+
* @param output - raw NUL-separated records.
|
|
296
|
+
* @param maxFiles - cap applied across all four lists.
|
|
297
|
+
* @returns the lists.
|
|
298
|
+
*/
|
|
299
|
+
function parseStatus(output, maxFiles) {
|
|
300
|
+
const changes = {
|
|
301
|
+
staged: [],
|
|
302
|
+
unstaged: [],
|
|
303
|
+
untracked: [],
|
|
304
|
+
conflicted: [],
|
|
305
|
+
total: 0
|
|
306
|
+
};
|
|
307
|
+
if (typeof output !== "string" || output.length === 0) return changes;
|
|
308
|
+
const records = output.split("\0");
|
|
309
|
+
let total = 0;
|
|
310
|
+
for (let index = 0; index < records.length; index += 1) {
|
|
311
|
+
const record = records[index];
|
|
312
|
+
if (record.length === 0) continue;
|
|
313
|
+
const kind = record.charAt(0);
|
|
314
|
+
if (kind === "1") {
|
|
315
|
+
const parts = record.split(" ");
|
|
316
|
+
if (parts.length < 9) continue;
|
|
317
|
+
const code = parts[1];
|
|
318
|
+
const path = parts.slice(8).join(" ");
|
|
319
|
+
const [x, y] = [code.charAt(0), code.charAt(1)];
|
|
320
|
+
if (x !== ".") {
|
|
321
|
+
changes.staged.push(changeEntry(path, x, null));
|
|
322
|
+
total += 1;
|
|
323
|
+
}
|
|
324
|
+
if (y !== ".") {
|
|
325
|
+
changes.unstaged.push(changeEntry(path, y, null));
|
|
326
|
+
total += 1;
|
|
327
|
+
}
|
|
328
|
+
} else if (kind === "2") {
|
|
329
|
+
const parts = record.split(" ");
|
|
330
|
+
if (parts.length < 10) continue;
|
|
331
|
+
const code = parts[1];
|
|
332
|
+
const path = parts.slice(9).join(" ");
|
|
333
|
+
const origPath = records[index + 1] ?? null;
|
|
334
|
+
index += 1;
|
|
335
|
+
const [x, y] = [code.charAt(0), code.charAt(1)];
|
|
336
|
+
if (x !== ".") {
|
|
337
|
+
changes.staged.push(changeEntry(path, x, origPath));
|
|
338
|
+
total += 1;
|
|
339
|
+
}
|
|
340
|
+
if (y !== ".") {
|
|
341
|
+
changes.unstaged.push(changeEntry(path, y, origPath));
|
|
342
|
+
total += 1;
|
|
343
|
+
}
|
|
344
|
+
} else if (kind === "u") {
|
|
345
|
+
const parts = record.split(" ");
|
|
346
|
+
if (parts.length < 11) continue;
|
|
347
|
+
const path = parts.slice(10).join(" ");
|
|
348
|
+
changes.conflicted.push({
|
|
349
|
+
path,
|
|
350
|
+
origPath: null,
|
|
351
|
+
status: "conflicted",
|
|
352
|
+
code: "U",
|
|
353
|
+
staged: false
|
|
354
|
+
});
|
|
355
|
+
total += 1;
|
|
356
|
+
} else if (kind === "?") {
|
|
357
|
+
const path = record.slice(2);
|
|
358
|
+
changes.untracked.push({
|
|
359
|
+
path,
|
|
360
|
+
origPath: null,
|
|
361
|
+
status: "untracked",
|
|
362
|
+
code: "?",
|
|
363
|
+
staged: false
|
|
364
|
+
});
|
|
365
|
+
total += 1;
|
|
366
|
+
}
|
|
367
|
+
if (total >= maxFiles) break;
|
|
368
|
+
}
|
|
369
|
+
changes.total = total;
|
|
370
|
+
return changes;
|
|
371
|
+
}
|
|
372
|
+
/** Read the working-tree changes of a repository. */
|
|
373
|
+
async function readChanges(exec, limits) {
|
|
374
|
+
return parseStatus((await run(exec, [
|
|
375
|
+
"status",
|
|
376
|
+
"--porcelain=v2",
|
|
377
|
+
"-z",
|
|
378
|
+
"--untracked-files=normal"
|
|
379
|
+
], "status")).stdout, limits.maxFiles);
|
|
380
|
+
}
|
|
381
|
+
/** Parse one `for-each-ref` record into a branch entry. */
|
|
382
|
+
function branchOf(fields) {
|
|
383
|
+
const [refname, short, head, upstream, track, hash, date] = fields;
|
|
384
|
+
const subject = fields.slice(7).join(" ");
|
|
385
|
+
if (refname === void 0 || short === void 0) return null;
|
|
386
|
+
const kind = refname.startsWith("refs/heads/") ? "local" : refname.startsWith("refs/remotes/") ? "remote" : null;
|
|
387
|
+
if (kind === null) return null;
|
|
388
|
+
if (kind === "remote" && short.endsWith("/HEAD")) return null;
|
|
389
|
+
const parsedTrack = parseTrack(track ?? "");
|
|
390
|
+
return {
|
|
391
|
+
name: short,
|
|
392
|
+
kind,
|
|
393
|
+
current: head === "*",
|
|
394
|
+
upstream: upstream === void 0 || upstream.length === 0 ? null : upstream,
|
|
395
|
+
ahead: parsedTrack.ahead,
|
|
396
|
+
behind: parsedTrack.behind,
|
|
397
|
+
hash: hash ?? "",
|
|
398
|
+
subject: subject ?? "",
|
|
399
|
+
date: parseDate(date),
|
|
400
|
+
remote: kind === "remote" ? short.split("/")[0] : null
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
/** Parse `%(upstream:track)` such as `[ahead 2, behind 1]` or `[gone]`. */
|
|
404
|
+
function parseTrack(text) {
|
|
405
|
+
const aheadMatch = /ahead (\d+)/.exec(text);
|
|
406
|
+
const behindMatch = /behind (\d+)/.exec(text);
|
|
407
|
+
return {
|
|
408
|
+
ahead: aheadMatch === null ? null : Number(aheadMatch[1]),
|
|
409
|
+
behind: behindMatch === null ? null : Number(behindMatch[1])
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
/** List local and remote branches, newest commit first but with the current branch first. */
|
|
413
|
+
async function readBranches(exec, limits) {
|
|
414
|
+
const result = await run(exec, [
|
|
415
|
+
"for-each-ref",
|
|
416
|
+
"--sort=-committerdate",
|
|
417
|
+
`--format=${[
|
|
418
|
+
"%(refname)",
|
|
419
|
+
"%(refname:short)",
|
|
420
|
+
"%(HEAD)",
|
|
421
|
+
"%(upstream:short)",
|
|
422
|
+
"%(upstream:track)",
|
|
423
|
+
"%(objectname:short)",
|
|
424
|
+
"%(committerdate:unix)",
|
|
425
|
+
"%(contents:subject)"
|
|
426
|
+
].join(" ")}`,
|
|
427
|
+
"refs/heads",
|
|
428
|
+
"refs/remotes"
|
|
429
|
+
], "for-each-ref");
|
|
430
|
+
const local = [];
|
|
431
|
+
const remote = [];
|
|
432
|
+
for (const line of result.stdout.split("\n")) {
|
|
433
|
+
if (line.length === 0) continue;
|
|
434
|
+
const branch = branchOf(line.split(" "));
|
|
435
|
+
if (branch === null) continue;
|
|
436
|
+
if (branch.kind === "local") local.push(branch);
|
|
437
|
+
else remote.push(branch);
|
|
438
|
+
}
|
|
439
|
+
return {
|
|
440
|
+
local: [...local.filter((branch) => branch.current), ...local.filter((branch) => !branch.current)].slice(0, limits.maxBranches),
|
|
441
|
+
remote: remote.slice(0, limits.maxBranches)
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
/** Stashed work, newest first. */
|
|
445
|
+
async function readStashes(exec) {
|
|
446
|
+
const result = await run(exec, [
|
|
447
|
+
"stash",
|
|
448
|
+
"list",
|
|
449
|
+
"--format=%gd%x00%gs"
|
|
450
|
+
], "stash list");
|
|
451
|
+
const stashes = [];
|
|
452
|
+
for (const line of result.stdout.split("\n")) {
|
|
453
|
+
if (line.length === 0) continue;
|
|
454
|
+
const [ref, message] = line.split("\0");
|
|
455
|
+
const match = /^stash@\{(\d+)\}$/.exec(ref ?? "");
|
|
456
|
+
if (match === null) continue;
|
|
457
|
+
stashes.push({
|
|
458
|
+
index: Number(match[1]),
|
|
459
|
+
message: message ?? ""
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
return stashes;
|
|
463
|
+
}
|
|
464
|
+
/** Tags, newest first. */
|
|
465
|
+
async function readTags(exec, limits) {
|
|
466
|
+
if (limits.maxTags === 0) return [];
|
|
467
|
+
const result = await run(exec, [
|
|
468
|
+
"for-each-ref",
|
|
469
|
+
"--sort=-creatordate",
|
|
470
|
+
"--format=%(refname:short) %(creatordate:unix)",
|
|
471
|
+
"refs/tags"
|
|
472
|
+
], "for-each-ref");
|
|
473
|
+
const tags = [];
|
|
474
|
+
for (const line of result.stdout.split("\n")) {
|
|
475
|
+
if (line.length === 0) continue;
|
|
476
|
+
const [name, date] = line.split(" ");
|
|
477
|
+
if (name === void 0 || name.length === 0) continue;
|
|
478
|
+
tags.push({
|
|
479
|
+
name,
|
|
480
|
+
date: parseDate(date)
|
|
481
|
+
});
|
|
482
|
+
if (tags.length >= limits.maxTags) break;
|
|
483
|
+
}
|
|
484
|
+
return tags;
|
|
485
|
+
}
|
|
486
|
+
/** Current remote-tracking tips, keyed by short ref name. */
|
|
487
|
+
async function readRemoteTips(exec) {
|
|
488
|
+
const result = await run(exec, [
|
|
489
|
+
"for-each-ref",
|
|
490
|
+
"--format=%(refname:short)%09%(objectname)",
|
|
491
|
+
"refs/remotes"
|
|
492
|
+
], "for-each-ref");
|
|
493
|
+
const tips = /* @__PURE__ */ new Map();
|
|
494
|
+
for (const line of result.stdout.split("\n")) {
|
|
495
|
+
const [ref, hash] = line.split(" ");
|
|
496
|
+
if (ref !== void 0 && hash !== void 0 && ref.length > 0) tips.set(ref, hash);
|
|
497
|
+
}
|
|
498
|
+
return tips;
|
|
499
|
+
}
|
|
500
|
+
/** Configured remotes with their fetch URLs. */
|
|
501
|
+
async function readRemotes(exec) {
|
|
502
|
+
const result = await run(exec, ["remote", "-v"], "remote");
|
|
503
|
+
const seen = /* @__PURE__ */ new Map();
|
|
504
|
+
for (const line of result.stdout.split("\n")) {
|
|
505
|
+
const match = /^(\S+)\t(\S*) \(fetch\)$/.exec(line);
|
|
506
|
+
if (match === null) continue;
|
|
507
|
+
const name = match[1];
|
|
508
|
+
const url = match[2];
|
|
509
|
+
if (!seen.has(name)) seen.set(name, url);
|
|
510
|
+
}
|
|
511
|
+
return [...seen.entries()].map(([name, url]) => ({
|
|
512
|
+
name,
|
|
513
|
+
url
|
|
514
|
+
}));
|
|
515
|
+
}
|
|
516
|
+
/** Parse a Git `--date=unix` timestamp into milliseconds, or null. */
|
|
517
|
+
function parseDate(text) {
|
|
518
|
+
const seconds = Number(text);
|
|
519
|
+
return Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1e3) : null;
|
|
520
|
+
}
|
|
521
|
+
/** Parse one count line from `rev-list --count`, or null. */
|
|
522
|
+
function parseCount(text) {
|
|
523
|
+
const value = Number(text);
|
|
524
|
+
return Number.isFinite(value) && value >= 0 ? value : null;
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* The repository identity block shared by `summary` and `status`.
|
|
528
|
+
* @param options - the seam, the checkout root, and the limits.
|
|
529
|
+
* @returns the `repo` and `changes` objects of the wire contract.
|
|
530
|
+
*/
|
|
531
|
+
async function readRepo({ exec, root, limits }) {
|
|
532
|
+
const { commonDir, gitDir } = await gitDirectories(exec, root);
|
|
533
|
+
const [branch, head, upstream, remotes, fetched, pending, changes] = await Promise.all([
|
|
534
|
+
currentBranch(exec),
|
|
535
|
+
headCommit(exec),
|
|
536
|
+
upstreamBranch(exec),
|
|
537
|
+
readRemotes(exec),
|
|
538
|
+
lastFetchAt(commonDir),
|
|
539
|
+
pendingOperation(gitDir),
|
|
540
|
+
readChanges(exec, limits)
|
|
541
|
+
]);
|
|
542
|
+
const counts = await aheadBehind(exec, upstream);
|
|
543
|
+
return {
|
|
544
|
+
repo: {
|
|
545
|
+
root,
|
|
546
|
+
name: root.split(/[\\/]/).filter((part) => part.length > 0).pop() ?? root,
|
|
547
|
+
branch,
|
|
548
|
+
detached: branch === null && head.unborn === false,
|
|
549
|
+
unborn: head.unborn,
|
|
550
|
+
upstream,
|
|
551
|
+
ahead: counts.ahead,
|
|
552
|
+
behind: counts.behind,
|
|
553
|
+
remotes,
|
|
554
|
+
head: head.head,
|
|
555
|
+
lastFetchAt: fetched,
|
|
556
|
+
isWorktree: commonDir !== gitDir,
|
|
557
|
+
pending,
|
|
558
|
+
totalChanges: changes.total
|
|
559
|
+
},
|
|
560
|
+
changes: {
|
|
561
|
+
staged: changes.staged,
|
|
562
|
+
unstaged: changes.unstaged,
|
|
563
|
+
untracked: changes.untracked,
|
|
564
|
+
conflicted: changes.conflicted
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Read the repository identity, branches, stashes, and tags in one call.
|
|
570
|
+
* @param request - `exec`, `cwd`, and `limits`.
|
|
571
|
+
* @returns the `Summary` of the wire contract.
|
|
572
|
+
* @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.
|
|
573
|
+
*/
|
|
574
|
+
async function gitSummary({ exec, cwd, limits = {} }) {
|
|
575
|
+
const bounds = resolveLimits(limits);
|
|
576
|
+
const root = await repositoryRoot(exec, cwd);
|
|
577
|
+
if (root === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
|
|
578
|
+
const [{ repo, changes }, branches, stashes, tags] = await Promise.all([
|
|
579
|
+
readRepo({
|
|
580
|
+
exec,
|
|
581
|
+
root,
|
|
582
|
+
limits: bounds
|
|
583
|
+
}),
|
|
584
|
+
readBranches(exec, bounds),
|
|
585
|
+
readStashes(exec),
|
|
586
|
+
readTags(exec, bounds)
|
|
587
|
+
]);
|
|
588
|
+
return {
|
|
589
|
+
repo,
|
|
590
|
+
changes,
|
|
591
|
+
branches,
|
|
592
|
+
stashes,
|
|
593
|
+
tags
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* Read the repository identity and working-tree changes only, for polling.
|
|
598
|
+
* @param request - `exec`, `cwd`, and `limits`.
|
|
599
|
+
* @returns the light snapshot.
|
|
600
|
+
* @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.
|
|
601
|
+
*/
|
|
602
|
+
async function gitStatus({ exec, cwd, limits = {} }) {
|
|
603
|
+
const bounds = resolveLimits(limits);
|
|
604
|
+
const root = await repositoryRoot(exec, cwd);
|
|
605
|
+
if (root === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
|
|
606
|
+
return await readRepo({
|
|
607
|
+
exec,
|
|
608
|
+
root,
|
|
609
|
+
limits: bounds
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
/** Largest patch handed to the model. */
|
|
613
|
+
var COMMIT_MESSAGE_DIFF_BYTES = 49152;
|
|
614
|
+
/** Recent commit subjects read for style. */
|
|
615
|
+
var COMMIT_MESSAGE_RECENT = 8;
|
|
616
|
+
/** Conventional Commits subject prefix, used to observe the repository style. */
|
|
617
|
+
var CONVENTIONAL_SUBJECT = /^(?:feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(?:\([^)]+\))?!?:\s+/;
|
|
618
|
+
/** Record and field separators that keep multi-line bodies apart in one log call. */
|
|
619
|
+
var LOG_RECORD = "";
|
|
620
|
+
var LOG_FIELD = "";
|
|
621
|
+
/**
|
|
622
|
+
* Read the changes a commit message should describe. Staged changes win; a
|
|
623
|
+
* checkout with none staged is described by its working tree instead.
|
|
624
|
+
* @param request - the `exec` seam, a directory inside the checkout, and limits.
|
|
625
|
+
* @returns the scope, changed paths, patch, truncation flag, and recent subjects.
|
|
626
|
+
* @throws {GitError} `NOT_A_REPO` outside a work tree, or a structured Git failure.
|
|
627
|
+
*/
|
|
628
|
+
async function gitCommitMessageContext({ exec, cwd, limits = {} }) {
|
|
629
|
+
const bounds = resolveLimits(limits);
|
|
630
|
+
const root = await repositoryRoot(exec, cwd);
|
|
631
|
+
if (root === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
|
|
632
|
+
const { changes } = await readRepo({
|
|
633
|
+
exec,
|
|
634
|
+
root,
|
|
635
|
+
limits: bounds
|
|
636
|
+
});
|
|
637
|
+
const stagedFiles = changes.staged.map(changeFile);
|
|
638
|
+
const worktreeFiles = [
|
|
639
|
+
...changes.unstaged,
|
|
640
|
+
...changes.untracked,
|
|
641
|
+
...changes.conflicted
|
|
642
|
+
].map(changeFile);
|
|
643
|
+
const staged = stagedFiles.length > 0;
|
|
644
|
+
const files = staged ? stagedFiles : worktreeFiles;
|
|
645
|
+
const args = staged ? [
|
|
646
|
+
"diff",
|
|
647
|
+
"--cached",
|
|
648
|
+
"--no-color",
|
|
649
|
+
"--no-ext-diff",
|
|
650
|
+
"-M",
|
|
651
|
+
"--unified=3"
|
|
652
|
+
] : [
|
|
653
|
+
"diff",
|
|
654
|
+
"--no-color",
|
|
655
|
+
"--no-ext-diff",
|
|
656
|
+
"-M",
|
|
657
|
+
"--unified=3"
|
|
658
|
+
];
|
|
659
|
+
const patch = files.length === 0 ? "" : (await run(exec, args, "diff")).stdout;
|
|
660
|
+
const history = await exec(argvOf([
|
|
661
|
+
"log",
|
|
662
|
+
`-${COMMIT_MESSAGE_RECENT}`,
|
|
663
|
+
`--format=%s${LOG_FIELD}%b${LOG_RECORD}`
|
|
664
|
+
]), { allowedExitCodes: [0, 128] });
|
|
665
|
+
const commits = history.exitCode === 0 ? history.stdout.split(LOG_RECORD).map((record) => record.replace(/^\r?\n/, "")).filter((record) => record.trim().length > 0).map((record) => {
|
|
666
|
+
const [subject = "", body = ""] = record.split(LOG_FIELD);
|
|
667
|
+
return {
|
|
668
|
+
subject: subject.trim(),
|
|
669
|
+
body: body.trim()
|
|
670
|
+
};
|
|
671
|
+
}) : [];
|
|
672
|
+
const recent = commits.map((commit) => commit.subject).filter((subject) => subject.length > 0);
|
|
673
|
+
const half = Math.ceil(commits.length / 2);
|
|
674
|
+
const recentConventional = half > 0 && commits.filter((commit) => CONVENTIONAL_SUBJECT.test(commit.subject)).length >= half;
|
|
675
|
+
const recentHasBody = half > 0 && commits.filter((commit) => commit.body.length > 0).length >= half;
|
|
676
|
+
const truncated = Buffer.byteLength(patch, "utf8") > COMMIT_MESSAGE_DIFF_BYTES;
|
|
677
|
+
return {
|
|
678
|
+
staged,
|
|
679
|
+
files,
|
|
680
|
+
diff: truncated ? `${Buffer.from(patch, "utf8").subarray(0, COMMIT_MESSAGE_DIFF_BYTES).toString("utf8")}\n… (diff truncated)` : patch,
|
|
681
|
+
truncated,
|
|
682
|
+
recent,
|
|
683
|
+
recentConventional,
|
|
684
|
+
recentHasBody
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
/** Project one change-list entry onto the prompt's file view. */
|
|
688
|
+
function changeFile(entry) {
|
|
689
|
+
return {
|
|
690
|
+
status: entry.status,
|
|
691
|
+
path: entry.path
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
/** Reject a path that would escape the repository or confuse Git's argument parser. */
|
|
695
|
+
function checkedPath(path) {
|
|
696
|
+
if (typeof path !== "string" || path.length === 0) throw new GitError("INVALID", "a file path is required");
|
|
697
|
+
if (path.includes("\0")) throw new GitError("INVALID", "a path must not contain a NUL byte");
|
|
698
|
+
if (isAbsolute(path)) throw new GitError("INVALID", "a path must be relative to the repository root");
|
|
699
|
+
const normalized = normalize(path).split("\\").join("/");
|
|
700
|
+
if (normalized === ".." || normalized.startsWith("../")) throw new GitError("INVALID", "a path must stay inside the repository");
|
|
701
|
+
return normalized;
|
|
702
|
+
}
|
|
703
|
+
/** Reject a ref argument the client asks to walk. */
|
|
704
|
+
function checkedRef(ref) {
|
|
705
|
+
if (typeof ref !== "string" || ref.length === 0) throw new GitError("INVALID", "a ref is required");
|
|
706
|
+
if (ref.startsWith("-") || /\s/.test(ref) || ref.includes("\0")) throw new GitError("INVALID", `"${ref}" is not a valid ref`);
|
|
707
|
+
return ref;
|
|
708
|
+
}
|
|
709
|
+
/** One Git config value, or null when unset. */
|
|
710
|
+
async function configValue(exec, key) {
|
|
711
|
+
const result = await exec(argvOf([
|
|
712
|
+
"config",
|
|
713
|
+
"--get",
|
|
714
|
+
key
|
|
715
|
+
]), { allowedExitCodes: [0, 1] });
|
|
716
|
+
return result.exitCode === 0 ? result.stdout.trim() : null;
|
|
717
|
+
}
|
|
718
|
+
/** Reject anything that is not a commit identity. */
|
|
719
|
+
function checkedHash(hash) {
|
|
720
|
+
if (typeof hash !== "string" || !/^[0-9a-f]{4,64}$/i.test(hash)) throw new GitError("INVALID", "a commit hash is required");
|
|
721
|
+
return hash.toLowerCase();
|
|
722
|
+
}
|
|
723
|
+
/** Resolve a ref or abbreviation to a full commit hash. */
|
|
724
|
+
async function resolveCommit(exec, ref) {
|
|
725
|
+
const result = await exec(argvOf([
|
|
726
|
+
"rev-parse",
|
|
727
|
+
"--verify",
|
|
728
|
+
"--quiet",
|
|
729
|
+
`${checkedRef(ref)}^{commit}`
|
|
730
|
+
]), { allowedExitCodes: [
|
|
731
|
+
0,
|
|
732
|
+
1,
|
|
733
|
+
128
|
|
734
|
+
] });
|
|
735
|
+
if (result.exitCode !== 0) throw new GitError("INVALID", `"${ref}" does not name a commit`);
|
|
736
|
+
return firstLine$1(result.stdout);
|
|
737
|
+
}
|
|
738
|
+
/** The first parent of a commit, or null for a root commit. */
|
|
739
|
+
async function firstParent(exec, commit) {
|
|
740
|
+
const result = await exec(argvOf([
|
|
741
|
+
"rev-parse",
|
|
742
|
+
"--verify",
|
|
743
|
+
"--quiet",
|
|
744
|
+
`${commit}^`
|
|
745
|
+
]), { allowedExitCodes: [
|
|
746
|
+
0,
|
|
747
|
+
1,
|
|
748
|
+
128
|
|
749
|
+
] });
|
|
750
|
+
return result.exitCode === 0 ? firstLine$1(result.stdout) : null;
|
|
751
|
+
}
|
|
752
|
+
/** Count added and deleted lines in a unified diff. */
|
|
753
|
+
function countDiffLines(text) {
|
|
754
|
+
let added = 0;
|
|
755
|
+
let deleted = 0;
|
|
756
|
+
for (const line of text.split("\n")) {
|
|
757
|
+
if (line.startsWith("+++") || line.startsWith("---")) continue;
|
|
758
|
+
if (line.startsWith("+")) added += 1;
|
|
759
|
+
else if (line.startsWith("-")) deleted += 1;
|
|
760
|
+
}
|
|
761
|
+
return {
|
|
762
|
+
added,
|
|
763
|
+
deleted
|
|
764
|
+
};
|
|
765
|
+
}
|
|
766
|
+
/** Build the wire `Diff` from raw patch text. */
|
|
767
|
+
function diffOf({ path, staged, text, maxDiffBytes }) {
|
|
768
|
+
const tooLarge = text.length > maxDiffBytes;
|
|
769
|
+
const body = tooLarge ? text.slice(0, maxDiffBytes) : text;
|
|
770
|
+
const binary = /^Binary files .* differ$/m.test(body);
|
|
771
|
+
const counts = binary ? {
|
|
772
|
+
added: 0,
|
|
773
|
+
deleted: 0
|
|
774
|
+
} : countDiffLines(body);
|
|
775
|
+
return {
|
|
776
|
+
path,
|
|
777
|
+
staged,
|
|
778
|
+
text: body,
|
|
779
|
+
binary,
|
|
780
|
+
tooLarge,
|
|
781
|
+
added: counts.added,
|
|
782
|
+
deleted: counts.deleted
|
|
783
|
+
};
|
|
784
|
+
}
|
|
785
|
+
/** Render a synthetic unified diff for an untracked file. */
|
|
786
|
+
async function untrackedDiff(root, path, maxDiffBytes) {
|
|
787
|
+
const absolute = join(root, path);
|
|
788
|
+
let buffer;
|
|
789
|
+
try {
|
|
790
|
+
buffer = await readFile(absolute);
|
|
791
|
+
} catch {
|
|
792
|
+
throw new GitError("GIT_FAILED", `${path} could not be read`);
|
|
793
|
+
}
|
|
794
|
+
if (buffer.subarray(0, 8e3).includes(0)) return {
|
|
795
|
+
path,
|
|
796
|
+
staged: false,
|
|
797
|
+
text: `Binary file ${path} is untracked\n`,
|
|
798
|
+
binary: true,
|
|
799
|
+
tooLarge: false,
|
|
800
|
+
added: 0,
|
|
801
|
+
deleted: 0
|
|
802
|
+
};
|
|
803
|
+
const text = buffer.toString("utf8");
|
|
804
|
+
const lines = text.split("\n");
|
|
805
|
+
if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
|
|
806
|
+
const tooLarge = buffer.byteLength > maxDiffBytes || text.length > maxDiffBytes;
|
|
807
|
+
const shown = tooLarge ? lines.slice(0, Math.max(0, Math.floor(maxDiffBytes / 40))) : lines;
|
|
808
|
+
return {
|
|
809
|
+
path,
|
|
810
|
+
staged: false,
|
|
811
|
+
text: [...[
|
|
812
|
+
`diff --git a/${path} b/${path}`,
|
|
813
|
+
"new file mode 100644",
|
|
814
|
+
"--- /dev/null",
|
|
815
|
+
`+++ b/${path}`,
|
|
816
|
+
`@@ -0,0 +1,${lines.length} @@`
|
|
817
|
+
], ...shown.map((line) => `+${line}`)].join("\n"),
|
|
818
|
+
binary: false,
|
|
819
|
+
tooLarge,
|
|
820
|
+
added: lines.length,
|
|
821
|
+
deleted: 0
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Read one working-tree file's unified diff.
|
|
826
|
+
* @param request - `exec`, `cwd`, `limits`, `path`, `staged`, and `untracked`.
|
|
827
|
+
* @returns the `Diff` of the wire contract.
|
|
828
|
+
* @throws {GitError} `INVALID` for an unsafe path, `NOT_A_REPO` outside a work tree, or a structured Git failure.
|
|
829
|
+
*/
|
|
830
|
+
async function gitDiff({ exec, cwd, limits = {}, path, staged = false, untracked = false }) {
|
|
831
|
+
const bounds = resolveLimits(limits);
|
|
832
|
+
const root = await repositoryRoot(exec, cwd);
|
|
833
|
+
if (root === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
|
|
834
|
+
const checked = checkedPath(path);
|
|
835
|
+
if (untracked) return await untrackedDiff(root, checked, bounds.maxDiffBytes);
|
|
836
|
+
const args = [
|
|
837
|
+
"diff",
|
|
838
|
+
"--no-color",
|
|
839
|
+
"--no-ext-diff",
|
|
840
|
+
"-U3"
|
|
841
|
+
];
|
|
842
|
+
if (staged) args.push("--cached");
|
|
843
|
+
args.push("--", checked);
|
|
844
|
+
return diffOf({
|
|
845
|
+
path: checked,
|
|
846
|
+
staged,
|
|
847
|
+
text: (await run(exec, args, "diff")).stdout,
|
|
848
|
+
maxDiffBytes: bounds.maxDiffBytes
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
/**
|
|
852
|
+
* Read one branch's or ref's commits, newest first.
|
|
853
|
+
* @param request - `exec`, `cwd`, `limits`, `ref`, `skip`, and `limit`.
|
|
854
|
+
* @returns the page of commits.
|
|
855
|
+
* @throws {GitError} `INVALID` for an unknown ref, `NOT_A_REPO` outside a work tree, or a structured Git failure.
|
|
856
|
+
*/
|
|
857
|
+
async function gitCommits({ exec, cwd, limits = {}, ref, skip = 0, limit }) {
|
|
858
|
+
const bounds = resolveLimits(limits);
|
|
859
|
+
if (await repositoryRoot(exec, cwd) === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
|
|
860
|
+
const commit = await resolveCommit(exec, ref);
|
|
861
|
+
const take = typeof limit === "number" && Number.isSafeInteger(limit) && limit > 0 ? Math.min(limit, 200) : bounds.maxCommits;
|
|
862
|
+
const offset = typeof skip === "number" && Number.isSafeInteger(skip) && skip > 0 ? skip : 0;
|
|
863
|
+
const result = await exec(argvOf([
|
|
864
|
+
"log",
|
|
865
|
+
`-n${take + 1}`,
|
|
866
|
+
`--skip=${offset}`,
|
|
867
|
+
"--date=unix",
|
|
868
|
+
"--pretty=format:%H%x00%h%x00%s%x00%an%x00%at%x00%P%x00%D",
|
|
869
|
+
commit
|
|
870
|
+
]), { allowedExitCodes: [0, 128] });
|
|
871
|
+
if (result.exitCode !== 0) throw new GitError("GIT_FAILED", `git log failed: ${firstLine$1(result.stderr)}`, excerpt$1(result.stderr));
|
|
872
|
+
const commits = [];
|
|
873
|
+
for (const line of result.stdout.split("\n")) {
|
|
874
|
+
if (line.length === 0) continue;
|
|
875
|
+
const [hash, short, subject, author, date, parents, refs] = line.split("\0");
|
|
876
|
+
commits.push({
|
|
877
|
+
hash: hash ?? "",
|
|
878
|
+
short: short ?? "",
|
|
879
|
+
subject: subject ?? "",
|
|
880
|
+
author: author ?? "",
|
|
881
|
+
date: parseDate(date),
|
|
882
|
+
parents: (parents ?? "").split(" ").filter(Boolean).length,
|
|
883
|
+
refs: (refs ?? "").split(", ").map((entry) => entry.trim()).filter((entry) => entry.length > 0)
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
return {
|
|
887
|
+
ref: commit,
|
|
888
|
+
commits: commits.slice(0, take),
|
|
889
|
+
more: commits.length > take
|
|
890
|
+
};
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* Read the commit history of one file, newest first, following renames.
|
|
894
|
+
* @param request - `exec`, `cwd`, `limits`, `path`, `skip`, and `limit`.
|
|
895
|
+
* @returns the page of commits.
|
|
896
|
+
* @throws {GitError} `INVALID` for an unsafe path, `NOT_A_REPO` outside a work tree, or a structured Git failure.
|
|
897
|
+
*/
|
|
898
|
+
async function gitFileHistory({ exec, cwd, limits = {}, path, skip = 0, limit }) {
|
|
899
|
+
const bounds = resolveLimits(limits);
|
|
900
|
+
if (await repositoryRoot(exec, cwd) === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
|
|
901
|
+
const checked = checkedPath(path);
|
|
902
|
+
const take = typeof limit === "number" && Number.isSafeInteger(limit) && limit > 0 ? Math.min(limit, 200) : bounds.maxCommits;
|
|
903
|
+
const offset = typeof skip === "number" && Number.isSafeInteger(skip) && skip > 0 ? skip : 0;
|
|
904
|
+
const result = await exec(argvOf([
|
|
905
|
+
"log",
|
|
906
|
+
`-n${take + 1}`,
|
|
907
|
+
`--skip=${offset}`,
|
|
908
|
+
"--follow",
|
|
909
|
+
"--date=unix",
|
|
910
|
+
"--pretty=format:%H%x00%h%x00%s%x00%an%x00%at%x00%P%x00%D",
|
|
911
|
+
"--",
|
|
912
|
+
checked
|
|
913
|
+
]), { allowedExitCodes: [0, 128] });
|
|
914
|
+
if (result.exitCode !== 0) throw new GitError("GIT_FAILED", `git log failed: ${firstLine$1(result.stderr)}`, excerpt$1(result.stderr));
|
|
915
|
+
const commits = [];
|
|
916
|
+
for (const line of result.stdout.split("\n")) {
|
|
917
|
+
if (line.length === 0) continue;
|
|
918
|
+
const [hash, short, subject, author, date, parents, refs] = line.split("\0");
|
|
919
|
+
commits.push({
|
|
920
|
+
hash: hash ?? "",
|
|
921
|
+
short: short ?? "",
|
|
922
|
+
subject: subject ?? "",
|
|
923
|
+
author: author ?? "",
|
|
924
|
+
date: parseDate(date),
|
|
925
|
+
parents: (parents ?? "").split(" ").filter(Boolean).length,
|
|
926
|
+
refs: (refs ?? "").split(", ").map((entry) => entry.trim()).filter((entry) => entry.length > 0)
|
|
927
|
+
});
|
|
928
|
+
}
|
|
929
|
+
return {
|
|
930
|
+
path: checked,
|
|
931
|
+
commits: commits.slice(0, take),
|
|
932
|
+
more: commits.length > take
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
/** Parse `--numstat -z` output into path → line counts. */
|
|
936
|
+
function parseNumstat(output) {
|
|
937
|
+
const counts = /* @__PURE__ */ new Map();
|
|
938
|
+
const fields = output.split("\0");
|
|
939
|
+
for (let index = 0; index < fields.length; index += 1) {
|
|
940
|
+
const record = fields[index];
|
|
941
|
+
if (record.length === 0) continue;
|
|
942
|
+
const firstTab = record.indexOf(" ");
|
|
943
|
+
const secondTab = record.indexOf(" ", firstTab + 1);
|
|
944
|
+
if (firstTab < 0 || secondTab < 0) continue;
|
|
945
|
+
const additions = record.slice(0, firstTab);
|
|
946
|
+
const deletions = record.slice(firstTab + 1, secondTab);
|
|
947
|
+
const rest = record.slice(secondTab + 1);
|
|
948
|
+
const path = rest.length > 0 ? rest : fields[index + 2] ?? "";
|
|
949
|
+
if (rest.length === 0) index += 2;
|
|
950
|
+
counts.set(path, {
|
|
951
|
+
additions: additions === "-" ? null : Number(additions),
|
|
952
|
+
deletions: deletions === "-" ? null : Number(deletions)
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
return counts;
|
|
956
|
+
}
|
|
957
|
+
/**
|
|
958
|
+
* Read the files one commit changed, against its first parent.
|
|
959
|
+
* @param request - `exec`, `cwd`, `limits`, and `hash`.
|
|
960
|
+
* @returns the changed files with their line counts.
|
|
961
|
+
* @throws {GitError} `INVALID` for an unknown commit, `NOT_A_REPO` outside a work tree, or a structured Git failure.
|
|
962
|
+
*/
|
|
963
|
+
async function gitCommitFiles({ exec, cwd, limits = {}, hash }) {
|
|
964
|
+
const bounds = resolveLimits(limits);
|
|
965
|
+
if (await repositoryRoot(exec, cwd) === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
|
|
966
|
+
const commit = await resolveCommit(exec, checkedHash(hash));
|
|
967
|
+
const parent = await firstParent(exec, commit);
|
|
968
|
+
const [names, numstat] = await Promise.all([parent === null ? run(exec, [
|
|
969
|
+
"diff-tree",
|
|
970
|
+
"--root",
|
|
971
|
+
"-r",
|
|
972
|
+
"--no-commit-id",
|
|
973
|
+
"--name-status",
|
|
974
|
+
commit
|
|
975
|
+
], "diff-tree") : run(exec, [
|
|
976
|
+
"diff",
|
|
977
|
+
"--name-status",
|
|
978
|
+
"-M",
|
|
979
|
+
parent,
|
|
980
|
+
commit
|
|
981
|
+
], "diff"), parent === null ? run(exec, [
|
|
982
|
+
"diff-tree",
|
|
983
|
+
"--root",
|
|
984
|
+
"-r",
|
|
985
|
+
"--no-commit-id",
|
|
986
|
+
"--numstat",
|
|
987
|
+
"-z",
|
|
988
|
+
"-M",
|
|
989
|
+
commit
|
|
990
|
+
], "diff-tree") : run(exec, [
|
|
991
|
+
"diff",
|
|
992
|
+
"--numstat",
|
|
993
|
+
"-z",
|
|
994
|
+
"-M",
|
|
995
|
+
parent,
|
|
996
|
+
commit
|
|
997
|
+
], "diff")]);
|
|
998
|
+
const counts = parseNumstat(numstat.stdout);
|
|
999
|
+
const files = [];
|
|
1000
|
+
let additions = 0;
|
|
1001
|
+
let deletions = 0;
|
|
1002
|
+
for (const line of names.stdout.split("\n")) {
|
|
1003
|
+
if (line.length === 0) continue;
|
|
1004
|
+
const fields = line.split(" ");
|
|
1005
|
+
const code = (fields[0] ?? "M").charAt(0);
|
|
1006
|
+
const renamed = code === "R" || code === "C";
|
|
1007
|
+
const path = renamed ? fields[2] ?? "" : fields[1] ?? "";
|
|
1008
|
+
if (path.length === 0) continue;
|
|
1009
|
+
const stat = counts.get(path) ?? {
|
|
1010
|
+
additions: 0,
|
|
1011
|
+
deletions: 0
|
|
1012
|
+
};
|
|
1013
|
+
additions += stat.additions ?? 0;
|
|
1014
|
+
deletions += stat.deletions ?? 0;
|
|
1015
|
+
files.push({
|
|
1016
|
+
path,
|
|
1017
|
+
origPath: renamed ? fields[1] ?? null : null,
|
|
1018
|
+
status: STATUS_OF_CODE[code] ?? "modified",
|
|
1019
|
+
code,
|
|
1020
|
+
staged: false,
|
|
1021
|
+
additions: stat.additions,
|
|
1022
|
+
deletions: stat.deletions
|
|
1023
|
+
});
|
|
1024
|
+
if (files.length >= bounds.maxFiles) break;
|
|
1025
|
+
}
|
|
1026
|
+
return {
|
|
1027
|
+
hash: commit,
|
|
1028
|
+
files,
|
|
1029
|
+
additions,
|
|
1030
|
+
deletions,
|
|
1031
|
+
truncated: files.length >= bounds.maxFiles
|
|
1032
|
+
};
|
|
1033
|
+
}
|
|
1034
|
+
/**
|
|
1035
|
+
* Read one file's diff inside a commit.
|
|
1036
|
+
* @param request - `exec`, `cwd`, `limits`, `hash`, and `path`.
|
|
1037
|
+
* @returns the `Diff` of the wire contract.
|
|
1038
|
+
* @throws {GitError} `INVALID` for an unknown commit or unsafe path, `NOT_A_REPO` outside a work tree, or a structured Git failure.
|
|
1039
|
+
*/
|
|
1040
|
+
async function gitCommitDiff({ exec, cwd, limits = {}, hash, path }) {
|
|
1041
|
+
const bounds = resolveLimits(limits);
|
|
1042
|
+
if (await repositoryRoot(exec, cwd) === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
|
|
1043
|
+
const commit = await resolveCommit(exec, checkedHash(hash));
|
|
1044
|
+
const checked = checkedPath(path);
|
|
1045
|
+
const parent = await firstParent(exec, commit);
|
|
1046
|
+
return diffOf({
|
|
1047
|
+
path: checked,
|
|
1048
|
+
staged: false,
|
|
1049
|
+
text: (await run(exec, parent === null ? [
|
|
1050
|
+
"show",
|
|
1051
|
+
"--no-color",
|
|
1052
|
+
"--no-ext-diff",
|
|
1053
|
+
"--format=",
|
|
1054
|
+
"-U3",
|
|
1055
|
+
commit,
|
|
1056
|
+
"--",
|
|
1057
|
+
checked
|
|
1058
|
+
] : [
|
|
1059
|
+
"diff",
|
|
1060
|
+
"--no-color",
|
|
1061
|
+
"--no-ext-diff",
|
|
1062
|
+
"-U3",
|
|
1063
|
+
parent,
|
|
1064
|
+
commit,
|
|
1065
|
+
"--",
|
|
1066
|
+
checked
|
|
1067
|
+
], "diff")).stdout,
|
|
1068
|
+
maxDiffBytes: bounds.maxDiffBytes
|
|
1069
|
+
});
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Read one stash entry's patch.
|
|
1073
|
+
* @param request - `exec`, `cwd`, `limits`, and `index`.
|
|
1074
|
+
* @returns the `Diff` of the wire contract, addressed as `stash@{index}`.
|
|
1075
|
+
* @throws {GitError} `INVALID` for a missing index, `NOT_A_REPO` outside a work tree, or a structured Git failure.
|
|
1076
|
+
*/
|
|
1077
|
+
async function gitStashDiff({ exec, cwd, limits = {}, index }) {
|
|
1078
|
+
const bounds = resolveLimits(limits);
|
|
1079
|
+
if (await repositoryRoot(exec, cwd) === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
|
|
1080
|
+
const ref = `stash@{${checkedStashIndex(index)}}`;
|
|
1081
|
+
const result = await exec(argvOf([
|
|
1082
|
+
"stash",
|
|
1083
|
+
"show",
|
|
1084
|
+
"-p",
|
|
1085
|
+
"--no-color",
|
|
1086
|
+
ref
|
|
1087
|
+
]), { allowedExitCodes: [0, 128] });
|
|
1088
|
+
if (result.exitCode !== 0) throw new GitError("GIT_FAILED", `git stash show failed: ${firstLine$1(result.stderr)}`, excerpt$1(result.stderr));
|
|
1089
|
+
return diffOf({
|
|
1090
|
+
path: ref,
|
|
1091
|
+
staged: false,
|
|
1092
|
+
text: result.stdout,
|
|
1093
|
+
maxDiffBytes: bounds.maxDiffBytes
|
|
1094
|
+
});
|
|
1095
|
+
}
|
|
1096
|
+
/** Validate a stash index from the client. */
|
|
1097
|
+
function checkedStashIndex(index) {
|
|
1098
|
+
if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) throw new GitError("INVALID", "a stash index is required");
|
|
1099
|
+
return index;
|
|
1100
|
+
}
|
|
1101
|
+
/** Validate a local branch name with Git's own rule. */
|
|
1102
|
+
async function checkBranchName(exec, name) {
|
|
1103
|
+
if (typeof name !== "string" || name.trim().length === 0) throw new GitError("INVALID", "a branch name is required");
|
|
1104
|
+
if ((await exec(argvOf([
|
|
1105
|
+
"check-ref-format",
|
|
1106
|
+
"--branch",
|
|
1107
|
+
name
|
|
1108
|
+
]), { allowedExitCodes: [
|
|
1109
|
+
0,
|
|
1110
|
+
1,
|
|
1111
|
+
128
|
|
1112
|
+
] })).exitCode !== 0) throw new GitError("INVALID", `"${name}" is not a valid branch name`);
|
|
1113
|
+
return name;
|
|
1114
|
+
}
|
|
1115
|
+
/** Validate a tag name with Git's own rule. */
|
|
1116
|
+
async function checkTagName(exec, name) {
|
|
1117
|
+
if (typeof name !== "string" || name.trim().length === 0) throw new GitError("INVALID", "a tag name is required");
|
|
1118
|
+
if ((await exec(argvOf(["check-ref-format", `refs/tags/${name}`]), { allowedExitCodes: [
|
|
1119
|
+
0,
|
|
1120
|
+
1,
|
|
1121
|
+
128
|
|
1122
|
+
] })).exitCode !== 0) throw new GitError("INVALID", `"${name}" is not a valid tag name`);
|
|
1123
|
+
return name;
|
|
1124
|
+
}
|
|
1125
|
+
/** Whether a local branch exists. */
|
|
1126
|
+
async function localBranchExists(exec, name) {
|
|
1127
|
+
return (await exec(argvOf([
|
|
1128
|
+
"show-ref",
|
|
1129
|
+
"--verify",
|
|
1130
|
+
"--quiet",
|
|
1131
|
+
`refs/heads/${name}`
|
|
1132
|
+
]), { allowedExitCodes: [
|
|
1133
|
+
0,
|
|
1134
|
+
1,
|
|
1135
|
+
128
|
|
1136
|
+
] })).exitCode === 0;
|
|
1137
|
+
}
|
|
1138
|
+
/** Whether the repository has no commit yet. */
|
|
1139
|
+
async function isUnborn(exec) {
|
|
1140
|
+
return (await exec(argvOf([
|
|
1141
|
+
"rev-parse",
|
|
1142
|
+
"--verify",
|
|
1143
|
+
"--quiet",
|
|
1144
|
+
"HEAD"
|
|
1145
|
+
]), { allowedExitCodes: [
|
|
1146
|
+
0,
|
|
1147
|
+
1,
|
|
1148
|
+
128
|
|
1149
|
+
] })).exitCode !== 0;
|
|
1150
|
+
}
|
|
1151
|
+
/** Read the checked-out branch name, for operations that need one. */
|
|
1152
|
+
async function requireBranch(exec) {
|
|
1153
|
+
const branch = await currentBranch(exec);
|
|
1154
|
+
if (branch === null) throw new GitError("INVALID", "the repository has no checked-out branch");
|
|
1155
|
+
return branch;
|
|
1156
|
+
}
|
|
1157
|
+
/** Configured remote names, in the order `git remote` prints them. */
|
|
1158
|
+
async function remoteNames(exec) {
|
|
1159
|
+
return (await run(exec, ["remote"], "remote")).stdout.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
|
|
1160
|
+
}
|
|
1161
|
+
/** The remote a publish should target: `origin` when configured, else the only one, else the first. */
|
|
1162
|
+
async function defaultRemote(exec) {
|
|
1163
|
+
const names = await remoteNames(exec);
|
|
1164
|
+
if (names.length === 0) return null;
|
|
1165
|
+
return names.includes("origin") ? "origin" : names[0];
|
|
1166
|
+
}
|
|
1167
|
+
/** A configured remote name, for commands that address one. */
|
|
1168
|
+
function checkedRemoteName(name) {
|
|
1169
|
+
const value = typeof name === "string" ? name.trim() : "";
|
|
1170
|
+
if (value.length === 0) throw new GitError("INVALID", "a remote name is required");
|
|
1171
|
+
if (value.startsWith("-") || /[\s\0-\x1f\x7f]/.test(value)) throw new GitError("INVALID", `"${value}" is not a valid remote name`);
|
|
1172
|
+
return value;
|
|
1173
|
+
}
|
|
1174
|
+
/** A remote URL handed to `git remote add`. */
|
|
1175
|
+
function checkedRemoteUrl(url) {
|
|
1176
|
+
const value = typeof url === "string" ? url.trim() : "";
|
|
1177
|
+
if (value.length === 0) throw new GitError("INVALID", "a remote URL is required");
|
|
1178
|
+
if (value.startsWith("-") || /[\0-\x1f\x7f]/.test(value)) throw new GitError("INVALID", `"${value}" is not a valid remote URL`);
|
|
1179
|
+
return value;
|
|
1180
|
+
}
|
|
1181
|
+
/** A GitHub repository name or `owner/name`, as `gh repo create` accepts it. */
|
|
1182
|
+
function checkedGithubRepository(name) {
|
|
1183
|
+
const value = typeof name === "string" ? name.trim() : "";
|
|
1184
|
+
if (value.length === 0) throw new GitError("INVALID", "a GitHub repository name is required");
|
|
1185
|
+
if (!/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)?$/.test(value)) throw new GitError("INVALID", `"${value}" is not a valid GitHub repository name`);
|
|
1186
|
+
return value;
|
|
1187
|
+
}
|
|
1188
|
+
/** Initialize a new repository in the Session directory. */
|
|
1189
|
+
async function initRepository(exec, cwd) {
|
|
1190
|
+
if (await repositoryRoot(exec, cwd) !== null) throw new GitError("INVALID", "the directory is already inside a Git work tree");
|
|
1191
|
+
return await mutate(exec, [
|
|
1192
|
+
"init",
|
|
1193
|
+
"-b",
|
|
1194
|
+
"main"
|
|
1195
|
+
], "init");
|
|
1196
|
+
}
|
|
1197
|
+
/** Run one mutating operation and report it. */
|
|
1198
|
+
async function mutate(exec, args, operation, options = {}) {
|
|
1199
|
+
const result = await run(exec, args, operation, options);
|
|
1200
|
+
return {
|
|
1201
|
+
message: `git ${operation} completed`,
|
|
1202
|
+
detail: excerpt$1(result.stdout)
|
|
1203
|
+
};
|
|
1204
|
+
}
|
|
1205
|
+
/** Names of the operations the checkout can be in the middle of, and their abort command. */
|
|
1206
|
+
var ABORTABLE = Object.freeze({
|
|
1207
|
+
"cherry-pick": ["cherry-pick", "--abort"],
|
|
1208
|
+
revert: ["revert", "--abort"],
|
|
1209
|
+
rebase: ["rebase", "--abort"],
|
|
1210
|
+
merge: ["merge", "--abort"]
|
|
1211
|
+
});
|
|
1212
|
+
/**
|
|
1213
|
+
* Append one repository-relative path to `.gitignore`.
|
|
1214
|
+
* @param root - repository root.
|
|
1215
|
+
* @param path - relative path to ignore.
|
|
1216
|
+
* @returns the operation result.
|
|
1217
|
+
*/
|
|
1218
|
+
async function addToIgnoreFile(root, path) {
|
|
1219
|
+
const file = join(root, ".gitignore");
|
|
1220
|
+
let current = "";
|
|
1221
|
+
try {
|
|
1222
|
+
current = await readFile(file, "utf8");
|
|
1223
|
+
} catch {}
|
|
1224
|
+
const pattern = path.startsWith("#") || path.startsWith("!") ? `\\${path}` : path;
|
|
1225
|
+
if (current.split(/\r?\n/).map((line) => line.trim()).includes(pattern)) return {
|
|
1226
|
+
message: "already ignored",
|
|
1227
|
+
detail: null
|
|
1228
|
+
};
|
|
1229
|
+
const prefix = current.length === 0 || current.endsWith("\n") ? current : `${current}\n`;
|
|
1230
|
+
await writeFile(file, `${prefix}${pattern}\n`, "utf8");
|
|
1231
|
+
return {
|
|
1232
|
+
message: `added ${pattern} to .gitignore`,
|
|
1233
|
+
detail: null
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
/** Whether the platform can reveal a path in its file manager. */
|
|
1237
|
+
function revealCommand(absolute) {
|
|
1238
|
+
if (process.platform === "darwin") return [
|
|
1239
|
+
"open",
|
|
1240
|
+
"-R",
|
|
1241
|
+
absolute
|
|
1242
|
+
];
|
|
1243
|
+
if (process.platform === "win32") return ["explorer.exe", `/select,${absolute}`];
|
|
1244
|
+
return ["xdg-open", dirname(absolute)];
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* Read the GitHub account the CLI would publish under.
|
|
1248
|
+
* @param request - the `exec` seam bound to the repository.
|
|
1249
|
+
* @returns availability, login, and a refusal reason.
|
|
1250
|
+
*/
|
|
1251
|
+
async function gitGithubInfo({ exec }) {
|
|
1252
|
+
const unavailable = (reason) => ({
|
|
1253
|
+
available: false,
|
|
1254
|
+
login: null,
|
|
1255
|
+
reason
|
|
1256
|
+
});
|
|
1257
|
+
try {
|
|
1258
|
+
await exec(["gh", "--version"], {
|
|
1259
|
+
allowedExitCodes: [0],
|
|
1260
|
+
timeoutMs: GITHUB_PROBE_TIMEOUT_MS
|
|
1261
|
+
});
|
|
1262
|
+
} catch {
|
|
1263
|
+
return unavailable("gh is not installed");
|
|
1264
|
+
}
|
|
1265
|
+
if ((await exec([
|
|
1266
|
+
"gh",
|
|
1267
|
+
"auth",
|
|
1268
|
+
"status"
|
|
1269
|
+
], {
|
|
1270
|
+
allowedExitCodes: [0, 1],
|
|
1271
|
+
timeoutMs: GITHUB_PROBE_TIMEOUT_MS
|
|
1272
|
+
})).exitCode !== 0) return unavailable("gh is not signed in");
|
|
1273
|
+
const account = await exec([
|
|
1274
|
+
"gh",
|
|
1275
|
+
"api",
|
|
1276
|
+
"user",
|
|
1277
|
+
"--jq",
|
|
1278
|
+
".login"
|
|
1279
|
+
], {
|
|
1280
|
+
allowedExitCodes: [0, 1],
|
|
1281
|
+
timeoutMs: GITHUB_PROBE_TIMEOUT_MS
|
|
1282
|
+
});
|
|
1283
|
+
const login = account.stdout.split(/\r?\n/).map((line) => line.trim()).find((line) => line.length > 0) ?? "";
|
|
1284
|
+
if (account.exitCode !== 0 || login.length === 0) return unavailable("the GitHub account could not be read");
|
|
1285
|
+
return {
|
|
1286
|
+
available: true,
|
|
1287
|
+
login,
|
|
1288
|
+
reason: null
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1291
|
+
/**
|
|
1292
|
+
* Run one Git operation.
|
|
1293
|
+
* @param request - `exec`, `cwd`, `operation`, and `params`.
|
|
1294
|
+
* @returns the operation result.
|
|
1295
|
+
* @throws {GitError} `INVALID` for malformed parameters, `NOT_A_REPO` outside a work tree, or a structured Git failure.
|
|
1296
|
+
*/
|
|
1297
|
+
async function gitAction({ exec, cwd, operation, params = {} }) {
|
|
1298
|
+
if (operation === "initRepository") return await initRepository(exec, cwd);
|
|
1299
|
+
const root = await repositoryRoot(exec, cwd);
|
|
1300
|
+
if (root === null) throw new GitError("NOT_A_REPO", `${cwd} is not inside a Git work tree`);
|
|
1301
|
+
const paths = Array.isArray(params.paths) ? params.paths.map(checkedPath) : [];
|
|
1302
|
+
const requirePaths = () => {
|
|
1303
|
+
if (paths.length === 0) throw new GitError("INVALID", "at least one path is required");
|
|
1304
|
+
return paths;
|
|
1305
|
+
};
|
|
1306
|
+
const network = { timeoutMs: NETWORK_TIMEOUT_MS };
|
|
1307
|
+
switch (operation) {
|
|
1308
|
+
case "stage": return await mutate(exec, [
|
|
1309
|
+
"add",
|
|
1310
|
+
"-A",
|
|
1311
|
+
"--",
|
|
1312
|
+
...requirePaths()
|
|
1313
|
+
], "add");
|
|
1314
|
+
case "unstage": {
|
|
1315
|
+
const target = requirePaths();
|
|
1316
|
+
if (await isUnborn(exec)) return await mutate(exec, [
|
|
1317
|
+
"reset",
|
|
1318
|
+
"-q",
|
|
1319
|
+
"--",
|
|
1320
|
+
...target
|
|
1321
|
+
], "reset");
|
|
1322
|
+
return await mutate(exec, [
|
|
1323
|
+
"restore",
|
|
1324
|
+
"--staged",
|
|
1325
|
+
"--",
|
|
1326
|
+
...target
|
|
1327
|
+
], "restore");
|
|
1328
|
+
}
|
|
1329
|
+
case "discard": {
|
|
1330
|
+
const target = requirePaths();
|
|
1331
|
+
if (params.untracked === true) return await mutate(exec, [
|
|
1332
|
+
"clean",
|
|
1333
|
+
"-fdq",
|
|
1334
|
+
"--",
|
|
1335
|
+
...target
|
|
1336
|
+
], "clean");
|
|
1337
|
+
return await mutate(exec, [
|
|
1338
|
+
"restore",
|
|
1339
|
+
"--worktree",
|
|
1340
|
+
"--",
|
|
1341
|
+
...target
|
|
1342
|
+
], "restore");
|
|
1343
|
+
}
|
|
1344
|
+
case "stageAll": return await mutate(exec, ["add", "-A"], "add");
|
|
1345
|
+
case "unstageAll": return await mutate(exec, ["reset", "-q"], "reset");
|
|
1346
|
+
case "commit": {
|
|
1347
|
+
const message = typeof params.message === "string" ? params.message.trim() : "";
|
|
1348
|
+
if (message.length === 0) throw new GitError("INVALID", "a commit message is required");
|
|
1349
|
+
const args = [
|
|
1350
|
+
"commit",
|
|
1351
|
+
"-m",
|
|
1352
|
+
message
|
|
1353
|
+
];
|
|
1354
|
+
if (params.amend === true) args.push("--amend");
|
|
1355
|
+
if (params.signoff === true) args.push("--signoff");
|
|
1356
|
+
return await mutate(exec, args, "commit");
|
|
1357
|
+
}
|
|
1358
|
+
case "undoCommit":
|
|
1359
|
+
if ((await exec(argvOf([
|
|
1360
|
+
"rev-parse",
|
|
1361
|
+
"--verify",
|
|
1362
|
+
"--quiet",
|
|
1363
|
+
"HEAD^"
|
|
1364
|
+
]), { allowedExitCodes: [
|
|
1365
|
+
0,
|
|
1366
|
+
1,
|
|
1367
|
+
128
|
|
1368
|
+
] })).exitCode !== 0) throw new GitError("INVALID", "there is no commit to undo");
|
|
1369
|
+
return await mutate(exec, [
|
|
1370
|
+
"reset",
|
|
1371
|
+
"--soft",
|
|
1372
|
+
"HEAD^"
|
|
1373
|
+
], "reset");
|
|
1374
|
+
case "fetch": {
|
|
1375
|
+
const args = ["fetch", "--prune"];
|
|
1376
|
+
if (params.all !== false) args.push("--all");
|
|
1377
|
+
const before = await readRemoteTips(exec);
|
|
1378
|
+
const result = await mutate(exec, args, "fetch", network);
|
|
1379
|
+
const after = await readRemoteTips(exec);
|
|
1380
|
+
const changed = [];
|
|
1381
|
+
for (const [ref, hash] of after) {
|
|
1382
|
+
const previous = before.get(ref);
|
|
1383
|
+
if (previous !== hash) changed.push({
|
|
1384
|
+
ref,
|
|
1385
|
+
from: previous ?? null,
|
|
1386
|
+
to: hash
|
|
1387
|
+
});
|
|
1388
|
+
}
|
|
1389
|
+
for (const [ref, hash] of before) if (!after.has(ref)) changed.push({
|
|
1390
|
+
ref,
|
|
1391
|
+
from: hash,
|
|
1392
|
+
to: null
|
|
1393
|
+
});
|
|
1394
|
+
return {
|
|
1395
|
+
...result,
|
|
1396
|
+
updated: changed.length > 0,
|
|
1397
|
+
changed
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
case "pullBranch": {
|
|
1401
|
+
const name = checkedRef(typeof params.name === "string" ? params.name.trim() : "");
|
|
1402
|
+
const remote = await configValue(exec, `branch.${name}.remote`);
|
|
1403
|
+
const merge = await configValue(exec, `branch.${name}.merge`);
|
|
1404
|
+
if (remote === null || merge === null || remote.length === 0 || remote === ".") throw new GitError("INVALID", `branch "${name}" has no upstream branch`);
|
|
1405
|
+
const upstreamRef = `${remote}/${merge.startsWith("refs/heads/") ? merge.slice(11) : merge}`;
|
|
1406
|
+
await mutate(exec, [
|
|
1407
|
+
"fetch",
|
|
1408
|
+
"--prune",
|
|
1409
|
+
remote
|
|
1410
|
+
], "fetch", network);
|
|
1411
|
+
const upstream = await exec(argvOf([
|
|
1412
|
+
"rev-parse",
|
|
1413
|
+
"--verify",
|
|
1414
|
+
"--quiet",
|
|
1415
|
+
`${upstreamRef}^{commit}`
|
|
1416
|
+
]), { allowedExitCodes: [0, 1] });
|
|
1417
|
+
if (upstream.exitCode !== 0) throw new GitError("INVALID", `upstream "${upstreamRef}" is missing`);
|
|
1418
|
+
const remoteTip = firstLine$1(upstream.stdout);
|
|
1419
|
+
const local = await exec(argvOf([
|
|
1420
|
+
"rev-parse",
|
|
1421
|
+
"--verify",
|
|
1422
|
+
"--quiet",
|
|
1423
|
+
`refs/heads/${name}^{commit}`
|
|
1424
|
+
]), { allowedExitCodes: [0, 1] });
|
|
1425
|
+
if (local.exitCode !== 0) throw new GitError("INVALID", `branch "${name}" is missing`);
|
|
1426
|
+
const localTip = firstLine$1(local.stdout);
|
|
1427
|
+
const counted = await exec(argvOf([
|
|
1428
|
+
"rev-list",
|
|
1429
|
+
"--count",
|
|
1430
|
+
`${localTip}..${remoteTip}`
|
|
1431
|
+
]), { allowedExitCodes: [0, 1] });
|
|
1432
|
+
const commits = Number.parseInt(firstLine$1(counted.stdout), 10) || 0;
|
|
1433
|
+
if (localTip === remoteTip || commits === 0) return {
|
|
1434
|
+
message: `branch "${name}" is already up to date`,
|
|
1435
|
+
detail: null,
|
|
1436
|
+
commits: 0
|
|
1437
|
+
};
|
|
1438
|
+
const current = await exec(argvOf([
|
|
1439
|
+
"symbolic-ref",
|
|
1440
|
+
"--quiet",
|
|
1441
|
+
"--short",
|
|
1442
|
+
"HEAD"
|
|
1443
|
+
]), { allowedExitCodes: [0, 1] });
|
|
1444
|
+
if (current.exitCode === 0 && current.stdout.trim() === name) await mutate(exec, [
|
|
1445
|
+
"merge",
|
|
1446
|
+
"--ff-only",
|
|
1447
|
+
remoteTip
|
|
1448
|
+
], "merge");
|
|
1449
|
+
else {
|
|
1450
|
+
if ((await exec(argvOf([
|
|
1451
|
+
"merge-base",
|
|
1452
|
+
"--is-ancestor",
|
|
1453
|
+
localTip,
|
|
1454
|
+
remoteTip
|
|
1455
|
+
]), { allowedExitCodes: [0, 1] })).exitCode !== 0) throw new GitError("INVALID", `branch "${name}" cannot fast-forward`);
|
|
1456
|
+
await mutate(exec, [
|
|
1457
|
+
"update-ref",
|
|
1458
|
+
`refs/heads/${name}`,
|
|
1459
|
+
remoteTip,
|
|
1460
|
+
localTip
|
|
1461
|
+
], "update-ref");
|
|
1462
|
+
}
|
|
1463
|
+
return {
|
|
1464
|
+
message: `pulled ${name}`,
|
|
1465
|
+
detail: null,
|
|
1466
|
+
commits
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
case "pull": {
|
|
1470
|
+
const args = ["pull", "--no-edit"];
|
|
1471
|
+
if (params.rebase === true) args.push("--rebase");
|
|
1472
|
+
if (params.ffOnly === true) args.push("--ff-only");
|
|
1473
|
+
return await mutate(exec, args, "pull", network);
|
|
1474
|
+
}
|
|
1475
|
+
case "publish": {
|
|
1476
|
+
const branch = await requireBranch(exec);
|
|
1477
|
+
const url = typeof params.url === "string" ? params.url.trim() : "";
|
|
1478
|
+
const requested = params.remote === void 0 ? void 0 : checkedRemoteName(params.remote);
|
|
1479
|
+
let remote;
|
|
1480
|
+
if (url.length > 0) {
|
|
1481
|
+
remote = requested ?? "origin";
|
|
1482
|
+
if ((await remoteNames(exec)).includes(remote)) throw new GitError("INVALID", `remote "${remote}" already exists`);
|
|
1483
|
+
await mutate(exec, [
|
|
1484
|
+
"remote",
|
|
1485
|
+
"add",
|
|
1486
|
+
remote,
|
|
1487
|
+
checkedRemoteUrl(url)
|
|
1488
|
+
], "remote add");
|
|
1489
|
+
} else remote = requested ?? await defaultRemote(exec);
|
|
1490
|
+
if (remote === null) throw new GitError("INVALID", "the repository has no remote to publish to");
|
|
1491
|
+
return await mutate(exec, [
|
|
1492
|
+
"push",
|
|
1493
|
+
"--set-upstream",
|
|
1494
|
+
remote,
|
|
1495
|
+
branch
|
|
1496
|
+
], "push", network);
|
|
1497
|
+
}
|
|
1498
|
+
case "publishGithub": {
|
|
1499
|
+
const branch = await requireBranch(exec);
|
|
1500
|
+
const name = checkedGithubRepository(params.name);
|
|
1501
|
+
const visibility = params.private === true ? "--private" : params.public === true ? "--public" : null;
|
|
1502
|
+
if (visibility === null) throw new GitError("INVALID", "choose a public or private GitHub repository");
|
|
1503
|
+
if ((await remoteNames(exec)).length > 0) throw new GitError("INVALID", "the repository already has a remote");
|
|
1504
|
+
try {
|
|
1505
|
+
await exec([
|
|
1506
|
+
"gh",
|
|
1507
|
+
"repo",
|
|
1508
|
+
"create",
|
|
1509
|
+
name,
|
|
1510
|
+
visibility,
|
|
1511
|
+
"--source",
|
|
1512
|
+
root,
|
|
1513
|
+
"--remote",
|
|
1514
|
+
"origin"
|
|
1515
|
+
], { timeoutMs: NETWORK_TIMEOUT_MS });
|
|
1516
|
+
} catch (error) {
|
|
1517
|
+
throw failureOf(error, "GitHub repository");
|
|
1518
|
+
}
|
|
1519
|
+
return await mutate(exec, [
|
|
1520
|
+
"push",
|
|
1521
|
+
"--set-upstream",
|
|
1522
|
+
"origin",
|
|
1523
|
+
branch
|
|
1524
|
+
], "push", network);
|
|
1525
|
+
}
|
|
1526
|
+
case "push": {
|
|
1527
|
+
const args = ["push"];
|
|
1528
|
+
if (params.forceWithLease === true) args.push("--force-with-lease");
|
|
1529
|
+
if (params.tags === true) args.push("--tags");
|
|
1530
|
+
if (params.setUpstream === true) {
|
|
1531
|
+
const branch = await requireBranch(exec);
|
|
1532
|
+
const remote = params.remote === void 0 ? await defaultRemote(exec) : checkedRemoteName(params.remote);
|
|
1533
|
+
if (remote === null) throw new GitError("INVALID", "the repository has no remote to publish to");
|
|
1534
|
+
args.push("--set-upstream", remote, branch);
|
|
1535
|
+
}
|
|
1536
|
+
return await mutate(exec, args, "push", network);
|
|
1537
|
+
}
|
|
1538
|
+
case "checkoutBranch": {
|
|
1539
|
+
const name = typeof params.name === "string" ? params.name : "";
|
|
1540
|
+
if (name.length === 0) throw new GitError("INVALID", "a branch name is required");
|
|
1541
|
+
if (params.kind === "remote") {
|
|
1542
|
+
const local = name.split("/").slice(1).join("/");
|
|
1543
|
+
if (local.length === 0) throw new GitError("INVALID", `"${name}" is not a remote branch`);
|
|
1544
|
+
await checkBranchName(exec, local);
|
|
1545
|
+
if (await localBranchExists(exec, local)) return await mutate(exec, ["switch", local], "switch");
|
|
1546
|
+
return await mutate(exec, [
|
|
1547
|
+
"switch",
|
|
1548
|
+
"-c",
|
|
1549
|
+
local,
|
|
1550
|
+
"--track",
|
|
1551
|
+
name
|
|
1552
|
+
], "switch");
|
|
1553
|
+
}
|
|
1554
|
+
await checkBranchName(exec, name);
|
|
1555
|
+
return await mutate(exec, ["switch", name], "switch");
|
|
1556
|
+
}
|
|
1557
|
+
case "checkoutCommit": return await mutate(exec, [
|
|
1558
|
+
"switch",
|
|
1559
|
+
"--detach",
|
|
1560
|
+
await resolveCommit(exec, checkedHash(params.hash))
|
|
1561
|
+
], "switch");
|
|
1562
|
+
case "createBranch": {
|
|
1563
|
+
const args = [
|
|
1564
|
+
"switch",
|
|
1565
|
+
"-c",
|
|
1566
|
+
await checkBranchName(exec, typeof params.name === "string" ? params.name.trim() : "")
|
|
1567
|
+
];
|
|
1568
|
+
if (typeof params.from === "string" && params.from.length > 0) args.push(await resolveCommit(exec, checkedRef(params.from)));
|
|
1569
|
+
return await mutate(exec, args, "switch");
|
|
1570
|
+
}
|
|
1571
|
+
case "renameBranch": return await mutate(exec, [
|
|
1572
|
+
"branch",
|
|
1573
|
+
"-m",
|
|
1574
|
+
await checkBranchName(exec, typeof params.from === "string" ? params.from : ""),
|
|
1575
|
+
await checkBranchName(exec, typeof params.to === "string" ? params.to.trim() : "")
|
|
1576
|
+
], "branch");
|
|
1577
|
+
case "deleteBranch": {
|
|
1578
|
+
const name = await checkBranchName(exec, typeof params.name === "string" ? params.name : "");
|
|
1579
|
+
return await mutate(exec, [
|
|
1580
|
+
"branch",
|
|
1581
|
+
params.force === true ? "-D" : "-d",
|
|
1582
|
+
name
|
|
1583
|
+
], "branch");
|
|
1584
|
+
}
|
|
1585
|
+
case "deleteRemoteBranch": {
|
|
1586
|
+
const name = typeof params.name === "string" ? params.name : "";
|
|
1587
|
+
if (name.length === 0) throw new GitError("INVALID", "a remote branch name is required");
|
|
1588
|
+
const slash = name.indexOf("/");
|
|
1589
|
+
if (slash <= 0 || slash === name.length - 1) throw new GitError("INVALID", `"${name}" is not a remote branch`);
|
|
1590
|
+
return await mutate(exec, [
|
|
1591
|
+
"push",
|
|
1592
|
+
name.slice(0, slash),
|
|
1593
|
+
"--delete",
|
|
1594
|
+
name.slice(slash + 1)
|
|
1595
|
+
], "push", network);
|
|
1596
|
+
}
|
|
1597
|
+
case "cherryPick": {
|
|
1598
|
+
const commit = await resolveCommit(exec, checkedHash(params.hash));
|
|
1599
|
+
const args = ["cherry-pick"];
|
|
1600
|
+
if (params.noCommit === true) args.push("--no-commit");
|
|
1601
|
+
if ((await run(exec, [
|
|
1602
|
+
"rev-list",
|
|
1603
|
+
"--parents",
|
|
1604
|
+
"-n1",
|
|
1605
|
+
commit
|
|
1606
|
+
], "rev-list")).stdout.trim().split(" ").filter(Boolean).length - 1 > 1) args.push("-m", "1");
|
|
1607
|
+
args.push(commit);
|
|
1608
|
+
return await mutate(exec, args, "cherry-pick");
|
|
1609
|
+
}
|
|
1610
|
+
case "revert": {
|
|
1611
|
+
const commit = await resolveCommit(exec, checkedHash(params.hash));
|
|
1612
|
+
const args = ["revert", "--no-edit"];
|
|
1613
|
+
if ((await run(exec, [
|
|
1614
|
+
"rev-list",
|
|
1615
|
+
"--parents",
|
|
1616
|
+
"-n1",
|
|
1617
|
+
commit
|
|
1618
|
+
], "rev-list")).stdout.trim().split(" ").filter(Boolean).length - 1 > 1) args.push("-m", "1");
|
|
1619
|
+
args.push(commit);
|
|
1620
|
+
return await mutate(exec, args, "revert");
|
|
1621
|
+
}
|
|
1622
|
+
case "abortOperation": {
|
|
1623
|
+
const kind = params.kind;
|
|
1624
|
+
const command = typeof kind === "string" ? ABORTABLE[kind] : void 0;
|
|
1625
|
+
if (command === void 0) throw new GitError("INVALID", `"${String(kind)}" is not an abortable operation`);
|
|
1626
|
+
return await mutate(exec, command, command.join(" "));
|
|
1627
|
+
}
|
|
1628
|
+
case "stashSave": {
|
|
1629
|
+
const args = ["stash", "push"];
|
|
1630
|
+
if (params.includeUntracked === true) args.push("-u");
|
|
1631
|
+
if (params.staged === true) args.push("--staged");
|
|
1632
|
+
const message = typeof params.message === "string" ? params.message.trim() : "";
|
|
1633
|
+
if (message.length > 0) args.push("-m", message);
|
|
1634
|
+
if (paths.length > 0) args.push("--", ...paths);
|
|
1635
|
+
return await mutate(exec, args, "stash push");
|
|
1636
|
+
}
|
|
1637
|
+
case "stashApply":
|
|
1638
|
+
case "stashPop":
|
|
1639
|
+
case "stashDrop": {
|
|
1640
|
+
const index = checkedStashIndex(params.index);
|
|
1641
|
+
const verb = operation === "stashApply" ? "apply" : operation === "stashPop" ? "pop" : "drop";
|
|
1642
|
+
return await mutate(exec, [
|
|
1643
|
+
"stash",
|
|
1644
|
+
verb,
|
|
1645
|
+
`stash@{${index}}`
|
|
1646
|
+
], `stash ${verb}`);
|
|
1647
|
+
}
|
|
1648
|
+
case "stashClear": return await mutate(exec, ["stash", "clear"], "stash clear");
|
|
1649
|
+
case "tagCreate": {
|
|
1650
|
+
const name = await checkTagName(exec, typeof params.name === "string" ? params.name.trim() : "");
|
|
1651
|
+
const message = typeof params.message === "string" ? params.message.trim() : "";
|
|
1652
|
+
const args = message.length > 0 ? [
|
|
1653
|
+
"tag",
|
|
1654
|
+
"-a",
|
|
1655
|
+
"-m",
|
|
1656
|
+
message,
|
|
1657
|
+
name
|
|
1658
|
+
] : ["tag", name];
|
|
1659
|
+
if (typeof params.at === "string" && params.at.length > 0) args.push(await resolveCommit(exec, checkedRef(params.at)));
|
|
1660
|
+
return await mutate(exec, args, "tag");
|
|
1661
|
+
}
|
|
1662
|
+
case "tagDelete": return await mutate(exec, [
|
|
1663
|
+
"tag",
|
|
1664
|
+
"-d",
|
|
1665
|
+
await checkTagName(exec, typeof params.name === "string" ? params.name : "")
|
|
1666
|
+
], "tag");
|
|
1667
|
+
case "addToIgnore": return await addToIgnoreFile(root, requirePaths()[0]);
|
|
1668
|
+
case "reveal": {
|
|
1669
|
+
const target = requirePaths()[0];
|
|
1670
|
+
const command = revealCommand(join(root, target));
|
|
1671
|
+
try {
|
|
1672
|
+
await exec(command, { allowedExitCodes: [0, 1] });
|
|
1673
|
+
} catch (error) {
|
|
1674
|
+
throw failureOf(error, "reveal");
|
|
1675
|
+
}
|
|
1676
|
+
return {
|
|
1677
|
+
message: "revealed in the file manager",
|
|
1678
|
+
detail: null
|
|
1679
|
+
};
|
|
1680
|
+
}
|
|
1681
|
+
default: throw new GitError("INVALID", `unknown operation "${operation}"`);
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
/** Every operation name this layer accepts, for the caller's request validation. */
|
|
1685
|
+
var OPERATIONS = Object.freeze([
|
|
1686
|
+
"stage",
|
|
1687
|
+
"unstage",
|
|
1688
|
+
"discard",
|
|
1689
|
+
"stageAll",
|
|
1690
|
+
"unstageAll",
|
|
1691
|
+
"commit",
|
|
1692
|
+
"undoCommit",
|
|
1693
|
+
"fetch",
|
|
1694
|
+
"pull",
|
|
1695
|
+
"pullBranch",
|
|
1696
|
+
"publish",
|
|
1697
|
+
"publishGithub",
|
|
1698
|
+
"push",
|
|
1699
|
+
"checkoutBranch",
|
|
1700
|
+
"checkoutCommit",
|
|
1701
|
+
"createBranch",
|
|
1702
|
+
"renameBranch",
|
|
1703
|
+
"deleteBranch",
|
|
1704
|
+
"deleteRemoteBranch",
|
|
1705
|
+
"cherryPick",
|
|
1706
|
+
"revert",
|
|
1707
|
+
"abortOperation",
|
|
1708
|
+
"stashSave",
|
|
1709
|
+
"stashApply",
|
|
1710
|
+
"stashPop",
|
|
1711
|
+
"stashDrop",
|
|
1712
|
+
"stashClear",
|
|
1713
|
+
"tagCreate",
|
|
1714
|
+
"tagDelete",
|
|
1715
|
+
"addToIgnore",
|
|
1716
|
+
"reveal",
|
|
1717
|
+
"initRepository"
|
|
1718
|
+
]);
|
|
1719
|
+
/** Set form of {@link WIRE_CODE_NAMES} used to recognize an already-coded failure. */
|
|
1720
|
+
var WIRE_CODES = /* @__PURE__ */ new Set([
|
|
1721
|
+
"NOT_A_REPO",
|
|
1722
|
+
"INVALID",
|
|
1723
|
+
"INVALID_REQUEST",
|
|
1724
|
+
"NO_SESSION",
|
|
1725
|
+
"NO_WORKSPACE",
|
|
1726
|
+
"GIT_FAILED",
|
|
1727
|
+
"TIMEOUT",
|
|
1728
|
+
"TOO_LARGE",
|
|
1729
|
+
"SPAWN_FAILED",
|
|
1730
|
+
"CANCELLED",
|
|
1731
|
+
"BUSY",
|
|
1732
|
+
"NETWORK",
|
|
1733
|
+
"FORBIDDEN",
|
|
1734
|
+
"INTERNAL"
|
|
1735
|
+
]);
|
|
1736
|
+
/** A rejected request as the route reports it, before it becomes an HTTP body. */
|
|
1737
|
+
var RequestError = class extends Error {
|
|
1738
|
+
/** Stable wire code such as `NOT_A_REPO`. */
|
|
1739
|
+
code;
|
|
1740
|
+
/** Raw Git output excerpt, when one exists. */
|
|
1741
|
+
detail;
|
|
1742
|
+
/**
|
|
1743
|
+
* @param code - stable wire code such as `NOT_A_REPO`.
|
|
1744
|
+
* @param message - operator-readable reason.
|
|
1745
|
+
* @param detail - raw Git output excerpt, when one exists.
|
|
1746
|
+
*/
|
|
1747
|
+
constructor(code, message, detail = null) {
|
|
1748
|
+
super(message);
|
|
1749
|
+
this.name = "RequestError";
|
|
1750
|
+
this.code = code;
|
|
1751
|
+
this.detail = detail;
|
|
1752
|
+
}
|
|
1753
|
+
};
|
|
1754
|
+
Object.freeze([
|
|
1755
|
+
"auto",
|
|
1756
|
+
"conventional",
|
|
1757
|
+
"single",
|
|
1758
|
+
"detailed"
|
|
1759
|
+
]);
|
|
1760
|
+
/** Longest accepted model output, in characters. */
|
|
1761
|
+
var MAX_MESSAGE_CHARS = 4e3;
|
|
1762
|
+
/** Changed paths listed in the prompt. */
|
|
1763
|
+
var MAX_PROMPT_FILES = 60;
|
|
1764
|
+
/** Recent commit subjects listed for style. */
|
|
1765
|
+
var MAX_PROMPT_RECENT = 8;
|
|
1766
|
+
/** Language names the app's locales map onto; everything else writes English. */
|
|
1767
|
+
var LANGUAGE_NAMES = Object.freeze({
|
|
1768
|
+
zh: "Simplified Chinese",
|
|
1769
|
+
ja: "Japanese",
|
|
1770
|
+
es: "Spanish",
|
|
1771
|
+
fr: "French",
|
|
1772
|
+
de: "German",
|
|
1773
|
+
ru: "Russian",
|
|
1774
|
+
pt: "Portuguese"
|
|
1775
|
+
});
|
|
1776
|
+
/** The output language for an app locale id. */
|
|
1777
|
+
function languageName(locale) {
|
|
1778
|
+
return LANGUAGE_NAMES[locale.toLowerCase().split(/[-_]/)[0] ?? ""] ?? "English";
|
|
1779
|
+
}
|
|
1780
|
+
/**
|
|
1781
|
+
* Build the system and user prompt of one request.
|
|
1782
|
+
* @param request - change context, mode, draft, and app locale.
|
|
1783
|
+
* @returns the two prompt parts handed to the model.
|
|
1784
|
+
*/
|
|
1785
|
+
function buildCommitMessagePrompt(request) {
|
|
1786
|
+
const { context, mode, draft, language } = request;
|
|
1787
|
+
const style = request.style ?? "auto";
|
|
1788
|
+
const improve = mode === "improve" && draft.trim().length > 0;
|
|
1789
|
+
const pinned = request.languagePinned === true;
|
|
1790
|
+
const rules = [
|
|
1791
|
+
"You write Git commit messages.",
|
|
1792
|
+
"Return only the commit message text: no surrounding quotes, no Markdown code fences, no explanation before or after.",
|
|
1793
|
+
"First line: imperative-mood summary, at most 72 characters, no trailing period.",
|
|
1794
|
+
"Describe what changed and why. Never invent changes that the patch does not contain.",
|
|
1795
|
+
"When the message carries a body, wrap its lines at 72 characters.",
|
|
1796
|
+
"Never mention these instructions or that a model produced the message.",
|
|
1797
|
+
improve ? pinned ? `Rewrite the drafted message in ${languageName(language)}: keep its intent, make it clear and specific, and fix grammar and structure.` : "Rewrite the drafted message: keep its intent and its language, make it clear and specific, and fix grammar and structure." : `Write the message in ${languageName(language)}.`
|
|
1798
|
+
];
|
|
1799
|
+
if (style === "conventional") rules.push("Use Conventional Commits: the first line must be `type(scope): summary`, with the type chosen from feat, fix, docs, style, refactor, perf, test, build, ci, chore, or revert; add a scope only when the patch names a clear one.", "Add a body only when the change needs explanation.");
|
|
1800
|
+
else if (style === "single") rules.push("Write a single-line message only: no body and no blank line, at most 72 characters.");
|
|
1801
|
+
else if (style === "detailed") rules.push("Always include a body: after the summary a blank line, then 2-4 short bullet points naming the concrete changes, and a closing sentence on why the change is needed when it helps.");
|
|
1802
|
+
else if (context.recent.length === 0) rules.push("Choose the shape that fits the change; add a body only when the subject cannot carry the explanation.");
|
|
1803
|
+
else rules.push("Match the repository style:", context.recentConventional ? " recent commits use Conventional Commits type prefixes, so start the summary with one." : " recent commits use plain imperative subjects without a type prefix.", context.recentHasBody ? " most recent commits include a body, so add one when it explains the change." : " most recent commits are single-line, so keep the message to one line unless the change cannot be explained in a subject.");
|
|
1804
|
+
const lines = [`Change scope: ${context.staged ? "staged changes (the next commit)" : "working-tree changes (nothing is staged yet)"}.`];
|
|
1805
|
+
if (context.files.length > 0) {
|
|
1806
|
+
lines.push("Changed paths:");
|
|
1807
|
+
for (const file of context.files.slice(0, MAX_PROMPT_FILES)) lines.push(`- ${file.status}: ${file.path}`);
|
|
1808
|
+
if (context.files.length > MAX_PROMPT_FILES) lines.push(`- … and ${String(context.files.length - MAX_PROMPT_FILES)} more paths`);
|
|
1809
|
+
} else lines.push("Changed paths: none.");
|
|
1810
|
+
if (context.recent.length > 0) {
|
|
1811
|
+
lines.push("Recent commit subjects (style reference):");
|
|
1812
|
+
for (const subject of context.recent.slice(0, MAX_PROMPT_RECENT)) lines.push(`- ${subject}`);
|
|
1813
|
+
}
|
|
1814
|
+
if (context.diff.length > 0) lines.push("Patch:", "```diff", context.diff, "```");
|
|
1815
|
+
if (improve) lines.push("Draft to improve:", "```text", draft.slice(0, MAX_MESSAGE_CHARS), "```");
|
|
1816
|
+
return {
|
|
1817
|
+
system: rules.join("\n"),
|
|
1818
|
+
user: lines.join("\n")
|
|
1819
|
+
};
|
|
1820
|
+
}
|
|
1821
|
+
/** A wrapped emphasis marker the model sometimes puts around the subject. */
|
|
1822
|
+
var BOUNDARY_QUOTES = /^["'`]|["'`]$/g;
|
|
1823
|
+
/**
|
|
1824
|
+
* Normalize one model answer into a commit message.
|
|
1825
|
+
* @param text - raw model output.
|
|
1826
|
+
* @returns the cleaned message, possibly empty.
|
|
1827
|
+
*/
|
|
1828
|
+
function cleanCommitMessage(text) {
|
|
1829
|
+
let value = String(text ?? "").replace(/\r\n/g, "\n").trim();
|
|
1830
|
+
const fenced = /^```[a-zA-Z]*\n([\s\S]*?)\n```$/.exec(value);
|
|
1831
|
+
if (fenced !== null) value = (fenced[1] ?? "").trim();
|
|
1832
|
+
value = value.replace(/^(?:commit message|message)\s*:\s*/i, "");
|
|
1833
|
+
if (value.length > 1) {
|
|
1834
|
+
const first = value[0];
|
|
1835
|
+
const last = value[value.length - 1];
|
|
1836
|
+
if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") value = value.slice(1, -1);
|
|
1837
|
+
}
|
|
1838
|
+
value = value.replace(BOUNDARY_QUOTES, "");
|
|
1839
|
+
value = value.split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
1840
|
+
return value.slice(0, MAX_MESSAGE_CHARS);
|
|
1841
|
+
}
|
|
1842
|
+
/**
|
|
1843
|
+
* Generate or improve one commit message.
|
|
1844
|
+
* @param request - change context, mode, draft, language, and the model seam.
|
|
1845
|
+
* @returns the cleaned message.
|
|
1846
|
+
* @throws {RequestError} `INVALID` for an empty change set or a missing model
|
|
1847
|
+
* route, `INTERNAL` when the model call fails or returns nothing usable.
|
|
1848
|
+
*/
|
|
1849
|
+
async function generateCommitMessage(request) {
|
|
1850
|
+
if (request.mode === "generate" && request.draft.trim().length === 0 && request.context.files.length === 0 && request.context.diff.length === 0) throw new RequestError("INVALID", "there are no changes to describe");
|
|
1851
|
+
if (request.generate === void 0) throw new RequestError("INVALID", "no model is configured to write commit messages");
|
|
1852
|
+
let raw;
|
|
1853
|
+
try {
|
|
1854
|
+
raw = await request.generate(buildCommitMessagePrompt(request));
|
|
1855
|
+
} catch (error) {
|
|
1856
|
+
throw new RequestError("INTERNAL", `the commit message could not be generated: ${error instanceof Error ? error.message : String(error)}`);
|
|
1857
|
+
}
|
|
1858
|
+
const message = cleanCommitMessage(raw);
|
|
1859
|
+
if (message.length === 0) throw new RequestError("INTERNAL", "the model returned an empty commit message");
|
|
1860
|
+
return { message };
|
|
1861
|
+
}
|
|
1862
|
+
// src/index.ts
|
|
1863
|
+
/** Exact route path; the handler answers this path and everything below it. */
|
|
1864
|
+
var ROUTE = "/api/dsh-git-scm";
|
|
1865
|
+
/** Default executable when the request names none (every request but `reveal`). */
|
|
1866
|
+
var GIT_COMMAND = "git";
|
|
1867
|
+
/** Flags before every Git subcommand: no index refresh writes, hooks, or fsmonitor. */
|
|
1868
|
+
var GIT_PREFIX = Object.freeze([
|
|
1869
|
+
"--no-optional-locks",
|
|
1870
|
+
"-c",
|
|
1871
|
+
"core.hooksPath=/dev/null",
|
|
1872
|
+
"-c",
|
|
1873
|
+
"core.fsmonitor=false"
|
|
1874
|
+
]);
|
|
1875
|
+
/** Deadline for one local Git command, including executable lookup. */
|
|
1876
|
+
var GIT_TIMEOUT_MS = 3e4;
|
|
1877
|
+
/** Deadline for a command that talks to a remote; the Git layer raises it per operation. */
|
|
1878
|
+
var REQUEST_TIMEOUT_MS = 42e4;
|
|
1879
|
+
/** Deadline for one commit-message model request. */
|
|
1880
|
+
var COMMIT_MESSAGE_TIMEOUT_MS = 9e4;
|
|
1881
|
+
/** Output tokens reserved for one commit-message request, thinking included. */
|
|
1882
|
+
var COMMIT_MESSAGE_MAX_TOKENS = 2048;
|
|
1883
|
+
/** Characters of model output accepted before assembly stops. */
|
|
1884
|
+
var COMMIT_MESSAGE_MAX_OUTPUT_CHARS = 8192;
|
|
1885
|
+
/** Auxiliary-purpose tag recorded for the model request. */
|
|
1886
|
+
var COMMIT_MESSAGE_PURPOSE = "git-commit-message";
|
|
1887
|
+
/** Grace period the provider grants a terminating process. */
|
|
1888
|
+
var GRACE_MS = 2e3;
|
|
1889
|
+
/** Captured bytes per output stream. */
|
|
1890
|
+
var MAX_OUTPUT_BYTES = 8388608;
|
|
1891
|
+
/** Characters of a returned diff. */
|
|
1892
|
+
var MAX_DIFF_BYTES = 409600;
|
|
1893
|
+
/** Accepted request body size. */
|
|
1894
|
+
var MAX_BODY_BYTES = 262144;
|
|
1895
|
+
/** How many requests one Session may have in flight. */
|
|
1896
|
+
var MAX_INFLIGHT_PER_SESSION = 4;
|
|
1897
|
+
/** List caps that keep one panel render bounded on a large repository. */
|
|
1898
|
+
var LIMITS = Object.freeze({
|
|
1899
|
+
maxBranches: 500,
|
|
1900
|
+
maxCommits: 40,
|
|
1901
|
+
maxTags: 30,
|
|
1902
|
+
maxFiles: 3e3,
|
|
1903
|
+
maxDiffBytes: MAX_DIFF_BYTES,
|
|
1904
|
+
maxOutputBytes: MAX_OUTPUT_BYTES
|
|
1905
|
+
});
|
|
1906
|
+
/** Services this plugin needs; `webServer` binds the route, `sessions` resolves the checkout. */
|
|
1907
|
+
var inject = [
|
|
1908
|
+
"subprocess",
|
|
1909
|
+
"sessions",
|
|
1910
|
+
"webServer"
|
|
1911
|
+
];
|
|
1912
|
+
/** Whether a decoded JSON value is a plain object. */
|
|
1913
|
+
function isRecord(value) {
|
|
1914
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1915
|
+
}
|
|
1916
|
+
/** Whether a caught failure already carries a wire code the page understands. */
|
|
1917
|
+
function isWireFailure(value) {
|
|
1918
|
+
return isRecord(value) && typeof value.code === "string" && WIRE_CODES.has(value.code) && typeof value.message === "string";
|
|
1919
|
+
}
|
|
1920
|
+
/** Format an unknown thrown value for an operator message. */
|
|
1921
|
+
function messageOf(error) {
|
|
1922
|
+
if (error instanceof Error) return error.message;
|
|
1923
|
+
return String(error);
|
|
1924
|
+
}
|
|
1925
|
+
/** Read the raw `detail` field a caught failure may carry. */
|
|
1926
|
+
function detailOf(error) {
|
|
1927
|
+
return isRecord(error) ? error.detail : void 0;
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* Mount the Git route for the calling profile.
|
|
1931
|
+
* @param ctx - Host Cordis context carrying the injected services.
|
|
1932
|
+
*/
|
|
1933
|
+
function apply(ctx) {
|
|
1934
|
+
/** Sessions whose requests are in flight, so one page cannot stack unbounded Git work. */
|
|
1935
|
+
const active = /* @__PURE__ */ new Map();
|
|
1936
|
+
/**
|
|
1937
|
+
* Run one program for one Session directory.
|
|
1938
|
+
* @param options - the Session directory and the request cancellation.
|
|
1939
|
+
* @returns the `exec` seam `host/git.ts` expects.
|
|
1940
|
+
*/
|
|
1941
|
+
function createExec({ cwd, signal }) {
|
|
1942
|
+
return async function exec(argv, options = {}) {
|
|
1943
|
+
const allowedExitCodes = options.allowedExitCodes ?? [0];
|
|
1944
|
+
const [program, ...args] = argv;
|
|
1945
|
+
const controller = new AbortController();
|
|
1946
|
+
const onAbort = () => {
|
|
1947
|
+
controller.abort(signal.reason);
|
|
1948
|
+
};
|
|
1949
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1950
|
+
let timedOut = false;
|
|
1951
|
+
const timer = setTimeout(() => {
|
|
1952
|
+
timedOut = true;
|
|
1953
|
+
controller.abort(/* @__PURE__ */ new Error("git command timed out"));
|
|
1954
|
+
}, options.timeoutMs ?? GIT_TIMEOUT_MS);
|
|
1955
|
+
timer.unref?.();
|
|
1956
|
+
const callSignal = controller.signal;
|
|
1957
|
+
try {
|
|
1958
|
+
const executable = await ctx.subprocess.resolveExecutable(program ?? GIT_COMMAND, void 0, callSignal);
|
|
1959
|
+
const isGit = program === GIT_COMMAND;
|
|
1960
|
+
const overrides = Object.entries(options.config ?? {});
|
|
1961
|
+
const command = [
|
|
1962
|
+
executable,
|
|
1963
|
+
...isGit ? GIT_PREFIX : [],
|
|
1964
|
+
...isGit ? overrides.flatMap(([key, value]) => ["-c", `${key}=${value}`]) : [],
|
|
1965
|
+
...args
|
|
1966
|
+
];
|
|
1967
|
+
let child;
|
|
1968
|
+
try {
|
|
1969
|
+
child = ctx.subprocess.spawn({
|
|
1970
|
+
argv: command,
|
|
1971
|
+
cwd,
|
|
1972
|
+
...isGit ? { env: { ...GIT_ENV } } : {},
|
|
1973
|
+
graceMs: GRACE_MS,
|
|
1974
|
+
signal: callSignal,
|
|
1975
|
+
stdio: {
|
|
1976
|
+
stdin: options.input === void 0 ? "ignore" : { data: options.input },
|
|
1977
|
+
stdout: { maxBytes: MAX_OUTPUT_BYTES },
|
|
1978
|
+
stderr: { maxBytes: MAX_OUTPUT_BYTES }
|
|
1979
|
+
}
|
|
1980
|
+
});
|
|
1981
|
+
} catch (error) {
|
|
1982
|
+
throw new RequestError("SPAWN_FAILED", `${program} could not start: ${messageOf(error)}`);
|
|
1983
|
+
}
|
|
1984
|
+
try {
|
|
1985
|
+
const outcome = await child.done;
|
|
1986
|
+
if (timedOut) throw new RequestError("TIMEOUT", `${program} ${args[0] ?? ""} timed out`);
|
|
1987
|
+
if (callSignal.aborted) throw new RequestError("CANCELLED", "the Git request was cancelled");
|
|
1988
|
+
const stdout = child.collected.stdout?.readFrom(0);
|
|
1989
|
+
const stderr = child.collected.stderr?.readFrom(0);
|
|
1990
|
+
if (stdout?.lossy === true || stderr?.lossy === true) throw new RequestError("TOO_LARGE", `${program} ${args[0] ?? ""} printed more than the output limit`);
|
|
1991
|
+
const out = stdout?.text ?? "";
|
|
1992
|
+
const err = stderr?.text ?? "";
|
|
1993
|
+
if (outcome.exitCode === null || !allowedExitCodes.includes(outcome.exitCode)) throw new RequestError("GIT_FAILED", `${program} ${args[0] ?? ""} failed (${outcome.signal ?? outcome.exitCode}): ${firstLine(err)}`, excerpt(err));
|
|
1994
|
+
return {
|
|
1995
|
+
stdout: out,
|
|
1996
|
+
stderr: err,
|
|
1997
|
+
exitCode: outcome.exitCode
|
|
1998
|
+
};
|
|
1999
|
+
} finally {
|
|
2000
|
+
child.terminate();
|
|
2001
|
+
await child.waitForExit().catch(() => void 0);
|
|
2002
|
+
}
|
|
2003
|
+
} catch (error) {
|
|
2004
|
+
if (error instanceof RequestError) throw error;
|
|
2005
|
+
if (timedOut) throw new RequestError("TIMEOUT", `${program} ${args[0] ?? ""} timed out`);
|
|
2006
|
+
if (callSignal.aborted) throw new RequestError("CANCELLED", "the Git request was cancelled");
|
|
2007
|
+
throw new RequestError("SPAWN_FAILED", `${program} ${args[0] ?? ""} could not run: ${messageOf(error)}`);
|
|
2008
|
+
} finally {
|
|
2009
|
+
clearTimeout(timer);
|
|
2010
|
+
signal.removeEventListener("abort", onAbort);
|
|
2011
|
+
}
|
|
2012
|
+
};
|
|
2013
|
+
}
|
|
2014
|
+
/**
|
|
2015
|
+
* Resolve the checkout directory a request belongs to.
|
|
2016
|
+
* @param sessionId - Session identity supplied by the page.
|
|
2017
|
+
* @returns the Session's absolute working directory.
|
|
2018
|
+
*/
|
|
2019
|
+
function directoryOf(sessionId) {
|
|
2020
|
+
if (typeof sessionId !== "string" || sessionId.length === 0) throw new RequestError("INVALID_REQUEST", "sessionId must be a non-empty string");
|
|
2021
|
+
const session = ctx.sessions.get(sessionId);
|
|
2022
|
+
if (session === void 0) throw new RequestError("NO_SESSION", "the Session is not loaded in this process");
|
|
2023
|
+
const workingDirectory = ctx.get("workingDirectory");
|
|
2024
|
+
const directory = workingDirectory === void 0 ? session.header.cwd : workingDirectory.get(session);
|
|
2025
|
+
if (directory === void 0 || directory === "") throw new RequestError("NO_WORKSPACE", "the Session has no working directory");
|
|
2026
|
+
return directory;
|
|
2027
|
+
}
|
|
2028
|
+
/**
|
|
2029
|
+
* Build the model call a commit-message request runs, when the app provides
|
|
2030
|
+
* both an adapter and a default route. The panel keeps working without it.
|
|
2031
|
+
* @param sessionId - Session whose request routing the model call joins.
|
|
2032
|
+
* @param signal - cancellation of the whole HTTP request.
|
|
2033
|
+
* @returns the model seam, or undefined when no route is configured.
|
|
2034
|
+
*/
|
|
2035
|
+
function createCommitMessageGenerator(sessionId, signal) {
|
|
2036
|
+
const llm = ctx.get("llm");
|
|
2037
|
+
const selection = ctx.get("agentDefaultModel")?.currentSelection?.();
|
|
2038
|
+
if (llm === void 0 || typeof llm.stream !== "function") return void 0;
|
|
2039
|
+
if (selection === void 0 || typeof selection.provider !== "string" || selection.provider.length === 0 || typeof selection.model !== "string" || selection.model.length === 0) return void 0;
|
|
2040
|
+
const provider = selection.provider;
|
|
2041
|
+
const model = selection.model;
|
|
2042
|
+
const auxiliaryEffort = async () => {
|
|
2043
|
+
try {
|
|
2044
|
+
const efforts = ((await llm.resolveModelInfo?.(provider, model, signal))?.reasoning?.efforts ?? []).map((effort) => typeof effort?.id === "string" ? effort.id : void 0).filter((id) => id !== void 0);
|
|
2045
|
+
if (efforts.length === 0) return void 0;
|
|
2046
|
+
return efforts.includes("off") ? "off" : efforts[0];
|
|
2047
|
+
} catch {
|
|
2048
|
+
return typeof selection.reasoningEffort === "string" ? selection.reasoningEffort : void 0;
|
|
2049
|
+
}
|
|
2050
|
+
};
|
|
2051
|
+
return async (prompt) => {
|
|
2052
|
+
const reasoningEffort = await auxiliaryEffort();
|
|
2053
|
+
const stream = llm.stream({
|
|
2054
|
+
provider,
|
|
2055
|
+
model,
|
|
2056
|
+
...reasoningEffort === void 0 ? {} : { reasoningEffort },
|
|
2057
|
+
system: prompt.system,
|
|
2058
|
+
messages: [{
|
|
2059
|
+
role: "user",
|
|
2060
|
+
content: [{
|
|
2061
|
+
type: "text",
|
|
2062
|
+
text: prompt.user
|
|
2063
|
+
}]
|
|
2064
|
+
}],
|
|
2065
|
+
temperature: .2,
|
|
2066
|
+
maxTokens: COMMIT_MESSAGE_MAX_TOKENS,
|
|
2067
|
+
sessionId,
|
|
2068
|
+
purpose: COMMIT_MESSAGE_PURPOSE,
|
|
2069
|
+
signal
|
|
2070
|
+
});
|
|
2071
|
+
let text = "";
|
|
2072
|
+
let reason;
|
|
2073
|
+
let stopped = false;
|
|
2074
|
+
for await (const chunk of stream) {
|
|
2075
|
+
const typed = chunk;
|
|
2076
|
+
if (typed.type === "text-delta" && typeof typed.text === "string") {
|
|
2077
|
+
text += typed.text;
|
|
2078
|
+
if (text.length >= COMMIT_MESSAGE_MAX_OUTPUT_CHARS) {
|
|
2079
|
+
stopped = true;
|
|
2080
|
+
break;
|
|
2081
|
+
}
|
|
2082
|
+
} else if (typed.type === "finish") reason = typed.reason;
|
|
2083
|
+
}
|
|
2084
|
+
if (!stopped) {
|
|
2085
|
+
const finish = reason;
|
|
2086
|
+
const failure = typeof finish?.failure?.message === "string" ? finish.failure.message : void 0;
|
|
2087
|
+
if (finish?.kind === "error") throw new Error(`the model request failed${failure === void 0 ? "" : `: ${failure}`}`);
|
|
2088
|
+
if (finish?.kind === "aborted") throw new Error("the model request was aborted");
|
|
2089
|
+
if (finish?.kind === "max-tokens" && text.trim().length > 0) return text;
|
|
2090
|
+
if (finish?.kind !== "stop") throw new Error(`the model did not finish normally${typeof finish?.kind === "string" ? ` (${finish.kind})` : ""}`);
|
|
2091
|
+
}
|
|
2092
|
+
return text;
|
|
2093
|
+
};
|
|
2094
|
+
}
|
|
2095
|
+
/**
|
|
2096
|
+
* Answer one decoded request with Git data.
|
|
2097
|
+
* @param body - the decoded body `{ sessionId, action, params }`.
|
|
2098
|
+
* @param signal - cancellation of the whole request.
|
|
2099
|
+
* @returns the action's JSON result.
|
|
2100
|
+
*/
|
|
2101
|
+
async function dispatch(body, signal) {
|
|
2102
|
+
if (body === null || typeof body !== "object") throw new RequestError("INVALID_REQUEST", "the request body must be a JSON object");
|
|
2103
|
+
const request = body;
|
|
2104
|
+
const rawSessionId = request.sessionId;
|
|
2105
|
+
const cwd = directoryOf(rawSessionId);
|
|
2106
|
+
const sessionId = rawSessionId;
|
|
2107
|
+
const action = request.action;
|
|
2108
|
+
if (typeof action !== "string") throw new RequestError("INVALID_REQUEST", "action must be a string");
|
|
2109
|
+
const params = request.params ?? {};
|
|
2110
|
+
if (params === null || typeof params !== "object" || Array.isArray(params)) throw new RequestError("INVALID_REQUEST", "params must be a JSON object");
|
|
2111
|
+
const fields = params;
|
|
2112
|
+
const inflight = active.get(sessionId) ?? 0;
|
|
2113
|
+
if (inflight >= MAX_INFLIGHT_PER_SESSION) throw new RequestError("BUSY", "too many Git requests are already running for this Session");
|
|
2114
|
+
active.set(sessionId, inflight + 1);
|
|
2115
|
+
try {
|
|
2116
|
+
const exec = createExec({
|
|
2117
|
+
cwd,
|
|
2118
|
+
signal
|
|
2119
|
+
});
|
|
2120
|
+
switch (action) {
|
|
2121
|
+
case "summary": return await gitSummary({
|
|
2122
|
+
exec,
|
|
2123
|
+
cwd,
|
|
2124
|
+
limits: LIMITS
|
|
2125
|
+
});
|
|
2126
|
+
case "github": return await gitGithubInfo({ exec });
|
|
2127
|
+
case "commitMessage": {
|
|
2128
|
+
const mode = fields.mode === "improve" ? "improve" : "generate";
|
|
2129
|
+
const draft = typeof fields.draft === "string" ? fields.draft : "";
|
|
2130
|
+
const language = typeof fields.language === "string" && fields.language.length > 0 ? fields.language : "en";
|
|
2131
|
+
const style = fields.style === "conventional" || fields.style === "single" || fields.style === "detailed" ? fields.style : "auto";
|
|
2132
|
+
const languagePinned = fields.languagePinned === true;
|
|
2133
|
+
const context = await gitCommitMessageContext({
|
|
2134
|
+
exec,
|
|
2135
|
+
cwd,
|
|
2136
|
+
limits: LIMITS
|
|
2137
|
+
});
|
|
2138
|
+
const deadline = AbortSignal.any([signal, AbortSignal.timeout(COMMIT_MESSAGE_TIMEOUT_MS)]);
|
|
2139
|
+
try {
|
|
2140
|
+
return await generateCommitMessage({
|
|
2141
|
+
context,
|
|
2142
|
+
mode,
|
|
2143
|
+
draft,
|
|
2144
|
+
language,
|
|
2145
|
+
style,
|
|
2146
|
+
languagePinned,
|
|
2147
|
+
generate: createCommitMessageGenerator(sessionId, deadline)
|
|
2148
|
+
});
|
|
2149
|
+
} catch (error) {
|
|
2150
|
+
if (deadline.aborted && deadline.reason instanceof Error && deadline.reason.name === "TimeoutError") throw new RequestError("TIMEOUT", "the commit message request timed out");
|
|
2151
|
+
throw error;
|
|
2152
|
+
}
|
|
2153
|
+
}
|
|
2154
|
+
case "status": return await gitStatus({
|
|
2155
|
+
exec,
|
|
2156
|
+
cwd,
|
|
2157
|
+
limits: LIMITS
|
|
2158
|
+
});
|
|
2159
|
+
case "commits": return await gitCommits({
|
|
2160
|
+
exec,
|
|
2161
|
+
cwd,
|
|
2162
|
+
limits: LIMITS,
|
|
2163
|
+
ref: requiredString(fields.ref, "params.ref"),
|
|
2164
|
+
skip: optionalCount(fields.skip),
|
|
2165
|
+
limit: optionalCount(fields.limit)
|
|
2166
|
+
});
|
|
2167
|
+
case "commitFiles": return await gitCommitFiles({
|
|
2168
|
+
exec,
|
|
2169
|
+
cwd,
|
|
2170
|
+
limits: LIMITS,
|
|
2171
|
+
hash: requiredString(fields.hash, "params.hash")
|
|
2172
|
+
});
|
|
2173
|
+
case "commitDiff": return await gitCommitDiff({
|
|
2174
|
+
exec,
|
|
2175
|
+
cwd,
|
|
2176
|
+
limits: LIMITS,
|
|
2177
|
+
hash: requiredString(fields.hash, "params.hash"),
|
|
2178
|
+
path: requiredString(fields.path, "params.path")
|
|
2179
|
+
});
|
|
2180
|
+
case "stashDiff": return await gitStashDiff({
|
|
2181
|
+
exec,
|
|
2182
|
+
cwd,
|
|
2183
|
+
limits: LIMITS,
|
|
2184
|
+
index: fields.index
|
|
2185
|
+
});
|
|
2186
|
+
case "fileHistory": return await gitFileHistory({
|
|
2187
|
+
exec,
|
|
2188
|
+
cwd,
|
|
2189
|
+
limits: LIMITS,
|
|
2190
|
+
path: requiredString(fields.path, "params.path"),
|
|
2191
|
+
skip: optionalCount(fields.skip),
|
|
2192
|
+
limit: optionalCount(fields.limit)
|
|
2193
|
+
});
|
|
2194
|
+
case "diff": return await gitDiff({
|
|
2195
|
+
exec,
|
|
2196
|
+
cwd,
|
|
2197
|
+
limits: LIMITS,
|
|
2198
|
+
path: requiredString(fields.path, "params.path"),
|
|
2199
|
+
staged: fields.staged === true,
|
|
2200
|
+
untracked: fields.untracked === true
|
|
2201
|
+
});
|
|
2202
|
+
case "action": {
|
|
2203
|
+
const operation = requiredString(fields.operation, "params.operation");
|
|
2204
|
+
if (!OPERATIONS.includes(operation)) throw new RequestError("INVALID_REQUEST", `unknown operation "${operation}"`);
|
|
2205
|
+
return await gitAction({
|
|
2206
|
+
exec,
|
|
2207
|
+
cwd,
|
|
2208
|
+
operation,
|
|
2209
|
+
params: fields
|
|
2210
|
+
});
|
|
2211
|
+
}
|
|
2212
|
+
default: throw new RequestError("INVALID_REQUEST", `unknown action "${action}"`);
|
|
2213
|
+
}
|
|
2214
|
+
} finally {
|
|
2215
|
+
const remaining = (active.get(sessionId) ?? 1) - 1;
|
|
2216
|
+
if (remaining <= 0) active.delete(sessionId);
|
|
2217
|
+
else active.set(sessionId, remaining);
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
/**
|
|
2221
|
+
* Answer one HTTP exchange; only same-origin JSON POSTs from the app page are admitted.
|
|
2222
|
+
* @param req - the request.
|
|
2223
|
+
* @param res - the response.
|
|
2224
|
+
* @returns settles after the response is written.
|
|
2225
|
+
*/
|
|
2226
|
+
async function handle(req, res) {
|
|
2227
|
+
if (req.method !== "POST") {
|
|
2228
|
+
res.writeHead(405, { allow: "POST" });
|
|
2229
|
+
res.end();
|
|
2230
|
+
return;
|
|
2231
|
+
}
|
|
2232
|
+
const origin = req.headers.origin;
|
|
2233
|
+
if (origin !== void 0 && !sameHost(origin, req.headers.host)) {
|
|
2234
|
+
writeJson(res, 403, {
|
|
2235
|
+
ok: false,
|
|
2236
|
+
error: {
|
|
2237
|
+
code: "FORBIDDEN",
|
|
2238
|
+
message: "requests must come from the app origin"
|
|
2239
|
+
}
|
|
2240
|
+
});
|
|
2241
|
+
try {
|
|
2242
|
+
req.resume();
|
|
2243
|
+
} catch {}
|
|
2244
|
+
return;
|
|
2245
|
+
}
|
|
2246
|
+
if (typeof req.headers["content-type"] !== "string" || !req.headers["content-type"].startsWith("application/json")) {
|
|
2247
|
+
writeJson(res, 415, {
|
|
2248
|
+
ok: false,
|
|
2249
|
+
error: {
|
|
2250
|
+
code: "INVALID_REQUEST",
|
|
2251
|
+
message: "content-type must be application/json"
|
|
2252
|
+
}
|
|
2253
|
+
});
|
|
2254
|
+
try {
|
|
2255
|
+
req.resume();
|
|
2256
|
+
} catch {}
|
|
2257
|
+
return;
|
|
2258
|
+
}
|
|
2259
|
+
const controller = new AbortController();
|
|
2260
|
+
res.on("close", () => {
|
|
2261
|
+
if (!res.writableEnded) controller.abort(/* @__PURE__ */ new Error("response closed"));
|
|
2262
|
+
});
|
|
2263
|
+
req.on("aborted", () => {
|
|
2264
|
+
controller.abort(/* @__PURE__ */ new Error("request aborted"));
|
|
2265
|
+
});
|
|
2266
|
+
req.on("error", () => {
|
|
2267
|
+
controller.abort(/* @__PURE__ */ new Error("request failed"));
|
|
2268
|
+
});
|
|
2269
|
+
const timeout = setTimeout(() => {
|
|
2270
|
+
controller.abort(/* @__PURE__ */ new Error("request timed out"));
|
|
2271
|
+
}, REQUEST_TIMEOUT_MS);
|
|
2272
|
+
timeout.unref?.();
|
|
2273
|
+
try {
|
|
2274
|
+
writeJson(res, 200, {
|
|
2275
|
+
ok: true,
|
|
2276
|
+
data: await dispatch(await readJson(req, MAX_BODY_BYTES), controller.signal)
|
|
2277
|
+
});
|
|
2278
|
+
} catch (error) {
|
|
2279
|
+
const failure = isWireFailure(error) ? new RequestError(error.code, messageOf(error), excerpt(detailOf(error))) : new RequestError("INTERNAL", messageOf(error), excerpt(detailOf(error)));
|
|
2280
|
+
if (failure.code === "INTERNAL") ctx.logger?.warn?.(error instanceof Error ? error : new Error(String(error)));
|
|
2281
|
+
if (res.headersSent) {
|
|
2282
|
+
res.destroy();
|
|
2283
|
+
return;
|
|
2284
|
+
}
|
|
2285
|
+
writeJson(res, 200, {
|
|
2286
|
+
ok: false,
|
|
2287
|
+
error: {
|
|
2288
|
+
code: failure.code,
|
|
2289
|
+
message: failure.message,
|
|
2290
|
+
detail: failure.detail
|
|
2291
|
+
}
|
|
2292
|
+
});
|
|
2293
|
+
} finally {
|
|
2294
|
+
clearTimeout(timeout);
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2297
|
+
ctx.effect(() => ctx.webServer.register({
|
|
2298
|
+
kind: "prefix",
|
|
2299
|
+
path: ROUTE,
|
|
2300
|
+
handler: (req, res) => handle(req, res)
|
|
2301
|
+
}), "dsh-git-scm: route");
|
|
2302
|
+
}
|
|
2303
|
+
/** Read one required string field of a request's params. */
|
|
2304
|
+
function requiredString(value, field) {
|
|
2305
|
+
if (typeof value !== "string" || value.length === 0) throw new RequestError("INVALID_REQUEST", `${field} must be a non-empty string`);
|
|
2306
|
+
return value;
|
|
2307
|
+
}
|
|
2308
|
+
/** Read an optional non-negative integer field of a request's params. */
|
|
2309
|
+
function optionalCount(value) {
|
|
2310
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
|
|
2311
|
+
}
|
|
2312
|
+
/**
|
|
2313
|
+
* Whether a browser Origin names the same host as the request.
|
|
2314
|
+
* @param origin - the Origin header value.
|
|
2315
|
+
* @param host - the Host header value.
|
|
2316
|
+
* @returns whether the request is same-origin.
|
|
2317
|
+
*/
|
|
2318
|
+
function sameHost(origin, host) {
|
|
2319
|
+
if (typeof host !== "string") return false;
|
|
2320
|
+
try {
|
|
2321
|
+
return new URL(origin).host === host;
|
|
2322
|
+
} catch {
|
|
2323
|
+
return false;
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
/**
|
|
2327
|
+
* Read a bounded JSON body.
|
|
2328
|
+
* @param req - the request.
|
|
2329
|
+
* @param limit - largest accepted body in bytes.
|
|
2330
|
+
* @returns the decoded body.
|
|
2331
|
+
*/
|
|
2332
|
+
async function readJson(req, limit) {
|
|
2333
|
+
const chunks = [];
|
|
2334
|
+
let size = 0;
|
|
2335
|
+
for await (const chunk of req) {
|
|
2336
|
+
size += chunk.length;
|
|
2337
|
+
if (size > limit) throw new RequestError("INVALID_REQUEST", "the request body is too large");
|
|
2338
|
+
chunks.push(chunk);
|
|
2339
|
+
}
|
|
2340
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
2341
|
+
if (text.trim().length === 0) return {};
|
|
2342
|
+
try {
|
|
2343
|
+
return JSON.parse(text);
|
|
2344
|
+
} catch {
|
|
2345
|
+
throw new RequestError("INVALID_REQUEST", "the request body is not valid JSON");
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
/**
|
|
2349
|
+
* Write one JSON response.
|
|
2350
|
+
* @param res - the response.
|
|
2351
|
+
* @param status - HTTP status.
|
|
2352
|
+
* @param body - JSON-serializable body.
|
|
2353
|
+
*/
|
|
2354
|
+
function writeJson(res, status, body) {
|
|
2355
|
+
const text = JSON.stringify(body);
|
|
2356
|
+
res.writeHead(status, {
|
|
2357
|
+
"content-type": "application/json; charset=utf-8",
|
|
2358
|
+
"content-length": Buffer.byteLength(text),
|
|
2359
|
+
"cache-control": "no-store"
|
|
2360
|
+
});
|
|
2361
|
+
res.end(text);
|
|
2362
|
+
}
|
|
2363
|
+
/**
|
|
2364
|
+
* The first non-empty line of Git's output, for a one-line diagnostic.
|
|
2365
|
+
* @param text - raw output.
|
|
2366
|
+
* @returns the first meaningful line.
|
|
2367
|
+
*/
|
|
2368
|
+
function firstLine(text) {
|
|
2369
|
+
return String(text ?? "").split(/\r?\n/).map((line) => line.trim()).find((line) => line.length > 0) ?? "no diagnostic";
|
|
2370
|
+
}
|
|
2371
|
+
/**
|
|
2372
|
+
* Bound raw output attached to a failure report.
|
|
2373
|
+
* @param text - raw output or detail.
|
|
2374
|
+
* @returns at most 2000 characters, or null.
|
|
2375
|
+
*/
|
|
2376
|
+
function excerpt(text) {
|
|
2377
|
+
if (typeof text !== "string" || text.length === 0) return null;
|
|
2378
|
+
return text.length <= 2e3 ? text : `${text.slice(0, 2e3)}…`;
|
|
2379
|
+
}
|
|
2380
|
+
export { apply, inject };
|
|
2381
|
+
|
|
2382
|
+
//# sourceMappingURL=index.js.map
|