package_hth_hw_evidence.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #!/usr/bin/env python3
  2. """Optional hardware/RTL evidence zip. No BRD/PDF/schematics."""
  3. from __future__ import annotations
  4. import hashlib
  5. import json
  6. import os
  7. import subprocess
  8. import time
  9. import zipfile
  10. from datetime import datetime, timezone
  11. from pathlib import Path
  12. from package_hth_review import write_zip_file, zip_file_mode
  13. def git_info(repo: Path) -> tuple[str, str]:
  14. def run(args: list[str]) -> str:
  15. try:
  16. return subprocess.check_output(args, cwd=repo, stderr=subprocess.DEVNULL, text=True).strip()
  17. except (subprocess.CalledProcessError, FileNotFoundError):
  18. return "unknown"
  19. return run(["git", "rev-parse", "HEAD"]), run(["git", "rev-parse", "--short", "HEAD"])
  20. def main() -> int:
  21. host_root = Path(__file__).resolve().parents[1]
  22. repo = host_root.parent
  23. head, short = git_info(repo)
  24. run_id = os.environ.get("HTH_RUN_ID") or datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  25. epoch = os.environ.get("SOURCE_DATE_EPOCH") or "1764000000"
  26. try:
  27. epoch = subprocess.check_output(["git", "log", "-1", "--format=%ct"], cwd=repo, text=True).strip()
  28. except (subprocess.CalledProcessError, FileNotFoundError):
  29. pass
  30. zip_date = time.gmtime(int(epoch))[:6]
  31. out = Path(f"/tmp/hth-platform-hw-evidence-r5-{short}-{run_id}.zip")
  32. root = "hth-platform-hw-r5"
  33. files: list[tuple[str, bytes, int]] = []
  34. def add_file(rel: str, path: Path, mode: int | None = None) -> None:
  35. if not path.is_file() or path.stat().st_size >= 32 * 1024 * 1024:
  36. return
  37. files.append((f"{root}/{rel}", path.read_bytes(), mode or zip_file_mode(path)))
  38. rtl_allow = (
  39. "src/generated/host-contract.json",
  40. "src/generated/golden-vectors.json",
  41. "docs/prod2u-door-temp-protocol.zh-CN.md",
  42. "projects/prod2u-door-temp/project.json",
  43. )
  44. for rel in rtl_allow:
  45. add_file(rel, repo / rel)
  46. rtl_src = repo / "src"
  47. if rtl_src.is_dir():
  48. for p in sorted(rtl_src.rglob("*")):
  49. if not p.is_file():
  50. continue
  51. if p.suffix.lower() not in {".v", ".sv", ".vh", ".svh", ".vhdl", ".vhd"}:
  52. continue
  53. rel = str(p.relative_to(repo))
  54. if any(tok in rel for tok in ("build/", "sim_build/", "__pycache__", ".git")):
  55. continue
  56. add_file(rel, p)
  57. run_dir = os.environ.get("HTH_RUN_DIR", "").strip()
  58. if run_dir:
  59. rd = Path(run_dir)
  60. for name in (
  61. "rtl-production-uart.log",
  62. "rtl-production-uart.meta",
  63. "rtl-raw.log",
  64. "rtl-frames.log",
  65. "rtl-result.txt",
  66. ):
  67. add_file(f"run/{name}", rd / name)
  68. for p in sorted(rd.glob("rtl*")):
  69. add_file(f"run/{p.name}", p)
  70. ident = {
  71. "package": "hth-platform-hw-evidence-r5",
  72. "git_commit": head,
  73. "git_short": short,
  74. "run_id": run_id,
  75. "note": "RTL/sim evidence only. BRD/PDF/schematics are not included.",
  76. }
  77. files.append((f"{root}/PACKAGE_IDENTITY.json", json.dumps(ident, indent=2).encode() + b"\n", 0o644))
  78. files.sort(key=lambda x: x[0])
  79. sha_lines = []
  80. man = []
  81. with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
  82. for name, data, mode in files:
  83. info_name = name
  84. zi = zipfile.ZipInfo(info_name)
  85. zi.create_system = 3
  86. zi.date_time = zip_date
  87. zi.external_attr = (mode & 0o777) << 16
  88. zi.compress_type = zipfile.ZIP_DEFLATED
  89. zf.writestr(zi, data)
  90. key = name[len(root) + 1 :]
  91. digest = hashlib.sha256(data).hexdigest()
  92. sha_lines.append(f"{digest} {key}")
  93. man.append({"path": key, "size": len(data), "mode": f"{mode:04o}", "sha256": digest, "source_class": "hw"})
  94. write_zip_file(zf, f"{root}/SHA256SUMS", ("\n".join(sha_lines) + "\n").encode(), 0o644)
  95. write_zip_file(zf, f"{root}/MANIFEST.json", json.dumps(man, indent=2).encode() + b"\n", 0o644)
  96. digest = hashlib.sha256(out.read_bytes()).hexdigest()
  97. print(f"zip={out}")
  98. print(f"bytes={out.stat().st_size}")
  99. print(f"sha256={digest}")
  100. return 0
  101. if __name__ == "__main__":
  102. raise SystemExit(main())