@mark1russell7/rigor-mutation 0.2.3 → 0.2.5

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.
@@ -1,4 +1,4 @@
1
- import { a as PLAN_FILE, d as parsePlan, f as readPlan, t as PARTIAL_FILE } from "./reporter-BYC384h-.js";
1
+ import { a as PLAN_FILE, d as parsePlan, f as readPlan, l as clockMinutes, t as PARTIAL_FILE } from "./reporter-BYC384h-.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { dirname, join, matchesGlob, posix, relative, resolve } from "node:path";
4
4
  import { appendFileSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
@@ -6,6 +6,7 @@ import { spawnSync } from "node:child_process";
6
6
  import { tmpdir } from "node:os";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { parseArgs } from "node:util";
9
+ import { escapeWorkflowData, escapeWorkflowProperty } from "@mark1russell7/text";
9
10
  // src/lane.ts
10
11
  /** The keys of the Stryker config that the lane owns. The field `stryker` of a package cannot have them. */
11
12
  const STRYKER_OWNED = [
@@ -17,6 +18,8 @@ const STRYKER_OWNED = [
17
18
  "dryRunTimeoutMinutes"
18
19
  ];
19
20
  const NAME = /^[\w-]+$/;
21
+ /** A `mutate` entry with a range, as Stryker reads it: `src/a.ts:1-300`, or `src/a.ts:1:4-300:2` with columns. */
22
+ const RANGE = /^(.+?):(\d+)(?::(\d+))?-(\d+)(?::(\d+))?$/;
20
23
  const isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
21
24
  /** This function tells if a value is an object of names, each with a reason that is not empty. */
22
25
  const isReasons = (x) => isRecord(x) && Object.values(x).every((r) => typeof r === "string" && r.trim() !== "");
@@ -32,7 +35,7 @@ function packageErrors(name, p) {
32
35
  const gate = p["gate"];
33
36
  const gateOver = p["gateOver"];
34
37
  if (gateOver !== void 0 && gateOver !== "part" && gateOver !== "package") errors.push(`${name}: "gateOver" is not "part" or "package"`);
35
- else if (gateOver === "package" && p["parts"] === void 0) errors.push(`${name}: "gateOver" is "package", but the package has no parts`);
38
+ else if (gateOver === "package" && p["parts"] === void 0 && p["cuts"] === void 0) errors.push(`${name}: "gateOver" is "package", but the package has no parts`);
36
39
  if (gate !== void 0 && (typeof gate !== "number" || !(gate >= 0 && gate <= 100))) errors.push(`${name}: "gate" is not a percent from 0 to 100`);
37
40
  if (p["vitestConfig"] !== void 0 && typeof p["vitestConfig"] !== "string") errors.push(`${name}: "vitestConfig" is not a file name`);
38
41
  for (const field of ["timeoutMS", "dryRunTimeoutMinutes"]) {
@@ -49,9 +52,21 @@ function packageErrors(name, p) {
49
52
  }
50
53
  if (p["notRead"] !== void 0 && !isReasons(p["notRead"])) errors.push(`${name}: "notRead" is not an object of files, each with a reason`);
51
54
  if (p["computedImports"] !== void 0 && !isReasons(p["computedImports"])) errors.push(`${name}: "computedImports" is not an object of files, each with a reason`);
55
+ const parts = p["parts"];
52
56
  const limits = p["staticLimits"];
53
57
  if (limits !== void 0 && !(isRecord(limits) && Object.values(limits).every((n) => typeof n === "number" && Number.isInteger(n) && n >= 0))) errors.push(`${name}: "staticLimits" is not an object of files, each with a count of 0 or more`);
54
- const parts = p["parts"];
58
+ const cuts = p["cuts"];
59
+ if (cuts !== void 0) {
60
+ if (!isRecord(cuts) || Object.keys(cuts).length === 0) errors.push(`${name}: "cuts" is not an object with groups`);
61
+ else for (const [group, cut] of Object.entries(cuts)) {
62
+ if (!NAME.test(group)) errors.push(`${name}: the group name "${group}" has a character that is not a letter, a digit, "_" or "-"`);
63
+ if (isRecord(parts) && parts[group] !== void 0) errors.push(`${name}: "${group}" is a part and a group of "cuts"`);
64
+ const files = isRecord(cut) ? cut["files"] : void 0;
65
+ const count = isRecord(cut) ? cut["count"] : void 0;
66
+ if (!isGlobs(files) || files.some((g) => g.startsWith("!") || RANGE.test(g))) errors.push(`${name}.${group}: "files" is not a list of globs without "!" and without a line range`);
67
+ if (!(typeof count === "number" && Number.isInteger(count) && count >= 1)) errors.push(`${name}.${group}: "count" is not a positive integer`);
68
+ }
69
+ }
55
70
  if (parts !== void 0) {
56
71
  if (!isRecord(parts) || Object.keys(parts).length === 0) errors.push(`${name}: "parts" is not an object with parts`);
57
72
  else for (const [part, globs] of Object.entries(parts)) {
@@ -75,6 +90,7 @@ function parseLane(json) {
75
90
  if (fall !== void 0 && (typeof fall !== "number" || !(fall >= 0 && fall <= 100))) errors.push(`"maxTestFall" is not a percent from 0 to 100`);
76
91
  const planned = json["plannedFalls"];
77
92
  if (planned !== void 0 && !isReasons(planned)) errors.push(`"plannedFalls" is not an object of selections, each with a reason`);
93
+ if (json["costs"] !== void 0 && (typeof json["costs"] !== "string" || json["costs"] === "")) errors.push(`"costs" is not a file name`);
78
94
  const positive = (v) => typeof v === "number" && v > 0 && Number.isFinite(v);
79
95
  for (const field of [
80
96
  "planPerClock",
@@ -91,39 +107,68 @@ function parseLane(json) {
91
107
  if (unknown.length > 0) throw new Error(`the lane is not valid:\n "plannedFalls" names no selection of the lane: ${unknown.join(", ")}`);
92
108
  return lane;
93
109
  }
94
- /** This function gives the names of all the selections of a lane: each package, then each part of the package. */
110
+ /** This function gives the numbered parts of a group: the group itself for a count of 1. */
111
+ const numberedParts = (name, count) => count === 1 ? [name] : Array.from({ length: count }, (_unused, i) => `${name}.${String(i + 1)}`);
112
+ /** This function tells if a package has parts or groups of `cuts`. */
113
+ const hasParts = (p) => p.parts !== void 0 || p.cuts !== void 0;
114
+ /**
115
+ * This function gives the names of all the selections of a lane. These are each package, each part of the package,
116
+ * and each group of `cuts` of the package with its numbered parts.
117
+ */
95
118
  function selectionNames(lane) {
96
- return Object.entries(lane.packages).flatMap(([name, p]) => [name, ...Object.keys(p.parts ?? {}).map((part) => `${name}.${part}`)]);
119
+ return Object.entries(lane.packages).flatMap(([name, p]) => [
120
+ name,
121
+ ...Object.keys(p.parts ?? {}).map((part) => `${name}.${part}`),
122
+ ...Object.entries(p.cuts ?? {}).flatMap(([group, cut]) => [.../* @__PURE__ */ new Set([`${name}.${group}`, ...numberedParts(`${name}.${group}`, cut.count)])])
123
+ ]);
97
124
  }
98
- /** This function gives the selections of a full run: the parts of each package with parts, else the package. Each file is in one run. */
125
+ /**
126
+ * This function gives the selections of a full run. These are the parts and the numbered parts of each package with
127
+ * parts or groups, else the package. Each file is in one run.
128
+ */
99
129
  function runSelections(lane) {
100
- return Object.entries(lane.packages).flatMap(([name, p]) => p.parts === void 0 ? [name] : Object.keys(p.parts).map((part) => `${name}.${part}`));
130
+ return Object.entries(lane.packages).flatMap(([name, p]) => !hasParts(p) ? [name] : [...Object.keys(p.parts ?? {}).map((part) => `${name}.${part}`), ...Object.entries(p.cuts ?? {}).flatMap(([group, cut]) => numberedParts(`${name}.${group}`, cut.count))]);
131
+ }
132
+ /** This function gives the selections of a full run of one package: its parts and numbered parts, else the package. */
133
+ function packageRuns(lane, pkg) {
134
+ return runSelections({ packages: Object.fromEntries(Object.entries(lane.packages).filter(([name]) => name === pkg)) });
101
135
  }
102
136
  /**
103
- * This function gives the selection of a name: a package, or a part of a package.
137
+ * This function gives the selection of a name. The name is a package, a part, a group of `cuts` or a numbered part of a
138
+ * group. A numbered part mutates the entries that `cutOf` gives. Without `cutOf`, it mutates its full group.
104
139
  *
105
- * @throws Error when the lane has no package or part of that name
140
+ * @throws Error when the lane has no selection of that name
106
141
  */
107
- function select(lane, name) {
108
- const [pkg = "", part, ...rest] = name.split(".");
142
+ function select(lane, name, cutOf) {
143
+ const [pkg = "", part, number, ...rest] = name.split(".");
109
144
  const p = lane.packages[pkg];
110
- const globs = part === void 0 ? void 0 : p?.parts?.[part];
111
- if (p === void 0 || rest.length > 0 || part !== void 0 && globs === void 0) throw new Error(`the lane has no package or part "${name}". It has: ${selectionNames(lane).join(", ")}`);
112
- const mutate = globs === void 0 ? p.mutate : [...globs, ...p.mutate.filter((g) => g.startsWith("!"))];
113
- return {
145
+ const group = part === void 0 ? void 0 : p?.cuts?.[part];
146
+ const globs = part === void 0 ? void 0 : p?.parts?.[part] ?? group?.files;
147
+ const index = Number(number) - 1;
148
+ const cut = group !== void 0 && part !== void 0 && group.count > 1 && number === String(index + 1) && index >= 0 && index < group.count ? {
149
+ group: part,
150
+ count: group.count,
151
+ index
152
+ } : void 0;
153
+ if (p === void 0 || rest.length > 0 || part !== void 0 && globs === void 0 || number !== void 0 && cut === void 0) throw new Error(`the lane has no selection "${name}". It has: ${selectionNames(lane).join(", ")}`);
154
+ const not = p.mutate.filter((g) => g.startsWith("!"));
155
+ const own = globs === void 0 ? p.mutate : [...cut === void 0 || cutOf === void 0 ? globs : cutOf(pkg, cut, [...globs, ...not]), ...not];
156
+ const base = {
114
157
  name,
115
158
  pkg,
116
159
  dir: p.dir,
117
- mutate,
160
+ mutate: own,
118
161
  gate: p.gate,
119
162
  vitestConfig: p.vitestConfig,
120
163
  timeoutMS: p.timeoutMS,
121
164
  dryRunTimeoutMinutes: p.dryRunTimeoutMinutes,
122
165
  stryker: p.stryker
123
166
  };
167
+ return cut === void 0 ? base : {
168
+ ...base,
169
+ cut
170
+ };
124
171
  }
125
- /** A `mutate` entry with a range, as Stryker reads it: `src/a.ts:1-300`, or `src/a.ts:1:4-300:2` with columns. */
126
- const RANGE = /^(.+?):(\d+)(?::(\d+))?-(\d+)(?::(\d+))?$/;
127
172
  function rangeOf(entry) {
128
173
  const m = RANGE.exec(entry);
129
174
  if (m?.[1] === void 0) return void 0;
@@ -212,8 +257,8 @@ function rangeErrors(pkg, file, ranges, lines) {
212
257
  */
213
258
  function partErrors(lane, pkg, files, lines) {
214
259
  const p = lane.packages[pkg];
215
- if (p?.parts === void 0) return [];
216
- const parts = Object.keys(p.parts).map((part) => ({
260
+ if (p === void 0 || !hasParts(p)) return [];
261
+ const parts = [...Object.keys(p.parts ?? {}), ...Object.keys(p.cuts ?? {})].map((part) => ({
217
262
  part,
218
263
  mutate: select(lane, `${pkg}.${part}`).mutate
219
264
  }));
@@ -239,6 +284,230 @@ function partErrors(lane, pkg, files, lines) {
239
284
  }
240
285
  return errors;
241
286
  }
287
+ // src/cut.ts
288
+ /** The closing line of a method of a class, or of a function at the top of a file. */
289
+ const CLOSING_LINE = /^ {0,2}\}$/u;
290
+ /** The first line of a declaration at the top of a file or in a class body, with its name. */
291
+ const DECLARATION = /^ {0,2}(?:export +)?(?:(?:async|static|private|protected|public|readonly|get|set|declare|abstract) +)*(?:(?:function\*?|class|const|let|interface|type|enum) +)?([#$A-Za-z_][\w$]*) *[(<=:{]/u;
292
+ /** The words that start a statement and not a declaration. */
293
+ const STATEMENTS = /* @__PURE__ */ new Set([
294
+ "if",
295
+ "for",
296
+ "while",
297
+ "switch",
298
+ "return",
299
+ "throw",
300
+ "do",
301
+ "try",
302
+ "catch",
303
+ "else"
304
+ ]);
305
+ /** This function gives the lines of a text. */
306
+ const linesOf = (text) => text.split(/\r?\n/u);
307
+ /**
308
+ * This function cuts a text into segments. Each segment ends on a closing line, and the last segment ends on the last
309
+ * line. The key of a segment is the name of its first declaration, with `#2` for the second segment of that name. A
310
+ * segment with no name has the key `@n`. A key thus stays the same when a change moves the lines.
311
+ */
312
+ function segmentsOf(text) {
313
+ const lines = linesOf(text);
314
+ const segments = [];
315
+ const seen = /* @__PURE__ */ new Map();
316
+ let start = 1;
317
+ let name;
318
+ const close = (end) => {
319
+ const base = name ?? `@${String(segments.length + 1)}`;
320
+ const n = (seen.get(base) ?? 0) + 1;
321
+ seen.set(base, n);
322
+ segments.push({
323
+ key: n === 1 ? base : `${base}#${String(n)}`,
324
+ start,
325
+ end
326
+ });
327
+ start = end + 1;
328
+ name = void 0;
329
+ };
330
+ lines.forEach((line, index) => {
331
+ const declared = DECLARATION.exec(line)?.[1];
332
+ if (name === void 0 && declared !== void 0 && !STATEMENTS.has(declared)) name = declared;
333
+ if (CLOSING_LINE.test(line)) close(index + 1);
334
+ });
335
+ if (start <= lines.length) close(lines.length);
336
+ return segments;
337
+ }
338
+ /** This function gives the cost map of a text from the plan of its lines: the planned net time of each segment. */
339
+ function costMapOf(text, run, lines) {
340
+ const segments = segmentsOf(text);
341
+ const cost = Object.fromEntries(segments.map((segment) => [segment.key, 0]));
342
+ for (const [line, , , netMs] of lines) {
343
+ const segment = segments.find((s) => s.start <= line && line <= s.end);
344
+ if (segment !== void 0) cost[segment.key] = (cost[segment.key] ?? 0) + netMs;
345
+ }
346
+ return {
347
+ run,
348
+ segments: cost
349
+ };
350
+ }
351
+ /**
352
+ * This function gives the weight of each line of a text from a cost map. A segment spreads its cost over its lines. A
353
+ * segment that the map does not name has the mean cost of a line of the named segments. Thus a new function has a cost.
354
+ */
355
+ function lineWeights(text, map) {
356
+ const segments = segmentsOf(text);
357
+ const named = segments.filter((s) => map.segments[s.key] !== void 0);
358
+ const namedLines = named.reduce((sum, s) => sum + s.end - s.start + 1, 0);
359
+ const namedCost = named.reduce((sum, s) => sum + (map.segments[s.key] ?? 0), 0);
360
+ const mean = namedLines === 0 ? 1 : namedCost / namedLines;
361
+ return segments.flatMap((s) => {
362
+ const size = s.end - s.start + 1;
363
+ const cost = map.segments[s.key];
364
+ return Array.from({ length: size }, () => cost === void 0 ? mean : cost / size);
365
+ });
366
+ }
367
+ /**
368
+ * This function gives the weight of each line of each file from the cost maps of its package. A file with no map has
369
+ * the mean weight of a line of the files with a map, so a new file has a cost. With no map, each line has the weight 1.
370
+ */
371
+ function weightedFiles(texts, maps = {}) {
372
+ const known = texts.flatMap(({ path, text }) => {
373
+ const map = maps[path];
374
+ return map === void 0 ? [] : [lineWeights(text, map)];
375
+ });
376
+ const lineCount = known.reduce((n, w) => n + w.length, 0);
377
+ const mean = lineCount === 0 ? 1 : known.flat().reduce((n, w) => n + w, 0) / lineCount;
378
+ return texts.map(({ path, text }) => {
379
+ const lines = linesOf(text);
380
+ const map = maps[path];
381
+ return {
382
+ path,
383
+ lines,
384
+ weights: map === void 0 ? lines.map(() => mean) : lineWeights(text, map)
385
+ };
386
+ });
387
+ }
388
+ /**
389
+ * This function gives the lightest cut of the lines at the candidates into `count` parts. It gives the index of the
390
+ * candidate at the end of each part but the last. With a limit, a part over the limit is not possible, and the lightest
391
+ * cut has the smallest squares. With no limit, the lightest cut has the smallest largest part, then the smallest squares.
392
+ */
393
+ function lightestCut(candidates, sumTo, total, count, limit) {
394
+ const lighter = (x, y) => y === void 0 || (limit === void 0 ? x.max < y.max || x.max === y.max && x.squares < y.squares : x.squares < y.squares);
395
+ const extend = (prior, from, to, before) => {
396
+ const weight = sumTo(to) - sumTo(from);
397
+ if (prior === void 0 || limit !== void 0 && weight > limit) return void 0;
398
+ return {
399
+ max: Math.max(prior.max, weight),
400
+ squares: prior.squares + weight ** 2,
401
+ before
402
+ };
403
+ };
404
+ const start = {
405
+ max: 0,
406
+ squares: 0,
407
+ before: -1
408
+ };
409
+ const cuts = [candidates.map((end) => extend(start, -1, end, -1))];
410
+ for (let part = 1; part < count - 1; part += 1) {
411
+ const last = cuts[part - 1] ?? [];
412
+ cuts.push(candidates.map((end, k) => {
413
+ let best;
414
+ for (let i = part - 1; i < k; i += 1) {
415
+ const cut = extend(last[i], candidates[i] ?? -1, end, i);
416
+ if (cut !== void 0 && lighter(cut, best)) best = cut;
417
+ }
418
+ return best;
419
+ }));
420
+ }
421
+ let best;
422
+ (cuts[count - 2] ?? []).forEach((prior, k) => {
423
+ const cut = extend(prior, candidates[k] ?? -1, total, k);
424
+ if (cut !== void 0 && lighter(cut, best)) best = cut;
425
+ });
426
+ const picks = [];
427
+ let at = best?.before ?? -1;
428
+ for (let part = count - 2; part >= 0; part -= 1) {
429
+ picks.unshift(at);
430
+ at = cuts[part]?.[at]?.before ?? -1;
431
+ }
432
+ return {
433
+ picks,
434
+ max: best?.max ?? Number.POSITIVE_INFINITY
435
+ };
436
+ }
437
+ /**
438
+ * This function gives the last line of each part but the last, counted from 1. A line is an end line when `isEnd` of
439
+ * its index from 0 is true. Of all cuts at end lines into `count` parts, it takes the cuts with the smallest largest
440
+ * part. Of these, it takes the cut with the smallest sum of squares.
441
+ *
442
+ * @throws Error when the lines have fewer end lines than the count of parts needs
443
+ */
444
+ function endsOf(size, isEnd, count, weights) {
445
+ if (count < 2) return [];
446
+ const sums = [];
447
+ let total = 0;
448
+ for (let at = 0; at < size; at += 1) {
449
+ total += weights[at] ?? 0;
450
+ sums.push(total);
451
+ }
452
+ const sumTo = (at) => at < 0 ? 0 : at >= size ? total : sums[at] ?? 0;
453
+ const candidates = Array.from({ length: Math.max(0, size - 1) }, (_unused, at) => at).filter(isEnd);
454
+ if (candidates.length < count - 1) throw new Error(`the files have ${String(candidates.length + 1)} places for the end of a part, and the cut needs ${String(count)}`);
455
+ const { max } = lightestCut(candidates, sumTo, size, count);
456
+ const { picks } = lightestCut(candidates, sumTo, size, count, max);
457
+ return picks.map((pick) => (candidates[pick] ?? 0) + 1);
458
+ }
459
+ /**
460
+ * This function cuts the files of a group into `count` parts of near the same weight. It gives the entries of `mutate`
461
+ * of each part. The files follow one another in their order. A part ends on the closing line of a method, or on the last
462
+ * line of a file. A part holds whole files, and a range of lines of a file at each end. Each input gives one result.
463
+ *
464
+ * @throws Error when the files have fewer end lines than the count of parts needs
465
+ */
466
+ function cutByCost(files, count) {
467
+ const lines = files.flatMap((file) => file.lines);
468
+ const starts = [];
469
+ let at = 0;
470
+ for (const file of files) {
471
+ starts.push(at);
472
+ at += file.lines.length;
473
+ }
474
+ const fileEnds = new Set(starts.slice(1).map((start) => start - 1));
475
+ const isEnd = (line) => fileEnds.has(line) || CLOSING_LINE.test(lines[line] ?? "");
476
+ const ends = endsOf(lines.length, isEnd, count, files.flatMap((file) => file.weights));
477
+ return Array.from({ length: count }, (_unused, part) => {
478
+ const from = (ends[part - 1] ?? 0) + 1;
479
+ const to = ends[part] ?? lines.length;
480
+ return files.flatMap((file, index) => {
481
+ const start = starts[index] ?? 0;
482
+ const first = Math.max(from, start + 1) - start;
483
+ const last = Math.min(to, start + file.lines.length) - start;
484
+ if (first > last) return [];
485
+ return [first === 1 && last === file.lines.length ? file.path : `${file.path}:${String(first)}-${String(last)}`];
486
+ });
487
+ });
488
+ }
489
+ /** This function gives the planned net time of the entries of a part in milliseconds: the sum of the weights of their lines. */
490
+ function plannedMs(entries, files) {
491
+ const byPath = new Map(files.map((file) => [file.path, file.weights]));
492
+ return entries.reduce((sum, entry) => {
493
+ const [, path = entry, first, last] = /^(.+):(\d+)-(\d+)$/u.exec(entry) ?? [];
494
+ const weights = byPath.get(path) ?? [];
495
+ const from = first === void 0 ? 1 : Number(first);
496
+ const to = last === void 0 ? weights.length : Number(last);
497
+ return sum + weights.slice(from - 1, to).reduce((n, w) => n + w, 0);
498
+ }, 0);
499
+ }
500
+ /**
501
+ * This function reads the JSON of a file of cost maps.
502
+ *
503
+ * @throws Error when the JSON is not an object of packages, each an object of files, each with a run and segments
504
+ */
505
+ function parseCostMaps(json) {
506
+ const isRecord = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
507
+ const isMap = (m) => isRecord(m) && typeof m["run"] === "string" && isRecord(m["segments"]) && Object.values(m["segments"]).every((n) => typeof n === "number" && n >= 0);
508
+ if (!isRecord(json) || !Object.values(json).every((files) => isRecord(files) && Object.values(files).every(isMap))) throw new Error(`the cost maps are not an object of packages, each an object of files, each with "run" and "segments"`);
509
+ return json;
510
+ }
242
511
  // src/config.ts
243
512
  /**
244
513
  * The file URL of the module of the reporter `rigor-partial`: the source in the workspace, the build in the package of
@@ -928,6 +1197,15 @@ const HELP = `rigor-mutation: the mutation tests of a repository, with Stryker a
928
1197
  target gives a warning. A selection over the stop fails, and so
929
1198
  does a file over its count of "staticLimits". --reports reads
930
1199
  <dir>/mutation-<selection>/plan.json.
1200
+ rigor-mutation costs <run> --reports <dir> write the cost maps of the lane into the file of "costs", from
1201
+ <dir>/mutation-<selection>/plan.json of each selection of the
1202
+ run <run>. A file of the plans with no line gets a map of 0.
1203
+ The maps of the other files stay.
1204
+ rigor-mutation cost-check [<selection>...] the estimate of the clock of each numbered part of a group of
1205
+ "cuts" under the cost maps. A part over "targetMinutes" fails.
1206
+ No selection checks each numbered part of the lane.
1207
+ rigor-mutation minutes the target and the stop of the lane, as the lines
1208
+ target=<minutes> and stop=<minutes> for GITHUB_OUTPUT.
931
1209
  rigor-mutation disables [--write] compare the disable comments with their list
932
1210
  rigor-mutation load-check [<selection>...] [--collect] [--runner <file>]
933
1211
  refuse each relative path of a package that leaves its folder.
@@ -945,8 +1223,10 @@ const HELP = `rigor-mutation: the mutation tests of a repository, with Stryker a
945
1223
  for example the output of git diff --name-only. A changed test file selects
946
1224
  its source file of the same name.
947
1225
 
948
- A selection is a package ("collections") or a part of a package ("collections.impl").
949
- Each file of a package with parts must be in exactly one part. list --runs, and config and scores
1226
+ A selection is a package ("collections"), a part of a package ("collections.impl"), a group of
1227
+ "cuts" ("collections.base") or a numbered part of a group ("collections.base.2"). The cost maps
1228
+ cut a group into numbered parts of near the same cost. A part ends on a closing line or at the end
1229
+ of a file. Each file of a package with parts must be in exactly one part or group. list --runs, and config and scores
950
1230
  of a part, fail when it is not.
951
1231
  The score of a selection reads <dir>/${REPORT_DIR}/mutation.json, or the file of --report.
952
1232
  `;
@@ -1028,7 +1308,7 @@ function collectCheck(lane, laneDir, pkg, files) {
1028
1308
  faults: [],
1029
1309
  collected: void 0
1030
1310
  };
1031
- const own = runSelections(lane).map((n) => select(lane, n)).filter((s) => s.pkg === pkg);
1311
+ const own = packageRuns(lane, pkg).map((n) => selectIn(lane, laneDir, n));
1032
1312
  const sources = files.map((f) => f.file).filter((f) => !TEST.test(f));
1033
1313
  const mutated = Object.fromEntries(own.map((s) => [s.name, sources.filter((f) => globsSelect(s.mutate, f))]));
1034
1314
  const config = own[0] === void 0 ? {} : strykerConfig(own[0]);
@@ -1116,10 +1396,41 @@ function typescriptMajor(dir) {
1116
1396
  const lineCount = (text) => text === "" ? 0 : text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
1117
1397
  /** This function tells if a file of the package of a selection, from its folder, exists. */
1118
1398
  const existsIn = (laneDir, s) => (file) => existsSync(resolve(laneDir, s.dir, file));
1399
+ /** This function gives the cost maps of the lane, or none when the lane has no file of maps or the file does not exist. */
1400
+ function costMapsOf(lane, laneDir) {
1401
+ const file = lane.costs === void 0 ? void 0 : resolve(laneDir, lane.costs);
1402
+ return file === void 0 || !existsSync(file) ? {} : parseCostMaps(readJson(file));
1403
+ }
1404
+ /** This function gives the files of a group of a package, in the order of their paths, with the weight of each line. */
1405
+ function groupFiles(lane, laneDir, pkg, globs, maps) {
1406
+ const dir = resolve(laneDir, lane.packages[pkg]?.dir ?? ".");
1407
+ return weightedFiles(sourcesOf(dir, dir).filter((file) => globsSelect(globs, file)).map((path) => ({
1408
+ path,
1409
+ text: readFileSync(resolve(dir, path), "utf8")
1410
+ })), maps[pkg] ?? {});
1411
+ }
1412
+ /** The cut of each lane, so that each command reads the files of a group one time. */
1413
+ const cuts = /* @__PURE__ */ new WeakMap();
1414
+ /** This function gives the selection of a name, with the cut by cost of a numbered part of a group. */
1415
+ function selectIn(lane, laneDir, name) {
1416
+ let cutOf = cuts.get(lane);
1417
+ if (cutOf === void 0) {
1418
+ const maps = costMapsOf(lane, laneDir);
1419
+ const parts = /* @__PURE__ */ new Map();
1420
+ cutOf = (pkg, cut, globs) => {
1421
+ const key = `${pkg}.${cut.group}`;
1422
+ const cutParts = parts.get(key) ?? cutByCost(groupFiles(lane, laneDir, pkg, globs, maps), cut.count);
1423
+ parts.set(key, cutParts);
1424
+ return cutParts[cut.index] ?? [];
1425
+ };
1426
+ cuts.set(lane, cutOf);
1427
+ }
1428
+ return select(lane, name, cutOf);
1429
+ }
1119
1430
  function checkParts(lane, laneDir, pkgs) {
1120
1431
  const errors = pkgs.flatMap((pkg) => {
1121
1432
  const p = lane.packages[pkg];
1122
- if (p?.parts === void 0) return [];
1433
+ if (p === void 0 || p.parts === void 0 && p.cuts === void 0) return [];
1123
1434
  const dir = resolve(laneDir, p.dir);
1124
1435
  if (!existsSync(dir)) return [`${pkg}: the folder ${p.dir} does not exist`];
1125
1436
  return partErrors(lane, pkg, sourcesOf(dir, dir), (file) => lineCount(readFileSync(resolve(dir, file), "utf8")));
@@ -1176,7 +1487,7 @@ function scores(lane, laneDir, names, o, io) {
1176
1487
  const falls = [];
1177
1488
  const byPackage = (s) => s.name !== s.pkg && lane.packages[s.pkg]?.gateOver === "package";
1178
1489
  const results = names.map((name) => {
1179
- const all = select(lane, name);
1490
+ const all = selectIn(lane, laneDir, name);
1180
1491
  const s = byPackage(all) ? {
1181
1492
  ...all,
1182
1493
  gate: void 0
@@ -1231,7 +1542,7 @@ function scores(lane, laneDir, names, o, io) {
1231
1542
  const totals = [...new Set(packages)].map((pkg) => {
1232
1543
  const p = lane.packages[pkg];
1233
1544
  const parts = results.filter((r) => select(lane, r.name).pkg === pkg && r.name !== pkg);
1234
- const missing = Object.keys(p?.parts ?? {}).map((part) => `${pkg}.${part}`).filter((n) => !names.includes(n));
1545
+ const missing = packageRuns(lane, pkg).filter((n) => n !== pkg && !names.includes(n));
1235
1546
  return packageScore(pkg, p?.gate, parts, missing);
1236
1547
  });
1237
1548
  const withFault = (s, pkg) => {
@@ -1275,10 +1586,10 @@ ${summaryMarkdown(shown)}
1275
1586
  function testFileReasons(lane, laneDir, names, reports, note) {
1276
1587
  const reasons = /* @__PURE__ */ new Map();
1277
1588
  for (const [pkg, p] of Object.entries(lane.packages)) {
1278
- const own = p.parts === void 0 ? [pkg] : Object.keys(p.parts).map((part) => `${pkg}.${part}`);
1589
+ const own = packageRuns(lane, pkg);
1279
1590
  const read = own.flatMap((n) => reports.get(n) ?? []);
1280
1591
  if (!own.every((n) => names.includes(n)) || read.length < own.length) continue;
1281
- const at = p.parts === void 0 || p.gateOver === "package" ? pkg : own.at(-1) ?? pkg;
1592
+ const at = own[0] === pkg || p.gateOver === "package" ? pkg : own.at(-1) ?? pkg;
1282
1593
  const blind = own.filter((n) => reports.get(n)?.testFiles === void 0);
1283
1594
  if (blind.length > 0) {
1284
1595
  note(at, ` the test files of ${pkg} over all its selections are not known: the reports of ${blind.join(", ")} have no "testFiles"`);
@@ -1295,11 +1606,6 @@ function testFileReasons(lane, laneDir, names, reports, note) {
1295
1606
  }
1296
1607
  return reasons;
1297
1608
  }
1298
- /** This function escapes the text of a workflow command of GitHub Actions. A property escapes also `:` and `,`. */
1299
- const escapeCommand = (text, property = false) => {
1300
- const data = text.replaceAll("%", "%25").replaceAll("\r", "%0D").replaceAll("\n", "%0A");
1301
- return property ? data.replaceAll(":", "%3A").replaceAll(",", "%2C") : data;
1302
- };
1303
1609
  /**
1304
1610
  * This function gives a warning annotation for each score that does not pass and each planned fall. The annotation is on
1305
1611
  * the check line, so a no read is not a green check with the reason only in the log. This is true also for a run that
@@ -1307,7 +1613,7 @@ const escapeCommand = (text, property = false) => {
1307
1613
  */
1308
1614
  function annotations(results, falls) {
1309
1615
  const noReads = results.filter((s) => !s.pass && s.outcome !== "block");
1310
- const line = (title, message) => `::warning title=${escapeCommand(title, true)}::${escapeCommand(message)}`;
1616
+ const line = (title, message) => `::warning title=${escapeWorkflowProperty(title)}::${escapeWorkflowData(message)}`;
1311
1617
  return [
1312
1618
  ...noReads.map((s) => line(`Mutation gate: no read, ${String(noReads.length)} of ${String(results.length)} selections`, `${s.name}: ${s.reason ?? ""}`)),
1313
1619
  ...results.filter((s) => !s.pass && s.outcome === "block").map((s) => line("Mutation gate: under the gate", `${s.name}: ${s.reason ?? ""}`)),
@@ -1342,7 +1648,7 @@ function planCheck(lane, laneDir, names, o, io) {
1342
1648
  ...limits === void 0 ? {} : { staticLimits: limits }
1343
1649
  });
1344
1650
  io.stdout(`${read.line}\n${read.warnings.map((w) => ` WARN: ${w}\n`).join("")}${read.faults.map((f) => ` FAIL: ${f}\n`).join("")}`);
1345
- if (actions) for (const w of read.warnings) io.stdout(`::warning title=${escapeCommand("Mutation plan: over the target", true)}::${escapeCommand(w)}\n`);
1651
+ if (actions) for (const w of read.warnings) io.stdout(`::warning title=${escapeWorkflowProperty("Mutation plan: over the target")}::${escapeWorkflowData(w)}\n`);
1346
1652
  if (read.warnings.length > 0) warned += 1;
1347
1653
  if (read.faults.length > 0) failed += 1;
1348
1654
  }
@@ -1350,6 +1656,73 @@ function planCheck(lane, laneDir, names, o, io) {
1350
1656
  io.stdout(failed === 0 ? `plan-check: each plan of ${String(names.length)} selections is in its limits${over}\n` : `plan-check: ${String(failed)} of ${String(names.length)} selections fail${over}\n`);
1351
1657
  return failed === 0 ? 0 : 1;
1352
1658
  }
1659
+ /**
1660
+ * This function writes the cost maps of the lane from the plans of a run (`costs`). It adds the plan lines of each file
1661
+ * over the selections, so a file in two parts gets one map. A file that a selection mutates with no plan gets a map of
1662
+ * 0. The maps of the files of the other selections stay.
1663
+ */
1664
+ function writeCosts(lane, laneDir, run, reports, io) {
1665
+ if (lane.costs === void 0) throw new Error(`the lane has no field "costs" for the file of the cost maps`);
1666
+ if (reports === void 0) throw new Error(`"costs" takes --reports <dir>`);
1667
+ const lines = /* @__PURE__ */ new Map();
1668
+ const read = [];
1669
+ for (const name of selectionNames(lane)) {
1670
+ const file = resolve(io.cwd, reports, `mutation-${name}`, PLAN_FILE);
1671
+ if (!existsSync(file)) continue;
1672
+ read.push(name);
1673
+ const s = selectIn(lane, laneDir, name);
1674
+ const dir = resolve(laneDir, s.dir);
1675
+ const files = lines.get(s.pkg) ?? /* @__PURE__ */ new Map();
1676
+ lines.set(s.pkg, files);
1677
+ for (const source of sourcesOf(dir, dir).filter((f) => globsSelect(s.mutate, f))) files.set(source, files.get(source) ?? []);
1678
+ for (const [source, plan] of Object.entries(parsePlan(readJson(file)).files)) files.set(source, [...files.get(source) ?? [], ...plan.lines]);
1679
+ }
1680
+ if (read.length === 0) throw new Error(`there is no plan of a selection of the lane in ${reports}`);
1681
+ const maps = Object.fromEntries(Object.entries(costMapsOf(lane, laneDir)).map(([pkg, files]) => [pkg, { ...files }]));
1682
+ let count = 0;
1683
+ for (const [pkg, files] of lines) {
1684
+ const dir = resolve(laneDir, lane.packages[pkg]?.dir ?? ".");
1685
+ const own = maps[pkg] ?? {};
1686
+ maps[pkg] = own;
1687
+ for (const [source, plan] of files) {
1688
+ if (!existsSync(resolve(dir, source))) continue;
1689
+ own[source] = costMapOf(readFileSync(resolve(dir, source), "utf8"), run, plan);
1690
+ count += 1;
1691
+ }
1692
+ }
1693
+ const sorted = (x) => Object.fromEntries(Object.entries(x).toSorted(([a], [b]) => a.localeCompare(b)));
1694
+ const out = resolve(laneDir, lane.costs);
1695
+ mkdirSync(dirname(out), { recursive: true });
1696
+ writeFileSync(out, `${JSON.stringify(sorted(Object.fromEntries(Object.entries(maps).map(([pkg, files]) => [pkg, sorted(files)]))), null, 2)}\n`);
1697
+ io.stdout(`costs: ${String(count)} files from the plans of ${String(read.length)} selections of the run ${run}, in ${relative(io.cwd, out).replaceAll("\\", "/")}\n`);
1698
+ return 0;
1699
+ }
1700
+ /**
1701
+ * This function gives the estimate of the clock of each numbered part of a group under the cost maps (`cost-check`).
1702
+ * A part over the target fails, and so does a group with no cost map. The check reads only the files on the disk, so
1703
+ * each commit gives one result.
1704
+ */
1705
+ function costCheck(lane, laneDir, names, io) {
1706
+ const all = runSelections(lane).filter((n) => select(lane, n).cut !== void 0);
1707
+ const named = names.length === 0 ? all : names;
1708
+ const maps = costMapsOf(lane, laneDir);
1709
+ const target = lane.targetMinutes ?? 100;
1710
+ let failed = 0;
1711
+ for (const name of named) {
1712
+ const s = selectIn(lane, laneDir, name);
1713
+ if (s.cut === void 0) throw new Error(`the selection ${name} is not a numbered part of a group of "cuts"`);
1714
+ const group = lane.packages[s.pkg]?.cuts?.[s.cut.group];
1715
+ const not = (lane.packages[s.pkg]?.mutate ?? []).filter((g) => g.startsWith("!"));
1716
+ const files = groupFiles(lane, laneDir, s.pkg, [...group?.files ?? [], ...not], maps);
1717
+ const entries = s.mutate.filter((g) => !g.startsWith("!"));
1718
+ const minutes = clockMinutes(plannedMs(entries, files), lane.planPerClock);
1719
+ const fault = !files.some((f) => maps[s.pkg]?.[f.path] !== void 0) ? `the group ${s.pkg}.${s.cut.group} has no cost map. Write the maps with "costs" from the plans of a run.` : minutes > target ? `the estimate of ${minutes.toFixed(0)} minutes is over the target of ${String(target)}. Raise the count of the group ${s.pkg}.${s.cut.group}.` : void 0;
1720
+ io.stdout(`${name}: ${String(entries.length)} entries, with an estimate of ${minutes.toFixed(0)} minutes of the clock under the cost maps.${fault === void 0 ? "" : `\n FAIL: ${fault}`}\n`);
1721
+ if (fault !== void 0) failed += 1;
1722
+ }
1723
+ io.stdout(failed === 0 ? `cost-check: each of ${String(named.length)} parts is in its target\n` : `cost-check: ${String(failed)} of ${String(named.length)} parts fail\n`);
1724
+ return failed === 0 ? 0 : 1;
1725
+ }
1353
1726
  /** This function reads a file of test counts: an object from each selection to its count. */
1354
1727
  function readCounts(file) {
1355
1728
  const json = readJson(file);
@@ -1452,7 +1825,7 @@ function runCli(argv, io) {
1452
1825
  if (values.runs) checkParts(lane, laneDir, Object.keys(lane.packages));
1453
1826
  if (changed !== void 0 && !values.runs) throw new Error(`--changed of "list" takes --runs`);
1454
1827
  const runs = values.runs ? runSelections(lane) : selectionNames(lane);
1455
- const shown = changed === void 0 ? runs : runs.filter((n) => changedFiles(select(lane, n), changed, existsIn(laneDir, select(lane, n))).length > 0);
1828
+ const shown = changed === void 0 ? runs : runs.filter((n) => changedFiles(selectIn(lane, laneDir, n), changed, existsIn(laneDir, select(lane, n))).length > 0);
1456
1829
  io.stdout(shown.length === 0 ? "" : `${shown.join("\n")}\n`);
1457
1830
  return 0;
1458
1831
  }
@@ -1464,7 +1837,7 @@ function runCli(argv, io) {
1464
1837
  if (concurrency !== void 0 && !(Number.isInteger(concurrency) && concurrency > 0)) throw new Error(`--concurrency is not a positive integer`);
1465
1838
  if (values["dry-run"] && values.plan) throw new Error(`"config" takes --dry-run or --plan, not both`);
1466
1839
  checkPartsOf(lane, laneDir, [one()]);
1467
- const all = select(lane, one());
1840
+ const all = selectIn(lane, laneDir, one());
1468
1841
  const files = changed === void 0 ? void 0 : changedFiles(all, changed, existsIn(laneDir, all));
1469
1842
  if (files?.length === 0) throw new Error(`the selection ${all.name} has no changed file`);
1470
1843
  const selection = files === void 0 ? all : {
@@ -1499,6 +1872,11 @@ function runCli(argv, io) {
1499
1872
  report: values.report,
1500
1873
  reports: values.reports
1501
1874
  }, io);
1875
+ case "costs": return writeCosts(lane, laneDir, one(), values.reports, io);
1876
+ case "cost-check": return costCheck(lane, laneDir, names, io);
1877
+ case "minutes":
1878
+ io.stdout(`target=${String(lane.targetMinutes ?? 100)}\nstop=${String(lane.stopMinutes ?? 140)}\n`);
1879
+ return 0;
1502
1880
  case "disables": return disables(lane, laneDir, values.write, io);
1503
1881
  case "load-check": return loadCheck(lane, laneDir, names, io, {
1504
1882
  collect: values.collect,
@@ -1509,6 +1887,6 @@ function runCli(argv, io) {
1509
1887
  return 1;
1510
1888
  }
1511
1889
  }
1512
- export { select as A, rewritesTsconfig as C, parseLane as D, changedFiles as E, partErrors as O, TIMEOUT_MS as S, STRYKER_OWNED as T, summaryMarkdown as _, isConfigFile as a, PARTIAL_PLUGIN as b, compareDisables as c, isHitLimit as d, packageScore as f, scoreReport as g, partialScore as h, computedImports as i, selectionNames as j, runSelections as k, findDisables as l, parseReport as m, runCli as n, leavingPaths as o, parsePartial as p, collectFaults as r, relatedTestFiles as s, HELP as t, formatScore as u, DRY_RUN_TIMEOUT_MINUTES as v, strykerConfig as w, REPORT_DIR as x, NO_TSCONFIG as y };
1890
+ export { segmentsOf as A, rewritesTsconfig as C, lineWeights as D, cutByCost as E, parseLane as F, partErrors as I, runSelections as L, STRYKER_OWNED as M, changedFiles as N, parseCostMaps as O, packageRuns as P, select as R, TIMEOUT_MS as S, costMapOf as T, summaryMarkdown as _, isConfigFile as a, PARTIAL_PLUGIN as b, compareDisables as c, isHitLimit as d, packageScore as f, scoreReport as g, partialScore as h, computedImports as i, weightedFiles as j, plannedMs as k, findDisables as l, parseReport as m, runCli as n, leavingPaths as o, parsePartial as p, collectFaults as r, relatedTestFiles as s, HELP as t, formatScore as u, DRY_RUN_TIMEOUT_MINUTES as v, strykerConfig as w, REPORT_DIR as x, NO_TSCONFIG as y, selectionNames as z };
1513
1891
 
1514
- //# sourceMappingURL=run-DcH6lUvo.js.map
1892
+ //# sourceMappingURL=run-DYF5roXk.js.map