"""Which lines of a file a branch adds or changes, and which mutation tool mutates the file.""" import posixpath import re 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")} TEST_FOLDERS = frozenset({"__tests__", "test", "tests"}) TEST_NAME = re.compile(r"test_.*\.py|.*_test\.py|conftest\.py|.*\.(?:spec|test)\.[^.]+") def added_lines(diff: str) -> frozenset[int]: """The line numbers, in the new file, that a `git diff -U0` of one file adds or changes.""" return frozenset(line for hunk in HUNK.finditer(diff) for line in range(int(hunk[1]), int(hunk[1]) + int(hunk[2] or 1))) def runs(lines: typing.Iterable[int]) -> list[tuple[int, int]]: """The lines as runs of consecutive numbers, each as its first and last line, in order.""" found: list[tuple[int, int]] = [] for line in sorted(lines): if found and found[-1][1] == line - 1: found[-1] = (found[-1][0], line) else: found.append((line, line)) return found def tool_for(path: str) -> str | None: """The tool that mutates a file, by its extension; None for a test file, or a language none of the tools covers.""" folders, name = posixpath.split(path) if TEST_FOLDERS & set(folders.split("/")) or TEST_NAME.fullmatch(name): return None return TOOLS.get(posixpath.splitext(name)[1])