| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- #!/usr/bin/env python3
- """Regenerate curated candidate-count expectation from live board-data/build-info."""
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import subprocess
- import sys
- from pathlib import Path
- ROOT = Path(__file__).resolve().parents[2]
- VIEWER = ROOT / "tools" / "board-viewer"
- GENERATED = VIEWER / "generated"
- DEFAULT_OUT = ROOT / "tests" / "board_viewer" / "fixtures" / "candidate_count_expectation.json"
- CAPABILITIES = (
- "gpio",
- "pwm",
- "gpio_output",
- "gpio_input",
- "tach",
- "presence",
- "uart_tx",
- )
- def sha256_file(path: Path) -> str:
- return hashlib.sha256(path.read_bytes()).hexdigest()
- def _run_node(board_data: Path) -> tuple[dict[str, int], dict[str, list[str]]]:
- board_data_js = json.dumps(str(board_data))
- logic_js = json.dumps(str(VIEWER / "web" / "board-logic.mjs"))
- caps_js = json.dumps(list(CAPABILITIES))
- script = (
- "import {readFileSync} from 'node:fs';"
- f"import {{findCandidates}} from {logic_js};"
- f"const data = JSON.parse(readFileSync({board_data_js}, 'utf8'));"
- f"const caps = {caps_js};"
- "const candidate_counts = {};"
- "const candidate_keys = {};"
- "for (const cap of caps) {"
- " const c = findCandidates(data, cap);"
- " candidate_counts[cap] = c.length;"
- " candidate_keys[cap] = c.map((item) => `${item.reference}.${item.pin.number}`);"
- "}"
- "process.stdout.write(JSON.stringify({candidate_counts, candidate_keys}));"
- )
- result = subprocess.run(
- ["node", "--input-type=module", "--eval", script],
- cwd=str(ROOT),
- check=True,
- capture_output=True,
- text=True,
- )
- payload = json.loads(result.stdout)
- return payload["candidate_counts"], payload["candidate_keys"]
- def build_expectation() -> dict:
- board_data = GENERATED / "board-data.json"
- build_info = GENERATED / "build-info.json"
- if not board_data.is_file() or not build_info.is_file():
- raise SystemExit("generated board-data.json and build-info.json are required")
- info = json.loads(build_info.read_text(encoding="utf-8"))
- data = json.loads(board_data.read_text(encoding="utf-8"))
- counts, keys = _run_node(board_data)
- pin_count = sum(len(touchpoint.get("pins") or []) for touchpoint in data.get("touchpoints") or [])
- return {
- "schema": "prod2u-board-viewer-candidate-count-expectation-v1",
- "description": (
- "Curated fail-closed candidate counts bound to generated board-data/build-info digests. "
- "Do not relax cross_verified/power/ground/reserved/fixed-load blockers to match counts."
- ),
- "bound_to": {
- "board_data_path": "tools/board-viewer/generated/board-data.json",
- "board_data_sha256": sha256_file(board_data),
- "build_info_path": "tools/board-viewer/generated/build-info.json",
- "build_info_sha256": sha256_file(build_info),
- "board_data_asset_sha256": info["assets"]["board-data.json"]["sha256"],
- "brd_sha256": info["sources"]["brd"]["sha256"],
- },
- "candidate_counts": counts,
- "candidate_keys": keys,
- "ui_counts": {
- "touchpoints": len(data.get("touchpoints") or []),
- "pins": pin_count,
- },
- "blockers_must_remain": [
- "unverified_or_non_cross_verified",
- "power",
- "ground",
- "reserved",
- "fixed_load_conflict",
- "mechanical_or_non_electrical",
- "unknown_pad_role",
- ],
- }
- def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--out", type=Path, default=DEFAULT_OUT)
- parser.add_argument("--check", action="store_true", help="verify existing expectation instead of writing")
- args = parser.parse_args()
- expectation = build_expectation()
- if args.check:
- existing = json.loads(args.out.read_text(encoding="utf-8"))
- if existing != expectation:
- print("candidate expectation drift detected", file=sys.stderr)
- return 1
- print("candidate expectation: pass")
- return 0
- args.out.parent.mkdir(parents=True, exist_ok=True)
- args.out.write_text(json.dumps(expectation, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
- print(f"wrote {args.out}")
- print(json.dumps(expectation["candidate_counts"], indent=2))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|