"""Regenerate the Chapter 12 qc-nm worked evidence.""" from __future__ import annotations import csv import hashlib import json import re import shutil import subprocess from pathlib import Path BOOK = Path(__file__).resolve().parents[1] PROJECT = BOOK.parent / "nlmx" EXE = PROJECT / "target" / "release" / "nlmx.exe" INPUT = BOOK / "documents" / "ch12" / "input" RESULTS = BOOK / "documents" / "ch12" / "results" def rows(path: Path) -> list[dict[str, str]]: with path.open(newline="", encoding="utf-8") as handle: return [{k.lower(): v for k, v in row.items()} for row in csv.DictReader(handle)] def main() -> None: output = RESULTS / "flawed" if output.exists(): shutil.rmtree(output) output.parent.mkdir(parents=True, exist_ok=True) command = [str(EXE), "qc-nm", "-c", str(INPUT / "chapter12.qcn"), "-o", str(output), "--no-color"] completed = subprocess.run(command, cwd=PROJECT, text=True, capture_output=True) if completed.returncode != 0: raise RuntimeError(f"qc-nm failed ({completed.returncode})\n{completed.stdout}\n{completed.stderr}") summary = json.loads((output / "qc_nm_summary.json").read_text(encoding="utf-8")) changes = rows(output / "qc_nm_changes.csv") checklist = rows(output / "qc_nm_checklist.csv") version_out = subprocess.run([str(EXE), "--version"], cwd=PROJECT, text=True, capture_output=True).stdout match = re.search(r"\bv(\d+\.\d+\.\d+)\b", version_out) files = sorted(p.relative_to(output).as_posix() for p in output.rglob("*") if p.is_file()) evidence = { "version": match.group(1) if match else "unknown", "command": command, "exit_code": completed.returncode, "verdict_before": summary["verdict"], "counts_before": summary["counts"], "verdict_after": summary.get("verdict_after_fix"), "counts_after": summary.get("counts_after_fix"), "corrected_copy": summary.get("corrected_copy"), "changes": len(changes), "change_kinds": sorted({r.get("fix", "") for r in changes}), "failed_before": [r["id"] for r in checklist if r.get("status") == "FAIL"], "failed_after": [r["id"] for r in checklist if r.get("status_after_fix") == "FAIL"], "output_files": files, "diff_sha256": hashlib.sha256((output / "qc_nm_changes.diff").read_bytes()).hexdigest(), "corrected_sha256": hashlib.sha256((output / "flawed_qc.ctl").read_bytes()).hexdigest(), } (RESULTS / "example_summary.json").write_text(json.dumps(evidence, indent=2) + "\n", encoding="utf-8") print(json.dumps(evidence, indent=2)) if __name__ == "__main__": main()