#!/usr/bin/env python3
"""`repro --coverage DIR ...` for Rust: build with -Cinstrument-coverage, run, write lcov.info + html/.

usage: stitch-rust-cov APP_DIR [repro args...] --coverage DIR
"""
import os
import re
import subprocess
import sys
from pathlib import Path

app = Path(sys.argv[1])
args = sys.argv[2:]
i = args.index("--coverage")
out = Path(args[i + 1]).resolve()
args = args[:i] + args[i + 2:]
out.mkdir(parents=True, exist_ok=True)
crate = app / "crate"
proj = Path("/project")
vv = subprocess.run(["rustc", "-vV"], capture_output=True, text=True).stdout
triple = re.search(r"host: (\S+)", vv).group(1)
sysroot = subprocess.run(["rustc", "--print", "sysroot"], capture_output=True, text=True).stdout.strip()
tools = Path(sysroot) / "lib" / "rustlib" / triple / "bin"
tdir = proj / ".stitch" / "cargo-target" / "cov"
env = dict(os.environ, CARGO_HOME=str(proj / ".stitch" / "cargo"), RUSTFLAGS="-Cinstrument-coverage", CARGO_TARGET_DIR=str(tdir))
env.pop("RUSTC_WRAPPER", None)
r = subprocess.run(["cargo", "build", "--release", "--target", triple, "--bin", "worker"], cwd=crate, env=env,
                   capture_output=True, text=True)
if r.returncode != 0:
    sys.stderr.write(r.stderr[-6000:])
    sys.exit(3)
binary = tdir / triple / "release" / "worker"
raw = out / "profraw"
raw.mkdir(exist_ok=True)
run = subprocess.run([str(binary), *args], env=dict(os.environ, LLVM_PROFILE_FILE=str(raw / "cov-%p-%4m.profraw")))
prof = out / "cov.profdata"
subprocess.run([str(tools / "llvm-profdata"), "merge", "-sparse", *map(str, raw.glob("*.profraw")), "-o", str(prof)], check=True)
ign = ["-ignore-filename-regex=^/rustc/|/stitch/rust/|/\\.cargo/registry/src/index[^/]*/(libc|cfg-if)"]
with open(out / "lcov.info", "w") as f:
    subprocess.run([str(tools / "llvm-cov"), "export", "-format=lcov", str(binary), f"-instr-profile={prof}", *ign], stdout=f, check=True)
with open(out / "report.txt", "w") as f:
    subprocess.run([str(tools / "llvm-cov"), "report", str(binary), f"-instr-profile={prof}", *ign], stdout=f)
subprocess.run([str(tools / "llvm-cov"), "show", "-format=html", f"-output-dir={out / 'html'}", "-Xdemangler=llvm-cxxfilt",
                str(binary), f"-instr-profile={prof}", *ign])
# demangle function names; harness sources are a snapshot of /project/harness
text = (out / "lcov.info").read_text()
names = sorted(set(re.findall(r"^FN:\d+,(\S+)$", text, re.M)))
if names:
    dem = subprocess.run(["llvm-cxxfilt"], input="\n".join(names), capture_output=True, text=True).stdout.splitlines()
    if len(dem) == len(names):
        m = {n: re.sub(r"::h[0-9a-f]{16}$", "", d) for n, d in zip(names, dem)}
        text = re.sub(r"^(FN(?:DA)?:[\d]+,)(\S+)$", lambda x: x.group(1) + m.get(x.group(2), x.group(2)), text, flags=re.M)
text = text.replace(str(crate / "src") + "/", "/project/harness/")
(out / "lcov.info").write_text(text)
for p in raw.glob("*"):
    p.unlink()
raw.rmdir()
sys.exit(run.returncode)
