| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149 |
- #!/usr/bin/env python3
- """Tiny target registry: alias -> project/build entry. Not a product contract."""
- from __future__ import annotations
- import hashlib
- import json
- from pathlib import Path
- from collections.abc import Iterable
- from typing import Any, Mapping
- REGISTRY_REL = Path("projects") / "registry.json"
- # Active-closure ban list of retired 6400 *modules and source paths*. It is not
- # a protocol filter: the new 8-bit frame's TYPE bytes and macro names are legal
- # and must never be added here.
- FORBIDDEN_6400_SUBSTRINGS = (
- "startup_close_seek",
- "door_motor_engine",
- "door_action_dispatcher",
- "door_percent_planner",
- "door_motion",
- "door_axis",
- "door_calibration",
- "door_shared_dda",
- "door_rate_quantum",
- "door_profile_quantum",
- "prod2u_runtime_step_limit_gate",
- "output_target_ram",
- "host_i2c",
- "src/modules/pwm_scheduler.v",
- "src/project/command_controller.v",
- "src/project/project_adapter.v",
- "src/top/prod2u_p4_normal_v3_top",
- )
- def repo_root() -> Path:
- return Path(__file__).resolve().parents[1]
- def load_registry(root: Path | None = None, registry_path: Path | None = None) -> dict[str, Any]:
- base = Path(root) if root is not None else repo_root()
- path = registry_path or base / REGISTRY_REL
- payload = json.loads(path.read_text(encoding="utf-8"))
- if payload.get("schema") != "prod2u-target-registry-v1":
- raise ValueError("target registry schema mismatch")
- targets = payload.get("targets")
- if not isinstance(targets, dict) or not targets:
- raise ValueError("target registry has no targets")
- aliases = list(targets)
- if len(aliases) != len(set(aliases)):
- raise ValueError("target aliases are not unique")
- ids = [str(item.get("project_id")) for item in targets.values()]
- if len(ids) != len(set(ids)):
- raise ValueError("target project_id values are not unique")
- owner: dict[str, str] = {}
- for canonical, entry in targets.items():
- for alias in {canonical, str(entry['project_id']), *entry.get('aliases', [])}:
- key=str(alias).strip().lower()
- if not key or (key in owner and owner[key]!=canonical):
- raise ValueError(f"ambiguous target alias: {alias}")
- owner[key]=canonical
- return payload
- def list_aliases(root: Path | None = None) -> tuple[str, ...]:
- return tuple(load_registry(root)["targets"])
- def resolve_target(name: str, root: Path | None = None, registry_path: Path | None = None) -> dict[str, Any]:
- base = Path(root) if root is not None else repo_root()
- key = str(name).strip().lower()
- targets = load_registry(base, registry_path)["targets"]
- choices=[canonical for canonical, entry in targets.items() if key in
- {str(x).strip().lower() for x in {canonical, entry['project_id'], *entry.get('aliases', [])}}]
- if len(choices)!=1:
- known = ", ".join(sorted(targets))
- raise ValueError(f"unknown target {name!r}; known targets: {known}")
- canonical=choices[0]
- entry = dict(targets[canonical])
- entry["alias"] = canonical
- entry["root"] = str(base)
- return entry
- def sha256_file(path: Path) -> str:
- return hashlib.sha256(path.read_bytes()).hexdigest()
- def load_source_closure(path: Path, expected_project_id: str | None = None) -> tuple[str, ...]:
- payload = json.loads(path.read_text(encoding="utf-8"))
- if payload.get("schema") != "prod2u-source-closure-v1":
- raise ValueError(f"source closure schema mismatch: {path}")
- if expected_project_id and payload.get("project_id") != expected_project_id:
- raise ValueError(f"source closure project_id mismatch in {path}")
- sources = payload.get("sources")
- if not isinstance(sources, list) or not sources:
- raise ValueError(f"source closure missing sources: {path}")
- normalized: list[str] = []
- for value in sources:
- if not isinstance(value, str) or not value:
- raise ValueError("source closure entry must be a non-empty string")
- parts = Path(value).parts
- if ".." in parts or Path(value).is_absolute():
- raise ValueError(f"unsafe source closure path: {value}")
- normalized.append(value)
- if len(normalized) != len(set(normalized)):
- raise ValueError(f"source closure contains duplicates: {path}")
- root = next((parent for parent in path.resolve().parents if (parent/REGISTRY_REL).is_file()),None)
- if root is None:
- raise ValueError(f"source closure has no owning target registry: {path}")
- missing = [item for item in normalized if not (root / item).is_file()]
- # Generated headers may be absent before first generate.
- missing_real = [item for item in missing if not item.replace("\\", "/").startswith("generated/")]
- if missing_real:
- raise ValueError(f"source closure references missing files: {missing_real}")
- return tuple(normalized)
- def assert_6400_closure_clean(sources: Mapping[str, Any] | Iterable[str]) -> None:
- values = list(sources.get("sources", [])) if isinstance(sources, dict) else list(sources)
- joined = "\n".join(str(item) for item in values)
- hits = [token for token in FORBIDDEN_6400_SUBSTRINGS if token in joined]
- if hits:
- raise ValueError(f"6400 source closure contains forbidden motor/limit modules: {hits}")
- def unresolved_pins(project: Mapping[str, Any]) -> list[str]:
- names: list[str] = []
- for channel in project.get("outputs", {}).get("fan_channels", []):
- if str(channel.get("pin_status", "confirmed")) != "confirmed":
- names.append(str(channel.get("name", "unknown")))
- for channel in project.get("outputs", {}).get("ptc_channels", []):
- if str(channel.get("pin_status", "confirmed")) != "confirmed":
- names.append(str(channel.get("name", "unknown")))
- return names
- def target_status_line(alias: str, root: Path | None = None) -> str:
- entry = resolve_target(alias, root)
- if entry.get('status')=='CURRENT_PRODUCT_FULL_PENDING':
- return f"{entry['alias']:8} {entry['project_id']} / {entry['board']} / Full acceptance pending"
- if entry.get("production_bitstream") == "allowed":
- return f"{alias:8} release-ready"
- if entry.get("production_bitstream") == "blocked_td_not_wired":
- return f"{alias:8} logic-ready / release-blocked: 6400 production TD not wired"
- if entry.get("release_pin_policy") == "fail_closed_unresolved":
- return f"{alias:8} logic-ready / release-blocked: unresolved pins"
- return f"{alias:8} unknown"
|