Measure test coverage of only the lines a change adds, by joining a unified diff with a Cobertura XML or coverage.py JSON report. Use when asked for diff coverage, patch coverage, or whether the new lines of a PR are tested.
95%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Low
Low-risk findings worth noting
#!/usr/bin/env python3
"""Measure test coverage of exactly the lines a change adds or modifies.
Joins a unified diff with a Cobertura XML or coverage.py JSON report. Standard
library only, no network, no environment access, never runs git.
Usage:
python3 diff_coverage.py --diff change.patch --coverage coverage.xml
[--fail-under 80] [--format text|markdown|json]
Exit codes: 0 passed or no threshold, 1 below threshold, 2 usage, I/O or parse error.
"""
import argparse
import json
import re
import sys
import xml.etree.ElementTree as ET
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
MAX_DIFF_BYTES = 10_485_760
MAX_COVERAGE_BYTES = 52_428_800
HUNK_RE = re.compile(r"^@@ -(?P<os>\d+)(?:,(?P<oc>\d+))? \+(?P<ns>\d+)(?:,(?P<nc>\d+))? @@")
class DiffCoverageError(Exception):
"""Failure with a stable code: input_too_large, invalid_diff, unsafe_xml,
invalid_report or ambiguous_path."""
def __init__(self, code, message=""):
super().__init__(message[:200])
self.code = code
def parse_diff_lines(text, max_bytes=MAX_DIFF_BYTES):
"""Return {new_path: {new_line_number: added_line_text}} for every added line."""
if len(text.encode("utf-8")) > max_bytes:
raise DiffCoverageError("input_too_large", "diff input exceeds maximum size")
result = {}
current, skip = None, False
new_line = None
old_left = new_left = 0
for raw in text.splitlines():
line = raw.rstrip("\r")
if new_line is not None:
handled = True
if line.startswith("\\"):
pass
elif line.startswith("+"):
if current is not None and not skip:
result[current][new_line] = line[1:]
new_line += 1
new_left -= 1
elif line.startswith("-"):
old_left -= 1
elif line.startswith(" ") or line == "":
new_line += 1
new_left -= 1
old_left -= 1
else:
handled = False
if handled:
if new_left <= 0 and old_left <= 0:
new_line = None
continue
new_line = None
if line.startswith("+++ "):
path = line[4:].strip()
if path.startswith("b/") or path.startswith("a/"):
path = path[2:]
if path == "/dev/null":
current, skip = None, True
else:
current, skip = path, False
result.setdefault(current, {})
new_line = None
continue
if line.startswith("@@ "):
match = HUNK_RE.match(line)
if not match:
raise DiffCoverageError("invalid_diff", f"invalid hunk header: {line[:80]}")
old_left = int(match.group("oc") or 1)
new_left = int(match.group("nc") or 1)
new_line = int(match.group("ns"))
if new_left <= 0 and old_left <= 0:
new_line = None
return result
def parse_diff(text, max_bytes=MAX_DIFF_BYTES):
"""Return {new_path: set of added new-side line numbers}."""
return {path: set(lines) for path, lines in parse_diff_lines(text, max_bytes).items()}
def _check_size(text, max_bytes):
if len(text.encode("utf-8")) > max_bytes:
raise DiffCoverageError("input_too_large", "coverage input exceeds maximum size")
def _int(value):
try:
return int(value)
except (TypeError, ValueError):
return None
def _normalize(filename):
path = filename.replace("\\", "/")
while path.startswith("./"):
path = path[2:]
return path
def load_cobertura(text, max_bytes=MAX_COVERAGE_BYTES):
"""Return {path: {line: covered}}; a line is covered when any class entry has hits > 0."""
_check_size(text, max_bytes)
lowered = text.lower()
if "<!doctype" in lowered or "<!entity" in lowered:
raise DiffCoverageError("unsafe_xml", "XML input contains DOCTYPE or ENTITY")
try:
root = ET.XML(text)
except ET.ParseError as exc:
raise DiffCoverageError("invalid_report", f"malformed XML: {exc}") from exc
coverage = {}
for cls in root.iter("class"):
filename = cls.get("filename")
if filename is None:
continue
lines = coverage.setdefault(_normalize(filename), {})
for node in cls.findall("lines/line"):
number, hits = _int(node.get("number")), _int(node.get("hits"))
if number is None or hits is None:
continue
if number not in lines or not lines[number]:
lines[number] = hits > 0
return coverage
def load_coverage_json(text, max_bytes=MAX_COVERAGE_BYTES):
"""Return {path: {line: covered}} from a coverage.py JSON report."""
_check_size(text, max_bytes)
try:
data = json.loads(text)
except ValueError as exc:
raise DiffCoverageError("invalid_report", f"invalid JSON: {exc}") from exc
if not isinstance(data, dict) or "files" not in data:
raise DiffCoverageError("invalid_report", "missing 'files' key in coverage JSON")
if not isinstance(data["files"], dict):
raise DiffCoverageError("invalid_report", "'files' must be an object")
coverage = {}
for path, info in data["files"].items():
if not isinstance(info, dict):
continue
executed, missing = info.get("executed_lines", []), info.get("missing_lines", [])
if not isinstance(executed, list) or not isinstance(missing, list):
continue
lines = coverage.setdefault(path, {})
for number in executed:
if isinstance(number, int):
lines[number] = True
for number in missing:
if isinstance(number, int):
lines[number] = False
return coverage
def match_path(diff_path, coverage_paths):
"""Longest matching coverage path wins; a tie raises ambiguous_path."""
matches = [
c
for c in coverage_paths
if diff_path == c or diff_path.endswith("/" + c) or c.endswith("/" + diff_path)
]
if not matches:
return ""
longest = max(len(c) for c in matches)
best = [c for c in matches if len(c) == longest]
if len(set(best)) > 1:
joined = ", ".join(best[:5])
raise DiffCoverageError(
"ambiguous_path", f"multiple coverage paths match {diff_path!r}: {joined}"
)
return best[0]
def diff_coverage(changed, coverage, fail_under=None):
"""Return a report dict: files, percent (Decimal or None), passed, unmeasured_files."""
paths = list(coverage)
files, unmeasured = [], []
total_covered = total_exec = 0
for diff_path in sorted(changed):
cov_path = match_path(diff_path, paths)
if not cov_path:
unmeasured.append(diff_path)
continue
line_cover = coverage[cov_path]
covered, executable, missing = 0, 0, []
for number in sorted(changed[diff_path]):
if number in line_cover:
executable += 1
if line_cover[number]:
covered += 1
else:
missing.append(number)
files.append(
{"path": diff_path, "covered": covered, "executable": executable, "missing": missing}
)
total_covered += covered
total_exec += executable
if total_exec == 0:
percent, passed = None, True
else:
percent = (Decimal(total_covered) * 100 / Decimal(total_exec)).quantize(
Decimal("0.1"), rounding=ROUND_HALF_UP
)
passed = True if fail_under is None else percent >= fail_under
return {"files": files, "percent": percent, "passed": passed, "unmeasured_files": unmeasured}
def format_missing(numbers):
"""Condense [3, 4, 5, 9] into '3-5, 9'."""
ranges, i = [], 0
while i < len(numbers):
j = i
while j + 1 < len(numbers) and numbers[j + 1] == numbers[j] + 1:
j += 1
ranges.append(str(numbers[i]) if i == j else f"{numbers[i]}-{numbers[j]}")
i = j + 1
return ", ".join(ranges)
def render(report, fmt):
percent = report["percent"]
if fmt == "text":
lines = []
for f in report["files"]:
missing = format_missing(f["missing"])
tail = " missing " + missing if missing else ""
lines.append(f"{f['path']} {f['covered']}/{f['executable']}{tail}")
lines.append(
"Diff coverage: no executable changed lines"
if percent is None
else f"Diff coverage: {percent}%"
)
return "\n".join(lines)
if fmt == "markdown":
head = (
"## Diff coverage: no executable changed lines"
if percent is None
else f"## Diff coverage: {percent}%"
)
rows = [
f"| {f['path']} | {f['covered']}/{f['executable']} | {format_missing(f['missing'])} |"
for f in report["files"]
]
return (
"\n".join(
[head, "", "| File | Covered | Missing lines |", "| --- | --- | --- |", *rows]
)
+ "\n"
)
if fmt == "json":
data = dict(report, percent=None if percent is None else str(percent))
return json.dumps(data, indent=2)
raise ValueError(f"unsupported format: {fmt}")
def load_inputs(diff_path, coverage_path):
with open(diff_path, encoding="utf-8-sig") as handle:
diff_text = handle.read()
with open(coverage_path, encoding="utf-8-sig") as handle:
cov_text = handle.read()
head = cov_text.lstrip()[:1]
if head == "<":
coverage = load_cobertura(cov_text)
elif head == "{":
coverage = load_coverage_json(cov_text)
else:
raise DiffCoverageError(
"invalid_report", "cannot determine coverage format; expected XML (<) or JSON ({)"
)
return diff_text, coverage
def _percent(text):
try:
value = Decimal(text)
except InvalidOperation:
raise argparse.ArgumentTypeError(f"invalid percentage: {text!r}") from None
if not value.is_finite():
raise argparse.ArgumentTypeError("percentage must be finite")
return value
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--diff", required=True, help="path to a unified diff file")
parser.add_argument(
"--coverage", required=True, help="path to a Cobertura XML or coverage.py JSON file"
)
parser.add_argument(
"--fail-under", type=_percent, default=None, help="minimum percentage, for example 80"
)
parser.add_argument("--format", choices=("text", "markdown", "json"), default="text")
args = parser.parse_args(argv)
try:
diff_text, coverage = load_inputs(args.diff, args.coverage)
report = diff_coverage(parse_diff(diff_text), coverage, args.fail_under)
except (OSError, UnicodeError, DiffCoverageError) as exc:
print(f"Error: {exc}", file=sys.stderr)
return 2
print(render(report, args.format))
return 0 if report["passed"] else 1
if __name__ == "__main__":
sys.exit(main())