diff --git a/bin/mutate_changes/changed_lines.py b/bin/mutate_changes/changed_lines.py index a7a7abce..e45c6065 100644 --- a/bin/mutate_changes/changed_lines.py +++ b/bin/mutate_changes/changed_lines.py @@ -7,9 +7,9 @@ import typing # A hunk header of `git diff -U0`. The new side's count is 0 where the hunk only deletes, and left out where it is 1. HUNK = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@", re.MULTILINE) STRYKER = (".cjs", ".cts", ".js", ".jsx", ".mjs", ".mts", ".ts", ".tsx") -TOOLS = {".php": "infection", ".py": "mutmut", ".rs": "cargo-mutants", **dict.fromkeys(STRYKER, "stryker")} +TOOLS = {".go": "gremlins", ".php": "infection", ".py": "mutmut", ".rs": "cargo-mutants", **dict.fromkeys(STRYKER, "stryker")} TEST_FOLDERS = frozenset({"__tests__", "test", "tests"}) -TEST_NAME = re.compile(r"test_.*\.py|.*_test\.py|conftest\.py|.*\.(?:spec|test)\.[^.]+") +TEST_NAME = re.compile(r"test_.*\.py|.*_test\.py|conftest\.py|.*_test\.go|.*\.(?:spec|test)\.[^.]+") def added_lines(diff: str) -> frozenset[int]: diff --git a/bin/mutate_changes/in_diff_tools.py b/bin/mutate_changes/in_diff_tools.py index fbe9611a..7dfb6313 100644 --- a/bin/mutate_changes/in_diff_tools.py +++ b/bin/mutate_changes/in_diff_tools.py @@ -1,6 +1,8 @@ -"""Mutate a branch's changed lines with cargo-mutants, Stryker and Infection, each of which takes the changed lines itself.""" +"""Mutate a branch's changed lines with cargo-mutants, Gremlins, Stryker and Infection, each of which takes the changed lines itself.""" +import json import os import pathlib +import typing from mutate_changes.changed_lines import by_folder, label, runs from mutate_changes.tool_process import failed, Ran, remove, Run, scratch_folder @@ -10,6 +12,8 @@ from git_cli.git_repo import Git # cargo-mutants' exit codes for a run that finished: every mutant caught, some missed, and some timed out. CARGO_FINISHED = frozenset({0, 2, 3}) CARGO_OUTCOMES = ("caught", "missed", "timeout", "unviable") +# The statuses in Gremlins' report of a mutant that its tests don't kill. +GREMLINS_UNKILLED = frozenset({"LIVED", "NOT COVERED"}) def run_cargo_mutants(top: str, base: str, paths: list[str], run: Run, git: Git, jobs: int) -> list[str] | Failure: @@ -38,6 +42,39 @@ def run_cargo_mutants(top: str, base: str, paths: list[str], run: Run, git: Git, return [f"cargo-mutants: {sum(map(len, outcomes.values()))} mutants on changed lines, {len(uncaught)} not caught.", *uncaught] +def run_gremlins(top: str, base: str, run: Run, jobs: int) -> list[str] | Failure: + """A line with the number of mutants Gremlins reports as lived or not covered, then a line per mutant, as + `::: : `. + + Gremlins runs in top and mutates the Go lines the branch changes since base. It skips test files itself. Its git needs `run` to + hold the settings that `with_zero_diff_context` adds to an environment.""" + scratch = scratch_folder(top) + if isinstance(scratch, Failure): + return scratch + try: + report = os.path.join(os.path.relpath(scratch, top), "report.json") + ran = run(["gremlins", "unleash", "--diff", base, "--output", report, "--workers", str(jobs)], top) + if isinstance(ran, Failure) or ran.code: + return ran if isinstance(ran, Failure) else failed("gremlins", ran) + # Gremlins writes `null` for a list with no entry. + files = json.loads(pathlib.Path(scratch, "report.json").read_text(encoding="utf-8"))["files"] or [] + unkilled = sorted((file["file_name"], mutant["line"], mutant["column"], mutant["status"], mutant["type"]) for file in files for mutant in file["mutations"] or [] if mutant["status"] in GREMLINS_UNKILLED) + except (OSError, ValueError, KeyError, TypeError) as failure: + return Failure(f"could not read Gremlins' report in {scratch}: {failure}") + finally: + remove(scratch) + return [f"gremlins: {len(unkilled)} mutants not killed.", *(f"{path}:{line}:{column}: {status}: {mutator}" for path, line, column, status, mutator in unkilled)] + + +def with_zero_diff_context(env: typing.Mapping[str, str]) -> dict[str, str]: + """env with git set, through its GIT_CONFIG_* variables, to print no context lines around a change, after any setting env holds. + + Gremlins v0.6.0 mutates one run of lines per hunk, so a hunk must hold only the lines the branch changes.""" + held = env.get("GIT_CONFIG_COUNT", "0") + count = int(held) if held.isdecimal() else 0 + return {**env, "GIT_CONFIG_COUNT": str(count + 1), f"GIT_CONFIG_KEY_{count}": "diff.context", f"GIT_CONFIG_VALUE_{count}": "0"} + + def outcome_lines(path: pathlib.Path) -> list[str]: return path.read_text(encoding="utf-8", errors="replace").splitlines() if path.is_file() else [] diff --git a/bin/mutate_changes/main.py b/bin/mutate_changes/main.py index a984b473..503072e8 100644 --- a/bin/mutate_changes/main.py +++ b/bin/mutate_changes/main.py @@ -16,6 +16,8 @@ or __tests__/ folder. in its own process, so a mutant that only a child process reaches, such as a tool a test starts, shows as `no tests`. A pyproject.toml with a [tool.mutmut] section fails the run. A crash inside mutmut, such as a KeyError in its worker pool, becomes one line for its folder, naming the error and telling you to mutate that folder's changed lines by hand. +- .go: Gremlins, as `gremlins unleash --diff`, in the checkout's top. It skips *_test.go itself. Its git runs with diff.context=0, + set in GIT_CONFIG_* variables after any the environment holds, since Gremlins v0.6.0 mutates one run of lines per hunk. - .rs: cargo-mutants, as `cargo mutants --in-diff`, in the checkout's top. - .cjs, .cts, .js, .jsx, .mjs, .mts, .ts, .tsx: Stryker, as `npx --no --package=@stryker-mutator/core stryker run --mutate` on the changed lines, in the nearest folder above the file that holds a package.json. A file with no package.json above it isn't @@ -25,8 +27,12 @@ or __tests__/ folder. --prefix is shell text that runs each tool: sh runs ` "$@"` in the tool's folder, which $PWD names, with the tool's command as "$@". For example, 'uvx --from "mutmut>=3,<4"'. Without --prefix, the command runs as it is. A container must mount $PWD and run there, as 'docker compose -f "$(git rev-parse --show-toplevel)/compose.yaml" run --rm -v "$PWD:$PWD" -w "$PWD" app' does. "$1" -is the command's first word, mutmut, cargo, npx or vendor/bin/infection, so a prefix can pick what to run per tool: +is the command's first word, mutmut, cargo, gremlins, npx or vendor/bin/infection, so a prefix can pick what to run per tool: 'case "$1" in mutmut) set -- uvx --from "mutmut>=3,<4" "$@";; esac;'. +Gremlins' git runs in the container too. In a git worktree, git keeps its data in the main checkout, outside $PWD, so the container +mounts that folder as well, and it passes on the GIT_CONFIG_* variables that set diff.context, as `-e GIT_CONFIG_COUNT -e +GIT_CONFIG_KEY_0 -e GIT_CONFIG_VALUE_0` where the environment holds no setting of its own, and one more KEY and VALUE for each it holds: +'common="$(git rev-parse --path-format=absolute --git-common-dir)"; docker run --rm -v "$PWD:$PWD" -v "$common:$common" -w "$PWD" -e GIT_CONFIG_COUNT -e GIT_CONFIG_KEY_0 -e GIT_CONFIG_VALUE_0 "$@"'. --jobs sets how many tests each tool runs at once, 4 by default: one heavy slot's CPUs. Under run-heavy, a container that sets neither memory limit gets the slot's share, in MiB in RUN_HEAVY_MEMORY; set --jobs so that that many test runs fit in it. @@ -34,6 +40,8 @@ neither memory limit gets the slot's share, in MiB in RUN_HEAVY_MEMORY; set --jo It prints: - for mutmut, per folder, a line with the mutant count, then a line per mutant on a changed line that is not killed, as `:: : `, or `: : , on a line mutate-changes cannot find`; +- for Gremlins, a line with the number of mutants not killed, then a line per mutant that lived or is not covered, as + `::: : `; - for cargo-mutants, a line with the mutant count, then a line per mutant it missed or that timed out, as `::: : `; - for Stryker and Infection, a line naming the folder the tool ran in, then the tool's own report; @@ -57,7 +65,7 @@ from machine_load.slots import CPUS_PER_SLOT from git_cli.git_repo import default_ref, Git, top from failure import Failure from git_cli import git_repo -from mutate_changes.in_diff_tools import run_cargo_mutants, run_infection, run_stryker +from mutate_changes.in_diff_tools import run_cargo_mutants, run_gremlins, run_infection, run_stryker, with_zero_diff_context from mutate_changes.mutmut_tool import run_mutmut from mutate_changes.tool_process import run_tool @@ -125,6 +133,8 @@ def mutate(given: dict[str, str], env: typing.Mapping[str, str]) -> list[str] | for tool, files in sorted(changed.items()): if tool == "cargo-mutants": lines = run_cargo_mutants(checkout, merge_base, sorted(files), run, git, jobs) + elif tool == "gremlins": + lines = run_gremlins(checkout, merge_base, functools.partial(run, env=with_zero_diff_context(env)), jobs) elif tool == "infection": lines = run_infection(checkout, merge_base, run, jobs) elif tool == "stryker": diff --git a/bin/mutate_changes/test_mutate_changes.py b/bin/mutate_changes/test_mutate_changes.py index bcec2115..93e35949 100644 --- a/bin/mutate_changes/test_mutate_changes.py +++ b/bin/mutate_changes/test_mutate_changes.py @@ -66,12 +66,14 @@ class ChangedLines(unittest.TestCase): "src/Order.php": "infection", "web/app.tsx": "stryker", "web/app.mjs": "stryker", + "cmd/serve/main.go": "gremlins", "bin/x/test_main.py": None, "bin/x/main_test.py": None, "pkg/conftest.py": None, "tests/helpers.py": None, "web/app.test.ts": None, "web/app.spec.js": None, + "cmd/serve/main_test.go": None, "web/__tests__/a.js": None, "README.md": None, } @@ -140,8 +142,8 @@ class ChangedLines(unittest.TestCase): self.assertEqual(crash_in_mutmut(trace((f"{lib}/x.py", 1), error="")), None) def test_not_mutated_names_the_files_no_tool_covers_then_the_test_files(self): - self.assertEqual(not_mutated(["README.md", "a.py", "b.go", "test_a.py", "web/a.test.ts"]), ["Not mutated, as no tool covers their language: README.md, b.go.", "Not mutated, as test files: test_a.py, web/a.test.ts."]) - self.assertEqual((not_mutated(["a.py", "test_a.py"]), not_mutated(["a.py", "b.go"]), not_mutated([])), (["Not mutated, as test files: test_a.py."], ["Not mutated, as no tool covers their language: b.go."], [])) + self.assertEqual(not_mutated(["README.md", "a.py", "b.rb", "test_a.py", "web/a.test.ts"]), ["Not mutated, as no tool covers their language: README.md, b.rb.", "Not mutated, as test files: test_a.py, web/a.test.ts."]) + self.assertEqual((not_mutated(["a.py", "test_a.py"]), not_mutated(["a.py", "b.rb"]), not_mutated([])), (["Not mutated, as test files: test_a.py."], ["Not mutated, as no tool covers their language: b.rb."], [])) class MutmutSetup(unittest.TestCase): diff --git a/bin/mutate_changes/test_mutate_changes_runs.py b/bin/mutate_changes/test_mutate_changes_runs.py index a468094b..68bd4e79 100644 --- a/bin/mutate_changes/test_mutate_changes_runs.py +++ b/bin/mutate_changes/test_mutate_changes_runs.py @@ -62,10 +62,11 @@ else: print("Traceback (most recent call last):\n File \"/uv/site-packages/mutmut/__main__.py\", line 1050, in _run\n File \"/uv/site-packages/mutmut/workers/isolation.py\", line 889, in wait_for_result\n worker = pop(pid)\nKeyError: 974598") sys.exit(1) """ -# cargo-mutants, Infection and Stryker, which log the folder they run in and how they were called, and exit with the code the test +# cargo-mutants, Gremlins, Infection and Stryker, which log the folder they run in and how they were called, and exit with the code the test # gives. cargo-mutants also logs the diff it is given and writes its outcome files, all but unviable.txt, as a run without an # unviable mutant does; with CAUGHT_UNREADABLE set, nobody may read caught.txt, and with OUTPUT_LOCKED, nobody may delete from mutants.out. -FAKE_TOOLS = r"""import os, pathlib, sys +# Gremlins also logs the git settings it finds in its environment and writes a JSON report in Gremlins' shape, with BAD_REPORT set not JSON. +FAKE_TOOLS = r"""import json, os, pathlib, sys log, code, args = pathlib.Path(sys.argv[1]), int(sys.argv[2]), sys.argv[3:] with log.open("a") as written: written.write(f"{os.getcwd()}\n{' '.join(args)}\n") @@ -80,6 +81,13 @@ with log.open("a") as written: (outcomes / "caught.txt").chmod(0) if os.environ.get("OUTPUT_LOCKED"): outcomes.chmod(0o555) + if args[0] == "gremlins": + git_config = (name for name in sorted(os.environ) if name.startswith(("GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_", "GIT_CONFIG_VALUE_"))) + written.write("".join(f"{name}={os.environ[name]}\n" for name in git_config)) + killed, skipped, uncovered, lived = (dict(type=kind, status=status, line=line, column=column) for kind, status, line, column in (("ARITHMETIC_BASE", "KILLED", 4, 11), ("CONDITIONALS_BOUNDARY", "SKIPPED", 8, 11), ("CONDITIONALS_BOUNDARY", "NOT COVERED", 12, 11), ("ARITHMETIC_BASE", "LIVED", 4, 15))) + files = [dict(file_name="calc.go", mutations=[killed, skipped, uncovered, lived]), dict(file_name="sub/other.go", mutations=[dict(type="INVERT_NEGATIVES", status="LIVED", line=2, column=9)])] + report = "not json" if os.environ.get("BAD_REPORT") else json.dumps(dict(go_module="x", files=files)) + pathlib.Path(args[args.index("--output") + 1]).write_text(report) print(f"{args[0]} reports") sys.exit(code) """ @@ -404,6 +412,49 @@ class MutateChangesRuns(unittest.TestCase): self.assertRegex(ran.stderr, rf"^could not hand cargo-mutants the diff or read its outcomes in {re.escape(str(self.checkout.resolve()))}/\.mutate-changes-\w+: ") self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "README.md", "package.json", "pkg", "src", "web"]) + def change_go(self): + """Commit a Go file and its test, then change both.""" + (self.checkout / "calc.go").write_text("package calc\n\nfunc Add(a, b int) int {\n\treturn a + b\n}\n") + (self.checkout / "calc_test.go").write_text("package calc\n") + self.commit() + (self.checkout / "calc.go").write_text("package calc\n\nfunc Add(a, b int) int {\n\treturn a + b + 0\n}\n") + (self.checkout / "calc_test.go").write_text("package calc\n\nfunc helper() {}\n") + + def test_go_goes_to_gremlins_at_the_top_and_prints_each_mutant_that_lived_or_is_not_covered(self): + self.change_go() + fake = f"python3 {self.temp / 'fake_tools.py'} {self.log} 0" + ran = self.run_tool("--base", "HEAD", "--jobs=3", "--prefix", fake, cwd=self.checkout / "pkg") + report = ["gremlins: 3 mutants not killed.", "calc.go:4:15: LIVED: ARITHMETIC_BASE", "calc.go:12:11: NOT COVERED: CONDITIONALS_BOUNDARY", "sub/other.go:2:9: LIVED: INVERT_NEGATIVES"] + self.assertEqual((ran.returncode, ran.stdout.splitlines()[:-2], ran.stderr), (0, report, "")) + self.assertEqual(ran.stdout.splitlines()[-2], "Not mutated, as test files: calc_test.go.") + folder, command, config = self.log.read_text().split("\n", 2) + self.assertEqual(folder, str(self.checkout.resolve())) + base = self.git("rev-parse", "HEAD").strip() + self.assertRegex(command, rf"^gremlins unleash --diff {base} --output (\.mutate-changes-\w+)/report\.json --workers 3$") + # Gremlins mutates one run of lines per hunk, so the hunks hold the changed lines and no lines around them. + self.assertEqual(config, "GIT_CONFIG_COUNT=1\nGIT_CONFIG_KEY_0=diff.context\nGIT_CONFIG_VALUE_0=0\n") + self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "README.md", "calc.go", "calc_test.go", "pkg"]) + + def test_gremlins_git_settings_come_after_those_the_environment_holds(self): + self.change_go() + env = {"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "safe.directory", "GIT_CONFIG_VALUE_0": "*"} + self.run_tool("--base", "HEAD", "--prefix", f"python3 {self.temp / 'fake_tools.py'} {self.log} 0", env=env) + config = self.log.read_text().split("\n", 2)[2] + self.assertEqual(config, "GIT_CONFIG_COUNT=2\nGIT_CONFIG_KEY_0=safe.directory\nGIT_CONFIG_KEY_1=diff.context\nGIT_CONFIG_VALUE_0=*\nGIT_CONFIG_VALUE_1=0\n") + + def test_a_gremlins_run_that_fails_or_leaves_no_report_fails_the_run(self): + self.change_go() + fake = f"python3 {self.temp / 'fake_tools.py'} {self.log}" + ran = self.run_tool("--base", "HEAD", "--prefix", f"{fake} 1") + self.assertEqual((ran.returncode, ran.stderr), (1, "gremlins exited 1:\ngremlins reports\n")) + ran = self.run_tool("--base", "HEAD", "--prefix", f"{fake} 0", env={"BAD_REPORT": "1"}) + self.assertEqual(ran.returncode, 1) + self.assertRegex(ran.stderr, rf"^could not read Gremlins' report in {re.escape(str(self.checkout.resolve()))}/\.mutate-changes-\w+: ") + ran = self.run_tool("--base", "HEAD", env={"PATH": str(self.path_with_git())}) + self.assertEqual(ran.returncode, 1) + self.assertRegex(ran.stderr, "^gremlins unleash .* could not start: ") + self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "README.md", "calc.go", "calc_test.go", "pkg"]) + def test_a_branch_that_adds_no_line_a_tool_mutates_says_so_and_names_what_it_changes(self): # A file the branch deletes is no longer there to mutate, so the report doesn't name it. (self.checkout / "pkg" / "old.md").write_text("Gone.\n") @@ -425,6 +476,11 @@ class MutateChangesRuns(unittest.TestCase): ran = self.run_tool(flag) self.assertEqual((ran.returncode, ran.stdout.splitlines()[0]), (0, "Mutation-test the lines a branch adds or changes, and print each mutant its tests don't kill.")) + def test_help_shows_the_gremlins_prefix_that_mounts_gits_data_in_a_worktree(self): + text = self.run_tool("--help").stdout + self.assertIn("-v \"$common:$common\"", text) + self.assertIn("--git-common-dir", text) + def test_unknown_arguments_fail_saying_why(self): usage = "usage: mutate-changes [--base ] [--prefix ] [--jobs ]" for args, reason in ( diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 7dd7c724..c2ed3744 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -3284,3 +3284,7 @@ Read most (opens and searches): - `bin/mutate_changes/mutmut_mutants.py` 2 - `bin/mutate_changes/mutmut_setup.py` 2 - `skills/larv-review/SKILL.md` 2 + +## Reading cost, chunk fbec3b9bb507, finished 2026-11-19T13:23:00Z + +37393 new input tokens before the first commit.