package_prod2u.py 13 KB

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