|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Generate a Markdown coverage summary comment for CI.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import argparse |
| 7 | +import json |
| 8 | +import pathlib |
| 9 | +from typing import Dict, Iterable, List, Tuple |
| 10 | + |
| 11 | +from render_rust_coverage_summary import load_summary as load_rust_summary |
| 12 | + |
| 13 | +Row = Tuple[str, int, int, float] |
| 14 | + |
| 15 | + |
| 16 | +def parse_args(argv: Iterable[str] | None = None) -> argparse.Namespace: |
| 17 | + parser = argparse.ArgumentParser(description=__doc__ or "") |
| 18 | + parser.add_argument( |
| 19 | + "--rust-summary", |
| 20 | + type=pathlib.Path, |
| 21 | + required=True, |
| 22 | + help="Path to cargo-llvm-cov JSON summary", |
| 23 | + ) |
| 24 | + parser.add_argument( |
| 25 | + "--python-json", |
| 26 | + type=pathlib.Path, |
| 27 | + required=True, |
| 28 | + help="Path to coverage.py JSON report", |
| 29 | + ) |
| 30 | + parser.add_argument( |
| 31 | + "--output", |
| 32 | + type=pathlib.Path, |
| 33 | + required=True, |
| 34 | + help="Output Markdown file for the PR comment", |
| 35 | + ) |
| 36 | + parser.add_argument( |
| 37 | + "--repo-root", |
| 38 | + type=pathlib.Path, |
| 39 | + default=pathlib.Path.cwd(), |
| 40 | + help="Repository root used to relativise file paths (default: current working directory)", |
| 41 | + ) |
| 42 | + parser.add_argument( |
| 43 | + "--max-rows", |
| 44 | + type=int, |
| 45 | + default=20, |
| 46 | + help="Maximum number of per-file rows to display for each language (default: 20).", |
| 47 | + ) |
| 48 | + return parser.parse_args(argv) |
| 49 | + |
| 50 | + |
| 51 | +def _select_rows(rows: List[Row], max_rows: int) -> Tuple[List[Row], bool]: |
| 52 | + if max_rows <= 0 or len(rows) <= max_rows: |
| 53 | + return sorted(rows, key=lambda item: item[0]), False |
| 54 | + |
| 55 | + priority_sorted = sorted(rows, key=lambda item: (-item[2], item[0])) |
| 56 | + trimmed = priority_sorted[:max_rows] |
| 57 | + return sorted(trimmed, key=lambda item: item[0]), True |
| 58 | + |
| 59 | + |
| 60 | +def _format_table(rows: List[Row], headers: Tuple[str, str, str, str]) -> List[str]: |
| 61 | + lines = [ |
| 62 | + f"| {headers[0]} | {headers[1]} | {headers[2]} | {headers[3]} |", |
| 63 | + "| --- | ---: | ---: | ---: |", |
| 64 | + ] |
| 65 | + for name, total, missed, percent in rows: |
| 66 | + lines.append( |
| 67 | + f"| `{name}` | {total:,} | {missed:,} | {percent:5.1f}% |" |
| 68 | + ) |
| 69 | + return lines |
| 70 | + |
| 71 | + |
| 72 | +def _load_python_rows( |
| 73 | + report_path: pathlib.Path, |
| 74 | + repo_root: pathlib.Path, |
| 75 | +) -> Tuple[List[Row], Dict[str, float]]: |
| 76 | + try: |
| 77 | + payload = json.loads(report_path.read_text(encoding="utf-8")) |
| 78 | + except FileNotFoundError as exc: |
| 79 | + raise SystemExit(f"Python coverage JSON not found: {report_path}") from exc |
| 80 | + |
| 81 | + repo_root = repo_root.resolve() |
| 82 | + rows: List[Row] = [] |
| 83 | + |
| 84 | + for path_str, details in payload.get("files", {}).items(): |
| 85 | + summary = (details.get("summary") or {}) |
| 86 | + total = int(summary.get("num_statements", 0)) |
| 87 | + missed = int(summary.get("missing_lines", 0)) |
| 88 | + percent = float(summary.get("percent_covered", 0.0)) |
| 89 | + |
| 90 | + if total == 0 and missed == 0: |
| 91 | + continue |
| 92 | + |
| 93 | + file_path = pathlib.Path(path_str) |
| 94 | + if not file_path.is_absolute(): |
| 95 | + file_path = (repo_root / file_path).resolve() |
| 96 | + else: |
| 97 | + file_path = file_path.resolve() |
| 98 | + |
| 99 | + try: |
| 100 | + rel_path = file_path.relative_to(repo_root) |
| 101 | + except ValueError: |
| 102 | + continue |
| 103 | + |
| 104 | + rows.append((rel_path.as_posix(), total, missed, percent)) |
| 105 | + |
| 106 | + rows.sort(key=lambda item: item[0]) |
| 107 | + |
| 108 | + totals = payload.get("totals", {}) |
| 109 | + return rows, { |
| 110 | + "total": float(totals.get("num_statements", 0)), |
| 111 | + "covered": float(totals.get("covered_lines", 0)), |
| 112 | + "missed": float(totals.get("missing_lines", 0)), |
| 113 | + "percent": float(totals.get("percent_covered", 0.0)), |
| 114 | + } |
| 115 | + |
| 116 | + |
| 117 | +def _load_rust_rows( |
| 118 | + summary_path: pathlib.Path, |
| 119 | + repo_root: pathlib.Path, |
| 120 | +) -> Tuple[List[Row], Dict[str, float]]: |
| 121 | + rows, totals = load_rust_summary(summary_path, repo_root) |
| 122 | + # Normalise totals dict to expected keys |
| 123 | + total = float(totals.get("count", 0)) |
| 124 | + covered = float(totals.get("covered", 0)) |
| 125 | + missed = float(totals.get("notcovered", total - covered)) |
| 126 | + return rows, { |
| 127 | + "total": total, |
| 128 | + "covered": covered, |
| 129 | + "missed": missed, |
| 130 | + "percent": float(totals.get("percent", 0.0)), |
| 131 | + } |
| 132 | + |
| 133 | + |
| 134 | +def _format_summary_block( |
| 135 | + heading: str, |
| 136 | + column_label: str, |
| 137 | + totals: Dict[str, float], |
| 138 | + rows: List[Row], |
| 139 | + max_rows: int, |
| 140 | +) -> List[str]: |
| 141 | + display_rows, truncated = _select_rows(rows, max_rows) |
| 142 | + lines = [heading] |
| 143 | + total = int(totals.get("total", 0)) |
| 144 | + covered = int(totals.get("covered", 0)) |
| 145 | + missed = int(totals.get("missed", total - covered)) |
| 146 | + percent = totals.get("percent", 0.0) |
| 147 | + lines.append( |
| 148 | + f"**{percent:0.1f}%** covered ({covered:,} / {total:,} | {missed:,} missed)" |
| 149 | + ) |
| 150 | + lines.extend( |
| 151 | + _format_table(display_rows, ("File", column_label, "Miss", "Cover")) |
| 152 | + ) |
| 153 | + if truncated: |
| 154 | + lines.append( |
| 155 | + f"_Showing top {max_rows} entries by missed lines (of {len(rows)} total)._" |
| 156 | + ) |
| 157 | + return lines |
| 158 | + |
| 159 | + |
| 160 | +def main(argv: Iterable[str] | None = None) -> int: |
| 161 | + args = parse_args(argv) |
| 162 | + repo_root = args.repo_root.resolve() |
| 163 | + |
| 164 | + rust_rows, rust_totals = _load_rust_rows(args.rust_summary, repo_root) |
| 165 | + python_rows, python_totals = _load_python_rows(args.python_json, repo_root) |
| 166 | + |
| 167 | + output_lines: List[str] = ["### Coverage Summary", ""] |
| 168 | + |
| 169 | + output_lines.extend( |
| 170 | + _format_summary_block( |
| 171 | + "**Rust (lines)**", "Lines", rust_totals, rust_rows, args.max_rows |
| 172 | + ) |
| 173 | + ) |
| 174 | + output_lines.extend(["", ""]) |
| 175 | + output_lines.extend( |
| 176 | + _format_summary_block( |
| 177 | + "**Python (statements)**", "Stmts", python_totals, python_rows, args.max_rows |
| 178 | + ) |
| 179 | + ) |
| 180 | + output_lines.append("") |
| 181 | + output_lines.append( |
| 182 | + "_Generated automatically via `generate_coverage_comment.py`._" |
| 183 | + ) |
| 184 | + |
| 185 | + args.output.parent.mkdir(parents=True, exist_ok=True) |
| 186 | + args.output.write_text("\n".join(output_lines) + "\n", encoding="utf-8") |
| 187 | + return 0 |
| 188 | + |
| 189 | + |
| 190 | +if __name__ == "__main__": |
| 191 | + raise SystemExit(main()) |
0 commit comments