"""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 from failure import Failure 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: """A line with cargo-mutants' mutant count, then a line per mutant it missed or that timed out, as `::: : `. cargo-mutants runs in top.""" # cargo-mutants finds each file's path after a b/, a prefix that settings such as diff.mnemonicPrefix change. diff = git("diff", "--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", base, "--", *paths, cwd=top) if isinstance(diff, Failure): return diff scratch = scratch_folder(top) if isinstance(scratch, Failure): return scratch try: pathlib.Path(scratch, "branch.diff").write_text(diff, encoding="utf-8") relative = os.path.relpath(scratch, top) ran = run(["cargo", "mutants", "--in-diff", os.path.join(relative, "branch.diff"), "--output", relative, "--jobs", str(jobs)], top) if isinstance(ran, Failure) or ran.code not in CARGO_FINISHED: return ran if isinstance(ran, Failure) else failed("cargo mutants", ran) outcomes = {outcome: outcome_lines(pathlib.Path(scratch, "mutants.out", f"{outcome}.txt")) for outcome in CARGO_OUTCOMES} except OSError as failure: return Failure(f"could not hand cargo-mutants the diff or read its outcomes in {scratch}: {failure}") finally: remove(scratch) uncaught = [f"{location}: {outcome}: {mutation}" for outcome in ("missed", "timeout") for location, _, mutation in (line.partition(": ") for line in outcomes[outcome])] 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 [] # Stryker and Infection also exit nonzero on a mutation score below a threshold the project sets, which their exit code doesn't # tell from a run that broke, so either fails the run. def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: int) -> list[str] | Failure: """For each folder Stryker runs in, a line naming it, then Stryker's own report of the mutants on the changed lines. Last, a line naming the files with no package.json above them, if any. Stryker runs in the nearest folder above each file that holds a package.json. npx runs the project's own @stryker-mutator/core, else one an earlier npx run cached, and installs none.""" report: list[str] = [] unplaced: list[str] = [] for folder, files in sorted(by_folder(top, changed, ("package.json",)).items()): # by_folder falls back to top, where no package.json means there is no Stryker to run. if not os.path.isfile(os.path.join(top, folder, "package.json")): unplaced = sorted(files) continue mutate = ",".join(f"{path}:{first}-{last}" for path, lines in sorted(files.items()) for first, last in runs(lines)) ran = run(["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder)) if isinstance(ran, Failure) or ran.code: return ran if isinstance(ran, Failure) else whole_output(f"Stryker in {label(folder)}", ran) report.extend([f"Stryker in {label(folder)}:", *ran.output.splitlines()]) return [*report, *([f"Not mutated, as no package.json is above them: {', '.join(unplaced)}."] if unplaced else [])] def run_infection(top: str, base: str, run: Run, jobs: int) -> list[str] | Failure: """A line naming where Infection ran, top, then its own report of the mutants on the lines the branch changes since base.""" ran = run(["vendor/bin/infection", "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top) if isinstance(ran, Failure) or ran.code: return ran if isinstance(ran, Failure) else whole_output("Infection", ran) return ["Infection in the checkout's top:", *ran.output.splitlines()] def whole_output(name: str, ran: Ran) -> Failure: """A tool's exit code and its whole output. Stryker and Infection also exit nonzero on a mutation score below the project's threshold, where the output is the report of what survived.""" return Failure("\n".join([f"{name} exited {ran.code}:", *ran.output.splitlines()]))