package_prod2u.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. #!/usr/bin/env python3
  2. """Single canonical Base/Current/Delivery package dispatcher.
  3. Product-specific legacy packagers remain implementation details; this entrypoint
  4. is the only supported command surface and performs fail-closed ZIP verification.
  5. """
  6. from __future__ import annotations
  7. import argparse, hashlib, json, shutil, stat, sys, tempfile, zipfile
  8. from pathlib import Path, PurePosixPath
  9. ROOT = Path(__file__).resolve().parents[1]
  10. if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
  11. def sha(p: Path) -> str: return hashlib.sha256(p.read_bytes()).hexdigest()
  12. FIXED_TIME = (1980, 1, 1, 0, 0, 0)
  13. def _safe(name: str) -> str:
  14. p = PurePosixPath(name)
  15. if not name or name.startswith("/") or ".." in p.parts or "\\" in name:
  16. raise ValueError(f"unsafe package path: {name}")
  17. return name
  18. def _zip(path: Path, files: dict[str, bytes]) -> Path:
  19. from tools.package_archive import write_archive
  20. return write_archive(path,files)
  21. def _dual_paths() -> list[str]:
  22. """Current CPLD replay closure; missing dependencies fail before ZIP creation."""
  23. from tools.source_package_closure import current_cpld_paths
  24. return current_cpld_paths(ROOT)
  25. def _dual_current(output: Path, base_zip: Path) -> Path:
  26. from tools import package_archive as archive
  27. from tools.source_identity import source_identity
  28. from tools.source_package_closure import current_cpld_paths
  29. import subprocess
  30. base=archive.read_archive(base_zip);base_id,base_manifest_sha=archive.base_identity(base)
  31. origin=source_identity(ROOT)
  32. if origin['clean'] is False:raise ValueError('Current requires a clean source snapshot')
  33. base_sources={n:d for n,d in base['files'].items() if n not in archive.META}
  34. extras=[n for n in base_sources if (ROOT/n).is_file() and not n.startswith('src/legacy/')]
  35. wanted=current_cpld_paths(ROOT,extras)
  36. desired={n:(ROOT/n).read_bytes() for n in wanted}
  37. modes={n:archive.mode_for(n,d) for n,d in desired.items()}
  38. repos=[{'name':'cpld-temperature-control','commit':origin['commit'],'tree':origin['tree'],'path':'.'}]
  39. exclusions=[]
  40. for name in ('hth-platform','engineering-manifests'):
  41. repo=ROOT.parent/name if origin['source_kind']=='git' else ROOT/name
  42. if not repo.is_dir():raise ValueError('required workspace repository missing: '+str(repo))
  43. if origin['source_kind']=='git':
  44. def git(*args):return subprocess.check_output(['git',*args],cwd=repo,text=True).strip()
  45. if git('status','--porcelain'):raise ValueError('workspace repository is dirty: '+name)
  46. identity={'name':name,'commit':git('rev-parse','HEAD'),'tree':git('rev-parse','HEAD^{tree}'),'path':name}
  47. paths=subprocess.check_output(['git','ls-files','-z'],cwd=repo).decode().split('\0')
  48. paths=[x for x in paths if x]
  49. else:
  50. workspace=json.loads((ROOT/'WORKSPACE-SNAPSHOT.json').read_text())
  51. matches=[x for x in workspace['repos'] if x['name']==name]
  52. if len(matches)!=1:raise ValueError('exported repository identity missing: '+name)
  53. identity=matches[0]
  54. combined=json.loads((ROOT/'COMBINED-SOURCE-MANIFEST.json').read_text())
  55. paths=[x['path'][len(name)+1:] for x in combined['items'] if x['path'].startswith(name+'/')]
  56. repos.append(identity)
  57. for relative in paths:
  58. if relative.startswith('legacy-hth/') or relative=='AGENTS.md':
  59. exclusions.append(name+'/'+relative);continue
  60. path=repo/relative
  61. if not path.is_file() or path.is_symlink():raise ValueError('workspace source missing or unsafe: '+str(path))
  62. target=name+'/'+archive.safe_name(relative);desired[target]=path.read_bytes();modes[target]=archive.mode_for(target,desired[target])
  63. source_items=[{'path':n,'size':len(d),'sha256':archive.digest(d),'mode':modes[n]} for n,d in sorted(desired.items())]
  64. identity={'repos':repos,'base_id':base_id,'source_items':source_items,'format':'dual-current-v2'}
  65. snapshot=archive.digest(json.dumps(identity,sort_keys=True,separators=(',',':')).encode())[:16]
  66. changed={n:d for n,d in desired.items() if n not in base_sources or base_sources[n]!=d or base['modes'][n]!=modes[n]}
  67. replacements=[{'path':n,'base_sha256':archive.digest(base_sources[n]),'current_sha256':archive.digest(d)} for n,d in sorted(changed.items()) if n in base_sources]
  68. additions=sorted(set(changed)-set(base_sources))
  69. deletions=[{'path':n,'base_sha256':archive.digest(d)} for n,d in sorted(base_sources.items()) if n not in desired]
  70. payload=dict(changed)
  71. payload['BASE-REQUIRED.json']=archive.encode({'schema':'prod2u-base-required-v1','base_id':base_id,
  72. 'base_manifest_sha256':base_manifest_sha,'base_zip_sha256':base['sha256']})
  73. payload['WORKSPACE-SNAPSHOT.json']=archive.encode({'schema':'prod2u-workspace-snapshot-v1','snapshot_id':snapshot,'repos':repos,'base_id':base_id})
  74. payload['OVERLAY-REPLACEMENTS.json']=archive.encode({'schema':'prod2u-overlay-replacements-v1','replacements':replacements})
  75. payload['OVERLAY-ADDITIONS.json']=archive.encode({'schema':'prod2u-overlay-additions-v1','additions':additions})
  76. payload['OVERLAY-DELETIONS.json']=archive.encode({'schema':'prod2u-overlay-deletions-v1','deletions':deletions})
  77. payload['COMBINED-SOURCE-MANIFEST.json']=archive.encode({'schema':'prod2u-combined-source-v1','items':source_items})
  78. payload['EXCLUSIONS.json']=archive.encode({'scope':'current source replay','excluded_paths':exclusions,
  79. 'excluded_categories':['Git objects','toolchain binaries/licenses','build outputs','runtime caches','retired HTH implementation'],
  80. 'authority_note':'stale per-tool/per-repository agent instructions are not build dependencies'})
  81. payload['START-HERE.zh-CN.md']=('# 双产品源码增量包\n\nCurrent 单独仅能验证归档完整性,自检退出码3表示需要指定 Base。\n'
  82. '使用 tools/package_prod2u.py overlay 叠加后运行根目录 PACKAGE-SELF-CHECK.py。\n'
  83. 'CPLD 文件位于根目录;HTH 和 engineering-manifests 位于同名子目录。\n'
  84. 'python3 tools/fw_cli.py generate all --check;python3 tools/fw_cli.py test all --run-root <外部新目录>。\n'
  85. 'HTH 可从 hth-platform/pyproject.toml 安装并运行其中的源码测试。\n'
  86. '本包为源码重放,不代表 Full 软件或真实硬件验收。\n').encode()
  87. payload['PACKAGE-SELF-CHECK.py']=Path(archive.__file__).read_bytes()
  88. payload_modes={n:modes.get(n,archive.mode_for(n,d)) for n,d in payload.items()}
  89. manifest={'schema':'prod2u-dual-current-manifest-v2','profile':'current','products':['6400-front-rear','mrdimm-chamber'],
  90. 'source_commit':origin['commit'],'source_tree':origin['tree'],'snapshot_id':snapshot,'base_id':base_id,'repos':repos}
  91. files,final_modes=archive.finalize(payload,manifest,payload_modes)
  92. target=output/f'Prod2U-CPLD-Analysis-Current-{snapshot}-base-{base_id}.zip'
  93. archive.write_archive(target,files,final_modes);archive.read_archive(target);return target
  94. def _dual_overlay(base_zip: Path, current_zip: Path, output: Path) -> Path:
  95. from tools.package_archive import overlay
  96. return overlay(base_zip,current_zip,output)
  97. def verify(path: Path) -> dict:
  98. from tools.package_archive import read_archive
  99. data=read_archive(path)
  100. return {'status':'PASS','scope':'archive integrity only','package':str(path.resolve()),'sha256':data['sha256']}
  101. def dispatch_legacy(args: argparse.Namespace) -> Path:
  102. from tools import package_6400_canonical as c
  103. if args.action == "base": return c.package_base(args.output_dir)
  104. if args.action == "current": return _dual_current(args.output_dir, args.base_zip)
  105. if args.action == "overlay":
  106. with zipfile.ZipFile(args.current_zip) as z:
  107. try: current_schema = json.loads(z.read("PACKAGE-MANIFEST.json")).get("schema")
  108. except Exception: current_schema = None
  109. if current_schema in ("prod2u-dual-current-manifest-v1","prod2u-dual-current-manifest-v2"):
  110. return _dual_overlay(args.base_zip, args.current_zip, args.output_dir)
  111. from tools.overlay_6400_packages import run
  112. run(args.base_zip, args.current_zip, args.output_dir)
  113. return args.output_dir
  114. raise SystemExit("unsupported legacy action")
  115. def main(argv=None) -> int:
  116. ap=argparse.ArgumentParser(description=__doc__); sp=ap.add_subparsers(dest="action",required=True)
  117. for name in ("base","current","all"):
  118. p=sp.add_parser(name); p.add_argument("--output-dir",type=Path,default=ROOT/"dist")
  119. if name=="current": p.add_argument("--base-zip",type=Path,required=True)
  120. p=sp.add_parser("verify"); p.add_argument("package",type=Path)
  121. p=sp.add_parser("overlay"); p.add_argument("--base-zip",type=Path,required=True); p.add_argument("--current-zip",type=Path,required=True); p.add_argument("--output-dir",type=Path,required=True)
  122. p=sp.add_parser("delivery"); p.add_argument("--product",choices=("6400-v1.1","mrdimm-v1.2"),required=True); p.add_argument("--output-dir",type=Path,default=ROOT/"dist"); p.add_argument("--td-receipt",type=Path); p.add_argument("--gui-exe",type=Path); p.add_argument("--gui-zip",type=Path); p.add_argument("--status-json",type=Path)
  123. p.add_argument('--sdk-wheel',type=Path)
  124. a=ap.parse_args(argv)
  125. if a.action=="verify": print(json.dumps(verify(a.package),indent=2)); return 0
  126. if a.action == "all":
  127. base = dispatch_legacy(argparse.Namespace(action="base", output_dir=a.output_dir))
  128. current = dispatch_legacy(argparse.Namespace(action="current", output_dir=a.output_dir, base_zip=base))
  129. print(json.dumps({"status":"PASS","base":verify(base),"current":verify(current)}, indent=2))
  130. return 0
  131. if a.action in ("base","current","overlay"):
  132. result=dispatch_legacy(a)
  133. if a.action == "overlay":
  134. receipt = result / "OVERLAY-RECEIPT.json"
  135. payload = json.loads(receipt.read_text(encoding="utf-8")) if receipt.is_file() else {"status":"PASS"}
  136. print(json.dumps({**payload, "action": a.action, "output_dir": str(result.resolve())}, indent=2))
  137. else:
  138. print(json.dumps({**verify(result),"action":a.action},indent=2))
  139. return 0
  140. if a.action=="delivery":
  141. if a.product=="6400-v1.1":
  142. if not all((a.td_receipt,a.gui_exe,a.status_json)): ap.error("6400 delivery requires --td-receipt --gui-exe --status-json")
  143. from tools import package_6400_canonical
  144. result=package_6400_canonical.package_delivery(a.output_dir,a.td_receipt,a.gui_exe,a.gui_zip,a.status_json,a.sdk_wheel)
  145. else:
  146. required=(a.td_receipt,a.gui_exe,a.gui_zip)
  147. if not all(required): ap.error("mrdimm delivery requires --td-receipt --gui-exe --gui-zip")
  148. a.output_dir.mkdir(parents=True,exist_ok=True); commit="unknown"; receipt=json.loads(a.td_receipt.read_text(encoding="utf-8")); commit=str(receipt.get("commit",commit))
  149. # TD receipts retain the Linux artifact path. Resolve the copied
  150. # bitstream beside the receipt (the Windows fetch step preserves
  151. # this basename) so Delivery always contains the actual BIT.
  152. bit = None
  153. bit_meta = receipt.get("measurement_artifacts", {}).get("bitstream", {})
  154. bit_name = Path(str(bit_meta.get("path", ""))).name
  155. candidates = [a.td_receipt.parent / bit_name] if bit_name else []
  156. candidates += sorted(a.td_receipt.parent.glob("*.bit"))
  157. for candidate in candidates:
  158. if candidate.is_file(): bit = candidate; break
  159. if bit is None: ap.error("MRDIMM delivery requires fetched TD bitstream beside receipt")
  160. status = str(receipt.get("status", "unknown")).upper()
  161. candidate_status = {"status": "PASS" if status == "PASS" else "PARTIAL", "td_status": status, "timing_gate": receipt.get("timing_gate", {}), "structural_gate": receipt.get("structural_gate", {})}
  162. files = {
  163. "prod2u-mrdimm-v1.2.bit": bit.read_bytes(),
  164. "TD-RECEIPT.json": a.td_receipt.read_bytes(),
  165. a.gui_exe.name: a.gui_exe.read_bytes(),
  166. a.gui_zip.name: a.gui_zip.read_bytes(),
  167. "Wire-Contract.md": (ROOT/"projects/prod2u-door-temp/requirements.zh-CN.md").read_bytes(),
  168. "Snapshot-Contract.json": (ROOT/"src/generated/host-contract.json").read_bytes(),
  169. "CANDIDATE-STATUS.json": json.dumps(candidate_status,indent=2,sort_keys=True).encode()+b"\n",
  170. }
  171. manifest={"schema":"prod2u-delivery-v1","product":"mrdimm-chamber","board":"FCB V1.2","commit":commit,"status":"PASS" if status == "PASS" else "PARTIAL","hardware":"NOT RUN","members":sorted(files)}
  172. files["RELEASE-IDENTITY.json"] = (json.dumps(manifest,indent=2,sort_keys=True)+"\n").encode()
  173. files["SHA256SUMS"] = "".join(f"{hashlib.sha256(data).hexdigest()} {name}\n" for name,data in sorted(files.items())).encode()
  174. result=a.output_dir/f"Prod2U-MRDIMM-V1.2-Delivery-{commit[:8]}.zip"; _zip(result, files)
  175. print(json.dumps({**verify(result),"action":"delivery","product":a.product},indent=2)); return 0
  176. return 2
  177. if __name__=="__main__": raise SystemExit(main())