@mark1russell7/rigor-mutation 0.2.0 → 0.2.2

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,7 +1,10 @@
1
- import { PARTIAL_FILE } from "./reporter.js";
1
+ import { t as PARTIAL_FILE } from "./reporter-Cypwcaj9.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { dirname, join, matchesGlob, posix, relative, resolve } from "node:path";
4
- import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
4
+ import { appendFileSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
5
+ import { spawnSync } from "node:child_process";
6
+ import { tmpdir } from "node:os";
7
+ import { fileURLToPath } from "node:url";
5
8
  import { parseArgs } from "node:util";
6
9
  // src/lane.ts
7
10
  /** The keys of the Stryker config that the lane owns. The field `stryker` of a package cannot have them. */
@@ -45,6 +48,7 @@ function packageErrors(name, p) {
45
48
  }
46
49
  }
47
50
  if (p["notRead"] !== void 0 && !isReasons(p["notRead"])) errors.push(`${name}: "notRead" is not an object of files, each with a reason`);
51
+ if (p["computedImports"] !== void 0 && !isReasons(p["computedImports"])) errors.push(`${name}: "computedImports" is not an object of files, each with a reason`);
48
52
  const parts = p["parts"];
49
53
  if (parts !== void 0) {
50
54
  if (!isRecord(parts) || Object.keys(parts).length === 0) errors.push(`${name}: "parts" is not an object with parts`);
@@ -427,7 +431,16 @@ function readTestFiles(reports, dir) {
427
431
  * @param dir - the folder of the package, to make a full path of a report relative
428
432
  */
429
433
  function testFileFaults(reports, onDisk, notRead = {}, dir = "") {
430
- const read = readTestFiles(reports, dir);
434
+ return readFaults(readTestFiles(reports, dir), onDisk, notRead);
435
+ }
436
+ /**
437
+ * This function examines the test files of a package against the test files that its selections read (LANE.FILES).
438
+ * `load-check --collect` gives the files that the selections start. The reports give the files that they read.
439
+ *
440
+ * @param read - the test files that the selections read, from the folder of the package, with `/`
441
+ * @param onDisk - the test files of the package, from its folder, with `/`
442
+ */
443
+ function readFaults(read, onDisk, notRead = {}) {
431
444
  const files = new Set(onDisk);
432
445
  return {
433
446
  unread: onDisk.filter((f) => !read.has(f) && notRead[f] === void 0),
@@ -651,12 +664,21 @@ function target(file, path, known) {
651
664
  * @param vitestConfig - the field `vitestConfig` of the lane
652
665
  */
653
666
  function leavingPaths(files, vitestConfig) {
667
+ return loadWalk(files, vitestConfig).leaving.toSorted(byPlace);
668
+ }
669
+ /** This function orders places by file, then by line. */
670
+ function byPlace(a, b) {
671
+ if (a.file === b.file) return a.line - b.line;
672
+ return a.file < b.file ? -1 : 1;
673
+ }
674
+ /** This function walks the files that the run loads, from the test files and the config files. It gives them and the paths that leave the folder. */
675
+ function loadWalk(files, vitestConfig) {
654
676
  const texts = new Map(files.map((f) => [f.file, f.text]));
655
677
  const known = new Set(texts.keys());
656
678
  const queue = files.map((f) => f.file).filter((f) => TEST$1.test(f) || isConfigFile(f, vitestConfig));
657
679
  const loaded = new Set(queue);
658
- const found = [];
659
- for (let next = queue.shift(); next !== void 0; next = queue.shift()) for (const { line, path } of pathsOf(next, texts.get(next) ?? "", vitestConfig)) if (leaves(next, path)) found.push({
680
+ const leaving = [];
681
+ for (let next = queue.shift(); next !== void 0; next = queue.shift()) for (const { line, path } of pathsOf(next, texts.get(next) ?? "", vitestConfig)) if (leaves(next, path)) leaving.push({
660
682
  file: next,
661
683
  line,
662
684
  path
@@ -668,7 +690,26 @@ function leavingPaths(files, vitestConfig) {
668
690
  queue.push(t);
669
691
  }
670
692
  }
671
- return found.toSorted((a, b) => a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1);
693
+ return {
694
+ loaded,
695
+ leaving
696
+ };
697
+ }
698
+ const COMPUTED_IMPORT = /\bimport\s*\(\s*(?!(["'])[^"'`\r\n]*\1|`[^`$\r\n]*`)/;
699
+ /**
700
+ * This function gives each dynamic import with a computed path in the files that the run loads. The related walk of
701
+ * Vitest does not follow this type of import. So no selection starts a test file that reaches the mutated files only through
702
+ * it, and each mutant of these files survives. The function does not read comments and config files.
703
+ *
704
+ * @param files - the files of the package, from its folder
705
+ * @param vitestConfig - the field `vitestConfig` of the lane
706
+ */
707
+ function computedImports(files, vitestConfig) {
708
+ const { loaded } = loadWalk(files, vitestConfig);
709
+ return files.filter((f) => loaded.has(f.file) && !isConfigFile(f.file, vitestConfig)).flatMap((f) => f.text.split("\n").flatMap((lineText, i) => COMMENT.test(lineText) || !COMPUTED_IMPORT.test(lineText) ? [] : [{
710
+ file: f.file,
711
+ line: i + 1
712
+ }])).toSorted(byPlace);
672
713
  }
673
714
  const TYPE_STATEMENT = /^[ \t]*(?:import|export)[ \t]+type\b[^;]*;/gm;
674
715
  /** This function replaces each type import and export with its line ends, so the lines of the other paths stay. */
@@ -704,6 +745,138 @@ function relatedTestFiles(files, selected) {
704
745
  };
705
746
  return files.map((f) => f.file).filter((f) => TEST$1.test(f) && reaches(f));
706
747
  }
748
+ /**
749
+ * This function gives the reason of each fault of a collect. A test file that does not load gives no failed test, so
750
+ * each mutant that it detects survives (V-090 of Vex). A test file with no test detects no mutant. An error outside a
751
+ * test file and a package with no test file are faults too.
752
+ */
753
+ function collectFaults(collected) {
754
+ const faults = collected.files.flatMap((f) => {
755
+ if (f.errors.length > 0) return [`${f.file}: the file does not load: ${f.errors.join(" ")}`];
756
+ return f.children === 0 ? [`${f.file}: the file holds no test`] : [];
757
+ });
758
+ faults.push(...collected.unhandled.map((e) => `an error outside a test file: ${e}`));
759
+ if (collected.files.length === 0) faults.push("Vitest finds no test file");
760
+ return faults;
761
+ }
762
+ // src/sandbox.ts
763
+ /**
764
+ * The copy of `load-check --collect`. Stryker copies the files of a package to its sandbox, and it leaves out each file
765
+ * of its ignore rules. This copy takes the same files. So a test file loads in the copy only if it loads in Stryker.
766
+ * The walk is a port of `resolveInputFileNames` of `project-reader.js` in `@stryker-mutator/core` 10.
767
+ */
768
+ /** The rules that Stryker 10 applies to each project (`ALWAYS_IGNORE` of `project-reader.js`). */
769
+ const ALWAYS_IGNORE = [
770
+ "node_modules",
771
+ ".git",
772
+ "*.tsbuildinfo",
773
+ "/stryker.log",
774
+ ".next",
775
+ ".nuxt",
776
+ ".svelte-kit"
777
+ ];
778
+ const text = (value, otherwise) => typeof value === "string" ? value : otherwise;
779
+ const fileName = (reporter) => {
780
+ if (typeof reporter !== "object" || reporter === null) return void 0;
781
+ const name = reporter.fileName;
782
+ return typeof name === "string" ? name : void 0;
783
+ };
784
+ /**
785
+ * This function gives the ignore rules of Stryker for a Stryker config, in the order of Stryker. The defaults of
786
+ * `tempDirName`, `incrementalFile` and the reporters are the defaults of Stryker 10.
787
+ *
788
+ * @param config - the Stryker config of a selection, from `strykerConfig`
789
+ */
790
+ function ignoreRules(config) {
791
+ const patterns = config["ignorePatterns"];
792
+ return [
793
+ ...ALWAYS_IGNORE,
794
+ tempDirOf(config),
795
+ text(config["incrementalFile"], "reports/stryker-incremental.json"),
796
+ fileName(config["htmlReporter"]) ?? "reports/mutation/mutation.html",
797
+ fileName(config["jsonReporter"]) ?? "reports/mutation/mutation.json",
798
+ ...Array.isArray(patterns) ? patterns.filter((p) => typeof p === "string") : []
799
+ ];
800
+ }
801
+ /** This function gives the folder of the sandboxes of Stryker for a Stryker config. */
802
+ function tempDirOf(config) {
803
+ return text(config["tempDirName"], ".stryker-tmp");
804
+ }
805
+ /**
806
+ * This function gives the `Minimatch` of the Stryker that the folder `dir` resolves. Each folder uses its own Stryker,
807
+ * so the rules match as in its run. It gives a reason when the folder resolves no Stryker.
808
+ */
809
+ function minimatchOf(dir) {
810
+ try {
811
+ const core = createRequire(join(dir, "package.json")).resolve("@stryker-mutator/core/package.json");
812
+ return createRequire(core)("minimatch").Minimatch;
813
+ } catch (e) {
814
+ return `the folder resolves no @stryker-mutator/core, so the check cannot apply the ignore rules of Stryker: ${e instanceof Error ? e.message : String(e)}`;
815
+ }
816
+ }
817
+ /**
818
+ * This function gives each file of the folder `root` that Stryker copies to its sandbox, from `root`, with `/`. A rule
819
+ * with `!` takes a file back. Stryker does not go into a folder that a rule leaves out.
820
+ *
821
+ * @param rules - the ignore rules, from `ignoreRules`
822
+ */
823
+ function sandboxFiles(root, rules, Minimatch) {
824
+ const matchers = rules.map((pattern) => new Minimatch(pattern, {
825
+ dot: true,
826
+ flipNegate: true,
827
+ nocase: true
828
+ }));
829
+ const matchesFile = (name, path, rule) => rule.match(name) || rule.match(path) || rule.match(`/${path}`);
830
+ const matchesDirectory = (name, path, rule) => matchesFile(name, path, rule) || rule.match(`/${path}/`) || rule.match(`${path}/`) || rule.negate && (rule.match(`/${path}`, true) || rule.match(path, true));
831
+ const files = [];
832
+ const crawl = (relativeDir) => {
833
+ for (const entry of readdirSync(join(root, relativeDir), { withFileTypes: true })) {
834
+ const path = relativeDir === "" ? entry.name : `${relativeDir}/${entry.name}`;
835
+ let included = true;
836
+ for (const rule of matchers) {
837
+ if (rule.negate === included) continue;
838
+ if (entry.isDirectory() ? matchesDirectory(entry.name, path, rule) : matchesFile(entry.name, path, rule)) included = rule.negate;
839
+ }
840
+ if (!included) continue;
841
+ if (entry.isDirectory()) crawl(path);
842
+ else files.push(path);
843
+ }
844
+ };
845
+ crawl("");
846
+ return files.toSorted();
847
+ }
848
+ /**
849
+ * This function copies the files of `sandboxFiles` to a new folder in `<dir>/<tempDir>`, as Stryker makes its sandbox.
850
+ * It links the `node_modules` of the folder. On an error it removes the part of the copy that it made.
851
+ */
852
+ function copyOfFolder(dir, files, tempDir) {
853
+ const base = join(dir, tempDir);
854
+ mkdirSync(base, { recursive: true });
855
+ const copy = mkdtempSync(join(base, "load-check-"));
856
+ try {
857
+ for (const file of files) {
858
+ mkdirSync(dirname(join(copy, file)), { recursive: true });
859
+ copyFileSync(join(dir, file), join(copy, file));
860
+ }
861
+ if (existsSync(join(dir, "node_modules"))) symlinkSync(join(dir, "node_modules"), join(copy, "node_modules"), "junction");
862
+ return copy;
863
+ } catch (e) {
864
+ removeCopy(copy);
865
+ throw e;
866
+ }
867
+ }
868
+ /** This function removes a copy of `copyOfFolder`, and its folder of sandboxes when nothing else is in it. */
869
+ function removeCopy(copy) {
870
+ rmSync(copy, {
871
+ recursive: true,
872
+ force: true
873
+ });
874
+ const base = dirname(copy);
875
+ if (existsSync(base) && readdirSync(base).length === 0) rmSync(base, {
876
+ recursive: true,
877
+ force: true
878
+ });
879
+ }
707
880
  // src/run.ts
708
881
  /**
709
882
  * The CLI `rigor-mutation`. The work is in `runCli`, so a test can start the CLI in a fixture folder.
@@ -736,9 +909,16 @@ const HELP = `rigor-mutation: the mutation tests of a repository, with Stryker a
736
909
  fails for a test file that no report reads, and for an
737
910
  entry of "notRead" that is not true.
738
911
  rigor-mutation disables [--write] compare the disable comments with their list
739
- rigor-mutation load-check [<selection>...] refuse each relative path of a package that leaves its folder.
912
+ rigor-mutation load-check [<selection>...] [--collect] [--runner <file>]
913
+ refuse each relative path of a package that leaves its folder.
740
914
  Stryker starts the tests in a copy of the folder, so such a
741
915
  path finds no file. No selection checks each package.
916
+ With --collect, the Vitest of each package also loads each
917
+ test file in a copy of the folder, as Stryker does. A file
918
+ that does not load, has no test or that no selection
919
+ starts fails, and so does a computed dynamic import that
920
+ "computedImports" does not name. With --runner, the
921
+ version and the path of each Vitest go in the file.
742
922
 
743
923
  --lane <file> the lane file. The default is mutation.json.
744
924
  --changed <file> a file with one changed path on each line, from the folder of the lane file,
@@ -770,10 +950,90 @@ function sourcesOf(root, dir, tests = false) {
770
950
  return e.isFile() && SOURCE.test(e.name) && (tests || !TEST.test(e.name)) ? [relative(root, path).replaceAll("\\", "/")] : [];
771
951
  });
772
952
  }
773
- /** This function checks the relative paths of the package of each selection (`load-check`). */
774
- function loadCheck(lane, laneDir, names, io) {
953
+ /** The script of `load-check --collect`. It is beside this file, in the source and in the build. */
954
+ const COLLECT_SCRIPT = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./collect.ts" : "./collect.js", import.meta.url));
955
+ /**
956
+ * This function starts the collect of Vitest in a copy of the folder `dir`, in a new process. The copy takes the files
957
+ * that Stryker copies to its sandbox. The function gives the collect, or the reason when the process gives no collect.
958
+ *
959
+ * @param selections - the mutated files of each selection, from `dir`
960
+ * @param config - the Stryker config of the package, for its ignore rules
961
+ */
962
+ function collectIn(dir, vitestConfig, selections, config) {
963
+ const Minimatch = minimatchOf(dir);
964
+ if (typeof Minimatch === "string") return Minimatch;
965
+ const tmp = mkdtempSync(join(tmpdir(), "rigor-mutation-collect-"));
966
+ try {
967
+ const copy = copyOfFolder(dir, sandboxFiles(dir, ignoreRules(config), Minimatch), tempDirOf(config));
968
+ try {
969
+ const out = join(tmp, "collected.json");
970
+ const request = {
971
+ dir: copy,
972
+ ...vitestConfig === void 0 ? {} : { config: vitestConfig },
973
+ selections
974
+ };
975
+ writeFileSync(join(tmp, "request.json"), JSON.stringify(request));
976
+ const r = spawnSync(process.execPath, [
977
+ COLLECT_SCRIPT,
978
+ join(tmp, "request.json"),
979
+ out
980
+ ], {
981
+ cwd: copy,
982
+ encoding: "utf8",
983
+ maxBuffer: 67108864
984
+ });
985
+ if (!existsSync(out)) {
986
+ const why = (r.error?.message ?? `${r.stdout}${r.stderr}`).trim().split("\n").slice(-5).join(" ");
987
+ return `the collect of Vitest exited with ${String(r.status)}: ${why}`;
988
+ }
989
+ return JSON.parse(readFileSync(out, "utf8"));
990
+ } finally {
991
+ removeCopy(copy);
992
+ }
993
+ } finally {
994
+ rmSync(tmp, {
995
+ recursive: true,
996
+ force: true
997
+ });
998
+ }
999
+ }
1000
+ /**
1001
+ * This function gives the faults of the collect of a package (`load-check --collect`). A test file that does not load
1002
+ * is a fault. A test file that no selection starts is a fault (LANE.FILES). A computed dynamic import that the lane
1003
+ * does not name is a fault.
1004
+ */
1005
+ function collectCheck(lane, laneDir, pkg, files) {
1006
+ const p = lane.packages[pkg];
1007
+ if (p === void 0) return {
1008
+ faults: [],
1009
+ collected: void 0
1010
+ };
1011
+ const own = runSelections(lane).map((n) => select(lane, n)).filter((s) => s.pkg === pkg);
1012
+ const sources = files.map((f) => f.file).filter((f) => !TEST.test(f));
1013
+ const mutated = Object.fromEntries(own.map((s) => [s.name, sources.filter((f) => globsSelect(s.mutate, f))]));
1014
+ const config = own[0] === void 0 ? {} : strykerConfig(own[0]);
1015
+ const collected = collectIn(resolve(laneDir, p.dir), p.vitestConfig, mutated, config);
1016
+ const computed = computedImports(files, p.vitestConfig);
1017
+ const allowed = p.computedImports ?? {};
1018
+ const faults = [...computed.filter((c) => allowed[c.file] === void 0).map((c) => `${c.file}:${String(c.line)}: a dynamic import with a computed path. The related mode of Vitest does not follow it, so a test file that reaches the mutated files only through it starts in no selection. Import the file by its path, or give the reason in "computedImports"`), ...Object.keys(allowed).filter((f) => !computed.some((c) => c.file === f)).map((f) => `"computedImports" is not true: ${f} has no dynamic import with a computed path that the run loads`)];
1019
+ if (typeof collected === "string") return {
1020
+ faults: [collected, ...faults],
1021
+ collected: void 0
1022
+ };
1023
+ const onDisk = files.map((f) => f.file).filter((f) => TEST.test(f));
1024
+ const { unread, stale } = readFaults(new Set(own.flatMap((s) => runsAllTests(s) ? onDisk : collected.selections[s.name] ?? [])), onDisk, p.notRead);
1025
+ faults.push(...collectFaults(collected), ...unread.map((f) => `${f}: no selection starts the file, and "notRead" does not give its reason`), ...stale.map((f) => `"notRead" is not true: ${f} is not on the disk, or a selection starts it`));
1026
+ return {
1027
+ faults,
1028
+ collected
1029
+ };
1030
+ }
1031
+ /** This function checks the relative paths of the package of each selection, and with `--collect`, the load of each test file (`load-check`). */
1032
+ function loadCheck(lane, laneDir, names, io, options) {
775
1033
  const pkgs = [...new Set(names.length === 0 ? Object.keys(lane.packages) : names.map((n) => select(lane, n).pkg))];
776
1034
  let failed = 0;
1035
+ let unread = 0;
1036
+ const runners = {};
777
1037
  for (const pkg of pkgs) {
778
1038
  const s = select(lane, pkg);
779
1039
  const dir = resolve(laneDir, s.dir);
@@ -788,10 +1048,28 @@ function loadCheck(lane, laneDir, names, io) {
788
1048
  if (found.length === 0) io.stdout(`load-check ${pkg}: ${String(files.length)} files, no relative path leaves ${s.dir}
789
1049
  `);
790
1050
  else failed += 1;
1051
+ if (!options.collect) continue;
1052
+ const { faults, collected } = collectCheck(lane, laneDir, pkg, files);
1053
+ for (const fault of faults) io.stderr(`${s.dir}: ${fault}\n`);
1054
+ if (collected !== void 0) {
1055
+ runners[pkg] = {
1056
+ version: collected.version,
1057
+ path: collected.path
1058
+ };
1059
+ if (faults.length === 0) io.stdout(`load-check ${pkg}: Vitest ${collected.version} loads ${String(collected.files.length)} test files in a copy of ${s.dir}, and the selections start each one\n`);
1060
+ }
1061
+ if (faults.length > 0) unread += 1;
1062
+ }
1063
+ if (options.runner !== void 0) {
1064
+ const file = resolve(io.cwd, options.runner);
1065
+ mkdirSync(dirname(file), { recursive: true });
1066
+ writeFileSync(file, `${JSON.stringify(runners, null, 2)}\n`);
791
1067
  }
792
1068
  if (failed > 0) io.stderr(`load-check: ${String(failed)} packages have a relative path that leaves their folder. Import the file from its package, or move it into the folder.
793
1069
  `);
794
- return failed > 0 ? 1 : 0;
1070
+ if (unread > 0) io.stderr(`No read: ${String(unread)} packages have a test file that Vitest does not load, that holds no test, or that no selection starts. A mutant that only this file detects survives, so a score of the package is not a reading.
1071
+ `);
1072
+ return failed > 0 || unread > 0 ? 1 : 0;
795
1073
  }
796
1074
  const readJson = (file) => JSON.parse(readFileSync(file, "utf8"));
797
1075
  /**
@@ -1085,6 +1363,11 @@ function runCli(argv, io) {
1085
1363
  type: "boolean",
1086
1364
  default: false
1087
1365
  },
1366
+ collect: {
1367
+ type: "boolean",
1368
+ default: false
1369
+ },
1370
+ runner: { type: "string" },
1088
1371
  help: {
1089
1372
  type: "boolean",
1090
1373
  default: false
@@ -1151,12 +1434,15 @@ function runCli(argv, io) {
1151
1434
  alone: values.alone
1152
1435
  }, io);
1153
1436
  case "disables": return disables(lane, laneDir, values.write, io);
1154
- case "load-check": return loadCheck(lane, laneDir, names, io);
1437
+ case "load-check": return loadCheck(lane, laneDir, names, io, {
1438
+ collect: values.collect,
1439
+ runner: values.runner
1440
+ });
1155
1441
  default:
1156
1442
  io.stderr(`unknown command "${command}"\n\n${HELP}`);
1157
1443
  return 1;
1158
1444
  }
1159
1445
  }
1160
- export { STRYKER_OWNED as C, runSelections as D, partErrors as E, select as O, strykerConfig as S, parseLane as T, NO_TSCONFIG as _, relatedTestFiles as a, TIMEOUT_MS as b, formatScore as c, parsePartial as d, parseReport as f, DRY_RUN_TIMEOUT_MINUTES as g, summaryMarkdown as h, leavingPaths as i, selectionNames as k, isHitLimit as l, scoreReport as m, runCli as n, compareDisables as o, partialScore as p, isConfigFile as r, findDisables as s, HELP as t, packageScore as u, PARTIAL_PLUGIN as v, changedFiles as w, rewritesTsconfig as x, REPORT_DIR as y };
1446
+ 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 };
1161
1447
 
1162
- //# sourceMappingURL=run-B5WrsoMv.js.map
1448
+ //# sourceMappingURL=run-BvctkYlJ.js.map