@kyuki3rain/cupola 0.0.0-stage → 0.2.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 +184 -0
- package/LICENSE +202 -0
- package/README.md +41 -2
- package/dist/adr.js +106 -0
- package/dist/branch-store.js +73 -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 +728 -0
- package/dist/commands/epic.js +311 -0
- package/dist/commands/execution.js +482 -0
- package/dist/commands/install.js +109 -0
- package/dist/commands/locks.js +243 -0
- package/dist/commands/reaction.js +185 -0
- package/dist/commands/revision.js +139 -0
- package/dist/commands/run.js +1021 -0
- package/dist/commands/setup.js +414 -0
- package/dist/commands/spec.js +80 -0
- package/dist/commands/status.js +1457 -0
- package/dist/commands/trace.js +474 -0
- package/dist/commands/wait.js +105 -0
- package/dist/commands/work.js +126 -0
- package/dist/commands/workspace.js +137 -0
- package/dist/commands/worktree.js +422 -0
- package/dist/config.js +353 -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 +379 -0
- package/dist/execution.js +272 -0
- package/dist/feedback.js +20 -0
- package/dist/frontmatter.js +20 -0
- package/dist/git.js +365 -0
- package/dist/host/git.js +224 -0
- package/dist/host/github.js +387 -0
- package/dist/host/host.js +3 -0
- package/dist/host/index.js +63 -0
- package/dist/install.js +182 -0
- package/dist/io.js +46 -0
- package/dist/main.js +866 -0
- package/dist/method/v1.js +56 -0
- package/dist/reaction.js +110 -0
- package/dist/record.js +507 -0
- package/dist/release.js +84 -0
- package/dist/repo.js +13 -0
- package/dist/runbook.js +132 -0
- package/dist/safe-write.js +80 -0
- package/dist/spec.js +171 -0
- package/dist/status.js +321 -0
- package/dist/templates.js +50 -0
- package/dist/trace.js +275 -0
- package/dist/tracker/files.js +99 -0
- package/dist/tracker/github-issues.js +217 -0
- package/dist/tracker/index.js +34 -0
- package/dist/tracker/tracker.js +69 -0
- package/dist/tree.js +59 -0
- package/dist/trust.js +13 -0
- package/dist/version.js +5 -0
- package/dist/work.js +170 -0
- package/dist/workspace.js +324 -0
- package/npm-shrinkwrap.json +2014 -0
- package/package.json +41 -4
- package/skills/cupola-abort/SKILL.md +51 -0
- package/skills/cupola-adr/SKILL.md +54 -0
- package/skills/cupola-ask/SKILL.md +42 -0
- package/skills/cupola-catalog/SKILL.md +41 -0
- package/skills/cupola-catalog-draft/SKILL.md +116 -0
- package/skills/cupola-complete/SKILL.md +107 -0
- package/skills/cupola-decide/SKILL.md +99 -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 +166 -0
- package/skills/cupola-epic-create/SKILL.md +160 -0
- package/skills/cupola-epic-revise/SKILL.md +92 -0
- package/skills/cupola-epic-run/SKILL.md +166 -0
- package/skills/cupola-fix/SKILL.md +117 -0
- package/skills/cupola-init/SKILL.md +143 -0
- package/skills/cupola-intake/SKILL.md +95 -0
- package/skills/cupola-operate/SKILL.md +81 -0
- package/skills/cupola-resolve/SKILL.md +93 -0
- package/skills/cupola-respond/SKILL.md +73 -0
- package/skills/cupola-review/SKILL.md +131 -0
- package/skills/cupola-spec-design/SKILL.md +169 -0
- package/skills/cupola-spec-impl/SKILL.md +137 -0
- package/skills/cupola-spec-run/SKILL.md +137 -0
- package/skills/cupola-steering/SKILL.md +53 -0
- package/skills/cupola-try/SKILL.md +38 -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 +49 -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 +30 -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 +147 -0
- package/templates/method-1/execution.md +55 -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/no-go.md +28 -0
- package/templates/method-1/phase-outcome.json +29 -0
- package/templates/method-1/reaction.md +17 -0
- package/templates/method-1/record.json +63 -0
- package/templates/method-1/report.md +27 -0
- package/templates/method-1/runbook.md +45 -0
- package/templates/method-1/runner-result.json +6 -0
- package/templates/methods.json +13 -0
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { stripComments } from "./epic.js";
|
|
3
|
+
import { parseFrontMatter } from "./frontmatter.js";
|
|
4
|
+
import { withReactions } from "./status.js";
|
|
5
|
+
/**
|
|
6
|
+
* An execution: one run of a runbook, by a human, for an epic or a case. Its
|
|
7
|
+
* record is a permanent document next to the runbook
|
|
8
|
+
* (`<paths.runbooks>/<runbook>/executions/<n>.md`), written on its own branch
|
|
9
|
+
* one step at a time and merged at acceptance to accept it. Its status is derived from
|
|
10
|
+
* that document and its change, never stored.
|
|
11
|
+
*/
|
|
12
|
+
const KEBAB = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
13
|
+
export const EXECUTION_RESULTS = ["finished", "given-up"];
|
|
14
|
+
export const ExecutionFront = z.strictObject({
|
|
15
|
+
kind: z.literal("execution"),
|
|
16
|
+
method: z.number().int(),
|
|
17
|
+
id: z.string().regex(KEBAB, "a kebab-case name"),
|
|
18
|
+
runbook: z.string().regex(KEBAB, "a kebab-case name"),
|
|
19
|
+
/** The commit of the runbook it follows. */
|
|
20
|
+
version: z.string().min(1),
|
|
21
|
+
/** The epic or case it is for. */
|
|
22
|
+
for: z.string().regex(KEBAB, "an epic or case id"),
|
|
23
|
+
params: z.record(z.string(), z.union([z.string(), z.number(), z.boolean()])).default({}),
|
|
24
|
+
started: z.union([z.string(), z.date()]),
|
|
25
|
+
result: z.enum(EXECUTION_RESULTS).nullable().default(null),
|
|
26
|
+
});
|
|
27
|
+
const STEP_ID = "(?:P|X)\\d+";
|
|
28
|
+
const ARRANGED = new RegExp(`^-\\s+(${STEP_ID})\\s+(add|change|skip)(?:\\s+(?:after\\s+(${STEP_ID})|(first)))?\\s*:\\s*(.*)$`);
|
|
29
|
+
const RECORDED = new RegExp(`^-\\s+(${STEP_ID})\\s+(done|stopped)\\b[^:]*:\\s*(.*)$`);
|
|
30
|
+
/** Where `cupola execution record` writes the next step: before this marker. */
|
|
31
|
+
export const NEXT_STEP = "<!-- cupola:next-step -->";
|
|
32
|
+
/** Where it writes the end: before this marker. */
|
|
33
|
+
export const RESULT_MARK = "<!-- cupola:result -->";
|
|
34
|
+
/** Reads an execution's front matter and its ID-led entries; headings and prose are not read. */
|
|
35
|
+
export function parseExecution(raw) {
|
|
36
|
+
const text = raw.replace(/^/, "").replace(/\r\n?/g, "\n");
|
|
37
|
+
const { data, body } = parseFrontMatter(text);
|
|
38
|
+
const offset = text.slice(0, text.length - body.length).split("\n").length - 1;
|
|
39
|
+
const arrangement = [];
|
|
40
|
+
const records = [];
|
|
41
|
+
const placeholders = [];
|
|
42
|
+
let comment = false;
|
|
43
|
+
let fence = false;
|
|
44
|
+
body.split("\n").forEach((original, i) => {
|
|
45
|
+
const n = offset + i + 1;
|
|
46
|
+
if (/^\s*(```|~~~)/.test(original)) {
|
|
47
|
+
fence = !fence;
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (fence)
|
|
51
|
+
return;
|
|
52
|
+
let line;
|
|
53
|
+
[line, comment] = stripComments(original, comment);
|
|
54
|
+
if (line.includes("{{"))
|
|
55
|
+
placeholders.push(n);
|
|
56
|
+
const a = ARRANGED.exec(line);
|
|
57
|
+
if (a) {
|
|
58
|
+
const after = a[4] ? "first" : a[3];
|
|
59
|
+
arrangement.push({
|
|
60
|
+
step: a[1] ?? "",
|
|
61
|
+
how: a[2],
|
|
62
|
+
...(after ? { after } : {}),
|
|
63
|
+
line: n,
|
|
64
|
+
});
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const r = RECORDED.exec(line);
|
|
68
|
+
if (r)
|
|
69
|
+
records.push({
|
|
70
|
+
step: r[1] ?? "",
|
|
71
|
+
result: r[2],
|
|
72
|
+
text: (r[3] ?? "").trim(),
|
|
73
|
+
line: n,
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
return { front: data, arrangement, records, placeholders };
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The steps this execution carries out, in order: the runbook's, without
|
|
80
|
+
* those it skips, with those it adds after the step each names. Problems are
|
|
81
|
+
* arrangements that name a step that is not there.
|
|
82
|
+
*/
|
|
83
|
+
export function arrangedSteps(runbook, arrangement) {
|
|
84
|
+
const problems = [];
|
|
85
|
+
const steps = [...runbook];
|
|
86
|
+
let firsts = 0;
|
|
87
|
+
const added = new Map();
|
|
88
|
+
for (const a of arrangement) {
|
|
89
|
+
if (a.how === "add") {
|
|
90
|
+
if (a.step.startsWith("P")) {
|
|
91
|
+
problems.push({ message: `${a.step}: an added step is X1, X2, …`, line: a.line });
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (steps.includes(a.step)) {
|
|
95
|
+
problems.push({ message: `${a.step} is added twice`, line: a.line });
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (!a.after) {
|
|
99
|
+
problems.push({
|
|
100
|
+
message: `${a.step}: say where it goes: \`add after <step>\` or \`add first\``,
|
|
101
|
+
line: a.line,
|
|
102
|
+
});
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (a.after === "first") {
|
|
106
|
+
steps.splice(firsts, 0, a.step);
|
|
107
|
+
firsts += 1;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const at = steps.indexOf(a.after);
|
|
111
|
+
if (at < 0) {
|
|
112
|
+
problems.push({ message: `${a.step}: no step ${a.after} to add it after`, line: a.line });
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
// Several added after the same step keep the order they are written in.
|
|
116
|
+
const n = added.get(a.after) ?? 0;
|
|
117
|
+
steps.splice(at + 1 + n, 0, a.step);
|
|
118
|
+
added.set(a.after, n + 1);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
if (!runbook.includes(a.step))
|
|
122
|
+
problems.push({ message: `${a.step} is not a step of the runbook`, line: a.line });
|
|
123
|
+
}
|
|
124
|
+
const skipped = new Set(arrangement.filter((a) => a.how === "skip").map((a) => a.step));
|
|
125
|
+
return { steps: steps.filter((s) => !skipped.has(s)), problems };
|
|
126
|
+
}
|
|
127
|
+
/** How far an execution got, from its records. */
|
|
128
|
+
export function executionState(steps, records) {
|
|
129
|
+
const done = [...new Set(records.filter((r) => r.result === "done").map((r) => r.step))].filter((s) => steps.includes(s));
|
|
130
|
+
const last = records.at(-1);
|
|
131
|
+
const next = steps.find((s) => !done.includes(s));
|
|
132
|
+
return {
|
|
133
|
+
steps,
|
|
134
|
+
done,
|
|
135
|
+
...(last?.result === "stopped" ? { stopped: { step: last.step, text: last.text } } : {}),
|
|
136
|
+
...(next ? { next } : {}),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/** The status of an execution: from its record and its change only. */
|
|
140
|
+
export function deriveExecution(e) {
|
|
141
|
+
const { id, front, state, change } = e;
|
|
142
|
+
const operate = `cupola-operate ${id}`;
|
|
143
|
+
const base = {
|
|
144
|
+
work: { kind: "execution", id, component: "" },
|
|
145
|
+
change: change ?? null,
|
|
146
|
+
cards: [],
|
|
147
|
+
run: null,
|
|
148
|
+
execution: {
|
|
149
|
+
runbook: front.runbook,
|
|
150
|
+
for: front.for,
|
|
151
|
+
params: front.params,
|
|
152
|
+
result: front.result,
|
|
153
|
+
steps: state.steps,
|
|
154
|
+
done: state.done,
|
|
155
|
+
...(state.stopped ? { stopped: state.stopped.step } : {}),
|
|
156
|
+
...(state.next ? { next: state.next } : {}),
|
|
157
|
+
},
|
|
158
|
+
};
|
|
159
|
+
const ended = front.result === "given-up" ? "given up" : "finished";
|
|
160
|
+
if (change?.state === "merged") {
|
|
161
|
+
const complete = `cupola-complete ${id}`;
|
|
162
|
+
return {
|
|
163
|
+
...base,
|
|
164
|
+
status: "done",
|
|
165
|
+
turn: e.untidy ? "human" : "none",
|
|
166
|
+
gate: null,
|
|
167
|
+
next: e.untidy
|
|
168
|
+
? { kind: "run", text: `Merged: \`${complete}\` tidies up.`, command: complete }
|
|
169
|
+
: { kind: "nothing", text: `Done (${ended}).` },
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
if (change?.state === "closed") {
|
|
173
|
+
return {
|
|
174
|
+
...base,
|
|
175
|
+
status: "dropped",
|
|
176
|
+
turn: "none",
|
|
177
|
+
gate: null,
|
|
178
|
+
next: { kind: "nothing", text: "Dropped: its change was closed without merging." },
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
const operating = (text) => ({
|
|
182
|
+
...base,
|
|
183
|
+
status: "operating",
|
|
184
|
+
turn: "human",
|
|
185
|
+
gate: null,
|
|
186
|
+
next: { kind: "run", text, command: operate },
|
|
187
|
+
});
|
|
188
|
+
if (front.result) {
|
|
189
|
+
if (change?.state === "open" && !change.draft) {
|
|
190
|
+
const reach = e.reach ?? { read: change.url, merge: "merge it", reactions: true };
|
|
191
|
+
return withReactions({
|
|
192
|
+
...base,
|
|
193
|
+
status: "awaiting-acceptance",
|
|
194
|
+
turn: "human",
|
|
195
|
+
gate: "acceptance",
|
|
196
|
+
next: {
|
|
197
|
+
kind: "gate",
|
|
198
|
+
text: `Read the execution record (${ended}) in ${reach.read}, ${reach.merge} to accept it, then run the command; or comment, or give a No-Go (it goes back to a step) ${reach.reactions ? "on the change or " : ""}with \`cupola-decide ${id}\`.`,
|
|
199
|
+
command: `cupola-complete ${id}`,
|
|
200
|
+
},
|
|
201
|
+
}, id, e.gate);
|
|
202
|
+
}
|
|
203
|
+
return operating(`Recorded ${ended}, but its change is not ready: a No-Go sent it back to a step, or the run stopped before marking it; carry on.`);
|
|
204
|
+
}
|
|
205
|
+
if (e.waits && e.waits.length > 0 && state.done.length === 0 && !state.stopped) {
|
|
206
|
+
return {
|
|
207
|
+
...base,
|
|
208
|
+
status: "waiting",
|
|
209
|
+
turn: "none",
|
|
210
|
+
gate: null,
|
|
211
|
+
next: {
|
|
212
|
+
kind: "nothing",
|
|
213
|
+
text: `It waits for ${e.waits.join(", ")}, earlier in ${front.for}'s procedures; it starts once they are done.`,
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
if (state.stopped) {
|
|
218
|
+
return {
|
|
219
|
+
...base,
|
|
220
|
+
status: "blocked",
|
|
221
|
+
turn: "human",
|
|
222
|
+
gate: null,
|
|
223
|
+
next: {
|
|
224
|
+
kind: "run",
|
|
225
|
+
text: `Stopped at ${state.stopped.step}: ${state.stopped.text} Fix the cause and resume from ${state.stopped.step}, or give it up (\`${operate} --give-up\`).`,
|
|
226
|
+
command: operate,
|
|
227
|
+
},
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
if (!state.next)
|
|
231
|
+
return operating("Every step is done; record the end and mark the change ready.");
|
|
232
|
+
return operating(state.done.length > 0
|
|
233
|
+
? `${state.done.join(", ")} done; next ${state.next}.`
|
|
234
|
+
: `Start at ${state.next}.`);
|
|
235
|
+
}
|
|
236
|
+
/** What `cupola check` lints in an execution record. */
|
|
237
|
+
export function checkExecution(file, raw, runbookSteps) {
|
|
238
|
+
const problems = [];
|
|
239
|
+
const p = (message, line) => problems.push({ file, ...(line ? { line } : {}), message });
|
|
240
|
+
let doc;
|
|
241
|
+
try {
|
|
242
|
+
doc = parseExecution(raw);
|
|
243
|
+
}
|
|
244
|
+
catch (error) {
|
|
245
|
+
return [{ file, message: error.message }];
|
|
246
|
+
}
|
|
247
|
+
const front = ExecutionFront.safeParse(doc.front);
|
|
248
|
+
if (!front.success) {
|
|
249
|
+
for (const issue of front.error.issues)
|
|
250
|
+
p(`front matter ${issue.path.join(".") || "(root)"}: ${issue.message}`);
|
|
251
|
+
}
|
|
252
|
+
const parts = file.split("/");
|
|
253
|
+
const n = parts.at(-1)?.replace(/\.md$/, "");
|
|
254
|
+
const runbook = parts.at(-3);
|
|
255
|
+
if (front.success) {
|
|
256
|
+
if (front.data.runbook !== runbook)
|
|
257
|
+
p(`runbook is ${front.data.runbook}, but its folder is ${runbook}`);
|
|
258
|
+
if (front.data.id !== `${runbook}-${n}`)
|
|
259
|
+
p(`id is ${front.data.id}, expected ${runbook}-${n}`);
|
|
260
|
+
}
|
|
261
|
+
for (const line of doc.placeholders)
|
|
262
|
+
p("template placeholder left ({{…}})", line);
|
|
263
|
+
if (runbookSteps) {
|
|
264
|
+
const { steps, problems: arranged } = arrangedSteps(runbookSteps, doc.arrangement);
|
|
265
|
+
for (const a of arranged)
|
|
266
|
+
p(a.message, a.line);
|
|
267
|
+
for (const r of doc.records)
|
|
268
|
+
if (!steps.includes(r.step))
|
|
269
|
+
p(`${r.step} is not a step of this execution`, r.line);
|
|
270
|
+
}
|
|
271
|
+
return problems;
|
|
272
|
+
}
|
package/dist/feedback.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { trustedBy } from "./trust.js";
|
|
2
|
+
/**
|
|
3
|
+
* Whose remarks on a change count: the configured reviewer's (the review
|
|
4
|
+
* phase's findings) and those of people the configuration trusts (their
|
|
5
|
+
* reactions at a gate).
|
|
6
|
+
*/
|
|
7
|
+
/** Whether a remark's author is the reviewer asked for: a login, or `copilot` (a bot account). */
|
|
8
|
+
export function byReviewer(r, reviewer) {
|
|
9
|
+
return reviewer === "copilot"
|
|
10
|
+
? r.bot && /copilot/i.test(r.author)
|
|
11
|
+
: r.author.toLowerCase() === reviewer.toLowerCase();
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Whether what someone wrote may steer the work: the configured reviewer's, or
|
|
15
|
+
* that of someone the configuration trusts. Anyone else's is counted, never
|
|
16
|
+
* acted on.
|
|
17
|
+
*/
|
|
18
|
+
export function trusted(r, reviewer, trust) {
|
|
19
|
+
return trustedBy(trust, r) || byReviewer(r, reviewer);
|
|
20
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { parse } from "yaml";
|
|
2
|
+
/** Splits a Markdown document into its YAML front matter and body; `file` names it in errors. */
|
|
3
|
+
export function parseFrontMatter(text, file) {
|
|
4
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
|
|
5
|
+
if (!match)
|
|
6
|
+
return { data: {}, body: text };
|
|
7
|
+
const where = file ? `${file}: front matter` : "front matter";
|
|
8
|
+
let data;
|
|
9
|
+
try {
|
|
10
|
+
data = parse(match[1] ?? "") ?? {};
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
// A value with a colon in it is the usual cause: quoting it fixes it.
|
|
14
|
+
throw new Error(`${where}: ${error.message.split("\n")[0]} (quote a value that holds ": ", and write \\" for a quote inside the quotes)`);
|
|
15
|
+
}
|
|
16
|
+
if (typeof data !== "object" || Array.isArray(data)) {
|
|
17
|
+
throw new Error(`${where} is not a mapping`);
|
|
18
|
+
}
|
|
19
|
+
return { data: data, body: text.slice(match[0].length) };
|
|
20
|
+
}
|
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
|
+
}
|