import json
import pathlib
import re
import subprocess
import sys
ROOT = pathlib.Path(__file__).resolve().parent.parent
SRC = ROOT / "src"
MANIFEST = ROOT / "Cargo.toml"
def examples() -> list[str]:
text = MANIFEST.read_text()
return re.findall(r'^\[\[example\]\]\nname = "([^"]+)"', text, re.M)
def public_modules() -> set[str]:
lib = (SRC / "lib.rs").read_text()
names = set(re.findall(r"^\s*pub mod (\w+);", lib, re.M))
return {"lib.rs"} | {f"{n}.rs" for n in names}
def run(*args: str) -> str:
proc = subprocess.run(
args, cwd=ROOT, capture_output=True, text=True, check=False
)
if proc.returncode != 0:
sys.exit(
f"command failed: {' '.join(args)}\n"
f"{proc.stdout[-2000:]}\n{proc.stderr[-2000:]}"
)
return proc.stdout
def main() -> int:
names = examples()
if not names:
sys.exit("no examples declared in Cargo.toml")
print(f"running {len(names)} examples under instrumentation")
run("cargo", "llvm-cov", "clean", "--workspace")
for name in names:
run(
"cargo", "llvm-cov", "--no-report", "run",
"-q", "-p", "oxml-mcp", "--example", name,
)
report = run("cargo", "llvm-cov", "report", "--json")
counts: dict[str, dict[int, int]] = {}
for entry in json.loads(report)["data"]:
for item in entry["files"]:
per_line: dict[int, int] = {}
for line, _column, count, has_count, *_rest in item["segments"]:
if has_count:
per_line[line] = max(per_line.get(line, 0), count)
counts[item["filename"]] = per_line
total = 0
unexercised: list[str] = []
reachable = public_modules()
for path in sorted(SRC.rglob("*.rs")):
if path.name not in reachable:
continue
rel = path.relative_to(ROOT)
lines = path.read_text().splitlines()
declared = [
(n, t.strip())
for n, t in enumerate(lines, 1)
if t.strip().startswith(("pub fn ", "pub const fn "))
]
keys = [k for k in counts if k.endswith(str(rel))]
if not keys:
if declared:
unexercised.append(
f"{rel} has {len(declared)} public functions and no "
f"coverage data at all"
)
total += len(declared)
continue
for number, stripped in declared:
total += 1
count = counts[keys[0]].get(number)
if count is None:
unexercised.append(
f"{rel}:{number} (never instantiated) "
f"{stripped.rstrip(' {')}"
)
elif count == 0:
unexercised.append(f"{rel}:{number} {stripped.rstrip(' {')}")
if total == 0:
sys.exit("found no `pub fn` declarations -- the check is not working")
print(f"{total - len(unexercised)}/{total} public functions exercised")
if unexercised:
print("\nnot reached by any example:")
for item in unexercised:
print(f" {item}")
print("\nAdd an example that calls it, or make it private.")
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())