| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268 |
- #!/usr/bin/env python3
- """Import generated CPLD contracts and derive Go/Python constants."""
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- from pathlib import Path
- import subprocess
- import sys
- from typing import Any
- ROOT = Path(__file__).resolve().parents[1]
- DEFAULT_SOURCE = ROOT.parent / "cpld-temperature-control/generated/6400/host-contract.json"
- CPLD_CLOSURE = Path("products/6400-control/source-closure.json")
- CPLD_COSIM_WRAPPER = Path("tests/cocotb/prod2u_6400_v1_cocotb_top.v")
- def json_bytes(value: Any) -> bytes:
- return (json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode()
- def camel(name: str) -> str:
- return "".join(item.upper() if item in {"bmc", "ct", "ptc"} else item.title() for item in name.split("_"))
- def _validate_commit(value: str, label: str) -> str:
- value = value.strip().lower()
- if len(value) not in {40, 64} or any(ch not in "0123456789abcdef" for ch in value):
- raise ValueError(f"{label} must be a full hexadecimal Git object id")
- return value
- def _git_text(repo: Path, *args: str) -> str:
- return subprocess.run(
- ["git", "-C", str(repo), *args],
- check=True,
- capture_output=True,
- text=True,
- ).stdout.strip()
- def _source_input_paths(source: Path) -> tuple[Path, list[Path]]:
- source_root = source.resolve().parents[2]
- source_rel = source.resolve().relative_to(source_root)
- closure = json.loads((source_root / CPLD_CLOSURE).read_text(encoding="utf-8"))
- paths = [source_rel, CPLD_CLOSURE, CPLD_COSIM_WRAPPER]
- for value in closure["sources"]:
- path = Path(value)
- if path.is_absolute() or ".." in path.parts:
- raise ValueError(f"unsafe CPLD source path {value!r}")
- paths.append(path)
- unique = sorted(set(paths), key=lambda item: item.as_posix())
- missing = [item.as_posix() for item in unique if not (source_root / item).is_file()]
- if missing:
- raise FileNotFoundError("missing CPLD source inputs: " + ", ".join(missing))
- return source_root, unique
- def _source_input_hashes(source_root: Path, paths: list[Path]) -> dict[str, str]:
- return {
- path.as_posix(): hashlib.sha256((source_root / path).read_bytes()).hexdigest()
- for path in paths
- }
- def _source_input_bundle_sha256(file_hashes: dict[str, str]) -> str:
- return hashlib.sha256(json_bytes(file_hashes)).hexdigest()
- def resolve_provenance(
- source: Path, explicit_source_commit: str | None
- ) -> tuple[str, str, dict[str, str], str]:
- source_root, input_paths = _source_input_paths(source)
- package_commit = _validate_commit(_git_text(source_root, "rev-parse", "HEAD"), "package commit")
- source_commit = _validate_commit(
- explicit_source_commit or package_commit, "functional source commit"
- )
- subprocess.run(
- ["git", "-C", str(source_root), "cat-file", "-e", f"{source_commit}^{{commit}}"],
- check=True,
- capture_output=True,
- )
- if source_commit != package_commit:
- ancestor = subprocess.run(
- [
- "git",
- "-C",
- str(source_root),
- "merge-base",
- "--is-ancestor",
- source_commit,
- package_commit,
- ],
- capture_output=True,
- )
- if ancestor.returncode != 0:
- raise ValueError(
- f"functional source commit {source_commit} is not an ancestor of package commit {package_commit}"
- )
- file_hashes = _source_input_hashes(source_root, input_paths)
- for path in input_paths:
- try:
- committed = subprocess.run(
- ["git", "-C", str(source_root), "show", f"{source_commit}:{path.as_posix()}"],
- check=True,
- capture_output=True,
- ).stdout
- except subprocess.CalledProcessError as exc:
- raise ValueError(
- f"functional source commit {source_commit} does not contain {path.as_posix()}"
- ) from exc
- committed_sha = hashlib.sha256(committed).hexdigest()
- if committed_sha != file_hashes[path.as_posix()]:
- raise ValueError(
- f"package commit changes functional source input {path.as_posix()}: "
- f"source={committed_sha} package={file_hashes[path.as_posix()]}"
- )
- return (
- source_commit,
- package_commit,
- file_hashes,
- _source_input_bundle_sha256(file_hashes),
- )
- def outputs(source: Path, source_commit: str | None = None) -> dict[Path, bytes]:
- raw = source.read_bytes()
- contract = json.loads(raw)
- contract_sha = contract["contract_sha256"]
- wire = contract["wire"]
- snapshot = contract["snapshot"]
- golden_contract = contract["golden_vectors"]
- golden = golden_contract["frames"]
- source_file_sha = hashlib.sha256(raw).hexdigest()
- golden_raw = json_bytes(golden_contract)
- golden_file_sha = hashlib.sha256(golden_raw).hexdigest()
- (
- resolved_source_commit,
- resolved_package_commit,
- source_input_file_sha256,
- source_input_bundle_sha256,
- ) = resolve_provenance(source, source_commit)
- go_lines = [
- "// Code generated by tools/import_6400_contract.py; DO NOT EDIT.",
- "package protocol6400",
- "",
- f'const ContractSHA256 = "{contract_sha}"',
- f'const SourceContractFileSHA256 = "{source_file_sha}"',
- f'const SourceCommit = "{resolved_source_commit}"',
- f'const PackageCommit = "{resolved_package_commit}"',
- f"const SnapshotPayloadLen = {snapshot['payload_length']}",
- f"const CmdSetTarget byte = 0x{wire['commands']['SET_TARGET']['type']:02X}",
- f"const CmdGetSnapshot byte = 0x{wire['commands']['GET_SNAPSHOT']['type']:02X}",
- f"const CmdSetStimulus byte = 0x{wire['commands']['SET_STIMULUS']['type']:02X}",
- f"const RspSetTargetAck byte = 0x{wire['responses']['SET_TARGET_ACK']['type']:02X}",
- f"const RspGetSnapshotAck byte = 0x{wire['responses']['GET_SNAPSHOT_ACK']['type']:02X}",
- f"const RspSnapshotData byte = 0x{wire['responses']['SNAPSHOT_DATA']['type']:02X}",
- f"const RspStimulusAck byte = 0x{wire['responses']['SET_STIMULUS_ACK']['type']:02X}",
- f"const HostBaud = {wire['host_uart']['baud']}",
- f'const ProfileControl = "6400-control"',
- f'const ProfileIdentification = "6400-identification"',
- f'const ProfileSimDebug = "6400-sim-debug"',
- "",
- ]
- for field in snapshot["fields"]:
- go_lines.append(f"const Snapshot{camel(field['name'])}Offset = {field['offset']}")
- go_lines.extend([
- "",
- f'const GoldenSetTargetStop = "{golden["set_target_stop"].lower()}"',
- f'const GoldenSetTarget20 = "{golden["set_target_20"].lower()}"',
- f'const GoldenSetTarget70 = "{golden["set_target_70"].lower()}"',
- f'const GoldenGetSnapshot = "{golden["get_snapshot"].lower()}"',
- f'const GoldenSetTargetAck = "{golden["set_target_ack"].lower()}"',
- f'const GoldenGetSnapshotAck = "{golden["get_snapshot_ack"].lower()}"',
- f'const GoldenStimulusAck = "{golden["stimulus_ack"].lower()}"',
- f'const GoldenStimulusAllZeroOneSecond = "{golden["stimulus_all_zero_one_second"].lower()}"',
- "",
- ])
- py_lines = [
- '"""Generated 6400 wire and snapshot constants."""',
- f'CONTRACT_SHA256 = "{contract_sha}"',
- f'SOURCE_CONTRACT_FILE_SHA256 = "{source_file_sha}"',
- f'SOURCE_COMMIT = "{resolved_source_commit}"',
- f'PACKAGE_COMMIT = "{resolved_package_commit}"',
- f"SNAPSHOT_PAYLOAD_LENGTH = {snapshot['payload_length']}",
- f"HOST_BAUD = {wire['host_uart']['baud']}",
- "COMMANDS = " + repr({name: value["type"] for name, value in wire["commands"].items()}),
- "RESPONSES = " + repr({name: value["type"] for name, value in wire["responses"].items()}),
- "CANONICAL_PROFILES = " + repr(tuple(contract["canonical_profiles"])),
- "PROFILE_CAPABILITIES = " + repr(contract["canonical_profiles"]),
- "SNAPSHOT_FIELDS = " + repr({field["name"]: field for field in snapshot["fields"]}),
- "CHANNEL_MAP = " + repr(contract["channel_map"]["channels"]),
- "",
- ]
- profile_common = {
- "schema": "hth-6400-profile-v1",
- "contract_sha256": contract_sha,
- "source_commit": resolved_source_commit,
- "source_contract_file_sha256": source_file_sha,
- "golden_vectors_file_sha256": golden_file_sha,
- "serial": {"baud": wire["host_uart"]["baud"], "data_bits": 8, "parity": "N", "stop_bits": 1},
- "snapshot_payload_length": snapshot["payload_length"],
- "single_serial_owner": True,
- "one_outstanding_transaction": True,
- }
- production = {**profile_common, "profile_id": "6400-control", **contract["canonical_profiles"]["6400-control"]}
- identification = {**profile_common, "profile_id": "6400-identification", **contract["canonical_profiles"]["6400-identification"]}
- sim_debug = {**profile_common, "profile_id": "6400-sim-debug", **contract["canonical_profiles"]["6400-sim-debug"]}
- import_meta = {
- "schema": "hth-cpld-contract-import-v2",
- "source_repository": "cpld-temperature-control",
- "source_commit": resolved_source_commit,
- "package_commit": resolved_package_commit,
- "source_contract_file_sha256": source_file_sha,
- "contract_sha256": contract_sha,
- "golden_vectors_file_sha256": golden_file_sha,
- "source_input_bundle_sha256": source_input_bundle_sha256,
- "source_input_file_sha256": source_input_file_sha256,
- }
- return {
- ROOT / "contracts/6400/host-contract.json": raw,
- ROOT / "contracts/6400/SHA256SUMS": f"{source_file_sha} host-contract.json\n".encode(),
- ROOT / "generated/6400/host-contract.json": raw,
- ROOT / "generated/6400/golden-vectors.json": golden_raw,
- ROOT / "generated/6400/import-source.json": json_bytes(import_meta),
- ROOT / "internal/protocol6400/generated_contract.go": ("\n".join(go_lines)).encode(),
- ROOT / "sdk/python/hth_sdk/generated/thermal/contract.py": ("\n".join(py_lines)).encode(),
- ROOT / "sdk/python/hth_sdk/generated/thermal/__init__.py": b"from .contract import * # noqa: F401,F403\n",
- ROOT / "profiles/6400-control/profile.json": json_bytes(production),
- ROOT / "profiles/6400-identification/profile.json": json_bytes(identification),
- ROOT / "profiles/6400-sim-debug/profile.json": json_bytes(sim_debug),
- }
- def main() -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument("--source", type=Path, default=DEFAULT_SOURCE)
- parser.add_argument(
- "--source-commit",
- help=(
- "Functional contract/RTL commit. It may precede the current CPLD package HEAD "
- "only when every bound source input is byte-identical."
- ),
- )
- parser.add_argument("--check", action="store_true")
- args = parser.parse_args()
- expected = outputs(args.source, args.source_commit)
- drift = []
- for path, content in expected.items():
- if args.check:
- if not path.exists() or path.read_bytes() != content:
- drift.append(str(path.relative_to(ROOT)))
- else:
- path.parent.mkdir(parents=True, exist_ok=True)
- if not path.exists() or path.read_bytes() != content:
- path.write_bytes(content)
- if drift:
- print("generated drift: " + ", ".join(drift), file=sys.stderr)
- return 1
- print(f"PASS: {len(expected)} imported files")
- return 0
- if __name__ == "__main__":
- sys.exit(main())
|