| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154 |
- """Tiny target registry: alias -> build entry. Not a product contract."""
- from __future__ import annotations
- import json
- from dataclasses import dataclass
- from pathlib import Path
- from typing import Any, Mapping
- from tools.fw_targets import FORBIDDEN_6400_SUBSTRINGS, load_registry, resolve_target as resolve_entry
- ROOT = Path(__file__).resolve().parents[1]
- REGISTRY_PATH = ROOT / "projects" / "registry.json"
- class TargetError(ValueError):
- """Unknown or invalid firmware target."""
- @dataclass(frozen=True)
- class Target:
- alias: str
- project_id: str
- profile: str
- semantic_profile: str
- display_name: str
- project_config: Path
- requirements: Path
- source_closure: Path
- top_module: str
- generated_dir: Path
- params_header: Path
- host_contract: Path
- adc: Path
- sdc: Path
- td_project: Path
- verification_targets: Path
- release_pin_policy: str
- features: Mapping[str, bool]
- raw: Mapping[str, Any]
- def _load_registry(path: Path | None = None) -> dict[str, Any]:
- try:
- return load_registry(ROOT, path or REGISTRY_PATH)
- except ValueError as exc:
- raise TargetError(str(exc)) from exc
- def list_target_aliases(path: Path | None = None) -> tuple[str, ...]:
- payload = _load_registry(path)
- aliases: list[str] = []
- seen: set[str] = set()
- for name, entry in payload["targets"].items():
- if name in seen:
- raise TargetError(f"duplicate canonical alias: {name}")
- seen.add(name)
- aliases.append(name)
- for extra in entry.get("aliases", []):
- if extra == name:
- continue
- if extra in seen:
- raise TargetError(f"duplicate alias: {extra}")
- seen.add(str(extra))
- return tuple(aliases)
- def resolve_target(name: str, *, repo: Path | None = None, registry_path: Path | None = None) -> Target:
- if not isinstance(name, str) or not name.strip():
- raise TargetError("target name required")
- root = repo or ROOT
- try:
- entry=resolve_entry(name, root, registry_path)
- except ValueError as exc:
- raise TargetError(str(exc)) from exc
- canonical=entry['alias']
- project_rel = entry.get("project_config") or entry.get("project_json")
- if not project_rel:
- raise TargetError(f"{canonical} registry entry missing project_json")
- profile = str(entry.get("profile") or entry.get("project_profile") or entry.get("validation_profile"))
- verification_rel = entry['verification_targets']
- return Target(
- alias=canonical,
- project_id=str(entry["project_id"]),
- profile=profile,
- semantic_profile=str(entry.get("semantic_profile") or entry.get("validation_profile") or profile),
- display_name=str(entry["display_name"]),
- project_config=root / project_rel,
- requirements=root / entry["requirements"],
- source_closure=root / entry["source_closure"],
- top_module=str(entry["top_module"]),
- generated_dir=root / entry["generated_dir"],
- params_header=root / entry["params_header"],
- host_contract=root / entry["host_contract"],
- adc=root / entry["adc"],
- sdc=root / entry["sdc"],
- td_project=root / entry["td_project"],
- verification_targets=root / verification_rel,
- release_pin_policy=str(entry["release_pin_policy"]),
- features=dict(entry.get("features", {})),
- raw=entry,
- )
- def load_source_closure(target: Target) -> tuple[str, ...]:
- payload = json.loads(target.source_closure.read_text(encoding="utf-8"))
- if not isinstance(payload, Mapping):
- raise TargetError(f"{target.alias} source closure root must be an object")
- sources = payload.get("sources")
- if not isinstance(sources, list) or not sources:
- raise TargetError(f"{target.alias} source closure must contain sources")
- normalized: list[str] = []
- for value in sources:
- if not isinstance(value, str) or not value:
- raise TargetError("source closure entry must be a relative path")
- parts = Path(value).parts
- if ".." in parts or Path(value).is_absolute():
- raise TargetError(f"unsafe source path: {value}")
- normalized.append(value)
- if len(normalized) != len(set(normalized)):
- raise TargetError(f"{target.alias} source closure contains duplicates")
- missing = [
- path
- for path in normalized
- if not (Path(target.raw['root']) / path).is_file() and not path.replace("\\", "/").startswith("generated/")
- ]
- if missing:
- raise TargetError(f"{target.alias} source closure missing files: {missing}")
- if target.alias == "6400":
- banned = [path for path in normalized if any(marker in path for marker in FORBIDDEN_6400_SUBSTRINGS)]
- if banned:
- raise TargetError(f"6400 source closure includes motor/limit files: {banned}")
- return tuple(normalized)
- def unresolved_release_pins(project: Mapping[str, Any]) -> tuple[str, ...]:
- names: list[str] = []
- outputs = project.get("outputs", {})
- for kind in ("ptc_channels", "fan_channels"):
- for item in outputs.get(kind, []):
- if item.get("pin_status") == "tbd":
- names.append(str(item.get("logical_name") or item.get("name")))
- return tuple(names)
- def release_blocked(target: Target, project: Mapping[str, Any] | None = None) -> tuple[bool, tuple[str, ...]]:
- if target.release_pin_policy != "fail_closed_unresolved":
- return False, ()
- payload = project
- if payload is None:
- payload = json.loads(target.project_config.read_text(encoding="utf-8"))
- pins = unresolved_release_pins(payload)
- return bool(pins), pins
|