@mergelight/cli 0.1.18 → 0.1.19

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.
@@ -0,0 +1,381 @@
1
+ import { createHash } from "node:crypto";
2
+ import { appendFileSync, readFileSync } from "node:fs";
3
+ import { fetchPullRequest } from "./github.js";
4
+ import { folded as sameName, jobsToRun, mayChange } from "./jobs.js";
5
+ import { GitHub } from "./publish/api.js";
6
+ import { blobIsBinary, isBinary, isJobCommit, JOBS_TRAILER, MAX_CHANGE_BYTES, MAX_CHANGED_FILES, mirrorGit, newSecret, textOf, withoutSecrets } from "./run-jobs.js";
7
+ import { fetchMirror, headGuarded, jobFilesFor } from "./workspace.js";
8
+ /** A path as git keeps it: no leading or doubled slash, no "." or "..", no control characters. */
9
+ function plainPath(path) {
10
+ return (typeof path === "string" &&
11
+ path.length > 0 &&
12
+ path.length <= 4096 &&
13
+ !/[\u0000-\u001f\u007f]/.test(path) &&
14
+ path.split("/").every((part) => part !== "" && part !== "." && part !== ".."));
15
+ }
16
+ /** A path as macOS and Windows compare it: letter case and Unicode composition don't count. As run-jobs.ts does. */
17
+ const folded = sameName;
18
+ /**
19
+ * Checks a jobs result against the jobs that this pull request starts on the base branch, and against
20
+ * the head. Returns what to push, or why nothing may be. modes holds each changed path's mode at the
21
+ * head, and each folder's on the way (040000 for a folder), or null when the head has nothing there.
22
+ * files holds every file at the head, for the checks a new file needs.
23
+ */
24
+ export function checkPush(result, jobs, head, modes, guarded = [], files = []) {
25
+ const r = result;
26
+ if (!r || typeof r !== "object" || !Array.isArray(r.changes) || !Array.isArray(r.outcomes))
27
+ return { why: "The jobs result can't be read." };
28
+ if (r.head !== head)
29
+ return { why: `The jobs ran on ${String(r.head).slice(0, 7)}, but the branch is at ${head.slice(0, 7)} now. The next push runs them again.` };
30
+ if (r.changes.length > MAX_CHANGED_FILES)
31
+ return { why: `The jobs changed ${r.changes.length} files, over the limit of ${MAX_CHANGED_FILES}.` };
32
+ const changed = r.outcomes.filter((o) => o && o.status === "changed" && Array.isArray(o.files));
33
+ // What the result deletes: a deletion is checked like any change below, and the whole push is
34
+ // refused if one isn't allowed, so the checks that need them can count them already.
35
+ const deleting = new Set(r.changes.filter((c) => c?.deleted === true).map((c) => c.path).filter(plainPath));
36
+ const additions = [];
37
+ const deletions = [];
38
+ const seen = new Set();
39
+ let bytes = 0;
40
+ for (const change of r.changes) {
41
+ const path = change?.path;
42
+ if (!plainPath(path))
43
+ return { why: `A changed path isn't a plain path in the repository: ${JSON.stringify(path).slice(0, 100)}.` };
44
+ if (seen.has(path))
45
+ return { why: `${path} is changed twice.` };
46
+ seen.add(path);
47
+ // Never through a folder that is a link at the head: the file would land wherever the link leads.
48
+ const parts = path.split("/");
49
+ const folders = parts.slice(0, -1).map((_, i) => parts.slice(0, i + 1).join("/"));
50
+ const through = folders.find((at) => modes.get(at) === "120000");
51
+ if (through)
52
+ return { why: `${path} is inside ${through}, which is a link at the head.` };
53
+ // A folder on the way that is a file or a submodule at the head can't hold it, unless the same push
54
+ // deletes that file.
55
+ const blocked = folders.find((at) => modes.get(at) != null && modes.get(at) !== "040000" && !deleting.has(at));
56
+ if (blocked)
57
+ return { why: `${path} is inside ${blocked}, which isn't a folder at the head.` };
58
+ // Only an ordinary file may change: the commit can't keep a link, a submodule or a file that can run as one.
59
+ let mode = modes.get(path);
60
+ if (mode === undefined)
61
+ return { why: `${path} wasn't looked up at the head.` };
62
+ // A folder at the head becomes a file only when the same push deletes everything in it.
63
+ if (mode === "040000") {
64
+ const inside = files.filter((f) => f.startsWith(`${path}/`));
65
+ if (inside.length && inside.every((f) => deleting.has(f)))
66
+ mode = null;
67
+ }
68
+ if (mode !== null && mode !== "100644")
69
+ return { why: `${path} isn't an ordinary file at the head (mode ${mode}).` };
70
+ // Every job that says it changed the file must be one the base branch has, and one that may change it.
71
+ const by = changed.filter((o) => o.files.includes(path));
72
+ if (!by.length)
73
+ return { why: `No job says it changed ${path}.` };
74
+ for (const o of by) {
75
+ const job = jobs.find((j) => j.name === o.name);
76
+ if (!job)
77
+ return { why: `The job "${String(o.name).slice(0, 60)}" isn't on the base branch, or this pull request doesn't start it.` };
78
+ if (!mayChange(job, path, guarded, (p) => modes.get(p) === "120000"))
79
+ return { why: `The job "${job.name}" may not change ${path}.` };
80
+ }
81
+ if (change.deleted === true) {
82
+ if (mode === null)
83
+ return { why: `${path} is deleted, but the head has no such file.` };
84
+ deletions.push(path);
85
+ continue;
86
+ }
87
+ const contents = change.contents;
88
+ // Whole base64 only: Node decodes a cut-off string without a word, and a file would lose its end.
89
+ if (typeof contents !== "string" || contents.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(contents))
90
+ return { why: `The new contents of ${path} can't be read.` };
91
+ const decoded = Buffer.from(contents, "base64");
92
+ if (isBinary(decoded))
93
+ return { why: `${path} would be a binary file.` };
94
+ bytes += decoded.length;
95
+ if (bytes > MAX_CHANGE_BYTES)
96
+ return { why: `The jobs wrote more than ${MAX_CHANGE_BYTES / 1000} KB.` };
97
+ additions.push({ path, bytes: decoded });
98
+ }
99
+ // A new file whose name differs from another only in letter case is one file on macOS and Windows: the
100
+ // jobs step refuses that, and so does this one, against what the head keeps and the other new files.
101
+ // A file and a folder whose names differ only in letter case clash the same way.
102
+ const fresh = additions.filter((a) => modes.get(a.path) === null || modes.get(a.path) === "040000").map((a) => a.path);
103
+ if (fresh.length) {
104
+ const kept = [...files.filter((f) => !deleting.has(f)), ...fresh];
105
+ const count = new Map();
106
+ for (const f of kept)
107
+ count.set(folded(f), (count.get(folded(f)) ?? 0) + 1);
108
+ const parents = (f) => f.split("/").slice(0, -1).map((_, i, all) => all.slice(0, i + 1).join("/"));
109
+ const folders = new Set(kept.flatMap(parents).map(folded));
110
+ const clash = fresh.find((f) => (count.get(folded(f)) ?? 0) > 1 || folders.has(folded(f)) || parents(f).some((p) => count.has(folded(p))));
111
+ if (clash)
112
+ return { why: `${clash} differs from another file or folder only in letter case.` };
113
+ }
114
+ const names = new Set([...additions.map((a) => a.path), ...deletions].flatMap((p) => changed.filter((o) => o.files.includes(p)).map((o) => o.name)));
115
+ // Cut by characters, not UTF-16 units, so an emoji is never split in half. The jobs step took secrets
116
+ // out already; this step does it again with what it can see, as it trusts nothing in the file.
117
+ const summaryOf = (text) => (typeof text === "string" ? Array.from(withoutSecrets(text).replace(/\s+/g, " ")).slice(0, 300).join("") : "");
118
+ const pushed = changed.filter((o) => names.has(o.name)).map((o) => ({ name: o.name, summary: summaryOf(o.summary) }));
119
+ return { additions, deletions, jobs: pushed };
120
+ }
121
+ /** The commit message: what each job did, and the line that keeps jobs from running on their own commit. */
122
+ export function commitMessage(plan) {
123
+ const names = plan.jobs.map((j) => j.name);
124
+ const list = names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : (names[0] ?? "");
125
+ const lines = plan.jobs.map((j) => `- ${j.name}: ${j.summary.replace(new RegExp(`${JOBS_TRAILER}:`, "gi"), "")}`);
126
+ return { headline: `Run the job${names.length === 1 ? "" : "s"} ${list}`, body: `${lines.join("\n")}\n\n${JOBS_TRAILER}: ${names.join(", ")}` };
127
+ }
128
+ /**
129
+ * Each changed path's mode at the head, or null when the head has nothing there, and the mode of each
130
+ * folder on the way: 040000 for a folder. And every file at the head.
131
+ */
132
+ async function headTree(mirror, head, paths) {
133
+ const folders = paths.flatMap((p) => p.split("/").slice(0, -1).map((_, i, all) => p.split("/").slice(0, i + 1).join("/")));
134
+ const modes = new Map([...folders.map((f) => [f, null]), ...paths.map((p) => [p, null])]);
135
+ const files = [];
136
+ if (!paths.length)
137
+ return { modes, files };
138
+ // The whole tree: ls-tree reads paths as patterns, and a path must only ever match itself.
139
+ // With the login, as everything read from the mirror: it fetches what it doesn't have yet from GitHub.
140
+ const listed = await mirrorGit(mirror).run(["ls-tree", "-r", "-t", "-z", "--full-tree", head]);
141
+ if (listed.code !== 0)
142
+ throw new Error(`Couldn't read the file modes at ${head.slice(0, 7)}.`);
143
+ for (const entry of listed.stdout.split("\0")) {
144
+ const m = /^(\d{6}) \w+ [0-9a-f]+\t([\s\S]+)$/.exec(entry);
145
+ if (!m)
146
+ continue;
147
+ if (modes.has(m[2]))
148
+ modes.set(m[2], m[1]);
149
+ if (m[1] !== "040000")
150
+ files.push(m[2]);
151
+ }
152
+ return { modes, files };
153
+ }
154
+ /**
155
+ * The commit on the branch now, when it is ours: right on the commit we checked, with this very message.
156
+ * Read from the branch itself, which moves at once, not the pull request's head, which GitHub updates a
157
+ * little later. Null when it isn't, or can't be read.
158
+ */
159
+ async function landedCommit(api, branch, parent, message, plan) {
160
+ const ref = await api.get(`git/ref/heads/${branch.split("/").map(encodeURIComponent).join("/")}`).catch(() => null);
161
+ if (!ref)
162
+ return null;
163
+ const tip = await api.get(`commits/${ref.object.sha}`).catch(() => null);
164
+ if (!tip || tip.parents.length !== 1 || tip.parents[0]?.sha !== parent)
165
+ return null;
166
+ const same = (text) => text.replace(/\r\n/g, "\n").trim();
167
+ if (same(tip.commit.message) !== same(message))
168
+ return null;
169
+ // And it changed exactly these files, to these contents: another run with the same message did other
170
+ // things. GitHub shows a deleted file and an added one with the same contents as one rename.
171
+ const changed = new Map();
172
+ for (const f of tip.files ?? []) {
173
+ changed.set(f.filename, f);
174
+ if (f.previous_filename)
175
+ changed.set(f.previous_filename, { filename: f.previous_filename, status: "removed" });
176
+ }
177
+ const paths = [...plan.additions.map((a) => a.path), ...plan.deletions];
178
+ if (changed.size !== paths.length || !paths.every((p) => changed.has(p)))
179
+ return null;
180
+ // Each deletion as a deletion, and each file written with these contents.
181
+ if (!plan.deletions.every((p) => changed.get(p)?.status === "removed"))
182
+ return null;
183
+ return plan.additions.every((a) => changed.get(a.path)?.status !== "removed" && changed.get(a.path)?.sha === blobSha(a.bytes)) ? tip.sha : null;
184
+ }
185
+ /** The id git gives a file's contents. */
186
+ export function blobSha(bytes) {
187
+ return createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
188
+ }
189
+ /**
190
+ * Why the jobs' commit may not go onto this branch, or null when it may. Never onto a long-lived one: a
191
+ * pull request can come from main itself, such as one from main into a release branch, and a commit there
192
+ * would skip every review. The default branch and a protected one count.
193
+ */
194
+ export function longLivedBranch(branch, defaultBranch, isProtected) {
195
+ if (defaultBranch && branch === defaultBranch)
196
+ return `The pull request comes from ${branch}, the repository's default branch, and jobs never push to it.`;
197
+ if (isProtected)
198
+ return `The pull request comes from ${branch}, a protected branch, and jobs never push to one.`;
199
+ return null;
200
+ }
201
+ const CREATE_COMMIT = `mutation($input: CreateCommitOnBranchInput!) { createCommitOnBranch(input: $input) { commit { oid url } } }`;
202
+ /** Pushes a jobs result to its pull request. 0 when it pushed or had nothing to push or the branch moved, 1 when a check refused it. */
203
+ export async function pushJobs(ref, o) {
204
+ const output = (values) => {
205
+ if (process.env.GITHUB_OUTPUT)
206
+ appendFileSync(process.env.GITHUB_OUTPUT, Object.entries(values).map(([k, v]) => `${k}=${v.replace(/\n/g, " ")}\n`).join(""));
207
+ };
208
+ const refuse = (why, code) => {
209
+ o.log(`Nothing pushed. ${why}`);
210
+ output({ pushed: "false", why });
211
+ return code;
212
+ };
213
+ // Whatever goes wrong, the step's outputs say so: a later step that reports why nothing was pushed has a reason.
214
+ try {
215
+ let result;
216
+ try {
217
+ result = JSON.parse(readFileSync(o.from, "utf8"));
218
+ }
219
+ catch {
220
+ return refuse(`The jobs result in ${o.from} can't be read.`, 1);
221
+ }
222
+ // A file with no list of changes is a broken one, not a run with nothing to push.
223
+ if (!Array.isArray(result?.changes))
224
+ return refuse(`The jobs result in ${o.from} can't be read.`, 1);
225
+ if (!result.changes.length)
226
+ return refuse("The jobs changed nothing.", 0);
227
+ const pr = await fetchPullRequest(ref);
228
+ // GitHub gives a fork's pull request no token that can push to it, and Mergelight never asks for one.
229
+ // GitHub ignores letter case in a repository's name. A fork's pull request is no failure: nothing can be pushed to it.
230
+ if (!pr.sameRepo || !pr.headRef)
231
+ return refuse("The pull request comes from another repository, and nothing is pushed to one.", 0);
232
+ // Closed or merged while the jobs ran: a commit on its branch would go nowhere.
233
+ if (pr.state && pr.state !== "open")
234
+ return refuse("The pull request is closed.", 0);
235
+ const api = new GitHub(pr.owner, pr.repo, { dryRun: o.dryRun, log: o.log });
236
+ const branchPath = pr.headRef.split("/").map(encodeURIComponent).join("/");
237
+ const branch = await api.get(`branches/${branchPath}`);
238
+ const longLived = longLivedBranch(pr.headRef, pr.defaultBranch, branch?.protected === true);
239
+ if (longLived)
240
+ return refuse(longLived, 0);
241
+ if (result.head !== pr.headSha) {
242
+ // Run again after its push landed: the branch is now at the commit it made, right on the one the
243
+ // jobs ran on, with the jobs line and these very files. That is pushed, not refused.
244
+ const api = new GitHub(pr.owner, pr.repo, { dryRun: o.dryRun, log: o.log });
245
+ const tip = await api.get(`commits/${pr.headSha}`).catch(() => null);
246
+ // Each file as the commit left it, a rename's old name as removed: these very changes, contents too.
247
+ const changed = new Map();
248
+ for (const f of tip?.files ?? []) {
249
+ changed.set(f.filename, f);
250
+ if (f.previous_filename)
251
+ changed.set(f.previous_filename, { filename: f.previous_filename, status: "removed" });
252
+ }
253
+ const changes = result.changes.filter((c) => plainPath(c?.path));
254
+ const sameChange = (c) => {
255
+ const f = changed.get(c.path);
256
+ if (!f)
257
+ return false;
258
+ if ("deleted" in c)
259
+ return f.status === "removed";
260
+ return f.status !== "removed" && typeof c.contents === "string" && f.sha === blobSha(Buffer.from(c.contents, "base64"));
261
+ };
262
+ const ours = tip &&
263
+ tip.parents.length === 1 &&
264
+ tip.parents[0]?.sha === result.head &&
265
+ // The jobs line names the very jobs whose changes these are, as commitMessage writes it.
266
+ (tip.commit.message.trim().split("\n").pop() ?? "") === `${JOBS_TRAILER}: ${result.outcomes.filter((o) => o?.status === "changed" && Array.isArray(o.files) && o.files.some((f) => changes.some((c) => c.path === f))).map((o) => o.name).join(", ")}` &&
267
+ changed.size === changes.length &&
268
+ changes.every(sameChange);
269
+ if (ours) {
270
+ o.log(`Already pushed as ${pr.headSha.slice(0, 7)}.`);
271
+ output({ pushed: "true", commit: pr.headSha });
272
+ return 0;
273
+ }
274
+ return refuse(`The jobs ran on ${String(result.head).slice(0, 7)}, but the branch is at ${pr.headSha.slice(0, 7)} now. The next push runs them again.`, 0);
275
+ }
276
+ const { mirror, teamBase } = await fetchMirror(pr);
277
+ const git = mirrorGit(mirror);
278
+ // The jobs step runs no job on a commit jobs made, so a result for one is not its own.
279
+ if (await isJobCommit(git, pr.headSha))
280
+ return refuse("The newest commit is one that jobs made, and no job runs on it.", 1);
281
+ const { jobs: all, guarded: baseGuard, incomplete } = await jobFilesFor(mirror, teamBase);
282
+ // The guard on the base branch couldn't be worked out in full: what the jobs step ran on is not checked.
283
+ if (incomplete)
284
+ return refuse(incomplete.replace(/so no job runs/g, "so nothing is pushed"), 0);
285
+ // The head's own links and imports are guarded too, as in the jobs step.
286
+ const headGuard = await headGuarded(mirror, pr.headSha, all);
287
+ if ("why" in headGuard)
288
+ return refuse(headGuard.why.replace(/so no job runs/g, "so nothing is pushed"), 0);
289
+ const guarded = [...new Set([...baseGuard, ...headGuard.guarded])];
290
+ // Only the jobs this pull request starts, worked out again the way the jobs step does: a job whose
291
+ // files it doesn't change may change nothing, whatever the result file says.
292
+ const mergeBase = await git.run(["merge-base", teamBase, pr.headSha]);
293
+ if (mergeBase.code !== 0)
294
+ throw new Error(`Couldn't find where ${pr.headRef} branched off ${pr.baseRef}.`);
295
+ const touched = await git.run(["diff", "--name-only", "-z", "--no-renames", "--no-color", "--no-ext-diff", `${mergeBase.stdout.trim()}...${pr.headSha}`]);
296
+ if (touched.code !== 0)
297
+ throw new Error(`Couldn't read what the pull request changes.`);
298
+ const jobs = jobsToRun(all, touched.stdout.split("\0").filter(Boolean));
299
+ const paths = result.changes.map((c) => c?.path).filter(plainPath);
300
+ const { modes, files } = await headTree(mirror, pr.headSha, paths);
301
+ const plan = checkPush(result, jobs, pr.headSha, modes, guarded, files);
302
+ if ("why" in plan)
303
+ return refuse(plan.why, 1);
304
+ // Nor may a job delete a binary file, such as an image: checked against the head, as the jobs step does.
305
+ for (const path of plan.deletions) {
306
+ const binary = await blobIsBinary(git, `${pr.headSha}:${path}`);
307
+ if (binary === null)
308
+ throw new Error(`Couldn't read ${path} at ${pr.headSha.slice(0, 7)}.`);
309
+ if (binary)
310
+ return refuse(`${path} is a binary file, which a job may never delete.`, 1);
311
+ }
312
+ // The jobs step drops a job that writes a secret the file didn't have. The file it hands over is checked again.
313
+ for (const a of plan.additions) {
314
+ // The mirror holds no file contents until they are asked for, so this fetches them, with the login a private repository needs.
315
+ let old = modes.get(a.path) && modes.get(a.path) !== "040000" ? await git.bytes(["cat-file", "blob", `${pr.headSha}:${a.path}`]) : Buffer.alloc(0);
316
+ if (!old) {
317
+ // Too large to hold, such as a huge file a job shrank: compared with nothing, so any key in the
318
+ // new file counts as new, and the push is refused rather than one with a key let through.
319
+ const size = await git.run(["cat-file", "-s", `${pr.headSha}:${a.path}`]);
320
+ if (size.code !== 0 || !(Number(size.stdout.trim()) > 60 * 1024 * 1024))
321
+ throw new Error(`Couldn't read ${a.path} at ${pr.headSha.slice(0, 7)}.`);
322
+ old = Buffer.alloc(0);
323
+ }
324
+ // A job never writes text over a binary file, such as an image, as the jobs step checks too. Told
325
+ // from the file's start, so a file of any size is checked, and one that can't be is refused.
326
+ if (modes.get(a.path) && modes.get(a.path) !== "040000") {
327
+ const binary = await blobIsBinary(git, `${pr.headSha}:${a.path}`);
328
+ if (binary === null)
329
+ throw new Error(`Couldn't read ${a.path} at ${pr.headSha.slice(0, 7)}.`);
330
+ if (binary)
331
+ return refuse(`${a.path} is a binary file, which a job may never overwrite.`, 1);
332
+ }
333
+ // Read as the text it is, so a key in a UTF-16 file is seen too.
334
+ const secret = newSecret(textOf(a.bytes), textOf(old));
335
+ if (secret)
336
+ return refuse(`${a.path} would hold what looks like ${secret === "a key or token" ? "a key or token" : `the runner's ${secret}`}.`, 1);
337
+ }
338
+ const message = commitMessage(plan);
339
+ const input = {
340
+ branch: { repositoryNameWithOwner: `${pr.owner}/${pr.repo}`, branchName: pr.headRef },
341
+ // GitHub refuses when the branch has moved on since: a push that came in between is never undone.
342
+ expectedHeadOid: pr.headSha,
343
+ message,
344
+ fileChanges: {
345
+ additions: plan.additions.map((a) => ({ path: a.path, contents: a.bytes.toString("base64") })),
346
+ deletions: plan.deletions.map((path) => ({ path })),
347
+ },
348
+ };
349
+ let answer;
350
+ try {
351
+ answer = await api.write("POST", "/graphql", { query: CREATE_COMMIT, variables: { input } });
352
+ }
353
+ catch (err) {
354
+ // gh ends with an error when GitHub's answer holds one.
355
+ answer = { errors: [{ message: err instanceof Error ? err.message : String(err) }] };
356
+ }
357
+ if (o.dryRun)
358
+ return 0;
359
+ const commit = answer?.data?.createCommitOnBranch?.commit;
360
+ if (!commit) {
361
+ const why = answer?.errors?.map((e) => e.message).join(" ") ?? "GitHub gave no commit back.";
362
+ // An earlier try may have landed with its answer lost, and a later one then fails, saying the branch
363
+ // moved or with a server error: if the branch now has our commit, it was pushed.
364
+ const ours = await landedCommit(api, pr.headRef, pr.headSha, `${message.headline}\n\n${message.body}`, plan);
365
+ if (ours) {
366
+ o.log(`Pushed ${ours.slice(0, 7)}: ${message.headline}.`);
367
+ output({ pushed: "true", commit: ours });
368
+ return 0;
369
+ }
370
+ if (/STALE_DATA|expected branch to point to/i.test(why))
371
+ return refuse(`The branch moved while the jobs ran. The next push runs them again. (${why.slice(0, 200)})`, 0);
372
+ return refuse(`GitHub refused the commit: ${why.slice(0, 300)}`, 1);
373
+ }
374
+ o.log(`Pushed ${commit.oid.slice(0, 7)}: ${message.headline}. ${commit.url}`);
375
+ output({ pushed: "true", commit: commit.oid });
376
+ return 0;
377
+ }
378
+ catch (err) {
379
+ return refuse(`Something went wrong: ${(err instanceof Error ? err.message : String(err)).replace(/\s+/g, " ").slice(0, 300)}`, 1);
380
+ }
381
+ }
package/dist/render.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { checkerMissedLine } from "./publish/markdown.js";
1
2
  const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
2
3
  const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : s);
3
4
  const bold = paint("1");
@@ -68,11 +69,15 @@ export function renderTerminal(r) {
68
69
  const words = (...parts) => parts.filter(Boolean).join(" ");
69
70
  const hunters = words(r.provider.name, r.provider.model, r.provider.effort);
70
71
  const checker = r.verifier && r.verifier.name !== r.provider.name ? `, checked by ${words(r.verifier.name, r.verifier.model)}` : "";
72
+ // The other AI was meant to check, and couldn't: said here as on GitHub.
73
+ const missed = checkerMissedLine(r);
71
74
  const out = [];
72
75
  out.push(`${bold("Mergelight")} ${dim("·")} ${r.pr.owner}/${r.pr.repo}#${r.pr.number} ${dim("·")} ${r.pr.title}`);
73
76
  out.push(`${light.dot} ${light.color(bold(light.label))} ${dim(`(${counts})`)} ${dim(`· ${hunters}${checker} · ${duration(r.stats.duration_ms)} · ${r.pr.head_sha.slice(0, 7)}`)}`);
74
77
  const checked = r.trace.candidates.length;
75
78
  out.push(dim(`Checked ${checked} candidate${checked === 1 ? "" : "s"}, rejected ${r.trace.rejected.length}${r.trace.failed_hunters.length ? `, hunters failed: ${r.trace.failed_hunters.join(", ")}` : ""}`));
79
+ if (missed)
80
+ out.push(missed);
76
81
  out.push("");
77
82
  out.push(wrap(r.summary, ""));
78
83
  for (const f of posted) {
@@ -23,35 +23,78 @@ export const MAX_REPO_RULE_CHARS = 30_000;
23
23
  * out of code review.
24
24
  */
25
25
  export function frontMatter(text) {
26
+ const block = frontMatterBlock(text);
27
+ if (!block)
28
+ return { paths: [], body: text, scoped: false, forReview: true };
29
+ const forReview = !/^excludeAgent[ \t]*:.*\bcode-review\b/m.test(block.fm);
30
+ const patterns = listValue(block.fm, "applyTo|globs") ?? [];
31
+ // "**" anywhere in the list means every file.
32
+ const paths = patterns.some((p) => p === "**" || p === "*" || p === "**/*") ? [] : patterns;
33
+ return { paths, body: block.body, scoped: patterns.length > 0, forReview };
34
+ }
35
+ /** The front matter of a Markdown file and the text after it, or null when it has none. */
36
+ export function frontMatterBlock(text) {
26
37
  // The block between the first two "---" lines, which may be empty: an empty one must not reach on to a
27
38
  // later "---" divider and take the rules before it.
28
39
  const m = /^---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)??---[ \t]*(?:\r?\n|$)/.exec(text);
29
- if (!m)
30
- return { paths: [], body: text, scoped: false, forReview: true };
31
- const fm = m[1] ?? "";
32
- const forReview = !/^excludeAgent[ \t]*:.*\bcode-review\b/m.test(fm);
33
- const line = /^(?:applyTo|globs)[ \t]*:[ \t]*(.*)$/m.exec(fm);
34
- // A YAML comment after the value isn't part of it: applyTo: "src/billing/**" # billing only.
35
- let value = (line?.[1] ?? "").replace(/(?:^|[ \t])#.*$/, "").trim();
36
- if (line && !value) {
37
- // A YAML list on the lines below the key: "applyTo:" then " - src/billing/**".
40
+ return m ? { fm: m[1] ?? "", body: text.slice(m[0].length) } : null;
41
+ }
42
+ /**
43
+ * Without a YAML comment after it: applyTo: "src/billing/**" # billing only. A # inside quotes is part of
44
+ * the value, as in YAML.
45
+ */
46
+ function withoutYamlComment(value) {
47
+ let quote = null;
48
+ for (let i = 0; i < value.length; i++) {
49
+ const ch = value[i];
50
+ if (quote) {
51
+ // A quote closes only where YAML would end the value: at the end, or before a space, a comma or ].
52
+ if (ch === quote && (i + 1 === value.length || /[\s,\]]/.test(value[i + 1])))
53
+ quote = null;
54
+ // A quote opens only where a value or an item starts, as in YAML: one inside a word, like don't, is a letter.
55
+ }
56
+ else if ((ch === '"' || ch === "'") && (i === 0 || /[\s,[]/.test(value[i - 1])))
57
+ quote = ch;
58
+ else if (ch === "#" && (i === 0 || value[i - 1] === " " || value[i - 1] === "\t"))
59
+ return value.slice(0, i).trim();
60
+ }
61
+ // A quote that never closes isn't a quote: cut at the first comment, as before quotes were read.
62
+ return quote ? value.replace(/(?:^|[ \t])#.*$/, "").trim() : value.trim();
63
+ }
64
+ /** The value of a one-line key, without quotes or a comment, or null when the key isn't there. */
65
+ export function scalarValue(fm, key) {
66
+ const line = new RegExp(`^(?:${key})[ \\t]*:[ \\t]*(.*)$`, "m").exec(fm);
67
+ return line ? withoutYamlComment(line[1] ?? "").replace(/^(["'])(.*)\1$/, "$2").trim() : null;
68
+ }
69
+ /**
70
+ * The patterns a key names: a comma list, a [list], or a YAML list on the lines below it, with braces
71
+ * expanded. Null when the key isn't there. keys is one name, or names joined with "|".
72
+ */
73
+ export function listValue(fm, keys) {
74
+ const line = new RegExp(`^(?:${keys})[ \\t]*:[ \\t]*(.*)$`, "m").exec(fm);
75
+ if (!line)
76
+ return null;
77
+ const unquote = (p) => p.trim().replace(/^["']|["']$/g, "").trim();
78
+ const value = withoutYamlComment(line[1] ?? "");
79
+ // An inline value, or a YAML list on the lines below the key: "applyTo:" then " - src/billing/**".
80
+ // Teams write comma lists inside one item too ("- **/*.ts,**/*.tsx"), so every item is split on its
81
+ // commas, as Copilot reads it.
82
+ const items = value ? [value.replace(/^\[([\s\S]*)\]$/, "$1").replace(/^["']|["']$/g, "")] : [];
83
+ if (!value) {
38
84
  const after = fm.slice(line.index + line[0].length).split(/\r?\n/).slice(1);
39
- const items = [];
40
85
  for (const l of after) {
86
+ // A blank line or a comment between the items doesn't end the list.
87
+ if (/^[ \t]*(?:#.*)?$/.test(l))
88
+ continue;
41
89
  const item = /^[ \t]*-[ \t]*(.+)$/.exec(l);
42
90
  if (!item)
43
91
  break;
44
- items.push(item[1].replace(/(?:^|[ \t])#.*$/, "").trim());
92
+ // An item can be a [list] of its own, as the inline value can. Brackets go before quotes, so a
93
+ // quoted "[locale]" keeps its brackets, as it does inline.
94
+ items.push(unquote(withoutYamlComment(item[1]).replace(/^\[([\s\S]*)\]$/, "$1")));
45
95
  }
46
- value = items.join(",");
47
96
  }
48
- const patterns = splitOutsideBraces(value.trim().replace(/^\[([\s\S]*)\]$/, "$1").replace(/^["']|["']$/g, ""))
49
- .map((p) => p.trim().replace(/^["']|["']$/g, "").trim())
50
- .flatMap(expandBraces)
51
- .filter(Boolean);
52
- // "**" anywhere in the list means every file.
53
- const paths = patterns.some((p) => p === "**" || p === "*" || p === "**/*") ? [] : patterns;
54
- return { paths, body: text.slice(m[0].length), scoped: patterns.length > 0, forReview };
97
+ return items.flatMap(splitOutsideBraces).map(unquote).flatMap(expandBraces).filter(Boolean);
55
98
  }
56
99
  /** Splits on commas, but not on the ones inside braces, as in "**\/*.{ts,tsx},*.sql". */
57
100
  function splitOutsideBraces(value) {