@mark1russell7/rigor-mutation 0.2.3 → 0.2.4

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