@tayomi/deterministic-gates 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/core/run.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { execFile, type ExecFileException } from "node:child_process";
2
2
  import { accessSync, constants, existsSync } from "node:fs";
3
+ import { availableParallelism } from "node:os";
3
4
  import { delimiter, isAbsolute, join, resolve, sep } from "node:path";
4
5
  import { stripVTControlCharacters } from "node:util";
5
- import { FILES, type Gate, isCompared, TURN } from "./config.ts";
6
+ import { DIRS, ENGINE_PREFIX, FILES, type Gate, isCompared, TURN } from "./config.ts";
6
7
  import { isRecord, messageOf, readJsonFile } from "./json.ts";
8
+ import type { Project } from "./projects.ts";
7
9
 
8
10
  export interface Outcome {
9
11
  name: string;
@@ -18,6 +20,18 @@ export interface Outcome {
18
20
  * nothing tells a gate the turn broke from one that broke before it, but the agent is told to repair it.
19
21
  */
20
22
  broken?: boolean;
23
+ /** For a gate that runs in each project: the folders of the ones it failed in, the root of the repo left out. */
24
+ projects?: string[];
25
+ /** For a gate that runs in each project: what each of the ones it failed in said, which its output holds too. */
26
+ blocks?: Block[];
27
+ /** For such a gate that failed: the folders of the projects it ran out of time for, so did not judge. */
28
+ unjudged?: string[];
29
+ }
30
+
31
+ /** What a gate said in one project, by the folder of the project: a dot for the root of the repo. */
32
+ export interface Block {
33
+ dir: string;
34
+ output: string;
21
35
  }
22
36
 
23
37
  /** A gate that judged the turn and found a problem, or that broke: the only kinds that send the agent back. */
@@ -52,7 +66,6 @@ export function headed(own: string, lines: string[], env = process.env): string
52
66
  }
53
67
 
54
68
  const MAX_OUTPUT_MB = 16;
55
- const ENGINE_PREFIX = "{engine}/";
56
69
 
57
70
  /** A script of this engine: its .ts source, or the .js it is built to when the engine runs from its npm package. */
58
71
  function engineScript(name: string): string {
@@ -143,8 +156,12 @@ export function missingTool(root: string, gate: Gate): string | undefined {
143
156
  return missingProgram(root, gate.run[0] ?? "") ?? (gate.watch && missingProgram(root, gate.watch.run[0] ?? ""));
144
157
  }
145
158
 
146
- export function argumentsOf(gate: Gate, files: string[], turn: string): string[] {
147
- return gate.run.slice(1).flatMap((argument) => (argument === FILES ? files : [argument.replaceAll(TURN, turn)]));
159
+ export function argumentsOf(gate: Gate, files: string[], turn: string, dirs: string[] = []): string[] {
160
+ return gate.run.slice(1).flatMap((argument) => {
161
+ if (argument === FILES) return files;
162
+ if (argument === DIRS) return dirs;
163
+ return [argument.replaceAll(TURN, turn)];
164
+ });
148
165
  }
149
166
 
150
167
  /** Whether the gate is given the changed files, where another reads the whole project. */
@@ -152,6 +169,11 @@ export function givenFiles(gate: Gate): boolean {
152
169
  return gate.run.includes(FILES);
153
170
  }
154
171
 
172
+ /** Whether the gate is given the folders of the changed files. */
173
+ export function givenDirs(gate: Gate): boolean {
174
+ return gate.run.includes(DIRS);
175
+ }
176
+
155
177
  export function filesOf(gate: Gate, changed: string[]): string[] {
156
178
  const pattern = new RegExp(gate.files);
157
179
  return changed.filter((file) => pattern.test(file));
@@ -209,7 +231,8 @@ interface Executed {
209
231
  exitCode?: number;
210
232
  }
211
233
 
212
- async function execute(root: string, gate: Gate, args: string[]): Promise<Executed> {
234
+ /** Starts the command of a gate, found from the root of the repo, in the folder given: the root, or a project. */
235
+ async function execute(root: string, gate: Gate, args: string[], cwd = root): Promise<Executed> {
213
236
  const started = performance.now();
214
237
  const [name = ""] = gate.run;
215
238
  // A gate that cannot start fails alone: the other gates of the turn still report.
@@ -230,15 +253,16 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
230
253
  command.file,
231
254
  [...command.args, ...args],
232
255
  {
233
- cwd: root,
234
- timeout: gate.timeoutSeconds * 1000,
256
+ cwd,
257
+ // In whole milliseconds, as Node wants them: what is left of a shared time is not.
258
+ timeout: Math.ceil(gate.timeoutSeconds * 1000),
235
259
  maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
236
260
  env: { ...toolEnv(root), ...(gate.prompt?.replace ? { [PROMPT_REPLACED]: "1" } : {}) },
237
261
  },
238
262
  (error, stdout, stderr) => {
239
263
  resolve({
240
264
  ok: !error,
241
- output: outputOf(root, gate, command, error, `${stdout}${stderr}`),
265
+ output: outputOf(root, gate, command, error, `${stdout}${stderr}`, cwd),
242
266
  ms: performance.now() - started,
243
267
  timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
244
268
  cannotStart: error?.code === "ENOENT",
@@ -255,20 +279,25 @@ function outputOf(
255
279
  command: Command,
256
280
  error: ExecFileException | null,
257
281
  printed: string,
282
+ cwd: string,
258
283
  ): string {
259
284
  if (error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
260
285
  return `Printed more than ${MAX_OUTPUT_MB} MB: too much for the end of a turn. Make it quieter, or move it to CI.`;
261
- if (error?.killed === true)
262
- return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
286
+ if (error?.killed === true) return outOfTime(gate);
263
287
  if (error?.code === "ENOENT") return command.missing;
264
- const said = cleaned(root, printed);
288
+ const said = cleaned(root, printed, cwd);
265
289
  if (said || !error) return said;
266
290
  return `exit code ${String(error.code)}, no output`;
267
291
  }
268
292
 
269
- /** What a tool printed, for the agent: some tools colour despite NO_COLOR, and absolute paths only cost it tokens. */
270
- export function cleaned(root: string, printed: string): string {
271
- return stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
293
+ /**
294
+ * What a tool printed, for the agent: some tools colour despite NO_COLOR, and absolute paths only cost it tokens. A
295
+ * tool that ran in a project loses the path of that folder first, so its files read as the relative paths it prints.
296
+ */
297
+ export function cleaned(root: string, printed: string, cwd = root): string {
298
+ return [cwd, root]
299
+ .reduce((text, dir) => text.split(`${dir}${sep}`).join(""), stripVTControlCharacters(printed))
300
+ .trim();
272
301
  }
273
302
 
274
303
  /**
@@ -307,16 +336,113 @@ export async function check(
307
336
  turn: string,
308
337
  baseline: string | undefined,
309
338
  elsewhere = false,
339
+ dirs: string[] = [],
340
+ ): Promise<Outcome> {
341
+ const outcome = await ranIn(root, gate, files, turn, dirs);
342
+ if (!outcome.ok || !isCompared(gate)) return outcome;
343
+ return { ...outcome, ...addedLines(gate, outcome.output, baseline, files, elsewhere) };
344
+ }
345
+
346
+ /** What the command of a gate says of the files given, run once in a folder: by its exit code alone. */
347
+ async function ranIn(
348
+ root: string,
349
+ gate: Gate,
350
+ files: string[],
351
+ turn: string,
352
+ dirs: string[] = [],
353
+ cwd = root,
310
354
  ): Promise<Outcome> {
311
- const executed = await execute(root, gate, argumentsOf(gate, files, turn));
355
+ const executed = await execute(root, gate, argumentsOf(gate, files, turn, dirs), cwd);
312
356
  const { ok, output, ms, timedOut, cannotStart, exitCode = 0 } = executed;
313
357
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
314
358
  if (timedOut) return { ...ran, ok, output, timedOut };
315
359
  // A compared gate exits with 0 when it finds problems: any other code is its command that broke.
316
360
  const broke = cannotStart || isCompared(gate) || gate.brokenExitCodes?.includes(exitCode);
317
- if (!ok && broke) return { ...ran, ok, output, broken: true };
318
- if (!isCompared(gate) || !ok) return { ...ran, ok, output };
319
- return { ...ran, ...addedLines(gate, output, baseline, files, elsewhere) };
361
+ return { ...ran, ok, output, ...(!ok && broke ? { broken: true } : {}) };
362
+ }
363
+
364
+ const ROOT = ".";
365
+
366
+ /** What a project said, under its folder: a tool prints its paths from where it runs. The root needs no telling. */
367
+ export function underFolder({ dir, output }: Block): string {
368
+ return dir === ROOT ? output : `in ${dir}, paths relative to it:\n${output}`;
369
+ }
370
+
371
+ /** What a failed gate says last of the projects it ran out of time for. */
372
+ export function notJudged(dirs: string[]): string {
373
+ return `out of time, so not judged: ${dirs.join(", ")}`;
374
+ }
375
+
376
+ function outOfTime(gate: Gate): string {
377
+ return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
378
+ }
379
+
380
+ // Runs a task on each item, at most so many at once, and gives what they returned in the order of the items.
381
+ async function pooled<Item, Result>(items: Item[], limit: number, run: (item: Item) => Promise<Result>) {
382
+ const results: Result[] = [];
383
+ let next = 0;
384
+ const worker = async () => {
385
+ for (let at = next++; at < items.length; at = next++) results[at] = await run(items[at] as Item);
386
+ };
387
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
388
+ return results;
389
+ }
390
+
391
+ /**
392
+ * Runs a gate once in each project given, from the folder of the project, and gives one outcome for them all: the
393
+ * gate stays one gate, with one name to report under and to waive. It is red when a project failed, with the report
394
+ * of each failed project under its folder, broken when one broke, and out of time when none failed and one ran out
395
+ * of it. As many projects run at once as the machine has cores: a build takes them all by itself. With a shared
396
+ * time, as at the stop, the time of the gate is for all its projects, and one whose turn comes too late is not
397
+ * started; otherwise each has it whole.
398
+ */
399
+ export async function checkEach(
400
+ root: string,
401
+ gate: Gate,
402
+ projects: Project[],
403
+ turn: string,
404
+ sharedTime = false,
405
+ ): Promise<Outcome> {
406
+ const started = performance.now();
407
+ const ran = await pooled(projects, availableParallelism(), async ({ dir, files, dirs }) => {
408
+ const left = sharedTime ? gate.timeoutSeconds - (performance.now() - started) / 1000 : gate.timeoutSeconds;
409
+ if (left <= 0) return { dir, name: gate.name, ok: false, ms: 0, output: "", report: undefined, timedOut: true };
410
+ return { dir, ...(await ranIn(root, { ...gate, timeoutSeconds: left }, files, turn, dirs, join(root, dir))) };
411
+ });
412
+ const merged = { name: gate.name, ms: performance.now() - started, report: undefined };
413
+ const named = (outcomes: { dir: string }[]) => outcomes.map(({ dir }) => dir).filter((dir) => dir !== ROOT);
414
+ const red = ran.filter(failed);
415
+ const late = ran.filter(({ timedOut }) => timedOut);
416
+ if (red.length) {
417
+ const blocks = red.map(({ dir, output }) => ({ dir, output }));
418
+ // The root is named here, where nothing else would say a project was left.
419
+ const unjudged = late.map(({ dir }) => dir);
420
+ return {
421
+ ...merged,
422
+ ok: false,
423
+ output: [...blocks.map(underFolder), ...(unjudged.length ? [notJudged(unjudged)] : [])].join("\n\n"),
424
+ blocks,
425
+ ...(red.some(({ broken }) => broken) ? { broken: true } : {}),
426
+ ...(named(red).length ? { projects: named(red) } : {}),
427
+ ...(unjudged.length ? { unjudged } : {}),
428
+ };
429
+ }
430
+ if (late.length)
431
+ return {
432
+ ...merged,
433
+ ok: false,
434
+ output: outOfTime(gate),
435
+ timedOut: true,
436
+ ...(named(late).length ? { projects: named(late) } : {}),
437
+ };
438
+ return {
439
+ ...merged,
440
+ ok: true,
441
+ output: ran
442
+ .map(({ output }) => output)
443
+ .filter(Boolean)
444
+ .join("\n"),
445
+ };
320
446
  }
321
447
 
322
448
  /**
@@ -8,9 +8,20 @@ interface GitOptions {
8
8
  input?: string;
9
9
  }
10
10
 
11
- /** Runs git in the repo, and gives what it printed, trimmed. */
11
+ /**
12
+ * Runs git in the repo, and gives what it printed, without the line break that ends it, however long. Nothing else is
13
+ * trimmed: the name of a file may start with a space.
14
+ */
12
15
  function git(root: string, args: string[], { env = process.env, input }: GitOptions = {}): string {
13
- return execFileSync("git", args, { cwd: root, encoding: "utf8", env, input, stdio: "pipe" }).trim();
16
+ const printed = execFileSync("git", args, {
17
+ cwd: root,
18
+ encoding: "utf8",
19
+ env,
20
+ input,
21
+ stdio: "pipe",
22
+ maxBuffer: Infinity,
23
+ });
24
+ return printed.replace(/\n$/, "");
14
25
  }
15
26
 
16
27
  // One NUL after each path, which git otherwise quotes and escapes when it holds an accent.
@@ -119,29 +130,85 @@ export function changedSince(root: string, start: string, end = workingTree(root
119
130
  return paths(git(root, ["diff", "-z", "--name-only", start, end])).sort();
120
131
  }
121
132
 
122
- /** A move of HEAD, as its reflog tells it: the commit it left, the one it reached, and how. */
123
- export interface HeadMove {
124
- from: string | undefined;
125
- to: string;
126
- how: string;
133
+ /** A commit, with its parents, and when it was committed, in seconds. */
134
+ export interface Commit {
135
+ hash: string;
136
+ parents: string[];
137
+ at: number;
127
138
  }
128
139
 
129
- /** The moves of HEAD its reflog holds, oldest first: none in a repo with no commit, or that keeps no reflog. */
130
- export function headMoves(root: string): HeadMove[] {
140
+ /** The commit HEAD is on, and the tips of the branches: nothing in a repo with no commit. */
141
+ export function branchTips(root: string): { head?: string; tips: string[] } {
131
142
  try {
132
- const entries = git(root, ["reflog", "show", "--format=%H %gs", "HEAD"]).split("\n").filter(Boolean).reverse();
133
- const reached = entries.map((entry) => entry.slice(0, entry.indexOf(" ")));
134
- return entries.map((entry, at) => ({
135
- from: reached[at - 1],
136
- to: reached[at] ?? "",
137
- how: entry.slice(entry.indexOf(" ") + 1),
138
- }));
143
+ const head = git(root, ["rev-parse", "--verify", "--quiet", "HEAD"]);
144
+ const tips = git(root, ["for-each-ref", "--format=%(objectname)", "refs/heads"]).split("\n");
145
+ return { head, tips: [...new Set([head, ...tips.filter(Boolean)])] };
139
146
  } catch {
140
- return [];
147
+ return { tips: [] };
141
148
  }
142
149
  }
143
150
 
144
- /** The files a commit changed. For a merge, the ones it leaves unlike each of its parents: its resolved conflicts. */
145
- export function commitFiles(root: string, commit: string): string[] {
146
- return paths(git(root, ["diff-tree", "--no-commit-id", "--name-only", "-r", "-c", "--root", "-z", commit]));
151
+ /** The folder of git that the worktrees of a repo share: what tells that two of them are of the same repo. */
152
+ export function sharedDir(root: string): string {
153
+ try {
154
+ return git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
155
+ } catch {
156
+ return root;
157
+ }
158
+ }
159
+
160
+ /** Whether a commit is another one, or one it holds. */
161
+ export function isIn(root: string, commit: string, other: string): boolean {
162
+ try {
163
+ git(root, ["merge-base", "--is-ancestor", commit, other]);
164
+ return true;
165
+ } catch {
166
+ return false;
167
+ }
168
+ }
169
+
170
+ /** The commits these tips hold that none of the known commits does. It throws when git no longer has one of them. */
171
+ export function commitsPast(root: string, tips: string[], known: string[]): Commit[] {
172
+ const input = known.map((commit) => `^${commit}\n`).join("");
173
+ // Two lines a commit: "commit", its hash and its parents, then its time.
174
+ const lines = git(root, ["rev-list", "--parents", "--format=%ct", "--stdin", ...tips], { input }).split("\n");
175
+ return lines.filter(Boolean).flatMap((line, at, all) => {
176
+ if (at % 2) return [];
177
+ const [, hash = "", ...parents] = line.split(" ");
178
+ return [{ hash, parents, at: Number(all[at + 1]) }];
179
+ });
180
+ }
181
+
182
+ /** Lines a change wrote in a file: where they start, and how many. None of them, where it only cut lines out after that one. */
183
+ export interface WrittenLines {
184
+ at: number;
185
+ lines: number;
186
+ }
187
+
188
+ /**
189
+ * The lines of a file the working tree wrote since a commit that has the file. The file is compared with the one of
190
+ * the commit, not through the index, which does not know a file nobody added; and with the diff of git itself, plain,
191
+ * whatever colours or program the owner set for it.
192
+ */
193
+ export function writtenSince(root: string, commit: string, file: string): WrittenLines[] {
194
+ const plain = ["--no-color", "--no-ext-diff", "--no-textconv", "--unified=0", "--inter-hunk-context=0"];
195
+ // The name as it is: git would otherwise read the brackets of a file such as [slug].ts as a pattern.
196
+ const diff = git(root, ["--literal-pathspecs", "diff", ...plain, `${commit}:${file}`, "--", file]);
197
+ const hunks = diff.matchAll(/^@@ -\S+ \+(\d+)(?:,(\d+))? @@/gm);
198
+ return [...hunks].map(([, at, lines = "1"]) => ({ at: Number(at), lines: Number(lines) }));
199
+ }
200
+
201
+ // Fewer names at once than a command line holds.
202
+ const NAMES_AT_ONCE = 500;
203
+
204
+ /** The ones of these files a commit has. */
205
+ export function filesAt(root: string, commit: string, files: string[]): string[] {
206
+ const found: string[] = [];
207
+ for (let at = 0; at < files.length; at += NAMES_AT_ONCE) {
208
+ const names = files.slice(at, at + NAMES_AT_ONCE);
209
+ found.push(
210
+ ...paths(git(root, ["--literal-pathspecs", "ls-tree", "-r", "--name-only", "-z", commit, "--", ...names])),
211
+ );
212
+ }
213
+ return found;
147
214
  }
@@ -2,7 +2,7 @@ import { writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import type { GatesFiles } from "./config.ts";
5
- import type { Head } from "./head.ts";
5
+ import type { Head, There } from "./head.ts";
6
6
  import { isRecord, isStringArray, isStringRecord, readJsonFile } from "./json.ts";
7
7
 
8
8
  /** A red gate the agent chose to leave, with why, bound to the fingerprint of the report it saw. */
@@ -53,6 +53,8 @@ interface SessionState {
53
53
  told?: Record<string, string[]>;
54
54
  /** The repos a send-back of the session told the agent how to act in: the next ones there say it in one line. */
55
55
  conductTold?: string[];
56
+ /** What the session knows of the commits of each repo, for as long as it lasts, whatever repo its turns are in. */
57
+ there?: Record<string, There>;
56
58
  }
57
59
 
58
60
  const EMPTY: SessionState = { turns: {} };
@@ -80,7 +82,7 @@ function isTurnState(value: unknown): value is TurnState {
80
82
  isRecord(value) &&
81
83
  typeof value.start === "string" &&
82
84
  (value.head === undefined || typeof value.head === "string") &&
83
- (value.moves === undefined || typeof value.moves === "number") &&
85
+ (value.at === undefined || typeof value.at === "number") &&
84
86
  isStringRecord(value.baselines) &&
85
87
  isGatesFiles(value.config) &&
86
88
  typeof value.checked === "boolean" &&
@@ -88,6 +90,10 @@ function isTurnState(value: unknown): value is TurnState {
88
90
  );
89
91
  }
90
92
 
93
+ function isThere(value: unknown): value is There {
94
+ return isRecord(value) && isStringArray(value.known) && isStringArray(value.made);
95
+ }
96
+
91
97
  function isSessionState(value: unknown): value is SessionState {
92
98
  return (
93
99
  isRecord(value) &&
@@ -95,7 +101,8 @@ function isSessionState(value: unknown): value is SessionState {
95
101
  isRecord(value.turns) &&
96
102
  Object.values(value.turns).every(isTurnState) &&
97
103
  (value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray))) &&
98
- (value.conductTold === undefined || isStringArray(value.conductTold))
104
+ (value.conductTold === undefined || isStringArray(value.conductTold)) &&
105
+ (value.there === undefined || (isRecord(value.there) && Object.values(value.there).every(isThere)))
99
106
  );
100
107
  }
101
108
 
@@ -123,6 +130,16 @@ export function writeTurn(session: string, root: string, turn: TurnState): void
123
130
  writeSession(session, { ...state, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
124
131
  }
125
132
 
133
+ /** What the session knows of the commits of a repo, or nothing before its first turn there. */
134
+ export function readThere(session: string, root: string): There | undefined {
135
+ return readSession(session).there?.[root];
136
+ }
137
+
138
+ export function writeThere(session: string, root: string, there: There): void {
139
+ const state = readSession(session);
140
+ writeSession(session, { ...state, there: { ...state.there, [root]: there } });
141
+ }
142
+
126
143
  /** Ends the turn in progress without a check, as a prompt from a folder with no gates, or a failed start, does. */
127
144
  export function forgetTurn(session: string): void {
128
145
  forget(session, "current");
@@ -1,33 +1,112 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { mkdtempSync, rmSync } from "node:fs";
2
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { isRecord, readJsonFile } from "../core/json.ts";
6
6
  import { headed, packageScript } from "../core/run.ts";
7
+ import { filesAt, type WrittenLines, writtenSince } from "../core/snapshot.ts";
7
8
 
8
9
  // jscpd compared with the tree the turn started from. Its own console report lists every clone of the repo, the old
9
10
  // ones included, so this prints only the clones the turn added, one per line.
11
+ //
12
+ // jscpd tells a clone by its two files and where it stands in them, so it also calls new an old clone the turn only
13
+ // disturbed: two old files it pairs once the turn takes their copy out of a third, or a clone the turn cut in two by a
14
+ // line written in its middle. A clone is the turn's only when the turn wrote in one of its sides.
10
15
 
11
16
  function refuse(): never {
12
17
  throw new Error("Not a jscpd report.");
13
18
  }
14
- function place(value: unknown): string {
19
+
20
+ /** A place in a file, as jscpd counts: lines from 1, columns from 0. */
21
+ interface Place {
22
+ line: number;
23
+ column: number;
24
+ }
25
+
26
+ /** One of the two sides of a clone: its file, and where it starts and ends, between two tokens. */
27
+ interface Side {
28
+ name: string;
29
+ start: Place;
30
+ end: Place;
31
+ }
32
+
33
+ function placeOf(value: unknown, line: number, column: number): Place {
34
+ if (isRecord(value) && typeof value.line === "number" && typeof value.column === "number")
35
+ return { line: value.line, column: value.column };
36
+ return { line, column };
37
+ }
38
+
39
+ // Without the columns of a clone, as from another jscpd, its first and last lines count as whole.
40
+ function sideOf(value: unknown): Side {
15
41
  if (!isRecord(value)) refuse();
16
- const { name, start, end } = value;
42
+ const { name, start, end, startLoc, endLoc } = value;
17
43
  if (typeof name !== "string" || typeof start !== "number" || typeof end !== "number") refuse();
18
- return `${name}:${start}-${end}`;
44
+ return { name, start: placeOf(startLoc, start, 0), end: placeOf(endLoc, end, Infinity) };
45
+ }
46
+
47
+ /**
48
+ * Whether the turn wrote in a side of a clone: a line it wrote stands whole in it, or it cut lines out of its middle.
49
+ * A clone starts and ends between two tokens, often inside a line: a line it only starts or ends in is not in it, nor
50
+ * an empty one, which jscpd does not read.
51
+ */
52
+ export function wroteIn({ start, end }: Pick<Side, "start" | "end">, text: string, written: WrittenLines[]): boolean {
53
+ const lines = text.split("\n");
54
+ const whole = (at: number) => {
55
+ const line = lines[at - 1] ?? "";
56
+ if (!line.trim()) return false;
57
+ const starts = at > start.line || (at === start.line && start.column <= line.length - line.trimStart().length);
58
+ const ends = at < end.line || (at === end.line && end.column >= line.trimEnd().length);
59
+ return starts && ends;
60
+ };
61
+ return written.some(({ at, lines: count }) =>
62
+ count === 0 ? start.line <= at && at < end.line : Array.from({ length: count }, (_, more) => at + more).some(whole),
63
+ );
19
64
  }
20
65
 
21
- export function newClones(report: unknown): string[] {
66
+ /** The clones jscpd calls new, each as its two sides. */
67
+ function newPairs(report: unknown): Side[][] {
22
68
  if (!isRecord(report) || !Array.isArray(report.duplicates)) refuse();
23
69
  return report.duplicates.flatMap((clone: unknown) => {
24
70
  if (!isRecord(clone)) refuse();
25
- const line = `${place(clone.firstFile)} ~ ${place(clone.secondFile)}`;
26
- return clone.isNew === true ? [line] : [];
71
+ const sides = [sideOf(clone.firstFile), sideOf(clone.secondFile)];
72
+ return clone.isNew === true ? [sides] : [];
27
73
  });
28
74
  }
29
75
 
30
- function main(root: string, turn: string): void {
76
+ /** The clones jscpd calls new, one per line, less the ones the turn wrote in neither side of. */
77
+ export function newClones(report: unknown, wrote: (side: Side) => boolean = () => true): string[] {
78
+ return newPairs(report)
79
+ .filter((sides) => sides.some(wrote))
80
+ .map((sides) => sides.map(({ name, start, end }) => `${name}:${start.line}-${end.line}`).join(" ~ "));
81
+ }
82
+
83
+ /**
84
+ * Whether the turn wrote in a side of a clone, for the clones of a report. Each file is read once, however many
85
+ * clones it has: the whole check finds every clone of the repo new.
86
+ */
87
+ function turnWrote(root: string, turn: string, report: unknown): (side: Side) => boolean {
88
+ const names = [...new Set(newPairs(report).flatMap((sides) => sides.map(({ name }) => name)))];
89
+ const old = new Set(filesAt(root, turn, names));
90
+ const files = new Map<string, { text: string; written: WrittenLines[] }>();
91
+ return (side) => {
92
+ // A file the turn created is all its own, and one jscpd names from another folder is unknown here: checking too
93
+ // much beats leaving a hole.
94
+ if (!old.has(side.name)) return true;
95
+ try {
96
+ const file = files.get(side.name) ?? {
97
+ text: readFileSync(join(root, side.name), "utf8"),
98
+ written: writtenSince(root, turn, side.name),
99
+ };
100
+ files.set(side.name, file);
101
+ return wroteIn(side, file.text, file.written);
102
+ } catch {
103
+ return true;
104
+ }
105
+ };
106
+ }
107
+
108
+ /** The clones the turn added to the repo, as jscpd finds them. It throws what jscpd said when jscpd fails. */
109
+ export function turnClones(root: string, turn: string): string[] {
31
110
  const jscpd = packageScript(root, "jscpd");
32
111
  if (jscpd === undefined)
33
112
  throw new Error("jscpd is not installed in node_modules: install the dependencies of the repo.");
@@ -42,17 +121,28 @@ function main(root: string, turn: string): void {
42
121
  } catch (error) {
43
122
  // What jscpd said, without the stack of this script around it.
44
123
  const said = isRecord(error) && typeof error.stderr === "string" ? error.stderr.trim() : String(error);
45
- console.log(`jscpd failed: ${said}`);
46
- process.exitCode = 1;
47
- return;
124
+ throw new Error(`jscpd failed: ${said}`, { cause: error });
48
125
  }
49
- const clones = newClones(readJsonFile(join(output, "jscpd-report.json")));
50
- if (!clones.length) return;
51
- console.log(headed("New clones: reuse the code already there, or factor it out.", clones));
52
- process.exitCode = 1;
126
+ const report = readJsonFile(join(output, "jscpd-report.json"));
127
+ return newClones(report, turnWrote(root, turn, report));
53
128
  } finally {
54
129
  rmSync(output, { recursive: true, force: true });
55
130
  }
56
131
  }
57
132
 
133
+ function main(root: string, turn: string): void {
134
+ let clones: string[];
135
+ try {
136
+ clones = turnClones(root, turn);
137
+ } catch (error) {
138
+ if (!(error instanceof Error) || !error.message.startsWith("jscpd failed: ")) throw error;
139
+ console.log(error.message);
140
+ process.exitCode = 1;
141
+ return;
142
+ }
143
+ if (!clones.length) return;
144
+ console.log(headed("New clones: reuse the code already there, or factor it out.", clones));
145
+ process.exitCode = 1;
146
+ }
147
+
58
148
  if (import.meta.main) main(process.cwd(), process.argv[2] ?? "HEAD");