@kyuki3rain/cupola 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/CHANGELOG.md +26 -0
- package/LICENSE +202 -0
- package/README.md +40 -2
- package/dist/adr.js +106 -0
- package/dist/catalog.js +137 -0
- package/dist/check.js +192 -0
- package/dist/cli.js +8 -0
- package/dist/code.js +216 -0
- package/dist/commands/change.js +522 -0
- package/dist/commands/epic.js +311 -0
- package/dist/commands/install.js +109 -0
- package/dist/commands/locks.js +175 -0
- package/dist/commands/procedure.js +92 -0
- package/dist/commands/revision.js +139 -0
- package/dist/commands/run.js +1015 -0
- package/dist/commands/setup.js +382 -0
- package/dist/commands/spec.js +80 -0
- package/dist/commands/status.js +1158 -0
- package/dist/commands/trace.js +397 -0
- package/dist/commands/wait.js +102 -0
- package/dist/commands/work.js +121 -0
- package/dist/commands/workspace.js +126 -0
- package/dist/commands/worktree.js +422 -0
- package/dist/config.js +289 -0
- package/dist/day.js +29 -0
- package/dist/e2e-project.js +62 -0
- package/dist/e2e.js +207 -0
- package/dist/engine/cc-sdd.js +164 -0
- package/dist/epic.js +360 -0
- package/dist/feedback.js +34 -0
- package/dist/frontmatter.js +20 -0
- package/dist/git.js +365 -0
- package/dist/host/github.js +290 -0
- package/dist/host/host.js +1 -0
- package/dist/install.js +182 -0
- package/dist/io.js +46 -0
- package/dist/main.js +771 -0
- package/dist/method/v1.js +56 -0
- package/dist/procedure.js +60 -0
- package/dist/record.js +473 -0
- package/dist/release.js +84 -0
- package/dist/repo.js +13 -0
- package/dist/runbook.js +111 -0
- package/dist/safe-write.js +80 -0
- package/dist/spec.js +171 -0
- package/dist/status.js +190 -0
- package/dist/templates.js +49 -0
- package/dist/trace.js +275 -0
- package/dist/tracker/files.js +156 -0
- package/dist/tracker/github-issues.js +217 -0
- package/dist/tracker/index.js +27 -0
- package/dist/tracker/tracker.js +69 -0
- package/dist/tree.js +42 -0
- package/dist/trust.js +13 -0
- package/dist/version.js +5 -0
- package/dist/work.js +149 -0
- package/dist/workspace.js +299 -0
- package/npm-shrinkwrap.json +2014 -0
- package/package.json +41 -4
- package/skills/cupola-abort/SKILL.md +45 -0
- package/skills/cupola-adr/SKILL.md +41 -0
- package/skills/cupola-ask/SKILL.md +42 -0
- package/skills/cupola-catalog/SKILL.md +41 -0
- package/skills/cupola-catalog-draft/SKILL.md +114 -0
- package/skills/cupola-complete/SKILL.md +87 -0
- package/skills/cupola-decide/SKILL.md +60 -0
- package/skills/cupola-doc/SKILL.md +52 -0
- package/skills/cupola-e2e-setup/SKILL.md +78 -0
- package/skills/cupola-e2e-test/SKILL.md +115 -0
- package/skills/cupola-epic-accept/SKILL.md +162 -0
- package/skills/cupola-epic-create/SKILL.md +120 -0
- package/skills/cupola-epic-revise/SKILL.md +71 -0
- package/skills/cupola-epic-run/SKILL.md +127 -0
- package/skills/cupola-fix/SKILL.md +115 -0
- package/skills/cupola-init/SKILL.md +88 -0
- package/skills/cupola-intake/SKILL.md +78 -0
- package/skills/cupola-operate/SKILL.md +64 -0
- package/skills/cupola-resolve/SKILL.md +86 -0
- package/skills/cupola-review/SKILL.md +132 -0
- package/skills/cupola-spec-design/SKILL.md +164 -0
- package/skills/cupola-spec-impl/SKILL.md +135 -0
- package/skills/cupola-spec-run/SKILL.md +125 -0
- package/skills/cupola-steering/SKILL.md +46 -0
- package/templates/install/.kiro/steering/e2e.md +48 -0
- package/templates/install/.kiro/steering/operations.md +109 -0
- package/templates/install/.kiro/steering/principles.md +25 -0
- package/templates/install/CLAUDE.md +19 -0
- package/templates/install/adr/TEMPLATE.md +38 -0
- package/templates/install/cc-sdd/patches.json +31 -0
- package/templates/method-1/behavior-area.md +43 -0
- package/templates/method-1/behavior-index.md +16 -0
- package/templates/method-1/card.md +41 -0
- package/templates/method-1/case-draft.md +25 -0
- package/templates/method-1/case.md +38 -0
- package/templates/method-1/catalog-spec.md +33 -0
- package/templates/method-1/changes/adr.md +4 -0
- package/templates/method-1/changes/catalog.md +29 -0
- package/templates/method-1/changes/doc.md +5 -0
- package/templates/method-1/changes/e2e.md +7 -0
- package/templates/method-1/changes/epic.md +29 -0
- package/templates/method-1/changes/fix.md +21 -0
- package/templates/method-1/changes/release.md +23 -0
- package/templates/method-1/changes/spec.md +55 -0
- package/templates/method-1/changes/system.md +13 -0
- package/templates/method-1/cupola-issue-draft.md +17 -0
- package/templates/method-1/epic.md +136 -0
- package/templates/method-1/fix-spec.md +34 -0
- package/templates/method-1/fix.md +39 -0
- package/templates/method-1/lock.json +13 -0
- package/templates/method-1/phase-outcome.json +29 -0
- package/templates/method-1/record.json +63 -0
- package/templates/method-1/report.md +27 -0
- package/templates/method-1/runbook.md +39 -0
- package/templates/method-1/runner-result.json +6 -0
- package/templates/method-1/send-back.md +23 -0
- package/templates/methods.json +13 -0
package/dist/git.js
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import { execFile, spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
const exec = promisify(execFile);
|
|
5
|
+
/** Subcommands that talk to a remote, which can hang on a stalled connection. */
|
|
6
|
+
const NETWORK = new Set(["fetch", "ls-remote", "push", "pull", "clone"]);
|
|
7
|
+
/**
|
|
8
|
+
* How long a network call may take: a first try that is short, since a stalled
|
|
9
|
+
* connection (an ssh session that never answers) is far more common than a
|
|
10
|
+
* transfer this slow, and a longer second try.
|
|
11
|
+
*/
|
|
12
|
+
const NETWORK_TIMEOUTS_MS = [30_000, 90_000];
|
|
13
|
+
export async function git(cwd, args, limits = {}) {
|
|
14
|
+
if (!NETWORK.has(args[0] ?? "")) {
|
|
15
|
+
const { stdout } = await exec("git", args, { cwd, maxBuffer: 256 * 1024 * 1024 });
|
|
16
|
+
return stdout.trim();
|
|
17
|
+
}
|
|
18
|
+
if (args[0] === "push") {
|
|
19
|
+
// Forgotten when the push starts and again when it ends, so that nothing
|
|
20
|
+
// asked while it ran is kept; a failed push may have moved refs too.
|
|
21
|
+
remoteCache.clear();
|
|
22
|
+
try {
|
|
23
|
+
return await network(cwd, args, limits);
|
|
24
|
+
}
|
|
25
|
+
finally {
|
|
26
|
+
remoteCache.clear();
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const heads = headsQuery(args);
|
|
30
|
+
if (heads)
|
|
31
|
+
return answerHeads(cwd, heads, limits);
|
|
32
|
+
const once = fetchOnce(args);
|
|
33
|
+
if (once) {
|
|
34
|
+
const key = `${await repoKey(cwd)}\0${args.join("\0")}`;
|
|
35
|
+
const done = remoteCache.get(key);
|
|
36
|
+
if (done)
|
|
37
|
+
return done;
|
|
38
|
+
const pending = network(cwd, args, limits);
|
|
39
|
+
remoteCache.set(key, pending);
|
|
40
|
+
pending.catch(() => remoteCache.delete(key));
|
|
41
|
+
return pending;
|
|
42
|
+
}
|
|
43
|
+
return network(cwd, args, limits);
|
|
44
|
+
}
|
|
45
|
+
/** Runs a network call, bounded; a stalled try is stopped with everything it started. */
|
|
46
|
+
async function network(cwd, args, limits) {
|
|
47
|
+
const timeouts = limits.timeoutMs !== undefined ? [limits.timeoutMs, limits.timeoutMs] : NETWORK_TIMEOUTS_MS;
|
|
48
|
+
const attempts = limits.retry === false ? 1 : 2;
|
|
49
|
+
for (let attempt = 0;; attempt++) {
|
|
50
|
+
const timeout = timeouts[attempt] ?? NETWORK_TIMEOUTS_MS[1] ?? 90_000;
|
|
51
|
+
const result = await runBounded(cwd, args, timeout);
|
|
52
|
+
if (!result.stalled)
|
|
53
|
+
return result.stdout;
|
|
54
|
+
// A stalled connection is tried once more; a second stall is the caller's to handle.
|
|
55
|
+
if (attempt + 1 >= attempts) {
|
|
56
|
+
const waited = timeouts.slice(0, attempts).map((t) => `${t / 1000}s`);
|
|
57
|
+
throw new Error(`git ${args[0]} did not answer within ${attempts > 1 && waited[0] === waited[1] ? `${waited[0]} twice` : waited.join(", then ")}; check the connection to origin and run again`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Runs git bounded: a stalled try is stopped with everything it started (its
|
|
63
|
+
* transport: ssh, a credential helper), since killing git alone leaves ssh
|
|
64
|
+
* connected. git stays in the terminal's session, so ssh can still prompt and
|
|
65
|
+
* Ctrl-C still reaches it.
|
|
66
|
+
* Fails as `execFile` does, with `code` (the exit code) and `stderr`.
|
|
67
|
+
*/
|
|
68
|
+
function runBounded(cwd, args, timeout) {
|
|
69
|
+
return new Promise((resolvePromise, reject) => {
|
|
70
|
+
const child = spawn("git", args, {
|
|
71
|
+
cwd,
|
|
72
|
+
env: noPrompts(),
|
|
73
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
74
|
+
windowsHide: true,
|
|
75
|
+
});
|
|
76
|
+
child.stdout?.setEncoding("utf8");
|
|
77
|
+
child.stderr?.setEncoding("utf8");
|
|
78
|
+
let stdout = "";
|
|
79
|
+
let stderr = "";
|
|
80
|
+
let stalled = false;
|
|
81
|
+
child.stdout?.on("data", (d) => {
|
|
82
|
+
stdout += d;
|
|
83
|
+
});
|
|
84
|
+
child.stderr?.on("data", (d) => {
|
|
85
|
+
stderr += d;
|
|
86
|
+
});
|
|
87
|
+
const timer = setTimeout(() => {
|
|
88
|
+
stalled = true;
|
|
89
|
+
killTree(child.pid);
|
|
90
|
+
}, timeout);
|
|
91
|
+
// Once stopped, git's exit is the answer: a process that escaped the kill
|
|
92
|
+
// may still hold its output open, and is not waited for.
|
|
93
|
+
child.on("exit", () => {
|
|
94
|
+
if (!stalled)
|
|
95
|
+
return;
|
|
96
|
+
child.stdout?.destroy();
|
|
97
|
+
child.stderr?.destroy();
|
|
98
|
+
resolvePromise({ stalled: true });
|
|
99
|
+
});
|
|
100
|
+
child.on("error", (error) => {
|
|
101
|
+
clearTimeout(timer);
|
|
102
|
+
reject(error);
|
|
103
|
+
});
|
|
104
|
+
child.on("close", (code) => {
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
if (stalled)
|
|
107
|
+
resolvePromise({ stalled: true });
|
|
108
|
+
else if (code === 0)
|
|
109
|
+
resolvePromise({ stalled: false, stdout: stdout.trim() });
|
|
110
|
+
else
|
|
111
|
+
reject(Object.assign(new Error(`git ${args[0]} failed: ${stderr.trim()}`), {
|
|
112
|
+
code,
|
|
113
|
+
stdout,
|
|
114
|
+
stderr,
|
|
115
|
+
}));
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
/** Kills a process and its descendants, deepest first. */
|
|
120
|
+
function killTree(pid) {
|
|
121
|
+
if (pid === undefined)
|
|
122
|
+
return;
|
|
123
|
+
if (process.platform === "win32") {
|
|
124
|
+
spawnSync("taskkill", ["/pid", String(pid), "/t", "/f"], { windowsHide: true });
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const signal = (p, s) => {
|
|
128
|
+
try {
|
|
129
|
+
process.kill(p, s);
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
// already gone
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
// Stop each process before listing its children, so that none starts a
|
|
136
|
+
// child after the listing and is left running (holding git's output open).
|
|
137
|
+
const stopped = new Set();
|
|
138
|
+
const order = [];
|
|
139
|
+
let found = [pid];
|
|
140
|
+
while (found.length > 0) {
|
|
141
|
+
for (const p of found) {
|
|
142
|
+
signal(p, "SIGSTOP");
|
|
143
|
+
stopped.add(p);
|
|
144
|
+
order.unshift(p);
|
|
145
|
+
}
|
|
146
|
+
const ps = spawnSync("ps", ["-A", "-o", "pid=,ppid="], { encoding: "utf8" });
|
|
147
|
+
found = [];
|
|
148
|
+
for (const line of (ps.stdout ?? "").split("\n")) {
|
|
149
|
+
const [child, parent] = line.trim().split(/\s+/).map(Number);
|
|
150
|
+
if (child && parent !== undefined && stopped.has(parent) && !stopped.has(child))
|
|
151
|
+
found.push(child);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
for (const p of order)
|
|
155
|
+
signal(p, "SIGKILL");
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* What one command already learned from each origin: the branches on it, and
|
|
159
|
+
* the fetches into tracking refs it made. A command asks origin about each
|
|
160
|
+
* repository once, not once per question (worktrees share their repository's).
|
|
161
|
+
* A push forgets it all, since origin has changed.
|
|
162
|
+
*/
|
|
163
|
+
const remoteCache = new Map();
|
|
164
|
+
/** Starts a command afresh: what origin held for an earlier one may have changed since. */
|
|
165
|
+
export function forgetRemotes() {
|
|
166
|
+
remoteCache.clear();
|
|
167
|
+
}
|
|
168
|
+
async function repoKey(cwd) {
|
|
169
|
+
return resolve(cwd, await git(cwd, ["rev-parse", "--git-common-dir"]));
|
|
170
|
+
}
|
|
171
|
+
/** `ls-remote [--exit-code] --heads origin <refs/heads/…>`: answered from one listing of origin's branches. */
|
|
172
|
+
function headsQuery(args) {
|
|
173
|
+
const rest = args.slice(1);
|
|
174
|
+
const exitCode = rest[0] === "--exit-code";
|
|
175
|
+
if (exitCode)
|
|
176
|
+
rest.shift();
|
|
177
|
+
if (rest.length !== 3 || rest[0] !== "--heads" || rest[1] !== "origin")
|
|
178
|
+
return undefined;
|
|
179
|
+
const pattern = rest[2] ?? "";
|
|
180
|
+
if (!pattern.startsWith("refs/heads/") || /[?[\\]/.test(pattern))
|
|
181
|
+
return undefined;
|
|
182
|
+
return { pattern, exitCode };
|
|
183
|
+
}
|
|
184
|
+
async function answerHeads(cwd, query, limits) {
|
|
185
|
+
const key = `${await repoKey(cwd)}\0heads`;
|
|
186
|
+
let listing = remoteCache.get(key);
|
|
187
|
+
if (!listing) {
|
|
188
|
+
listing = network(cwd, ["ls-remote", "--heads", "origin"], limits);
|
|
189
|
+
remoteCache.set(key, listing);
|
|
190
|
+
listing.catch(() => remoteCache.delete(key));
|
|
191
|
+
}
|
|
192
|
+
const all = await listing;
|
|
193
|
+
const match = new RegExp(`^${query.pattern
|
|
194
|
+
.split("*")
|
|
195
|
+
.map((part) => part.replace(/[.+^${}()|]/g, "\\$&"))
|
|
196
|
+
.join(".*")}$`);
|
|
197
|
+
const lines = all.split("\n").filter((line) => match.test(line.split("\t")[1] ?? ""));
|
|
198
|
+
if (lines.length === 0 && query.exitCode) {
|
|
199
|
+
throw Object.assign(new Error(`git ls-remote: ${query.pattern} is not on origin`), {
|
|
200
|
+
code: 2,
|
|
201
|
+
stderr: "",
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
return lines.join("\n");
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* A fetch into tracking refs (every refspec names its destination) is made once
|
|
208
|
+
* per command. A fetch read through FETCH_HEAD is always made: the next fetch
|
|
209
|
+
* would overwrite what it read.
|
|
210
|
+
*/
|
|
211
|
+
function fetchOnce(args) {
|
|
212
|
+
if (args[0] !== "fetch")
|
|
213
|
+
return false;
|
|
214
|
+
const refspecs = args.slice(1).filter((a) => !a.startsWith("-") && a !== "origin");
|
|
215
|
+
return refspecs.length > 0 && refspecs.every((r) => r.includes(":"));
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* A remote call never waits on git's own prompt for a user name or password:
|
|
219
|
+
* it fails at once instead, and the caller reports it. An ssh prompt is left to
|
|
220
|
+
* the user's ssh setup (`core.sshCommand`, an agent) and stopped by the timeout.
|
|
221
|
+
*/
|
|
222
|
+
function noPrompts() {
|
|
223
|
+
return { ...process.env, GIT_TERMINAL_PROMPT: "0" };
|
|
224
|
+
}
|
|
225
|
+
/** Like `git`, but keeps the output exactly, leading and trailing blank lines included. */
|
|
226
|
+
export async function gitRaw(cwd, args) {
|
|
227
|
+
const { stdout } = await exec("git", args, { cwd, maxBuffer: 256 * 1024 * 1024 });
|
|
228
|
+
return stdout;
|
|
229
|
+
}
|
|
230
|
+
export async function gitUserEmail(cwd) {
|
|
231
|
+
try {
|
|
232
|
+
return await git(cwd, ["config", "user.email"]);
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
return "unknown";
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
export async function head(cwd) {
|
|
239
|
+
return git(cwd, ["rev-parse", "--short", "HEAD"]);
|
|
240
|
+
}
|
|
241
|
+
async function hasRemote(cwd, name) {
|
|
242
|
+
return (await git(cwd, ["remote"])).split("\n").includes(name);
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* The branch the work runs on. A run never writes on a detached HEAD or on the
|
|
246
|
+
* default branch: the record must not reach `main`.
|
|
247
|
+
*/
|
|
248
|
+
export async function workBranch(cwd) {
|
|
249
|
+
let branch;
|
|
250
|
+
try {
|
|
251
|
+
branch = await git(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
throw new Error("HEAD is detached; run in the work's worktree, on its branch");
|
|
255
|
+
}
|
|
256
|
+
const defaultBranch = await originDefaultBranch(cwd);
|
|
257
|
+
if (branch === defaultBranch ||
|
|
258
|
+
(defaultBranch === undefined && (branch === "main" || branch === "master"))) {
|
|
259
|
+
throw new Error(`${branch} is the default branch; run in the work's worktree, on its branch`);
|
|
260
|
+
}
|
|
261
|
+
return branch;
|
|
262
|
+
}
|
|
263
|
+
/** origin's default branch, or undefined when it cannot be told. */
|
|
264
|
+
export async function originDefaultBranch(cwd, limits = {}) {
|
|
265
|
+
try {
|
|
266
|
+
return (await git(cwd, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])).replace(/^origin\//, "");
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
// origin/HEAD is set by clone only; ask origin itself when it is missing.
|
|
270
|
+
try {
|
|
271
|
+
const head = await git(cwd, ["ls-remote", "--symref", "origin", "HEAD"], limits);
|
|
272
|
+
return /^ref: refs\/heads\/(\S+)\s+HEAD/m.exec(head)?.[1];
|
|
273
|
+
}
|
|
274
|
+
catch {
|
|
275
|
+
return undefined;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Whether origin's copy of the branch holds commits this checkout does not
|
|
281
|
+
* have. False when there is no origin or the branch is not on it yet.
|
|
282
|
+
*/
|
|
283
|
+
export async function behindOrigin(cwd, branch) {
|
|
284
|
+
if (!(await hasRemote(cwd, "origin")))
|
|
285
|
+
return false;
|
|
286
|
+
try {
|
|
287
|
+
await git(cwd, ["ls-remote", "--exit-code", "--heads", "origin", `refs/heads/${branch}`]);
|
|
288
|
+
}
|
|
289
|
+
catch (error) {
|
|
290
|
+
// Exit code 2: origin is reachable and the branch is not on it yet.
|
|
291
|
+
if (error.code === 2)
|
|
292
|
+
return false;
|
|
293
|
+
throw new Error(`cannot reach origin to check ${branch}; try again when it is reachable`);
|
|
294
|
+
}
|
|
295
|
+
await git(cwd, ["fetch", "--quiet", "origin", `refs/heads/${branch}`]);
|
|
296
|
+
try {
|
|
297
|
+
await git(cwd, ["merge-base", "--is-ancestor", "FETCH_HEAD", "HEAD"]);
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
return true;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Commits the given paths only, and pushes the branch to origin under its own
|
|
306
|
+
* name, so that anyone can pick the work up. A failed push is an
|
|
307
|
+
* error: the commit stays local, and a later run pushes it once resolved.
|
|
308
|
+
*/
|
|
309
|
+
export async function commitPaths(cwd, branch, paths, message) {
|
|
310
|
+
await git(cwd, ["add", "--all", "--", ...paths]);
|
|
311
|
+
const staged = await git(cwd, ["diff", "--cached", "--name-only", "--", ...paths]);
|
|
312
|
+
if (staged !== "") {
|
|
313
|
+
await git(cwd, ["commit", "--quiet", "--only", "-m", message, "--", ...paths]);
|
|
314
|
+
}
|
|
315
|
+
return { committed: staged !== "", pushed: await pushBranch(cwd, branch) };
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Pushes the branch to origin under its own name; false when there is no
|
|
319
|
+
* origin. A failed push is an error: the commits stay local until resolved.
|
|
320
|
+
*/
|
|
321
|
+
export async function pushBranch(cwd, branch) {
|
|
322
|
+
if (!(await hasRemote(cwd, "origin")))
|
|
323
|
+
return false;
|
|
324
|
+
try {
|
|
325
|
+
await git(cwd, ["push", "--quiet", "-u", "origin", `HEAD:refs/heads/${branch}`]);
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
const lines = (error.stderr ?? "").split("\n").map((l) => l.trim());
|
|
329
|
+
const detail = lines.filter((l) => /^(!|error:|fatal:)/.test(l)).join("; ") ||
|
|
330
|
+
lines.filter((l) => l !== "" && !l.startsWith("hint:")).at(-1) ||
|
|
331
|
+
"unknown reason";
|
|
332
|
+
throw new Error(`committed on ${branch} but could not push it (${detail}). Nobody else can see this progress ` +
|
|
333
|
+
`until it is pushed: pull origin ${branch}, resolve, push, and run again`);
|
|
334
|
+
}
|
|
335
|
+
return true;
|
|
336
|
+
}
|
|
337
|
+
/** Runs git with extra environment and standard input, for plumbing that needs them. */
|
|
338
|
+
export function gitWith(cwd, args, opts = {}) {
|
|
339
|
+
return new Promise((resolvePromise, reject) => {
|
|
340
|
+
const child = spawn("git", args, {
|
|
341
|
+
cwd,
|
|
342
|
+
env: { ...process.env, ...opts.env },
|
|
343
|
+
stdio: [opts.input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
|
|
344
|
+
});
|
|
345
|
+
let stdout = "";
|
|
346
|
+
let stderr = "";
|
|
347
|
+
child.stdout?.on("data", (d) => {
|
|
348
|
+
stdout += d;
|
|
349
|
+
});
|
|
350
|
+
child.stderr?.on("data", (d) => {
|
|
351
|
+
stderr += d;
|
|
352
|
+
});
|
|
353
|
+
child.on("error", reject);
|
|
354
|
+
child.on("close", (code) => {
|
|
355
|
+
if (code === 0)
|
|
356
|
+
resolvePromise(stdout.trim());
|
|
357
|
+
else
|
|
358
|
+
reject(Object.assign(new Error(`git ${args[0]} failed: ${stderr.trim()}`), { code, stderr }));
|
|
359
|
+
});
|
|
360
|
+
if (opts.input !== undefined && child.stdin) {
|
|
361
|
+
child.stdin.on("error", () => { }); // git may exit before reading all of it; its exit code says why
|
|
362
|
+
child.stdin.end(opts.input);
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
const exec = promisify(execFile);
|
|
7
|
+
export async function gh(cwd, args, accept) {
|
|
8
|
+
try {
|
|
9
|
+
const { stdout } = await exec("gh", args, { cwd, maxBuffer: 64 * 1024 * 1024 });
|
|
10
|
+
return stdout.trim();
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
const e = error;
|
|
14
|
+
if (typeof e.code === "number" && accept?.(e.code, e.stderr ?? ""))
|
|
15
|
+
return (e.stdout ?? "").trim();
|
|
16
|
+
if (e.code === "ENOENT") {
|
|
17
|
+
throw new Error("the GitHub CLI (gh) is not installed; install it and run `gh auth login`");
|
|
18
|
+
}
|
|
19
|
+
const detail = (e.stderr ?? "").trim() || "gh failed without a message";
|
|
20
|
+
const auth = /auth|login|token|credential/i.test(detail) ? " (see `gh auth status`)" : "";
|
|
21
|
+
throw new Error(`GitHub: ${detail}${auth}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Runs gh with a description passed as a file, never through a pipe. */
|
|
25
|
+
export async function withBody(body, f) {
|
|
26
|
+
const dir = await mkdtemp(join(tmpdir(), "cupola-body-"));
|
|
27
|
+
try {
|
|
28
|
+
const file = join(dir, "body.md");
|
|
29
|
+
await writeFile(file, body);
|
|
30
|
+
return await f(file);
|
|
31
|
+
}
|
|
32
|
+
finally {
|
|
33
|
+
await rm(dir, { recursive: true, force: true });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
/** The owner in a repository URL of any form: https, ssh, scp-like, host aliases, enterprise hosts. */
|
|
37
|
+
export function ownerOf(url) {
|
|
38
|
+
return /[:/]([^/:]+)\/[^/]+?(?:\.git)?\/?$/.exec(url.trim())?.[1]?.toLowerCase();
|
|
39
|
+
}
|
|
40
|
+
/** `owner/repo` of a repository URL of any form, lowercased. */
|
|
41
|
+
export function repoOf(url) {
|
|
42
|
+
const m = /[:/]([^/:]+)\/([^/]+?)(?:\.git)?\/?$/.exec(url.trim());
|
|
43
|
+
return m ? `${m[1]}/${m[2]}`.toLowerCase() : undefined;
|
|
44
|
+
}
|
|
45
|
+
/** The owner of origin's repository, which is where work branches are pushed. */
|
|
46
|
+
async function originOwner(cwd) {
|
|
47
|
+
const { stdout } = await exec("git", ["remote", "get-url", "origin"], { cwd });
|
|
48
|
+
const owner = ownerOf(stdout);
|
|
49
|
+
if (!owner)
|
|
50
|
+
throw new Error(`cannot tell the owner of origin from ${stdout.trim()}`);
|
|
51
|
+
return owner;
|
|
52
|
+
}
|
|
53
|
+
/** Hidden in every answer Cupola writes, so that it can tell its answers from anyone else's. */
|
|
54
|
+
const ANSWER = "<!-- cupola:answer -->";
|
|
55
|
+
/** Hidden in the comment that settles a review's remark, which GitHub cannot resolve itself. */
|
|
56
|
+
const settledMark = (id) => `<!-- cupola:settled ${id} -->`;
|
|
57
|
+
/** Hidden in the comment that answers a review's remark. */
|
|
58
|
+
const onMark = (id) => `<!-- cupola:on ${id} -->`;
|
|
59
|
+
const FEEDBACK_QUERY = `query($owner: String!, $repo: String!, $number: Int!) {
|
|
60
|
+
repository(owner: $owner, name: $repo) {
|
|
61
|
+
pullRequest(number: $number) {
|
|
62
|
+
reviews(first: 100) {
|
|
63
|
+
nodes { id author { login __typename } authorAssociation body submittedAt }
|
|
64
|
+
pageInfo { hasNextPage }
|
|
65
|
+
}
|
|
66
|
+
reviewThreads(first: 100) {
|
|
67
|
+
nodes {
|
|
68
|
+
id isResolved path line originalLine
|
|
69
|
+
comments(first: 100) {
|
|
70
|
+
nodes { author { login __typename } authorAssociation body createdAt }
|
|
71
|
+
pageInfo { hasNextPage }
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
pageInfo { hasNextPage }
|
|
75
|
+
}
|
|
76
|
+
comments(first: 100) {
|
|
77
|
+
nodes { author { login __typename } authorAssociation body }
|
|
78
|
+
pageInfo { hasNextPage }
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}`;
|
|
83
|
+
function who(r) {
|
|
84
|
+
return {
|
|
85
|
+
author: r.author?.login ?? "",
|
|
86
|
+
association: r.authorAssociation || "NONE",
|
|
87
|
+
bot: r.author?.__typename === "Bot",
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* GitHub's review threads and review bodies as feedback (see `Feedback`). A
|
|
92
|
+
* mark settles or answers only when someone `trusted` wrote it.
|
|
93
|
+
*/
|
|
94
|
+
export function feedbackOf(pr, trusted = () => true) {
|
|
95
|
+
const pages = [
|
|
96
|
+
pr.reviews,
|
|
97
|
+
pr.reviewThreads,
|
|
98
|
+
pr.comments,
|
|
99
|
+
...pr.reviewThreads.nodes.map((t) => t.comments),
|
|
100
|
+
];
|
|
101
|
+
if (pages.some((p) => p.pageInfo?.hasNextPage)) {
|
|
102
|
+
throw new Error("the change has more than 100 reviews, threads, or comments; Cupola cannot read them all yet");
|
|
103
|
+
}
|
|
104
|
+
const said = pr.comments.nodes.filter((c) => trusted(who(c))).map((c) => c.body);
|
|
105
|
+
const has = (mark) => said.some((b) => b.includes(mark));
|
|
106
|
+
const threads = pr.reviewThreads.nodes.flatMap((t) => {
|
|
107
|
+
const [first, ...rest] = t.comments.nodes;
|
|
108
|
+
if (!first)
|
|
109
|
+
return [];
|
|
110
|
+
// The latest remark that counts: an outsider's reply neither answers nor reopens it.
|
|
111
|
+
const last = [first, ...rest].filter((c) => trusted(who(c))).at(-1);
|
|
112
|
+
return [
|
|
113
|
+
{
|
|
114
|
+
id: `thread:${t.id}`,
|
|
115
|
+
...who(first),
|
|
116
|
+
body: first.body,
|
|
117
|
+
at: first.createdAt,
|
|
118
|
+
place: { path: t.path, line: t.line ?? t.originalLine ?? null },
|
|
119
|
+
replies: rest.map((c) => ({ ...who(c), body: c.body, at: c.createdAt })),
|
|
120
|
+
open: !t.isResolved,
|
|
121
|
+
answered: last?.body.includes(ANSWER) ?? false,
|
|
122
|
+
},
|
|
123
|
+
];
|
|
124
|
+
});
|
|
125
|
+
// A review's own remark is on the whole change; GitHub keeps no thread for it.
|
|
126
|
+
const bodies = pr.reviews.nodes
|
|
127
|
+
.filter((r) => r.body.trim() !== "" && r.submittedAt)
|
|
128
|
+
.map((r) => {
|
|
129
|
+
const id = `review:${r.id}`;
|
|
130
|
+
return {
|
|
131
|
+
id,
|
|
132
|
+
...who(r),
|
|
133
|
+
body: r.body,
|
|
134
|
+
at: r.submittedAt ?? "",
|
|
135
|
+
place: null,
|
|
136
|
+
replies: [],
|
|
137
|
+
open: !has(settledMark(id)),
|
|
138
|
+
answered: has(onMark(id)),
|
|
139
|
+
};
|
|
140
|
+
});
|
|
141
|
+
const answers = pr.reviews.nodes
|
|
142
|
+
.filter((r) => r.submittedAt)
|
|
143
|
+
.map((r) => ({ ...who(r), at: r.submittedAt ?? "" }));
|
|
144
|
+
return { feedback: [...threads, ...bodies].sort((a, b) => a.at.localeCompare(b.at)), answers };
|
|
145
|
+
}
|
|
146
|
+
function toChange(pr) {
|
|
147
|
+
return {
|
|
148
|
+
number: pr.number,
|
|
149
|
+
url: pr.url,
|
|
150
|
+
state: pr.state.toLowerCase(),
|
|
151
|
+
draft: pr.isDraft,
|
|
152
|
+
...(pr.headRefOid ? { head: pr.headRefOid } : {}),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
const FIELDS = "number,url,state,isDraft,headRepositoryOwner,headRefOid";
|
|
156
|
+
/** GitHub through the `gh` CLI, run in the repository so that it targets its remote. */
|
|
157
|
+
export function github(cwd) {
|
|
158
|
+
return {
|
|
159
|
+
async findChange(branch) {
|
|
160
|
+
const owner = await originOwner(cwd);
|
|
161
|
+
const out = await gh(cwd, [
|
|
162
|
+
"pr",
|
|
163
|
+
"list",
|
|
164
|
+
"--head",
|
|
165
|
+
branch,
|
|
166
|
+
"--state",
|
|
167
|
+
"all",
|
|
168
|
+
"--limit",
|
|
169
|
+
"20",
|
|
170
|
+
"--json",
|
|
171
|
+
FIELDS,
|
|
172
|
+
]);
|
|
173
|
+
// Another fork may have a branch of the same name; only origin's is this work's.
|
|
174
|
+
const pr = JSON.parse(out).find((p) => p.headRepositoryOwner?.login.toLowerCase() === owner);
|
|
175
|
+
return pr ? toChange(pr) : undefined;
|
|
176
|
+
},
|
|
177
|
+
async openChange({ branch, base, title, body, draft }) {
|
|
178
|
+
const owner = await originOwner(cwd);
|
|
179
|
+
const url = await withBody(body, (file) => {
|
|
180
|
+
const args = [
|
|
181
|
+
"pr",
|
|
182
|
+
"create",
|
|
183
|
+
"--head",
|
|
184
|
+
`${owner}:${branch}`,
|
|
185
|
+
"--base",
|
|
186
|
+
base,
|
|
187
|
+
"--title",
|
|
188
|
+
title,
|
|
189
|
+
"--body-file",
|
|
190
|
+
file,
|
|
191
|
+
];
|
|
192
|
+
if (draft)
|
|
193
|
+
args.push("--draft");
|
|
194
|
+
return gh(cwd, args);
|
|
195
|
+
});
|
|
196
|
+
const created = url.split("\n").at(-1) ?? url;
|
|
197
|
+
return toChange(JSON.parse(await gh(cwd, ["pr", "view", created, "--json", FIELDS])));
|
|
198
|
+
},
|
|
199
|
+
async body(number) {
|
|
200
|
+
return JSON.parse(await gh(cwd, ["pr", "view", String(number), "--json", "body"]))
|
|
201
|
+
.body;
|
|
202
|
+
},
|
|
203
|
+
async setBody(number, body) {
|
|
204
|
+
await withBody(body, (file) => gh(cwd, ["pr", "edit", String(number), "--body-file", file]));
|
|
205
|
+
},
|
|
206
|
+
async markReady(number) {
|
|
207
|
+
await gh(cwd, ["pr", "ready", String(number)]);
|
|
208
|
+
},
|
|
209
|
+
async markDraft(number) {
|
|
210
|
+
await gh(cwd, ["pr", "ready", String(number), "--undo"]);
|
|
211
|
+
},
|
|
212
|
+
async closeChange(number, comment) {
|
|
213
|
+
// One call, so that a retry after a failure does not post the comment twice.
|
|
214
|
+
await gh(cwd, ["pr", "close", String(number), "--comment", comment]);
|
|
215
|
+
},
|
|
216
|
+
async requestReview(number, reviewer) {
|
|
217
|
+
const who = reviewer === "copilot" ? "@copilot" : reviewer;
|
|
218
|
+
await gh(cwd, ["pr", "edit", String(number), "--add-reviewer", who]);
|
|
219
|
+
},
|
|
220
|
+
async feedback(number, trusted) {
|
|
221
|
+
const out = JSON.parse(await gh(cwd, [
|
|
222
|
+
"api",
|
|
223
|
+
"graphql",
|
|
224
|
+
"-f",
|
|
225
|
+
`query=${FEEDBACK_QUERY}`,
|
|
226
|
+
"-F",
|
|
227
|
+
"owner={owner}",
|
|
228
|
+
"-F",
|
|
229
|
+
"repo={repo}",
|
|
230
|
+
"-F",
|
|
231
|
+
`number=${number}`,
|
|
232
|
+
]));
|
|
233
|
+
return feedbackOf(out.data.repository.pullRequest, trusted);
|
|
234
|
+
},
|
|
235
|
+
async answer(number, id, body, settle) {
|
|
236
|
+
const [kind, node] = [id.slice(0, id.indexOf(":")), id.slice(id.indexOf(":") + 1)];
|
|
237
|
+
if (kind === "thread") {
|
|
238
|
+
await gh(cwd, [
|
|
239
|
+
"api",
|
|
240
|
+
"graphql",
|
|
241
|
+
"-f",
|
|
242
|
+
"query=mutation($id: ID!, $body: String!) { addPullRequestReviewThreadReply(input: {pullRequestReviewThreadId: $id, body: $body}) { comment { id } } }",
|
|
243
|
+
"-f",
|
|
244
|
+
`id=${node}`,
|
|
245
|
+
"-f",
|
|
246
|
+
`body=${body}\n\n${ANSWER}`,
|
|
247
|
+
]);
|
|
248
|
+
if (settle) {
|
|
249
|
+
await gh(cwd, [
|
|
250
|
+
"api",
|
|
251
|
+
"graphql",
|
|
252
|
+
"-f",
|
|
253
|
+
"query=mutation($id: ID!) { resolveReviewThread(input: {threadId: $id}) { thread { id } } }",
|
|
254
|
+
"-f",
|
|
255
|
+
`id=${node}`,
|
|
256
|
+
]);
|
|
257
|
+
}
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
if (kind !== "review")
|
|
261
|
+
throw new Error(`no feedback ${id} on GitHub`);
|
|
262
|
+
const marks = `${ANSWER} ${onMark(id)}${settle ? ` ${settledMark(id)}` : ""}`;
|
|
263
|
+
await withBody(`${body}\n\n${marks}`, (file) => gh(cwd, ["pr", "comment", String(number), "--body-file", file]));
|
|
264
|
+
},
|
|
265
|
+
async hasCi() {
|
|
266
|
+
// GitHub also lists workflows it runs itself (e.g. the Copilot reviewer, under
|
|
267
|
+
// `dynamic/`); only files in .github/workflows/ are the repository's CI.
|
|
268
|
+
const out = await gh(cwd, [
|
|
269
|
+
"api",
|
|
270
|
+
"--paginate",
|
|
271
|
+
"repos/{owner}/{repo}/actions/workflows",
|
|
272
|
+
"--jq",
|
|
273
|
+
'.workflows[] | select(.state == "active") | .path',
|
|
274
|
+
]);
|
|
275
|
+
return out.split("\n").some((path) => path.startsWith(".github/workflows/"));
|
|
276
|
+
},
|
|
277
|
+
async checks(number) {
|
|
278
|
+
// gh exits 8 while checks are pending, and 1 when one failed or when there are none;
|
|
279
|
+
// any other exit 1 (authentication, network) is a failure, not "no checks".
|
|
280
|
+
const out = await gh(cwd, ["pr", "checks", String(number), "--json", "name,bucket"], (code, stderr) => code === 8 ||
|
|
281
|
+
(code === 1 && (/no checks reported/i.test(stderr) || stderr.trim() === "")));
|
|
282
|
+
if (out === "")
|
|
283
|
+
return [];
|
|
284
|
+
return JSON.parse(out).map((c) => ({
|
|
285
|
+
name: c.name,
|
|
286
|
+
state: c.bucket,
|
|
287
|
+
}));
|
|
288
|
+
},
|
|
289
|
+
};
|
|
290
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|