deploy_unpacked_release.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. #!/usr/bin/env python3
  2. """Assemble and deploy a completely unpacked (non-archive) Windows release tree
  3. covering 6400 V2.0, 6400 V1.1, MRDIMM V1.2, shared tools, board viewer, SDK, and docs.
  4. """
  5. from __future__ import annotations
  6. import argparse
  7. import base64
  8. from datetime import datetime, timezone
  9. import hashlib
  10. import json
  11. import os
  12. from pathlib import Path
  13. import shutil
  14. import subprocess
  15. import sys
  16. ROOT = Path(__file__).resolve().parents[1]
  17. BAUDS = (921600, 460800, 230400, 115200)
  18. def sha256_bytes(data: bytes) -> str:
  19. return hashlib.sha256(data).hexdigest()
  20. def sha256_file(path: Path) -> str:
  21. h = hashlib.sha256()
  22. with path.open("rb") as f:
  23. while chunk := f.read(1024 * 1024):
  24. h.update(chunk)
  25. return h.hexdigest()
  26. def copy_file(src: Path, dst: Path) -> None:
  27. dst.parent.mkdir(parents=True, exist_ok=True)
  28. shutil.copy2(src, dst)
  29. os.chmod(dst, 0o644)
  30. def write_text_crlf(dst: Path, text: str) -> None:
  31. dst.parent.mkdir(parents=True, exist_ok=True)
  32. dst.write_bytes(text.replace("\r\n", "\n").replace("\n", "\r\n").encode("utf-8"))
  33. def export_git_tree(repo: Path, ref: str, dst_dir: Path, *, exclude_prefixes: tuple[str, ...] = ()) -> int:
  34. count = 0
  35. raw = subprocess.check_output(["git", "-C", str(repo), "ls-tree", "-r", "-z", "--name-only", ref])
  36. for rel in raw.decode("utf-8").split("\0"):
  37. if not rel or any(rel == p or rel.startswith(p + "/") for p in exclude_prefixes):
  38. continue
  39. blob = subprocess.check_output(["git", "-C", str(repo), "show", f"{ref}:{rel}"])
  40. target = dst_dir / rel
  41. target.parent.mkdir(parents=True, exist_ok=True)
  42. target.write_bytes(blob)
  43. os.chmod(target, 0o644)
  44. count += 1
  45. return count
  46. def copy_working_tracked(repo: Path, dst_dir: Path, *, exclude_prefixes: tuple[str, ...] = ()) -> int:
  47. count = 0
  48. raw = subprocess.check_output(["git", "-C", str(repo), "ls-files", "-z"])
  49. for rel in raw.decode("utf-8").split("\0"):
  50. if not rel or any(rel == p or rel.startswith(p + "/") for p in exclude_prefixes):
  51. continue
  52. src = repo / rel
  53. if src.is_file():
  54. copy_file(src, dst_dir / rel)
  55. count += 1
  56. return count
  57. def copy_firmware_group(runs: dict[int, Path], dst_firmware: Path, stem: str) -> list[dict]:
  58. entries = []
  59. for baud in BAUDS:
  60. run_dir = runs[baud]
  61. receipt = json.loads((run_dir / "td-receipt.json").read_text(encoding="utf-8"))
  62. bit_rel = receipt["bitstream"]
  63. bit_src = Path(bit_rel) if Path(bit_rel).is_absolute() else (run_dir / bit_rel)
  64. bmk_src = bit_src.with_suffix(".bmk")
  65. if not bit_src.is_file():
  66. raise FileNotFoundError(f"missing bitstream: {bit_src}")
  67. if not bmk_src.is_file():
  68. raise FileNotFoundError(f"missing .bmk readback mask: {bmk_src}")
  69. if sha256_file(bit_src) != receipt.get("bitstream_sha256"):
  70. raise ValueError(f"bitstream SHA mismatch in {run_dir}")
  71. out_dir = dst_firmware / str(baud)
  72. out_dir.mkdir(parents=True, exist_ok=True)
  73. copy_file(bit_src, out_dir / f"{stem}_{baud}.bit")
  74. copy_file(bmk_src, out_dir / f"{stem}_{baud}.bmk")
  75. copy_file(bit_src, out_dir / "firmware.bit")
  76. copy_file(bmk_src, out_dir / "firmware.bmk")
  77. copy_file(run_dir / "td-receipt.json", out_dir / "td-receipt.json")
  78. entries.append({
  79. "baud": baud,
  80. "file": f"{stem}_{baud}.bit",
  81. "bit_sha256": receipt["bitstream_sha256"],
  82. "bmk_sha256": sha256_file(bmk_src),
  83. "metrics": receipt.get("metrics", {}),
  84. })
  85. return entries
  86. def main(argv: list[str] | None = None) -> int:
  87. parser = argparse.ArgumentParser(description=__doc__)
  88. parser.add_argument("--stage-dir", type=Path, default=Path("/data/prod2u/releases/v3.3.0-unpacked"))
  89. parser.add_argument("--destination", default=r"C:\Prod2U_Releases\v3.3.0-unpacked")
  90. parser.add_argument("--host", default="administrator@192.168.2.24")
  91. parser.add_argument("--v2-gui-dir", type=Path,
  92. default=Path("/data/prod2u/windows-exes/v330-b473cb32/windows-gui-20261124T094720Z-5ff363a4/artifacts/6400-v2"))
  93. parser.add_argument("--mrdimm-gui-dir", type=Path,
  94. default=Path("/data/prod2u/windows-exes/v330-b473cb32/windows-gui-20261124T094720Z-5ff363a4/artifacts/mrdimm-chamber"))
  95. parser.add_argument("--v11-exe", type=Path,
  96. default=Path("/data/prod2u/windows-exes/v330-6400-v11/Prod2U-6400-V11-PID-GUI-v3.3.0.exe"))
  97. parser.add_argument("--pwm-scope-exe", type=Path,
  98. default=Path("/data/prod2u/windows-exes/v330-extra/Prod2U-6400-V2-PWM-Scope-v3.3.0.exe"))
  99. parser.add_argument("--hth-repo", type=Path, default=Path("/workspace/hth-platform"))
  100. parser.add_argument("--v11-branch", default="6400-v1.1")
  101. parser.add_argument("--no-deploy", action="store_true")
  102. args = parser.parse_args(argv)
  103. stage = args.stage_dir.resolve()
  104. if stage.exists():
  105. shutil.rmtree(stage)
  106. stage.mkdir(parents=True, exist_ok=True)
  107. # ------------------------------------------------------------------
  108. # 1. 6400 V2.0 (mainline dev)
  109. # ------------------------------------------------------------------
  110. v2_dir = stage / "6400_V2.0"
  111. v2_runs = {b: Path(f"/data/prod2u/cpld-runs/v330-b473cb32-6400-v2-{b}") for b in BAUDS}
  112. v2_fw = copy_firmware_group(v2_runs, v2_dir / "Firmware", "prod2u_6400_v2")
  113. copy_file(args.v2_gui_dir / "Prod2U-6400-V2-GUI-v3.3.0.exe", v2_dir / "Prod2U-6400-V2-GUI-v3.3.0.exe")
  114. if args.pwm_scope_exe.is_file():
  115. copy_file(args.pwm_scope_exe, v2_dir / "Prod2U-6400-V2-PWM-Scope-v3.3.0.exe")
  116. for name in ("prod2u_6400_v2.adc", "prod2u_6400_v2.sdc"):
  117. copy_file(ROOT / "constraints" / name, v2_dir / "Constraints" / name)
  118. for f in sorted((ROOT / "generated" / "6400-v2").iterdir()):
  119. if f.is_file():
  120. copy_file(f, v2_dir / "Generated" / f.name)
  121. for s in ("6400_v2_hex_gui.py", "prod2u_gui.py", "pwm_scope.py", "get_all.py",
  122. "monitor_10min.py", "serial_hardware_check.py", "stream_receiver.py", "run_v3_protocol.py"):
  123. copy_file(ROOT / "tools" / s, v2_dir / "Scripts" / s)
  124. for v in ("hth_protocol.py", "prod2u_status.py"):
  125. copy_file(ROOT / "tools" / "_vendor" / v, v2_dir / "Scripts" / "_vendor" / v)
  126. write_text_crlf(v2_dir / "RUN_6400_V2_GUI.cmd", "@echo off\r\ncd /d \"%~dp0\"\r\nstart \"\" \"%~dp0Prod2U-6400-V2-GUI-v3.3.0.exe\"\r\n")
  127. write_text_crlf(
  128. v2_dir / "RUN_PWM_SCOPE_MAP.cmd",
  129. "@echo off\r\nchcp 65001 >nul\r\ncd /d \"%~dp0\"\r\n"
  130. "if exist \"%~dp0Prod2U-6400-V2-PWM-Scope-v3.3.0.exe\" (\r\n"
  131. " \"%~dp0Prod2U-6400-V2-PWM-Scope-v3.3.0.exe\" --dry-run\r\n"
  132. ") else (\r\n"
  133. " py -3.12 \"%~dp0..\\Shared_Tools\\Repo_Source\\tools\\pwm_scope.py\" --dry-run\r\n"
  134. ")\r\npause\r\n",
  135. )
  136. # ------------------------------------------------------------------
  137. # 2. 6400 V1.1 (standalone branch 6400-v1.1)
  138. # ------------------------------------------------------------------
  139. v11_dir = stage / "6400_V1.1"
  140. v11_runs = {b: Path(f"/data/prod2u/cpld-runs/v330-6400v11-f78f9ffa-{b}") for b in BAUDS}
  141. v11_fw = copy_firmware_group(v11_runs, v11_dir / "Firmware", "prod2u_6400_v1_1")
  142. copy_file(args.v11_exe, v11_dir / "Prod2U-6400-V11-PID-GUI-v3.3.0.exe")
  143. v11_source_dir = v11_dir / "Source"
  144. export_git_tree(
  145. ROOT,
  146. args.v11_branch,
  147. v11_source_dir,
  148. exclude_prefixes=(
  149. "tools/board-viewer/node_modules",
  150. "reference/original/board",
  151. "reauth-backup",
  152. "evidence/input_reauth_r3",
  153. ),
  154. )
  155. for name in ("prod2u_6400_front_back.adc", "prod2u_6400_front_back.sdc"):
  156. copy_file(v11_source_dir / "constraints" / name, v11_dir / "Constraints" / name)
  157. for f in sorted((v11_source_dir / "generated" / "6400").iterdir()):
  158. if f.is_file():
  159. copy_file(f, v11_dir / "Generated" / f.name)
  160. for s in ("v11_nomcu_gui.py", "v11_adaptive_pid.py", "v11_bmc_net.py"):
  161. copy_file(v11_source_dir / "tools" / s, v11_dir / "Scripts" / s)
  162. copy_file(v11_source_dir / "VERSION", v11_dir / "Scripts" / "VERSION")
  163. write_text_crlf(v11_dir / "RUN_6400_V11_PID_GUI.cmd", "@echo off\r\ncd /d \"%~dp0\"\r\nstart \"\" \"%~dp0Prod2U-6400-V11-PID-GUI-v3.3.0.exe\"\r\n")
  164. write_text_crlf(
  165. v11_dir / "PROBE_BMC_192.168.2.168.cmd",
  166. "@echo off\r\nchcp 65001 >nul\r\ncd /d \"%~dp0\"\r\n"
  167. "\"%~dp0Prod2U-6400-V11-PID-GUI-v3.3.0.exe\" --probe-bmc 192.168.2.168\r\npause\r\n",
  168. )
  169. # ------------------------------------------------------------------
  170. # 3. MRDIMM V1.2 (mainline dev)
  171. # ------------------------------------------------------------------
  172. mr_dir = stage / "MRDIMM_V1.2"
  173. mr_runs = {b: Path(f"/data/prod2u/cpld-runs/v330-b473cb32-mrdimm-{b}") for b in BAUDS}
  174. mr_fw = copy_firmware_group(mr_runs, mr_dir / "Firmware", "prod2u_mrdimm")
  175. copy_file(args.mrdimm_gui_dir / "Prod2U-MRDIMM-GUI-v3.3.0.exe", mr_dir / "Prod2U-MRDIMM-GUI-v3.3.0.exe")
  176. for name in ("prod2u_mrdimm.adc", "prod2u_mrdimm.sdc", "prod2u_mrdimm_chamber.adc", "prod2u_mrdimm_chamber.sdc"):
  177. copy_file(ROOT / "constraints" / name, mr_dir / "Constraints" / name)
  178. for f in sorted((ROOT / "generated" / "mrdimm").iterdir()):
  179. if f.is_file():
  180. copy_file(f, mr_dir / "Generated" / f.name)
  181. for s in ("mrdimm_hex_gui.py", "prod2u_gui.py", "stream_receiver.py",
  182. "test_single_channel_motion.py", "serial_hardware_check.py", "run_v3_protocol.py"):
  183. copy_file(ROOT / "tools" / s, mr_dir / "Scripts" / s)
  184. for v in ("hth_protocol.py", "prod2u_status.py"):
  185. copy_file(ROOT / "tools" / "_vendor" / v, mr_dir / "Scripts" / "_vendor" / v)
  186. write_text_crlf(mr_dir / "RUN_MRDIMM_GUI.cmd", "@echo off\r\ncd /d \"%~dp0\"\r\nstart \"\" \"%~dp0Prod2U-MRDIMM-GUI-v3.3.0.exe\"\r\n")
  187. # ------------------------------------------------------------------
  188. # 4. Shared Tools: Full unpacked Repo_Source + Board Viewer + Thermal Web + hth-platform
  189. # ------------------------------------------------------------------
  190. shared = stage / "Shared_Tools"
  191. repo_dst = shared / "Repo_Source"
  192. copy_working_tracked(
  193. ROOT,
  194. repo_dst,
  195. exclude_prefixes=(
  196. "tools/board-viewer/node_modules",
  197. "tools/board-viewer/rust-server/target",
  198. "reference/original/board/EF2L45BG256B_MINI_V2.0",
  199. ),
  200. )
  201. # Include regenerated/untracked board-viewer runtime assets & schematics needed for offline Windows viewing
  202. bv_src = ROOT / "tools" / "board-viewer"
  203. bv_dst = repo_dst / "tools" / "board-viewer"
  204. for bundle in ("generated", "generated-v1_1", "generated-v2_0", "generated-v2_0_fan"):
  205. bdir = bv_src / bundle
  206. if bdir.is_dir():
  207. for f in sorted(bdir.iterdir()):
  208. if f.is_file():
  209. copy_file(f, bv_dst / bundle / f.name)
  210. for extra in ("v2_0_components_cache.json", "v2_0_fan_components_cache.json",
  211. "v2_0_schematic_bom.json", "v2_0_silkscreen_texts.json"):
  212. if (bv_src / extra).is_file():
  213. copy_file(bv_src / extra, bv_dst / extra)
  214. if (ROOT / "reference" / "original" / "schematics").is_dir():
  215. for f in sorted((ROOT / "reference" / "original" / "schematics").iterdir()):
  216. if f.is_file():
  217. copy_file(f, repo_dst / "reference" / "original" / "schematics" / f.name)
  218. for brd_rel in (
  219. "reference/original/board/FCB_FPGA_MCU_V1.2_20260717/FCB_FPGA+MCU_V1.2_20260717.brd",
  220. "reference/original/board/FCB_FPGA_MCU_V1.1_20260625/FCB_FPGA+MCU_V1.1_20260625.brd",
  221. "reference/original/board/FCB_FPGA_MCU_V2.0_20260914/FCB_FPGA+MCU_V2.0_20260914.brd",
  222. "reference/original/board/FCB_FAN_V2.0_20260914/FCB_FAN_V2.0_20260914.brd",
  223. ):
  224. brd_src = ROOT / brd_rel
  225. if brd_src.is_file():
  226. copy_file(brd_src, repo_dst / brd_rel)
  227. copy_working_tracked(args.hth_repo, shared / "hth-platform")
  228. write_text_crlf(
  229. shared / "OPEN_BOARD_VIEWER.cmd",
  230. "@echo off\r\nchcp 65001 >nul\r\ncall \"%~dp0Repo_Source\\tools\\board-viewer\\OPEN_BOARD_VIEWER.cmd\"\r\n",
  231. )
  232. write_text_crlf(
  233. shared / "START_THERMAL_WEB.cmd",
  234. "@echo off\r\nchcp 65001 >nul\r\ncd /d \"%~dp0Repo_Source\"\r\n"
  235. "start \"\" \"http://127.0.0.1:8766\"\r\n"
  236. "py -3.12 tools\\thermal_test_server.py --host 127.0.0.1 --port 8766\r\npause\r\n",
  237. )
  238. # ------------------------------------------------------------------
  239. # 5. Docs & Top-level README
  240. # ------------------------------------------------------------------
  241. docs_dir = stage / "Docs"
  242. copy_file(ROOT / "docs" / "CPLD_通讯协议v2.0.md", stage / "CPLD_通讯协议v2.0.md")
  243. for rel in (
  244. "docs/CPLD_通讯协议v2.0.md",
  245. "docs/releases/v3.3.0.md",
  246. "docs/evidence/6400-v2-electrical-alignment.md",
  247. "docs/pwm-scope.md",
  248. "docs/TD_USAGE.zh-CN.md",
  249. ):
  250. src = ROOT / rel
  251. if src.is_file():
  252. copy_file(src, docs_dir / src.name)
  253. v11_doc = v11_source_dir / "docs" / "releases" / "6400-v1.1-v3.3.0.md"
  254. if v11_doc.is_file():
  255. copy_file(v11_doc, docs_dir / "6400-v1.1-v3.3.0.md")
  256. dev_commit = subprocess.check_output(["git", "-C", str(ROOT), "rev-parse", "--short=8", "HEAD"], text=True).strip()
  257. v11_commit = subprocess.check_output(["git", "-C", str(ROOT), "rev-parse", "--short=8", args.v11_branch], text=True).strip()
  258. readme = f"""# Prod2U CPLD v3.3.0 全板卡非压缩包发布目录
  259. > 部署时间 (UTC): {datetime.now(timezone.utc).isoformat()}
  260. > 主线 `dev` (`6400-v2` + `mrdimm`): `{dev_commit}`
  261. > 独立分支 `6400-v1.1` (绝不合入 `dev`): `{v11_commit}`
  262. > 说明:本目录为**完全非压缩包**形式,所有 EXE、脚本、固件 `.bit`/`.bmk`、约束 `.adc`/`.sdc`、RTL 源码、电路板选脚查看器、SDK 与协议文档均可直接打开或双击运行,无需解压。
  263. ---
  264. ## 目录导航
  265. 1. **`6400_V2.0\\`** — **6400 V2.0 高温罩**(`dev` 主线)
  266. - `Prod2U-6400-V2-GUI-v3.3.0.exe`(可双击 `RUN_6400_V2_GUI.cmd`):实时串口控制 + 24 PTC / 4 进风 / 4 出风 / 3 SSR / 急停 `EPB1(F8)` / 开罩 `SB1(C11)` / 合罩 `SB2(A11)` / 4000Hz 80% 蜂鸣器 `H6` + 腔体温度曲线 & 70℃ 温度测试
  267. - `Prod2U-6400-V2-PWM-Scope-v3.3.0.exe`(可双击 `RUN_PWM_SCOPE_MAP.cmd`):20Hz PWM 示波器串口验收 & 35 路通道 / CT7428 映射工具(接板实测示例:`Prod2U-6400-V2-PWM-Scope-v3.3.0.exe --port COM3`)
  268. - `Firmware\\{{921600,460800,230400,115200}}\\prod2u_6400_v2_<baud>.bit` + `.bmk` + `td-receipt.json`(TD 2026.1 SP2 实测 `1,664` LUT / `1,009` Packed Slice @ 921600)
  269. - `Constraints\\prod2u_6400_v2.adc` / `.sdc`,`Generated\\` 协议契约,`Scripts\\` Python 源码
  270. 2. **`6400_V1.1\\`** — **6400 V1.1 无 MCU 方案**(独立分支 `6400-v1.1`)
  271. - `Prod2U-6400-V11-PID-GUI-v3.3.0.exe`(可双击 `RUN_6400_V11_PID_GUI.cmd`):Windows 自适应 PID(RLS + Smith 预测 + 三区间增益调度 + 均温微调)+ **BMC NET 直采 24 路 DIMM 温度(IPMI v2.0 RMCP+ UDP:623)**
  272. - `PROBE_BMC_192.168.2.168.cmd`:一键测试通过 BMC 网口直采 24 路 DIMM 温度
  273. - `Firmware\\{{921600,460800,230400,115200}}\\prod2u_6400_v1_1_<baud>.bit` + `.bmk` + `td-receipt.json`(TD 2026.1 SP2 实测 `1,284` LUT / `774` Packed Slice @ 921600)
  274. - `Constraints\\prod2u_6400_front_back.adc` / `.sdc`,`Scripts\\` (`v11_nomcu_gui.py`, `v11_adaptive_pid.py`, `v11_bmc_net.py`),`Source\\` 完整 `6400-v1.1` 分支源码
  275. 3. **`MRDIMM_V1.2\\`** — **MRDIMM V1.2(8000 / FCB V1.2)**(`dev` 主线)
  276. - `Prod2U-MRDIMM-GUI-v3.3.0.exe`(可双击 `RUN_MRDIMM_GUI.cmd`):12 轴有限段步进电机 + 4 FAN + 4 逻辑 PTC(24 物理) + 高温罩开关 `L3` + 4000Hz 80% 蜂鸣器 `H6` + CT/BMC 遥测
  277. - `Firmware\\{{921600,460800,230400,115200}}\\prod2u_mrdimm_<baud>.bit` + `.bmk` + `td-receipt.json`(TD 2026.1 SP2 实测 `2,021` LUT / `1,190` Packed Slice @ 921600)
  278. - `Constraints\\` + `Generated\\` + `Scripts\\`
  279. 4. **`Shared_Tools\\`** — **通用工具(非压缩包可直接运行)**
  280. - `OPEN_BOARD_VIEWER.cmd`:双击启动本地电路板选脚查看器(同步含 V1.1 / V1.2 / V2.0 / V2.0_FAN 与原理图 PDF)
  281. - `START_THERMAL_WEB.cmd`:双击在本地 `http://127.0.0.1:8766` 启动高温罩温度测试 Web 前后端(远程常驻服务位于 `http://192.168.2.25:8766/`)
  282. - `hth-platform\\`:完整 `hth_platform` Python SDK 与示例
  283. - `Repo_Source\\`:主线 `dev` 完整非压缩源码仓库
  284. 5. **`Docs\\` 与根目录 `CPLD_通讯协议v2.0.md`**
  285. - 完整覆盖三板最新通讯协议、引脚对齐与 TD 发布记录。
  286. """
  287. (stage / "00_README_目录说明.md").write_text(readme, encoding="utf-8")
  288. manifest_summary = {
  289. "version": "3.3.0",
  290. "dev_commit": dev_commit,
  291. "v11_commit": v11_commit,
  292. "firmware": {"6400-v2": v2_fw, "6400-v1.1": v11_fw, "mrdimm": mr_fw},
  293. }
  294. (stage / "RELEASE-INDEX.json").write_text(json.dumps(manifest_summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
  295. inventory = [
  296. {"path": p.relative_to(stage).as_posix(), "sha256": sha256_file(p), "size_bytes": p.stat().st_size}
  297. for p in sorted(stage.rglob("*"))
  298. if p.is_file() and p.name != "DELIVERY-SHA256.json"
  299. ]
  300. dest = args.destination.rstrip("/\\")
  301. long_paths = [
  302. f"{dest}\\{item['path'].replace('/', chr(92))}"
  303. for item in inventory
  304. if len(f"{dest}\\{item['path'].replace('/', chr(92))}") >= 235
  305. ]
  306. if long_paths:
  307. raise ValueError(f"Windows path length >=235 chars ({len(long_paths)} files), e.g. {long_paths[0]}")
  308. (stage / "DELIVERY-SHA256.json").write_bytes((json.dumps(inventory, indent=2, ensure_ascii=False) + "\n").encode("utf-8"))
  309. print(f"Staged {len(inventory)} unpacked files in {stage}")
  310. if args.no_deploy:
  311. return 0
  312. def ps(text: str) -> str:
  313. return "powershell -NoProfile -NonInteractive -EncodedCommand " + base64.b64encode(text.encode("utf-16le")).decode()
  314. def ps_q(text: str) -> str:
  315. return "'" + text.replace("'", "''") + "'"
  316. # Create or cleanly replace target unpacked directory, stream via tar over SSH (leaves zero archives on Windows)
  317. prep = f"""
  318. $ErrorActionPreference = 'Stop'
  319. $p = {ps_q(dest)}
  320. if (Test-Path $p) {{ Remove-Item -Recurse -Force $p }}
  321. New-Item -ItemType Directory -Path $p -Force | Out-Null
  322. """
  323. subprocess.run(["ssh", "-o", "ConnectTimeout=10", args.host, ps(prep)], check=True)
  324. tar_proc = subprocess.Popen(
  325. ["tar", "-cf", "-", "-C", str(stage), "."],
  326. stdout=subprocess.PIPE,
  327. )
  328. extract_code = (
  329. "import sys, tarfile\n"
  330. f"tarfile.open(fileobj=sys.stdin.buffer, mode='r|*').extractall({dest!r}, filter='data')\n"
  331. )
  332. b64_extract = base64.b64encode(extract_code.encode("utf-8")).decode("ascii")
  333. subprocess.run(
  334. ["ssh", "-o", "ConnectTimeout=10", args.host,
  335. f'py -3.12 -c "import base64; exec(base64.b64decode(\'{b64_extract}\'))"'],
  336. stdin=tar_proc.stdout,
  337. check=True,
  338. )
  339. tar_proc.stdout.close()
  340. if tar_proc.wait() != 0:
  341. raise RuntimeError("tar stream creation failed")
  342. verify = f"""
  343. $ErrorActionPreference = 'Stop'
  344. $ProgressPreference = 'SilentlyContinue'
  345. [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
  346. $root = {ps_q(dest)}
  347. $items = Get-Content -LiteralPath (Join-Path $root 'DELIVERY-SHA256.json') -Raw -Encoding UTF8 | ConvertFrom-Json
  348. $verified = 0
  349. foreach ($item in $items) {{
  350. $path = Join-Path $root $item.path
  351. if (-not (Test-Path -LiteralPath $path)) {{ throw ('Missing file: ' + $item.path) }}
  352. $actual = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant()
  353. $size = (Get-Item -LiteralPath $path).Length
  354. if ($actual -ne $item.sha256 -or $size -ne $item.size_bytes) {{
  355. throw ('SHA or size mismatch: ' + $item.path + ' actual=' + $actual + ' expected=' + $item.sha256)
  356. }}
  357. $verified++
  358. }}
  359. $receipt = @{{
  360. status = 'PASS'
  361. scope = 'unpacked directory transfer and per-file SHA256 verification'
  362. host = $env:COMPUTERNAME
  363. destination = $root
  364. verified_files = $verified
  365. hardware_validation = 'NOT_RUN_BY_DELIVERY'
  366. utc = [DateTime]::UtcNow.ToString('o')
  367. }}
  368. $receipt | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $root 'DELIVERY-RECEIPT.json') -Encoding UTF8
  369. Write-Output ('DELIVERY_UNPACKED_SHA256_PASS ' + $verified)
  370. """
  371. res = subprocess.run(
  372. ["ssh", "-o", "ConnectTimeout=10", args.host, ps(verify)],
  373. capture_output=True, text=True, check=True,
  374. )
  375. print(res.stdout.strip())
  376. receipt_local = stage.parent / (stage.name + "-delivery-receipt.json")
  377. scp_src = args.host + ":" + dest.replace("\\", "/") + "/DELIVERY-RECEIPT.json"
  378. subprocess.run(["scp", scp_src, str(receipt_local)], check=True)
  379. print(f"Receipt saved to {receipt_local}")
  380. return 0
  381. if __name__ == "__main__":
  382. raise SystemExit(main())