#!/usr/bin/env python3 """W90 nightly coverage summary (report-only, never a gate). Reads the per-profile ``coverage-report.json`` files archived by the nightly ``coverage-nightly`` job, compares the measured line coverage with the measured baseline entry in ``tools/coverage/baseline.json`` and prints a Markdown summary that includes the coverage gaps (top modules by uncovered lines). The summary is written to ``$GITHUB_STEP_SUMMARY`` by the workflow and archived as ``coverage_summary.md`` / ``coverage_summary.json``. Why this exists (W90): ``core-plus-v3`` (112 targets) is the default coverage signal in nightly - its report-only archive is always on, while the hard gate stays opt-in (``vars.VDE_COV_PROFILE_V3``). A nightly summary that shows the measured coverage *and* the top gap modules makes the report-only signal actionable without turning it into a build failure. Design rules: * report-only: exit 0 even when a profile directory/report is missing or the measured coverage is below the baseline gate (the dedicated gate steps enforce hard thresholds, this tool never does); * no third-party imports (stdlib only), so it runs on any runner; * the gate value always comes from ``baseline.json`` (measured baseline); hand-editing thresholds here is not supported by design. Usage: python tools/ci/coverage_summary.py \\ --dir core-pr=build-cov-nightly-report \\ --dir core=build-cov-nightly-core-report \\ --dir core-plus-v3=build-cov-nightly-core-plus-v3-report \\ --baseline tools/coverage/baseline.json --top 5 \\ --out coverage_summary.md --json-out coverage_summary.json python tools/ci/coverage_summary.py --self-test Exit codes: 0 = summary produced (report-only), 2 = usage error. """ from __future__ import annotations import argparse import datetime as _dt import json import os import sys import tempfile SCHEMA = "vde-coverage-summary/1" TOOL = "tools/ci/coverage_summary.py" DEFAULT_BASELINE = os.path.join("tools", "coverage", "baseline.json") DEFAULT_DIRS = ( ("core-pr", "build-cov-nightly-report"), ("core", "build-cov-nightly-core-report"), ("core-plus", "build-cov-nightly-core-plus-report"), ("core-plus-v2", "build-cov-nightly-core-plus-v2-report"), ("core-plus-v3", "build-cov-nightly-core-plus-v3-report"), ) GAP_TOTAL_MIN = 200 def _load_json(path): try: with open(path, encoding="utf-8") as fh: return json.load(fh) except (OSError, ValueError): return None def _load_baseline(path, warnings): data = _load_json(path) if not isinstance(data, dict): warnings.append("baseline 缺失或不可解析: %s" % path) return {} entries = data.get("entries") if not isinstance(entries, dict): warnings.append("baseline 无 entries 段: %s" % path) return {} return entries def _fmt_num(value, digits=1, suffix=""): if value is None: return "-" try: return ("%." + str(digits) + "f%s") % (float(value), suffix) except (TypeError, ValueError): return "-" def _profile_row(name, directory, baseline_entries): row = { "profile": name, "dir": directory, "status": "MISSING", "gate_line_pct": None, "line_pct": None, "func_pct": None, "branch_pct": None, "delta_pp": None, "lines_covered": None, "lines_total": None, } entry = baseline_entries.get(name) or {} try: row["gate_line_pct"] = float(entry["line_pct"]) except (KeyError, TypeError, ValueError): row["gate_line_pct"] = None report = _load_json(os.path.join(directory, "coverage-report.json")) if not isinstance(report, dict): row["note"] = "coverage-report.json 缺失(采集失败或未归档)" return row totals = report.get("totals") or {} row["line_pct"] = totals.get("line_pct") row["func_pct"] = totals.get("func_pct") row["branch_pct"] = totals.get("branch_pct") row["lines_covered"] = totals.get("lines_covered") row["lines_total"] = totals.get("lines_total") if row["line_pct"] is None: row["note"] = "coverage-report.json 无 totals.line_pct" return row if row["gate_line_pct"] is not None: try: delta = float(row["line_pct"]) - row["gate_line_pct"] row["delta_pp"] = round(delta, 2) row["status"] = "PASS" if delta >= 0 else "BELOW" except (TypeError, ValueError): row["status"] = "REPORT" else: row["status"] = "NO-BASELINE" gaps = _top_gaps(report) row["gaps"] = gaps return row def _top_gaps(report, limit=5): modules = report.get("modules") or {} gaps = [] for mod_name, data in modules.items(): if not isinstance(data, dict): continue total = data.get("lines_total") or 0 covered = data.get("lines_cov") or 0 uncovered = data.get("uncovered") if uncovered is None: uncovered = total - covered pct = (100.0 * covered / total) if total else 0.0 gaps.append({ "module": mod_name, "uncovered": int(uncovered), "lines_total": int(total), "lines_covered": int(covered), "line_pct": round(pct, 1), }) gaps.sort(key=lambda item: (-item["uncovered"], item["module"])) return gaps[:limit] def _low_modules(report, limit=5): modules = report.get("modules") or {} rows = [] for mod_name, data in modules.items(): if not isinstance(data, dict): continue total = data.get("lines_total") or 0 if total < GAP_TOTAL_MIN: continue covered = data.get("lines_cov") or 0 rows.append({ "module": mod_name, "line_pct": round(100.0 * covered / total, 1), "lines_total": int(total), }) rows.sort(key=lambda item: (item["line_pct"], item["module"])) return rows[:limit] def render_summary(rows, baseline_path, top_dirs, warnings): order = ["core-pr", "core", "core-plus", "core-plus-v2", "core-plus-v3"] rows = sorted(rows, key=lambda r: ( order.index(r["profile"]) if r["profile"] in order else 99, r["profile"])) lines = [] lines.append("## nightly coverage summary (W90, report-only)") lines.append("") lines.append("Gate = measured baseline (`%s`, refreshed by " "`tools/vde_coverage_check.py --update-baseline`); the v3 " "report-only archive is always on, the v3 hard gate is opt-in " "(VDE_COV_PROFILE_V3)." % baseline_path) lines.append("") lines.append("| profile | line % | gate (baseline) | delta pp | func % | " "branch % | status |") lines.append("| --- | ---: | ---: | ---: | ---: | ---: | --- |") for row in rows: lines.append("| %s | %s | %s | %s | %s | %s | %s |" % ( row["profile"], _fmt_num(row["line_pct"], 2), _fmt_num(row["gate_line_pct"], 2), ("%+.2f" % row["delta_pp"]) if row["delta_pp"] is not None else "-", _fmt_num(row["func_pct"], 2), _fmt_num(row["branch_pct"], 2), row["status"], )) for row in rows: if row.get("note"): lines.append("") lines.append("> %s: %s" % (row["profile"], row["note"])) lines.append("") lines.append("### coverage gaps: top %d modules by uncovered lines" % (top_dirs or 5)) lines.append("") lines.append("| profile | module | uncovered lines | covered/total lines " "| line % |") lines.append("| --- | --- | ---: | ---: | ---: |") for row in rows: for gap in (row.get("gaps") or []): lines.append("| %s | %s | %d | %d/%d | %.1f |" % ( row["profile"], gap["module"], gap["uncovered"], gap["lines_covered"], gap["lines_total"], gap["line_pct"])) lines.append("") lines.append("### lowest line-coverage modules (lines_total >= %d)" % GAP_TOTAL_MIN) lines.append("") lines.append("| profile | module | line % | lines total |") lines.append("| --- | --- | ---: | ---: |") for row in rows: report_dir = row["dir"] report = _load_json(os.path.join(report_dir, "coverage-report.json")) if not isinstance(report, dict): continue for low in _low_modules(report): lines.append("| %s | %s | %.1f | %d |" % ( row["profile"], low["module"], low["line_pct"], low["lines_total"])) for warning in warnings: lines.append("") lines.append("> warning: %s" % warning) lines.append("") return "\n".join(lines) def build_summary(dir_pairs, baseline_path, top=5): warnings = [] baseline_entries = _load_baseline(baseline_path, warnings) rows = [] for name, directory in dir_pairs: if not os.path.isdir(directory): warnings.append("profile %s 报告目录缺失: %s" % (name, directory)) rows.append(_profile_row(name, directory, baseline_entries)) for row in rows: gaps = row.get("gaps") or [] row["gaps"] = gaps[:top] markdown = render_summary(rows, baseline_path, top, warnings) payload = { "schema": SCHEMA, "tool": TOOL, "generated_at": _dt.datetime.now().astimezone().isoformat( timespec="seconds"), "baseline": baseline_path, "report_only": True, "profiles": rows, "warnings": warnings, } return markdown, payload # ------------------------------------------------------------------ self-test def _write_json(path, data): os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) with open(path, "w", encoding="utf-8") as fh: json.dump(data, fh, ensure_ascii=False, indent=2) def _fake_report(line_pct, func_pct, branch_pct): return { "schema": "vde-coverage/2", "totals": { "lines_total": 1000, "lines_covered": int(line_pct * 10), "line_pct": line_pct, "funcs_total": 100, "funcs_covered": int(func_pct), "func_pct": func_pct, "branches_total": 400, "branches_covered": int(branch_pct * 4), "branch_pct": branch_pct, }, "modules": { "brep": {"lines_total": 600, "lines_cov": int(line_pct * 6), "uncovered": 600 - int(line_pct * 6), "func_total": 40, "func_cov": 30, "branch_total": 240, "branch_cov": 100}, "boolean": {"lines_total": 300, "lines_cov": 150, "uncovered": 150, "func_total": 30, "func_cov": 20, "branch_total": 120, "branch_cov": 50}, "tiny": {"lines_total": 50, "lines_cov": 10, "uncovered": 40}, }, } def self_test(): failures = [] checks = [] def check(name, cond, detail=""): checks.append(name) if not cond: failures.append("%s: %s" % (name, detail)) tmp = tempfile.mkdtemp(prefix="cov-summary-selftest-") try: base = os.path.join(tmp, "baseline.json") _write_json(base, {"schema_version": 1, "entries": { "core-plus-v3": {"line_pct": 60.1618}, "core": {"line_pct": 34.6312}, }}) dir_ok = os.path.join(tmp, "ok") _write_json(os.path.join(dir_ok, "coverage-report.json"), _fake_report(60.5, 68.0, 37.0)) dir_below = os.path.join(tmp, "below") _write_json(os.path.join(dir_below, "coverage-report.json"), _fake_report(33.0, 40.0, 20.0)) dir_missing = os.path.join(tmp, "missing") os.makedirs(dir_missing, exist_ok=True) markdown, payload = build_summary([ ("core-plus-v3", dir_ok), ("core", dir_below), ("core-pr", dir_missing), ], base, top=2) status = {row["profile"]: row["status"] for row in payload["profiles"]} check("status-pass", status.get("core-plus-v3") == "PASS", str(status)) check("status-below", status.get("core") == "BELOW", str(status)) check("status-missing", status.get("core-pr") == "MISSING", str(status)) check("delta-sign", payload["profiles"][0]["delta_pp"] == 0.34, str(payload["profiles"][0].get("delta_pp"))) check("report-only", payload.get("report_only") is True) check("markdown-table", "| core-plus-v3 |" in markdown, markdown[:200]) check("markdown-gap-header", "coverage gaps" in markdown) check("markdown-gap-module", "| boolean |" in markdown, markdown) gap_section = markdown.split("### lowest line-coverage")[0] check("markdown-gap-limit", gap_section.count("| core-plus-v3 | brep |") == 1, gap_section) check("markdown-missing-note", "coverage-report.json 缺失" in markdown) low_section = (markdown.split("### lowest line-coverage")[1] if "### lowest line-coverage" in markdown else "") check("markdown-low-module-total-min", "tiny" not in low_section, low_section) check("exit-zero-report-only", True) finally: import shutil shutil.rmtree(tmp, ignore_errors=True) if failures: for failure in failures: print("[coverage-summary] SELF-TEST FAIL: %s" % failure) return 1 print("[coverage-summary] SELF-TEST PASS(%d 个 summary/gap 不变量用例)" % len(checks)) return 0 # ---------------------------------------------------------------------- main def _parse_dir(value): if "=" not in value: raise argparse.ArgumentTypeError( "--dir 需要 NAME=PATH 形式,得到: %r" % value) name, path = value.split("=", 1) name = name.strip() path = path.strip() if not name or not path: raise argparse.ArgumentTypeError( "--dir 需要 NAME=PATH 形式,得到: %r" % value) return name, path def main(argv=None): ap = argparse.ArgumentParser( description="W90 nightly coverage summary (report-only, gap top modules)") ap.add_argument("--dir", action="append", type=_parse_dir, default=None, metavar="NAME=PATH", help="profile 报告目录(可多次;默认 core-pr/core/" "core-plus/core-plus-v2/core-plus-v3 标准 nightly 目录)") ap.add_argument("--baseline", default=DEFAULT_BASELINE, help="measured baseline JSON(默认 %(default)s)") ap.add_argument("--top", type=int, default=5, help="每个 profile 输出的 gap 模块数(默认 5)") ap.add_argument("--out", default=None, help="Markdown 输出文件(默认打印到 stdout)") ap.add_argument("--json-out", default=None, help="JSON 输出文件") ap.add_argument("--self-test", action="store_true", help="运行内置自检") args = ap.parse_args(argv) if args.self_test: return self_test() dir_pairs = args.dir if args.dir else list(DEFAULT_DIRS) if not os.path.isfile(args.baseline): print("[coverage-summary] ERROR baseline 不存在: %s" % args.baseline, file=sys.stderr) return 2 markdown, payload = build_summary(dir_pairs, args.baseline, args.top) if args.out: with open(args.out, "w", encoding="utf-8") as fh: fh.write(markdown + "\n") print("[coverage-summary] markdown=%s" % args.out) else: print(markdown) if args.json_out: with open(args.json_out, "w", encoding="utf-8") as fh: json.dump(payload, fh, ensure_ascii=False, indent=2) print("[coverage-summary] json=%s" % args.json_out) below = [row["profile"] for row in payload["profiles"] if row["status"] == "BELOW"] missing = [row["profile"] for row in payload["profiles"] if row["status"] == "MISSING"] print("[coverage-summary] report-only: profiles=%d below_gate=%s " "missing=%s" % (len(payload["profiles"]), below or "-", missing or "-")) return 0 if __name__ == "__main__": sys.exit(main())