target_registry.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. """Tiny target registry: alias -> build entry. Not a product contract."""
  2. from __future__ import annotations
  3. import json
  4. from dataclasses import dataclass
  5. from pathlib import Path
  6. from typing import Any, Mapping
  7. from tools.fw_targets import FORBIDDEN_6400_SUBSTRINGS, load_registry, resolve_target as resolve_entry
  8. ROOT = Path(__file__).resolve().parents[1]
  9. REGISTRY_PATH = ROOT / "projects" / "registry.json"
  10. class TargetError(ValueError):
  11. """Unknown or invalid firmware target."""
  12. @dataclass(frozen=True)
  13. class Target:
  14. alias: str
  15. project_id: str
  16. profile: str
  17. semantic_profile: str
  18. display_name: str
  19. project_config: Path
  20. requirements: Path
  21. source_closure: Path
  22. top_module: str
  23. generated_dir: Path
  24. params_header: Path
  25. host_contract: Path
  26. adc: Path
  27. sdc: Path
  28. td_project: Path
  29. verification_targets: Path
  30. release_pin_policy: str
  31. features: Mapping[str, bool]
  32. raw: Mapping[str, Any]
  33. def _load_registry(path: Path | None = None) -> dict[str, Any]:
  34. try:
  35. return load_registry(ROOT, path or REGISTRY_PATH)
  36. except ValueError as exc:
  37. raise TargetError(str(exc)) from exc
  38. def list_target_aliases(path: Path | None = None) -> tuple[str, ...]:
  39. payload = _load_registry(path)
  40. aliases: list[str] = []
  41. seen: set[str] = set()
  42. for name, entry in payload["targets"].items():
  43. if name in seen:
  44. raise TargetError(f"duplicate canonical alias: {name}")
  45. seen.add(name)
  46. aliases.append(name)
  47. for extra in entry.get("aliases", []):
  48. if extra == name:
  49. continue
  50. if extra in seen:
  51. raise TargetError(f"duplicate alias: {extra}")
  52. seen.add(str(extra))
  53. return tuple(aliases)
  54. def resolve_target(name: str, *, repo: Path | None = None, registry_path: Path | None = None) -> Target:
  55. if not isinstance(name, str) or not name.strip():
  56. raise TargetError("target name required")
  57. root = repo or ROOT
  58. try:
  59. entry=resolve_entry(name, root, registry_path)
  60. except ValueError as exc:
  61. raise TargetError(str(exc)) from exc
  62. canonical=entry['alias']
  63. project_rel = entry.get("project_config") or entry.get("project_json")
  64. if not project_rel:
  65. raise TargetError(f"{canonical} registry entry missing project_json")
  66. profile = str(entry.get("profile") or entry.get("project_profile") or entry.get("validation_profile"))
  67. verification_rel = entry['verification_targets']
  68. return Target(
  69. alias=canonical,
  70. project_id=str(entry["project_id"]),
  71. profile=profile,
  72. semantic_profile=str(entry.get("semantic_profile") or entry.get("validation_profile") or profile),
  73. display_name=str(entry["display_name"]),
  74. project_config=root / project_rel,
  75. requirements=root / entry["requirements"],
  76. source_closure=root / entry["source_closure"],
  77. top_module=str(entry["top_module"]),
  78. generated_dir=root / entry["generated_dir"],
  79. params_header=root / entry["params_header"],
  80. host_contract=root / entry["host_contract"],
  81. adc=root / entry["adc"],
  82. sdc=root / entry["sdc"],
  83. td_project=root / entry["td_project"],
  84. verification_targets=root / verification_rel,
  85. release_pin_policy=str(entry["release_pin_policy"]),
  86. features=dict(entry.get("features", {})),
  87. raw=entry,
  88. )
  89. def load_source_closure(target: Target) -> tuple[str, ...]:
  90. payload = json.loads(target.source_closure.read_text(encoding="utf-8"))
  91. if not isinstance(payload, Mapping):
  92. raise TargetError(f"{target.alias} source closure root must be an object")
  93. sources = payload.get("sources")
  94. if not isinstance(sources, list) or not sources:
  95. raise TargetError(f"{target.alias} source closure must contain sources")
  96. normalized: list[str] = []
  97. for value in sources:
  98. if not isinstance(value, str) or not value:
  99. raise TargetError("source closure entry must be a relative path")
  100. parts = Path(value).parts
  101. if ".." in parts or Path(value).is_absolute():
  102. raise TargetError(f"unsafe source path: {value}")
  103. normalized.append(value)
  104. if len(normalized) != len(set(normalized)):
  105. raise TargetError(f"{target.alias} source closure contains duplicates")
  106. missing = [
  107. path
  108. for path in normalized
  109. if not (Path(target.raw['root']) / path).is_file() and not path.replace("\\", "/").startswith("generated/")
  110. ]
  111. if missing:
  112. raise TargetError(f"{target.alias} source closure missing files: {missing}")
  113. if target.alias == "6400":
  114. banned = [path for path in normalized if any(marker in path for marker in FORBIDDEN_6400_SUBSTRINGS)]
  115. if banned:
  116. raise TargetError(f"6400 source closure includes motor/limit files: {banned}")
  117. return tuple(normalized)
  118. def unresolved_release_pins(project: Mapping[str, Any]) -> tuple[str, ...]:
  119. names: list[str] = []
  120. outputs = project.get("outputs", {})
  121. for kind in ("ptc_channels", "fan_channels"):
  122. for item in outputs.get(kind, []):
  123. if item.get("pin_status") == "tbd":
  124. names.append(str(item.get("logical_name") or item.get("name")))
  125. return tuple(names)
  126. def release_blocked(target: Target, project: Mapping[str, Any] | None = None) -> tuple[bool, tuple[str, ...]]:
  127. if target.release_pin_policy != "fail_closed_unresolved":
  128. return False, ()
  129. payload = project
  130. if payload is None:
  131. payload = json.loads(target.project_config.read_text(encoding="utf-8"))
  132. pins = unresolved_release_pins(payload)
  133. return bool(pins), pins