#!/usr/bin/env python3 """Per-file line coverage from gcov, no external tools beyond gcc's gcov. `make coverage` builds apex-twin-cov with -O0 --coverage, runs the whole suite against it, then this script runs gcov per translation unit and prints the files worst-covered first. It never fails a build on a percentage; the number is a map for where the next test should go, not a gate. """ import glob import os import re import subprocess import sys HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BUILD = os.path.join(HERE, "build-cov") SOURCES = sorted(glob.glob(os.path.join(HERE, "src", "*.c"))) LINE_RE = re.compile(r"Lines executed:([\d.]+)% of (\d+)") def gcov_one(path): base = os.path.basename(path) out = subprocess.run(["gcov", "-b", "-c", "-o", BUILD, path], capture_output=True, text=True, cwd=HERE) text = out.stdout for block in re.split(r"^File '", text, flags=re.M)[1:]: name = block.split("'", 1)[0] if os.path.basename(name) != base: continue m = LINE_RE.search(block) if m is not None: pct = float(m.group(1)) total = int(m.group(2)) return pct, total, int(round(pct * total / 100.0)) return None def main(): if not os.path.isdir(BUILD): print("coverage: no %s (run make coverage)" % BUILD) return 1 rows = [] for src in SOURCES: got = gcov_one(src) if got is not None: rows.append((os.path.basename(src),) + got) for junk in glob.glob(os.path.join(HERE, "*.gcov")): os.unlink(junk) if not rows: print("coverage: gcov produced no data") return 1 total_lines = sum(r[2] for r in rows) total_hit = sum(r[3] for r in rows) rows.sort(key=lambda r: (r[1], r[2])) print("%-22s %8s %8s %8s" % ("file", "lines", "hit", "cover")) print("-" * 50) for name, pct, lines, hit in rows: print("%-22s %8d %8d %7.1f%%" % (name, lines, hit, pct)) print("-" * 50) print("%-22s %8d %8d %7.1f%%" % ("total", total_lines, total_hit, 100.0 * total_hit / total_lines if total_lines else 0.0)) return 0 if __name__ == "__main__": sys.exit(main())