package_prod2u.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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, re, shutil, stat, subprocess, 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 release_workspace():
  107. from tools.source_identity import source_identity
  108. from tools.package_archive import check_overlay
  109. origin=source_identity(ROOT)
  110. if origin['clean'] is False:raise ValueError('delivery requires clean source')
  111. names=('cpld-temperature-control','hth-platform','engineering-manifests')
  112. if origin['source_kind']=='exported':
  113. check_overlay(ROOT)
  114. listed=json.loads((ROOT/'WORKSPACE-SNAPSHOT.json').read_text(encoding='utf-8'))['repos']
  115. repos=[]
  116. for name in names:
  117. matches=[row for row in listed if row['name']==name]
  118. if len(matches)!=1:raise ValueError('workspace repository identity missing: '+name)
  119. repos.append(matches[0])
  120. sdk=ROOT/'hth-platform'
  121. else:
  122. repos=[]
  123. for name in names:
  124. path=ROOT if name=='cpld-temperature-control' else ROOT.parent/name
  125. identity=source_identity(path)
  126. if not identity['clean']:raise ValueError('delivery workspace repository is dirty: '+name)
  127. repos.append({'name':name,'commit':identity['commit'],'tree':identity['tree'],
  128. 'path':'.' if name=='cpld-temperature-control' else name})
  129. sdk=ROOT.parent/'hth-platform'
  130. for row in repos:
  131. if any(not re.fullmatch('[0-9a-f]{40}',str(row.get(k,''))) for k in ('commit','tree')):
  132. raise ValueError('invalid repository commit/tree: '+row['name'])
  133. return origin,repos,sdk
  134. def delivery_bit(receipt_path,receipt,explicit=None):
  135. expected=receipt.get('bitstream_sha256','')
  136. if not re.fullmatch('[0-9a-f]{64}',expected):raise ValueError('TD BIT identity missing')
  137. if explicit:
  138. candidates=[Path(explicit)]
  139. else:
  140. recorded=str(receipt.get('bitstream',''))
  141. name=PurePosixPath(recorded.replace('\\','/')).name
  142. candidates=[Path(recorded),receipt_path.parent/name,receipt_path.parent/'bitgen'/name] if name else []
  143. for path in candidates:
  144. if path.is_file() and sha(path)==expected:return path.resolve()
  145. raise ValueError('actual BIT missing or different from TD receipt')
  146. def product_delivery(product,output,td_receipt,gui_exe,gui_zip=None,status_json=None,sdk_wheel=None,bitstream=None):
  147. from tools import package_archive as archive
  148. from tools import build_product_gui as gui
  149. td_receipt,gui_exe,output=Path(td_receipt),Path(gui_exe),Path(output)
  150. receipt=json.loads(td_receipt.read_text(encoding='utf-8'))
  151. if receipt.get('profile')!=product or receipt.get('status')!='PASS':
  152. raise ValueError('delivery requires a PASS TD receipt for this product')
  153. bit=delivery_bit(td_receipt,receipt,bitstream)
  154. expected=gui.prepare_identity(product,bit,td_receipt)
  155. metadata_path=gui_exe.parent/'gui-build-metadata.json'
  156. metadata=json.loads(metadata_path.read_text(encoding='utf-8'))
  157. keys=('product','profile','board','contract_sha256','bitstream_sha256','bitstream_source_commit',
  158. 'bitstream_source_tree','source_manifest_sha256','td_receipt_sha256')
  159. if any(metadata.get(key)!=expected[key] for key in keys):
  160. raise ValueError('GUI product/BIT/source/TD identity mismatch')
  161. if any(not re.fullmatch('[0-9a-f]{40}',str(metadata.get(key,''))) for key in ('commit','source_tree')):
  162. raise ValueError('GUI source commit/tree missing')
  163. inspected=gui.inspect_executable(gui_exe,metadata,gui.gui_assets(product,metadata_path))
  164. validation_path=gui_exe.parent/'GUI-VALIDATION.json'
  165. validation=json.loads(validation_path.read_text(encoding='utf-8'))
  166. if (validation.get('exe_sha256')!=sha(gui_exe) or validation.get('self_test_exit')!=0 or
  167. any(validation.get(key)!=value for key,value in inspected.items())):
  168. raise ValueError('GUI actual bytes/embedded assets/Windows validation mismatch')
  169. if gui_zip:
  170. packed=archive.read_archive(gui_zip)['files']
  171. if packed.get(gui_exe.name)!=gui_exe.read_bytes() or packed.get('gui-build-metadata.json')!=metadata_path.read_bytes():
  172. raise ValueError('optional GUI archive does not contain the selected EXE and metadata')
  173. origin,repos,sdk=release_workspace()
  174. if origin['source_kind']=='git':
  175. tree=subprocess.check_output(['git','rev-parse',metadata['commit']+'^{tree}'],cwd=ROOT,text=True).strip()
  176. if tree!=metadata['source_tree']:raise ValueError('GUI Git tree mismatch')
  177. files={}
  178. def add(name,path):
  179. archive.safe_name(name)
  180. if name in files:raise ValueError('duplicate delivery member: '+name)
  181. files[name]=Path(path).read_bytes()
  182. add(bit.name,bit);add(gui_exe.name,gui_exe)
  183. add('TD-BUILD-RECEIPT.json',td_receipt);add('gui-build-metadata.json',metadata_path)
  184. add('GUI-VALIDATION.json',validation_path)
  185. if gui_zip:add(Path(gui_zip).name,gui_zip)
  186. generated=ROOT/'generated'/gui.PRODUCTS[product]['generated']
  187. for path in sorted(generated.iterdir()):
  188. if path.suffix in ('.json','.md','.txt'):add('contracts/'+path.name,path)
  189. wire='contracts/6400-wire.yaml' if product=='6400-front-rear' else 'contracts/mrdimm-wire.yaml'
  190. requirements='docs/prod2u-6400-front-back-protocol.zh-CN.md' if product=='6400-front-rear' else 'projects/mrdimm-chamber/requirements.zh-CN.md'
  191. add('contracts/wire.yaml',ROOT/wire);add('contracts/requirements.zh-CN.md',ROOT/requirements)
  192. sdk_paths=['pyproject.toml','README.zh-CN.md']
  193. # Include the source/examples invoked by the SDK guide, including existing
  194. # Go consumers. Keep repository-level verification orchestration outside it.
  195. for name in ('go.mod','golden-vectors.json','manual-uart-contract.json','host-i2c-register-map.json','send_uart_hex_debug.sh'):
  196. if (sdk/name).is_file():sdk_paths.append(name)
  197. for directory in ('python','cmd','internal','pkg','examples','tools'):
  198. for path in sorted((sdk/directory).rglob('*')):
  199. relative=path.relative_to(sdk).as_posix()
  200. if (path.is_file() and path.suffix in ('.py','.go','.c','.sh','.json') and
  201. '__pycache__' not in path.parts and relative!='tools/verify_consumers.py'):
  202. sdk_paths.append(relative)
  203. for name in sdk_paths:add('SDK/'+name,sdk/name)
  204. if sdk_wheel:
  205. with zipfile.ZipFile(sdk_wheel) as wheel:
  206. names=wheel.namelist()
  207. for name in names:archive.safe_name(name)
  208. if len({name.casefold() for name in names})!=len(names):raise ValueError('SDK wheel has duplicate members')
  209. for name in sdk_paths:
  210. installed=(name in ('python/hth_protocol.py','python/hth6400.py','python/prod2u_status.py') or name.startswith('python/prod2u_sdk/'))
  211. member=name.removeprefix('python/')
  212. if installed and (member not in names or wheel.read(member)!=(sdk/name).read_bytes()):
  213. raise ValueError('SDK wheel differs from current source: '+name)
  214. add(Path(sdk_wheel).name,sdk_wheel)
  215. if status_json:add('CANDIDATE-STATUS.json',status_json)
  216. else:files['CANDIDATE-STATUS.json']=archive.encode({'status':'QUICK_CANDIDATE_FULL_PENDING',
  217. 'td':'PASS','gui_windows_selftest':'PASS','scope':'verified BIT/GUI binding; Full acceptance is separate','hardware':'NOT_RUN'})
  218. candidate=json.loads(files['CANDIDATE-STATUS.json'])
  219. identity={'schema':'prod2u-release-identity-v2','product':product,'board':gui.PRODUCTS[product]['board'],
  220. 'repos':repos,'packager_commit':origin['commit'],'packager_tree':origin['tree'],
  221. 'bitstream_source_commit':receipt['commit'],'bitstream_source_tree':receipt['tree'],
  222. 'source_manifest_sha256':expected['source_manifest_sha256'],'contract_sha256':expected['contract_sha256'],
  223. 'bitstream_sha256':sha(bit),'gui_sha256':sha(gui_exe),'gui_source_commit':metadata['commit'],
  224. 'gui_source_tree':metadata['source_tree'],'td_receipt_sha256':sha(td_receipt),
  225. 'gui_validation_sha256':sha(validation_path),'sdk_wheel_sha256':sha(sdk_wheel) if sdk_wheel else None,
  226. 'toolchain':receipt.get('tool'),'td_run_id':receipt.get('run_id'),
  227. 'candidate_status':candidate,'hardware':'NOT_RUN'}
  228. files['RELEASE-IDENTITY.json']=archive.encode(identity)
  229. files['PACKAGE-SELF-CHECK.py']=Path(archive.__file__).read_bytes()
  230. files['START-HERE.zh-CN.md']=(
  231. '# '+product+' '+identity['board']+' 交付候选\n\n'
  232. '运行 python PACKAGE-SELF-CHECK.py 核对完整性。BIT、实际 Windows GUI、合同和源码身份见 RELEASE-IDENTITY.json。\n'
  233. 'GUI 是离线工具,不自动访问硬件。SDK/README.zh-CN.md 说明安装和使用;可安装随附 wheel 或 SDK 源码。\n'
  234. 'CANDIDATE-STATUS.json 保留实际验证范围;字节完整性不是 Full 软件或真实硬件验收。\n'
  235. 'Hardware/COM/JTAG/真实I2C/BMC/风扇/PTC/电机验证均为 NOT_RUN。\n').encode()
  236. files['EXCLUSIONS.json']=archive.encode({'excluded':['licenses','credentials','raw board files','large logs','toolchain installers'],
  237. 'scope':'product artifacts, current contracts and installable SDK source'})
  238. payload,modes=archive.finalize(files,{'schema':'prod2u-delivery-manifest-v2','profile':'delivery',
  239. 'product':product,'source_commit':origin['commit'],'source_tree':origin['tree'],'hardware':'NOT_RUN'})
  240. label='6400' if product=='6400-front-rear' else 'MRDIMM-V1.2'
  241. path=output/f'Prod2U-{label}-Delivery-{receipt["commit"][:8]}.zip'
  242. archive.write_archive(path,payload,modes);archive.read_archive(path)
  243. return path
  244. def dispatch_legacy(args: argparse.Namespace) -> Path:
  245. from tools import package_6400_canonical as c
  246. if args.action == "base": return c.package_base(args.output_dir)
  247. if args.action == "current": return _dual_current(args.output_dir, args.base_zip)
  248. if args.action == "overlay":
  249. with zipfile.ZipFile(args.current_zip) as z:
  250. try: current_schema = json.loads(z.read("PACKAGE-MANIFEST.json")).get("schema")
  251. except Exception: current_schema = None
  252. if current_schema in ("prod2u-dual-current-manifest-v1","prod2u-dual-current-manifest-v2"):
  253. return _dual_overlay(args.base_zip, args.current_zip, args.output_dir)
  254. from tools.overlay_6400_packages import run
  255. run(args.base_zip, args.current_zip, args.output_dir)
  256. return args.output_dir
  257. raise SystemExit("unsupported legacy action")
  258. def main(argv=None) -> int:
  259. ap=argparse.ArgumentParser(description=__doc__); sp=ap.add_subparsers(dest="action",required=True)
  260. for name in ("base","current","all"):
  261. p=sp.add_parser(name); p.add_argument("--output-dir",type=Path,default=ROOT/"dist")
  262. if name=="current": p.add_argument("--base-zip",type=Path,required=True)
  263. p=sp.add_parser("verify"); p.add_argument("package",type=Path)
  264. 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)
  265. 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)
  266. p.add_argument('--sdk-wheel',type=Path)
  267. p.add_argument('--bitstream',type=Path)
  268. a=ap.parse_args(argv)
  269. if a.action=="verify": print(json.dumps(verify(a.package),indent=2)); return 0
  270. if a.action == "all":
  271. base = dispatch_legacy(argparse.Namespace(action="base", output_dir=a.output_dir))
  272. current = dispatch_legacy(argparse.Namespace(action="current", output_dir=a.output_dir, base_zip=base))
  273. print(json.dumps({"status":"PASS","base":verify(base),"current":verify(current)}, indent=2))
  274. return 0
  275. if a.action in ("base","current","overlay"):
  276. result=dispatch_legacy(a)
  277. if a.action == "overlay":
  278. receipt = result / "OVERLAY-RECEIPT.json"
  279. payload = json.loads(receipt.read_text(encoding="utf-8")) if receipt.is_file() else {"status":"PASS"}
  280. print(json.dumps({**payload, "action": a.action, "output_dir": str(result.resolve())}, indent=2))
  281. else:
  282. print(json.dumps({**verify(result),"action":a.action},indent=2))
  283. return 0
  284. if a.action=="delivery":
  285. if not all((a.td_receipt,a.gui_exe)):ap.error("delivery requires --td-receipt and --gui-exe")
  286. product={"6400-v1.1":"6400-front-rear","mrdimm-v1.2":"mrdimm-chamber"}[a.product]
  287. result=product_delivery(product,a.output_dir,a.td_receipt,a.gui_exe,a.gui_zip,a.status_json,a.sdk_wheel,a.bitstream)
  288. print(json.dumps({**verify(result),"action":"delivery","product":a.product},indent=2));return 0
  289. return 2
  290. if __name__=="__main__": raise SystemExit(main())