forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBd305564Tahinli6 days ago3939 commits

mutate.py62 lines, 2.1 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Apply or revert one cargo-mutants mutant in place, from `cargo mutants --list --json`.
3
4Used by scripts/kill-matrix.sh on a scratch copy of the tree (never on the local checkout).
5
6 mutate.py apply <mutants.json> <index> <root> # writes the mutated file, saves the original
7 mutate.py revert <root> # restores every file saved by apply
8
9The original bytes are kept in <root>/.mutate-backup/ so revert is exact.
10"""
11import json
12import os
13import shutil
14import sys
15
16
17def offset(text_lines, line, col):
18 # cargo-mutants spans are 1-based line and 1-based char column (inclusive start, exclusive end).
19 return sum(len(l) for l in text_lines[: line - 1]) + (col - 1)
20
21
22def apply(json_path, index, root):
23 mutants = json.load(open(json_path))
24 m = mutants[index]
25 rel = m["file"]
26 path = os.path.join(root, rel)
27 backup_dir = os.path.join(root, ".mutate-backup")
28 os.makedirs(backup_dir, exist_ok=True)
29 backup = os.path.join(backup_dir, rel.replace("/", "__"))
30 if not os.path.exists(backup):
31 shutil.copy2(path, backup)
32 with open(path, encoding="utf-8", newline="") as f:
33 text = f.read()
34 lines = text.splitlines(keepends=True)
35 s = m["span"]["start"]
36 e = m["span"]["end"]
37 a = offset(lines, s["line"], s["column"])
38 b = offset(lines, e["line"], e["column"])
39 original = text[a:b]
40 new = text[:a] + m["replacement"] + text[b:]
41 with open(path, "w", encoding="utf-8", newline="") as f:
42 f.write(new)
43 print(f"mutant {index}: {rel}:{s['line']}:{s['column']} {original!r} -> {m['replacement']!r}")
44
45
46def revert(root):
47 backup_dir = os.path.join(root, ".mutate-backup")
48 if not os.path.isdir(backup_dir):
49 return
50 for name in os.listdir(backup_dir):
51 rel = name.replace("__", "/")
52 shutil.copy2(os.path.join(backup_dir, name), os.path.join(root, rel))
53 os.remove(os.path.join(backup_dir, name))
54
55
56if __name__ == "__main__":
57 if sys.argv[1] == "apply":
58 apply(sys.argv[2], int(sys.argv[3]), sys.argv[4])
59 elif sys.argv[1] == "revert":
60 revert(sys.argv[2])
61 else:
62 sys.exit(__doc__)