build_firmware_package.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. #!/usr/bin/env python3
  2. """Build the Prod2U door-temperature final firmware delivery package.
  3. This is a deterministic wrapper that collects:
  4. - the canonical bitstream from an explicit TD root,
  5. - original and provenance-augmented TD reports,
  6. - source-closure comparison across artifact/matrix/final dev commits,
  7. - selected TD stage evidence (syn/phy/bitgen reports and logs),
  8. - source/contracts/TD inputs,
  9. - generated host contract and golden vectors,
  10. - verification receipts (when available),
  11. - package manifest, SHA-256 sums, and an external selftest sidecar.
  12. It does not access COM/JTAG or program hardware.
  13. """
  14. from __future__ import annotations
  15. import argparse
  16. import hashlib
  17. import json
  18. import shutil
  19. import subprocess
  20. import sys
  21. import zipfile
  22. from datetime import datetime, timezone
  23. from pathlib import Path
  24. from typing import Any
  25. ROOT = Path(__file__).resolve().parents[1]
  26. TD_STAGE_SUFFIXES = {".rpt", ".timing", ".area", ".qor", ".log", ".logw"}
  27. REPO_TD_INPUTS = [
  28. "td/prod2u_p4_normal_v3.prj",
  29. "td/syn/prod2u_p4_normal_v3.tcl",
  30. "td/phy/prod2u_p4_normal_v3.tcl",
  31. "td/bitgen/prod2u_p4_normal_v3.tcl",
  32. ]
  33. class PackagingError(RuntimeError):
  34. """Raised when the firmware package cannot be produced safely."""
  35. def _sha256_file(path: Path) -> str:
  36. digest = hashlib.sha256()
  37. with path.open("rb") as stream:
  38. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  39. digest.update(chunk)
  40. return digest.hexdigest()
  41. def _sha256_bytes(data: bytes) -> str:
  42. return hashlib.sha256(data).hexdigest()
  43. def _read_json(path: Path) -> Any:
  44. return json.loads(path.read_text(encoding="utf-8-sig"))
  45. def _git_show_file(repo_root: Path, commit: str, relative_path: str) -> bytes:
  46. """Return the contents of a tracked path at a specific commit."""
  47. completed = subprocess.run(
  48. ["git", "-C", str(repo_root), "show", f"{commit}:{relative_path}"],
  49. stdout=subprocess.PIPE,
  50. stderr=subprocess.PIPE,
  51. check=False,
  52. )
  53. if completed.returncode != 0:
  54. raise PackagingError(
  55. f"git show failed for {commit}:{relative_path}: {completed.stderr.decode('utf-8', errors='ignore').strip()}"
  56. )
  57. return completed.stdout
  58. def _resolve_path(path: Path) -> Path:
  59. return Path(path).expanduser().resolve()
  60. def _inside(root: Path, candidate: Path) -> bool:
  61. """Return True if candidate is root or under root."""
  62. root = _resolve_path(root)
  63. candidate = _resolve_path(candidate)
  64. try:
  65. candidate.relative_to(root)
  66. return True
  67. except ValueError:
  68. return False
  69. def _validate_td_root(
  70. *,
  71. td_root: Path,
  72. bitstream_path: Path,
  73. td_report_path: Path,
  74. ) -> None:
  75. """Ensure bitstream and report belong to the selected TD root."""
  76. if not _inside(td_root, bitstream_path):
  77. raise PackagingError(f"bitstream {bitstream_path} is outside selected td_root {td_root}")
  78. if not _inside(td_root, td_report_path):
  79. raise PackagingError(f"td report {td_report_path} is outside selected td_root {td_root}")
  80. def _bitstream_path_from_td_root(td_root: Path) -> Path:
  81. return _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit")
  82. def _report_path_from_td_root(td_root: Path) -> Path:
  83. return _resolve_path(td_root / "report.json")
  84. def generate_source_closure_comparison(
  85. *,
  86. td_report: dict[str, Any],
  87. artifact_commit: str,
  88. matrix_commit: str,
  89. final_dev_commit: str,
  90. repo_root: Path = ROOT,
  91. snapshot_hashes: dict[str, dict[str, str]] | None = None,
  92. ) -> dict[str, Any]:
  93. """Compare synthesis inputs across artifact, matrix, and final dev commits.
  94. Modes:
  95. - ``commit_compare``: live repo ``git show`` commit-to-commit (default).
  96. - ``snapshot_hash``: compare caller-supplied SHA-256 maps (no git required).
  97. - ``comparison_unavailable_without_git``: every ``git show`` failed; do **not**
  98. report ``source_closure_equal=false`` with an empty ``production_changed_paths``
  99. as if that were a real commit diff. Full delivery packages must include a git
  100. bundle so replay can restore commit-to-commit comparison.
  101. """
  102. inputs = td_report.get("synthesis_input_manifest", {}).get("inputs", {})
  103. if not inputs:
  104. raise PackagingError("TD report has no synthesis_input_manifest.inputs")
  105. entries: list[dict[str, Any]] = []
  106. production_changed_paths: list[str] = []
  107. all_same = True
  108. commit_keys = (
  109. ("artifact_source_sha256", artifact_commit, "artifact"),
  110. ("matrix_commit_sha256", matrix_commit, "matrix"),
  111. ("final_dev_commit_sha256", final_dev_commit, "final_dev"),
  112. )
  113. if snapshot_hashes is not None:
  114. mode = "snapshot_hash"
  115. for relative_path, artifact_sha in sorted(inputs.items()):
  116. row: dict[str, Any] = {
  117. "path": relative_path,
  118. "artifact_expected_sha256": artifact_sha,
  119. }
  120. values: list[str | None] = []
  121. for key, _commit, label in commit_keys:
  122. sha = snapshot_hashes.get(label, {}).get(relative_path)
  123. row[key] = sha
  124. values.append(sha)
  125. if any(value is None for value in values):
  126. row["status"] = "unavailable"
  127. all_same = False
  128. elif values[0] == values[1] == values[2]:
  129. row["status"] = "same"
  130. else:
  131. row["status"] = "different"
  132. all_same = False
  133. if values[0] != values[2]:
  134. production_changed_paths.append(relative_path)
  135. entries.append(row)
  136. source_closure_equal: bool | None = all_same and all(
  137. entry["status"] == "same" for entry in entries
  138. )
  139. else:
  140. mode = "commit_compare"
  141. for relative_path, artifact_sha in sorted(inputs.items()):
  142. row = {"path": relative_path, "artifact_expected_sha256": artifact_sha}
  143. values = []
  144. for key, commit, _label in commit_keys:
  145. try:
  146. content = _git_show_file(repo_root, commit, relative_path)
  147. sha = _sha256_bytes(content)
  148. except PackagingError:
  149. sha = None
  150. row[key] = sha
  151. values.append(sha)
  152. if values[0] is None and values[1] is None and values[2] is None:
  153. # git show failed for every commit: not a fake "different" commit diff
  154. row["status"] = "unavailable"
  155. elif values[0] == values[1] == values[2] and values[0] is not None:
  156. row["status"] = "same"
  157. else:
  158. row["status"] = "different"
  159. all_same = False
  160. if values[0] != values[2]:
  161. production_changed_paths.append(relative_path)
  162. entries.append(row)
  163. if entries and all(entry["status"] == "unavailable" for entry in entries):
  164. mode = "comparison_unavailable_without_git"
  165. source_closure_equal = None
  166. production_changed_paths = []
  167. all_same = False
  168. else:
  169. if any(entry["status"] == "unavailable" for entry in entries):
  170. all_same = False
  171. source_closure_equal = all_same and all(
  172. entry["status"] == "same" for entry in entries
  173. )
  174. comparison_text = json.dumps(
  175. {
  176. "artifact_source_commit": artifact_commit,
  177. "matrix_commit": matrix_commit,
  178. "final_dev_commit": final_dev_commit,
  179. "mode": mode,
  180. "source_closure_equal": source_closure_equal,
  181. "production_changed_paths": production_changed_paths,
  182. "entries": entries,
  183. },
  184. sort_keys=True,
  185. )
  186. source_set_sha256 = _sha256_bytes(comparison_text.encode("utf-8"))
  187. return {
  188. "schema": "prod2u-source-closure-comparison-v1",
  189. "mode": mode,
  190. "artifact_source_commit": artifact_commit,
  191. "matrix_commit": matrix_commit,
  192. "final_dev_commit": final_dev_commit,
  193. "source_closure_equal": source_closure_equal,
  194. "production_changed_paths": production_changed_paths,
  195. "source_set_sha256": source_set_sha256,
  196. "inputs": entries,
  197. }
  198. def generate_td_provenance(
  199. *,
  200. original_report: dict[str, Any],
  201. artifact_commit: str,
  202. source_closure_comparison_sha256: str,
  203. bitstream_sha256: str,
  204. matrix_run_id: str | None,
  205. ) -> dict[str, Any]:
  206. """Bind the original TD run to the current matrix and source closure."""
  207. return {
  208. "schema": "prod2u-td-provenance-v1",
  209. "status": "bound_by_source_closure_comparison",
  210. "artifact_source_commit": artifact_commit,
  211. "original_td_run_id": original_report.get("run_id"),
  212. "original_placeholder_verification_run_id": original_report.get("verification_run_id"),
  213. "matrix_run_id": matrix_run_id,
  214. "source_closure_comparison_sha256": source_closure_comparison_sha256,
  215. "bitstream_sha256": bitstream_sha256,
  216. "original_report_path": "td/original-final_td_report.json",
  217. "project_config_sha256": original_report.get("project_config_sha256"),
  218. "td_source_manifest_sha256": original_report.get("td_source_manifest_sha256"),
  219. "synthesis_input_manifest_sha256": original_report.get("synthesis_input_manifest", {}).get("sha256"),
  220. }
  221. def _add_file(zipf: zipfile.ZipFile, src: Path, arcname: str, sha256_entries: list[str]) -> None:
  222. zipf.write(src, arcname)
  223. sha256_entries.append(f"{_sha256_file(src)} {arcname}")
  224. def _add_text(zipf: zipfile.ZipFile, text: str, arcname: str, sha256_entries: list[str]) -> None:
  225. payload = text.encode("utf-8")
  226. zipf.writestr(arcname, payload)
  227. sha256_entries.append(f"{_sha256_bytes(payload)} {arcname}")
  228. def _collect_td_stage_files(td_root: Path) -> list[tuple[Path, str]]:
  229. """Collect allowed evidence files from the selected TD build stages."""
  230. collected: list[tuple[Path, str]] = []
  231. stages = ["syn", "phy", "bitgen"]
  232. for stage in stages:
  233. stage_dir = _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / stage)
  234. if not stage_dir.is_dir():
  235. continue
  236. for item in stage_dir.iterdir():
  237. if item.is_file() and item.suffix.casefold() in TD_STAGE_SUFFIXES:
  238. collected.append((item, f"td/{stage}/{item.name}"))
  239. return collected
  240. def _selftest_package(
  241. *,
  242. zip_path: Path,
  243. expected_manifest: dict[str, Any],
  244. td_root: Path,
  245. ) -> dict[str, Any]:
  246. """Verify the built firmware package before writing the sidecar."""
  247. failures: list[str] = []
  248. with zipfile.ZipFile(zip_path, "r", allowZip64=True) as zipf:
  249. names = set(zipf.namelist())
  250. required = {
  251. "fw.bit",
  252. "BITSTREAM-SHA256.txt",
  253. "ARTIFACT-SOURCE-COMMIT.txt",
  254. "MATRIX-COMMIT.txt",
  255. "FINAL-DEV-COMMIT.txt",
  256. "SOURCE-CLOSURE-UNCHANGED.txt",
  257. "PACKAGE-MANIFEST.json",
  258. "SHA256SUMS.txt",
  259. "td/original-final_td_report.json",
  260. "td/TD-PROVENANCE.json",
  261. "evidence/SOURCE-CLOSURE-COMPARISON.json",
  262. "project.json",
  263. "config/source_closure.json",
  264. }
  265. missing = sorted(required - names)
  266. if missing:
  267. failures.append(f"missing_required_files:{missing}")
  268. bad = zipf.testzip()
  269. if bad is not None:
  270. failures.append(f"crc_failed:{bad}")
  271. manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
  272. if manifest["bitstream_sha256"] != expected_manifest["bitstream_sha256"]:
  273. failures.append("bitstream_sha_manifest_mismatch")
  274. # Detect stale repo TD logs from ROOT/td that should not be present
  275. for name in names:
  276. if name.startswith("td/") and "td_20260630" in name:
  277. failures.append(f"stale_td_log_in_package:{name}")
  278. return {
  279. "status": "fail" if failures else "pass",
  280. "failures": failures,
  281. "package_path": str(zip_path),
  282. "package_sha256": _sha256_file(zip_path),
  283. "td_root": str(td_root),
  284. }
  285. def build_firmware_package(
  286. *,
  287. output_dir: Path,
  288. package_name: str | None,
  289. td_root: Path,
  290. artifact_commit: str,
  291. matrix_commit: str,
  292. final_dev_commit: str,
  293. source_closure_unchanged: bool,
  294. bitstream_path: Path | None = None,
  295. td_report_path: Path | None = None,
  296. matrix_receipt_path: Path | None = None,
  297. matrix_run_id: str | None = None,
  298. ) -> tuple[Path, Path]:
  299. """Build and selftest the final firmware ZIP."""
  300. td_root = _resolve_path(td_root)
  301. if bitstream_path is None:
  302. bitstream_path = _bitstream_path_from_td_root(td_root)
  303. if td_report_path is None:
  304. td_report_path = _report_path_from_td_root(td_root)
  305. bitstream_path = _resolve_path(bitstream_path)
  306. td_report_path = _resolve_path(td_report_path)
  307. _validate_td_root(td_root=td_root, bitstream_path=bitstream_path, td_report_path=td_report_path)
  308. if not bitstream_path.is_file():
  309. raise FileNotFoundError(f"bitstream not found: {bitstream_path}")
  310. if not td_report_path.is_file():
  311. raise FileNotFoundError(f"TD report not found: {td_report_path}")
  312. td_report = _read_json(td_report_path)
  313. bitstream_sha256 = _sha256_file(bitstream_path)
  314. # Strong binding checks
  315. report_bitstream_sha = td_report.get("bitstream_sha256")
  316. if report_bitstream_sha and report_bitstream_sha != bitstream_sha256:
  317. raise PackagingError(
  318. f"TD report bitstream_sha256 {report_bitstream_sha} does not match actual {bitstream_sha256}"
  319. )
  320. report_commit = td_report.get("commit_full") or td_report.get("commit")
  321. if report_commit and report_commit != artifact_commit:
  322. raise PackagingError(
  323. f"TD report commit {report_commit} does not match artifact_source_commit {artifact_commit}"
  324. )
  325. report_project_sha = td_report.get("project_config_sha256")
  326. current_project_sha = _sha256_file(ROOT / "projects" / "prod2u-door-temp" / "project.json")
  327. if report_project_sha and report_project_sha != current_project_sha:
  328. raise PackagingError(
  329. f"TD report project_config_sha256 {report_project_sha} does not match current {current_project_sha}"
  330. )
  331. comparison = generate_source_closure_comparison(
  332. td_report=td_report,
  333. artifact_commit=artifact_commit,
  334. matrix_commit=matrix_commit,
  335. final_dev_commit=final_dev_commit,
  336. repo_root=ROOT,
  337. )
  338. if comparison["mode"] == "comparison_unavailable_without_git":
  339. raise PackagingError(
  340. "source closure comparison unavailable without git; "
  341. "full packages require a git bundle so replay can restore commit-to-commit compare"
  342. )
  343. if not source_closure_unchanged and comparison["source_closure_equal"]:
  344. # Caller claimed changed but comparison says same: trust explicit flag
  345. pass
  346. if source_closure_unchanged and comparison["source_closure_equal"] is not True:
  347. raise PackagingError(
  348. f"source_closure_unchanged requested but comparison differs: {comparison['production_changed_paths']}"
  349. )
  350. comparison_json = json.dumps(comparison, indent=2, sort_keys=True) + "\n"
  351. comparison_sha256 = _sha256_bytes(comparison_json.encode("utf-8"))
  352. provenance = generate_td_provenance(
  353. original_report=td_report,
  354. artifact_commit=artifact_commit,
  355. source_closure_comparison_sha256=comparison_sha256,
  356. bitstream_sha256=bitstream_sha256,
  357. matrix_run_id=matrix_run_id,
  358. )
  359. provenance_json = json.dumps(provenance, indent=2, sort_keys=True) + "\n"
  360. provenance_sha256 = _sha256_bytes(provenance_json.encode("utf-8"))
  361. timing = td_report.get("timing", {})
  362. resources_section = td_report.get("resources", {})
  363. utilization = resources_section.get("utilization", {})
  364. manifest: dict[str, Any] = {
  365. "schema": "prod2u-door-temp-final-package-manifest-v2",
  366. "package_name": package_name or f"prod2u-door-temp-final-{artifact_commit[:8]}-{bitstream_sha256[:8]}",
  367. "status": "VERIFIED_OFFLINE",
  368. "created_at": datetime.now(timezone.utc).isoformat(),
  369. "verification_scope": "offline",
  370. "hardware_validation": "not_run",
  371. "artifact_source_commit": artifact_commit,
  372. "matrix_commit": matrix_commit,
  373. "final_dev_commit": final_dev_commit,
  374. "td_run_id": td_report.get("run_id"),
  375. "matrix_run_id": matrix_run_id,
  376. "source_closure_unchanged": bool(comparison["source_closure_equal"]),
  377. "source_closure_comparison_mode": comparison["mode"],
  378. "project_config_sha256": current_project_sha,
  379. "td_source_manifest_sha256": td_report.get("td_source_manifest_sha256"),
  380. "synthesis_input_manifest_sha256": td_report.get("synthesis_input_manifest", {}).get("sha256"),
  381. "source_closure_comparison_sha256": comparison_sha256,
  382. "bitstream_sha256": bitstream_sha256,
  383. "matrix_receipt_sha256": _sha256_file(matrix_receipt_path) if matrix_receipt_path and matrix_receipt_path.is_file() else None,
  384. "original_td_receipt_sha256": _sha256_file(td_report_path),
  385. "td_provenance_sha256": provenance_sha256,
  386. "resources": {
  387. "lut": utilization.get("lut", {}).get("used"),
  388. "register": utilization.get("reg", {}).get("used"),
  389. "packed_slice": resources_section.get("packing", {}).get("total_slices"),
  390. "bram": utilization.get("bram", {}).get("used"),
  391. "dsp": utilization.get("dsp", {}).get("used"),
  392. },
  393. "timing": {
  394. "fmax_mhz": timing.get("fmax_mhz"),
  395. "setup_slack_ns": timing.get("worst_setup_slack_ns"),
  396. "hold_slack_ns": timing.get("worst_hold_slack_ns"),
  397. },
  398. }
  399. output_dir = _resolve_path(output_dir)
  400. output_dir.mkdir(parents=True, exist_ok=True)
  401. name = manifest["package_name"]
  402. zip_path = output_dir / f"{name}.zip"
  403. if zip_path.exists():
  404. zip_path.unlink()
  405. sha256_entries: list[str] = []
  406. with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as zipf:
  407. # Bitstream and provenance
  408. _add_file(zipf, bitstream_path, "fw.bit", sha256_entries)
  409. _add_text(zipf, bitstream_sha256, "BITSTREAM-SHA256.txt", sha256_entries)
  410. _add_text(zipf, artifact_commit, "ARTIFACT-SOURCE-COMMIT.txt", sha256_entries)
  411. _add_text(zipf, matrix_commit, "MATRIX-COMMIT.txt", sha256_entries)
  412. _add_text(zipf, final_dev_commit, "FINAL-DEV-COMMIT.txt", sha256_entries)
  413. _add_text(
  414. zipf,
  415. "true" if comparison["source_closure_equal"] is True else "false",
  416. "SOURCE-CLOSURE-UNCHANGED.txt",
  417. sha256_entries,
  418. )
  419. # Original TD report and provenance
  420. _add_file(zipf, td_report_path, "td/original-final_td_report.json", sha256_entries)
  421. _add_text(zipf, provenance_json, "td/TD-PROVENANCE.json", sha256_entries)
  422. # Selected TD stage evidence from the explicit TD root
  423. for src, arcname in _collect_td_stage_files(td_root):
  424. _add_file(zipf, src, arcname, sha256_entries)
  425. # Project contract and protocol
  426. _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "project.json", "project.json", sha256_entries)
  427. _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "requirements.zh-CN.md", "requirements.zh-CN.md", sha256_entries)
  428. _add_file(zipf, ROOT / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "docs/prod2u-door-temp-protocol.zh-CN.md", sha256_entries)
  429. # Generated artifacts
  430. for gen in (ROOT / "src" / "generated").iterdir():
  431. if gen.is_file():
  432. _add_file(zipf, gen, f"src/generated/{gen.name}", sha256_entries)
  433. # Constraints
  434. for adc in (ROOT / "constraints").iterdir():
  435. if adc.is_file():
  436. _add_file(zipf, adc, f"constraints/{adc.name}", sha256_entries)
  437. # Tracked TD inputs from the repo (not the build root)
  438. for td_input in REPO_TD_INPUTS:
  439. src = ROOT / td_input
  440. if src.is_file():
  441. _add_file(zipf, src, td_input, sha256_entries)
  442. # Source closure manifest
  443. _add_file(zipf, ROOT / "config" / "source_closure.json", "config/source_closure.json", sha256_entries)
  444. # Source-closure comparison
  445. _add_text(zipf, comparison_json, "evidence/SOURCE-CLOSURE-COMPARISON.json", sha256_entries)
  446. # Optional matrix receipt
  447. if matrix_receipt_path and matrix_receipt_path.is_file():
  448. _add_file(zipf, matrix_receipt_path, "evidence/matrix-receipt.json", sha256_entries)
  449. # Manifest and SHA256SUMS
  450. manifest_text = json.dumps(manifest, indent=2, sort_keys=True) + "\n"
  451. _add_text(zipf, manifest_text, "PACKAGE-MANIFEST.json", sha256_entries)
  452. _add_text(zipf, "\n".join(sha256_entries) + "\n", "SHA256SUMS.txt", sha256_entries)
  453. selftest = _selftest_package(zip_path=zip_path, expected_manifest=manifest, td_root=td_root)
  454. if selftest["status"] != "pass":
  455. zip_path.unlink(missing_ok=True)
  456. raise PackagingError(f"firmware package selftest failed: {selftest['failures']}")
  457. selftest["package_selftest_status"] = "pass"
  458. selftest["manifest"] = manifest
  459. sidecar_path = output_dir / f"{name}.selftest.json"
  460. sidecar_path.write_text(json.dumps(selftest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  461. return zip_path, sidecar_path
  462. def main(argv: list[str] | None = None) -> int:
  463. parser = argparse.ArgumentParser(description=__doc__)
  464. parser.add_argument("--output-dir", type=Path, default=Path.home() / "Downloads" / "CPLD-firmware")
  465. parser.add_argument("--package-name", help="package base name (default from commit/bitstream)")
  466. parser.add_argument("--td-root", type=Path, required=True)
  467. parser.add_argument("--bitstream", type=Path, default=None)
  468. parser.add_argument("--td-report", type=Path, default=None)
  469. parser.add_argument("--artifact-commit", required=True)
  470. parser.add_argument("--matrix-commit", required=True)
  471. parser.add_argument("--final-dev-commit", required=True)
  472. parser.add_argument("--source-closure-unchanged", action="store_true")
  473. parser.add_argument("--matrix-receipt", type=Path, default=None)
  474. parser.add_argument("--matrix-run-id", default=None)
  475. args = parser.parse_args(argv)
  476. try:
  477. zip_path, sidecar_path = build_firmware_package(
  478. output_dir=args.output_dir,
  479. package_name=args.package_name,
  480. td_root=args.td_root,
  481. artifact_commit=args.artifact_commit,
  482. matrix_commit=args.matrix_commit,
  483. final_dev_commit=args.final_dev_commit,
  484. source_closure_unchanged=args.source_closure_unchanged,
  485. bitstream_path=args.bitstream,
  486. td_report_path=args.td_report,
  487. matrix_receipt_path=args.matrix_receipt,
  488. matrix_run_id=args.matrix_run_id,
  489. )
  490. except (FileNotFoundError, PackagingError) as exc:
  491. print(f"error: {exc}", file=sys.stderr)
  492. return 1
  493. print(
  494. json.dumps(
  495. {"status": "pass", "package": str(zip_path), "selftest": str(sidecar_path)},
  496. indent=2,
  497. )
  498. )
  499. return 0
  500. if __name__ == "__main__":
  501. raise SystemExit(main())