Files
claude-config/bin/mutate_changes/mutmut_mutants.py
T

82 lines
4.6 KiB
Python

"""Which of mutmut 3's mutants the changed lines hold, from their names, `mutmut results` and the copy of each file mutmut writes under mutants/.
mutmut names a mutant `<module>.<key>__mutmut_<number>`. The key is x_<function> for a function at a module's top, and xǁ<class>ǁ<method> for a method of a class there; mutmut mutates no other code. Its mutants/ copy of a file holds the original of each function it mutates, as `<key>__mutmut_orig`, and each mutant as a copy of it."""
import ast
def function_keys(source: str, lines: frozenset[int]) -> list[str]:
"""mutmut's key of each function or method that one of the lines falls in, decorators included, in source order."""
keys = []
for node in ast.parse(source).body:
inner = node.body if isinstance(node, ast.ClassDef) else [node]
for function in inner:
if isinstance(function, (ast.AsyncFunctionDef, ast.FunctionDef)) and lines & set(range(first_line(function), (function.end_lineno or function.lineno) + 1)):
keys.append(f"xǁ{node.name}ǁ{function.name}" if isinstance(node, ast.ClassDef) else f"x_{function.name}")
return keys
def first_line(function: ast.AsyncFunctionDef | ast.FunctionDef) -> int:
return min([function.lineno, *(decorator.lineno for decorator in function.decorator_list)])
def module(path: str) -> str:
"""The module name mutmut gives a file, from its path relative to the folder mutmut runs in."""
return path.removesuffix(".py").replace("/", ".").removeprefix("src.")
def mutant_globs(path: str, keys: list[str]) -> list[str]:
"""The `mutmut run` patterns that pick each function's mutants. A pattern without __mutmut_ also matches the function, so mutmut runs only the tests that reach one of them."""
return [f"{module(path)}.{key}*".replace(".__init__.", ".") for key in keys]
def named(name: str, paths: list[str]) -> tuple[str, str, int] | None:
"""The path, of those given, holding the mutant mutmut names, with its function's key and its number; None where none holds it."""
prefix, _, number = name.rpartition("__mutmut_")
_, _, key = prefix.rpartition(".")
found = [path for path in paths if f"{module(path)}.{key}".replace(".__init__.", ".") == prefix]
return (found[0], key, int(number)) if found and number.isdigit() else None
def statuses(results: str) -> dict[str, str]:
"""Each mutant's status by name, from the ` <name>: <status>` lines `mutmut results --all true` prints."""
return {name: status for name, _, status in (line.strip().partition(": ") for line in results.splitlines()) if "__mutmut_" in name and status}
def mutated_line(source: str, copy: str, key: str, number: int) -> tuple[int, str] | None:
"""The source line a mutant changes, with that line as the mutant has it; None where the mutants/ copy lacks the mutant, or holds an original unlike the source.
A mutant keeps the original's lines, so the first line where they differ sits at the same offset from the source function's def."""
try:
function = defined(ast.parse(source), key)
copied = {node.name: node for node in ast.walk(ast.parse(copy)) if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef))}
except SyntaxError:
return None
original, mutant = copied.get(f"{key}__mutmut_orig"), copied.get(f"{key}__mutmut_{number}")
if function is None or original is None or mutant is None:
return None
expected = as_named(source.splitlines(), function, function.name)
kept, changed = (as_named(copy.splitlines(), node, function.name) for node in (original, mutant))
if kept != expected:
return None
offset = next((index for index, (was, now) in enumerate(zip(kept, changed)) if was != now), None)
return None if offset is None else (function.lineno + offset, changed[offset].strip())
def defined(tree: ast.Module, key: str) -> ast.AsyncFunctionDef | ast.FunctionDef | None:
"""The function or method mutmut's key names, from a module's top or a class there."""
if key.startswith("x_"):
scope, name = tree.body, key.removeprefix("x_")
elif len(parts := key.split("ǁ")) == 3:
_, owner, name = parts
classes = [node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == owner]
scope = classes[0].body if classes else []
else:
return None
return next((node for node in scope if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)) and node.name == name), None)
def as_named(lines: list[str], function: ast.AsyncFunctionDef | ast.FunctionDef, name: str) -> list[str]:
"""A function's lines from its def, decorators left out, with the def naming it name."""
spanned = lines[function.lineno - 1:function.end_lineno]
return [spanned[0].replace(function.name, name, 1), *spanned[1:]] if spanned else []