build_product_gui.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #!/usr/bin/env python3
  2. """One Windows GUI builder with product/TD/source/embedded-asset binding."""
  3. from pathlib import Path
  4. import argparse,hashlib,json,re,shutil,subprocess,sys,tempfile
  5. ROOT=Path(__file__).resolve().parents[1]
  6. if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT))
  7. sys.dont_write_bytecode=True
  8. from tools.source_identity import source_identity
  9. from tools import run_6400_td as td
  10. from tools.generate_target import generate_named_target
  11. PRODUCTS={'6400-front-rear':{'board':'FCB V1.1','script':'6400_hex_gui.py','generated':'6400'},
  12. 'mrdimm-chamber':{'board':'FCB V1.2','script':'mrdimm_hex_gui.py','generated':'mrdimm'}}
  13. def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
  14. def prepare_identity(product,bitstream,receipt_path):
  15. identity=source_identity(ROOT)
  16. if identity['clean'] is False:raise ValueError('GUI build requires a clean source snapshot')
  17. generate_named_target(product,check=True)
  18. receipt=json.loads(Path(receipt_path).read_text(encoding='utf-8'))
  19. if receipt.get('profile')!=product or receipt.get('status')!='PASS' or receipt.get('production') is not True or receipt.get('simulation_only') is not False:
  20. raise ValueError('GUI requires a passing production TD receipt for this product')
  21. if not receipt.get('timing_pass_25mhz') or receipt.get('warning_audit',{}).get('status')!='PASS':
  22. raise ValueError('TD timing/warning audit did not pass')
  23. if any(not re.fullmatch('[0-9a-f]{40}',str(receipt.get(k,''))) for k in ('commit','tree')):
  24. raise ValueError('TD source commit/tree missing')
  25. expected=td.input_manifest(product)
  26. if set(receipt.get('inputs',{}))!=set(expected):raise ValueError('TD input closure mismatch')
  27. for name,value in receipt['inputs'].items():
  28. if sha(ROOT/name)==value:continue
  29. # Windows CRLF checkout may differ from the exact Linux Git content.
  30. if identity['source_kind']=='git':
  31. canonical=subprocess.check_output(['git','show','HEAD:'+name],cwd=ROOT)
  32. if hashlib.sha256(canonical).hexdigest()==value:continue
  33. raise ValueError('source changed since TD: '+name)
  34. manifest_sha=hashlib.sha256(json.dumps(receipt['inputs'],sort_keys=True,separators=(',',':')).encode()).hexdigest()
  35. if manifest_sha!=receipt.get('source_manifest_sha256'):raise ValueError('TD source manifest identity mismatch')
  36. profile=td.HARDWARE_PROFILES[product]
  37. if receipt.get('project_sha256')!=receipt['inputs'][profile['project']] or receipt.get('source_closure_sha256')!=receipt['inputs'][profile['closure']]:
  38. raise ValueError('TD project/closure identity mismatch')
  39. bit_hash=sha(bitstream)
  40. if bit_hash!=receipt.get('bitstream_sha256'):raise ValueError('BIT does not match TD receipt')
  41. for name in ('hth_protocol','prod2u_status'):
  42. if sha(ROOT/f'tools/_vendor/{name}.py')!=(ROOT/f'tools/_vendor/{name}.sha256').read_text().strip():
  43. raise ValueError('vendored codec hash mismatch: '+name)
  44. contract=(ROOT/'generated'/PRODUCTS[product]['generated']/'contract-sha256.txt').read_text().strip()
  45. if not re.fullmatch('[0-9a-f]{64}',contract):raise ValueError('generated contract identity invalid')
  46. return {'product':product,'profile':product,'board':PRODUCTS[product]['board'],'commit':identity['commit'],
  47. 'source_tree':identity['tree'],'source_kind':identity['source_kind'],'contract_sha256':contract,
  48. 'bitstream_sha256':bit_hash,'bitstream_source_commit':receipt['commit'],'bitstream_source_tree':receipt['tree'],
  49. 'source_manifest_sha256':manifest_sha,'td_receipt_sha256':sha(receipt_path)}
  50. def validate_executable(exe,metadata,assets):
  51. from PyInstaller.archive.readers import CArchiveReader
  52. if Path(exe).read_bytes()[:2]!=b'MZ':raise ValueError('GUI is not a Windows PE executable')
  53. reader=CArchiveReader(str(exe))
  54. keys=[name for name in reader.toc if name.replace('\\','/').endswith('gui-build-metadata.json')]
  55. if len(keys)!=1:raise ValueError('embedded GUI metadata missing or ambiguous')
  56. embedded=json.loads(reader.extract(keys[0]))
  57. if embedded!=metadata:raise ValueError('actual embedded GUI metadata mismatch')
  58. asset_hashes={}
  59. for path,destination in assets:
  60. name=(destination+'/'+Path(path).name).removeprefix('./')
  61. matches=[key for key in reader.toc if key.replace('\\','/')==name]
  62. if len(matches)!=1:raise ValueError('embedded GUI asset missing: '+name)
  63. actual=hashlib.sha256(reader.extract(matches[0])).hexdigest()
  64. if actual!=sha(path):raise ValueError('embedded GUI asset differs from source: '+name)
  65. asset_hashes[name]=actual
  66. run=subprocess.run([str(exe),'--self-test'],capture_output=True,timeout=60,creationflags=getattr(subprocess,'CREATE_NO_WINDOW',0))
  67. if run.returncode:raise ValueError('offline GUI self-test failed: '+str(run.returncode))
  68. return {'schema':'prod2u-gui-validation-v1','exe_sha256':sha(exe),'self_test_exit':run.returncode,
  69. 'embedded_metadata':embedded,'embedded_assets_sha256':asset_hashes,'ui_visual_validation':'PENDING','hardware':'NOT_RUN'}
  70. def main(fixed_product=None):
  71. ap=argparse.ArgumentParser(description=__doc__)
  72. if fixed_product:ap.add_argument('--profile',choices=(fixed_product,),default=fixed_product)
  73. else:ap.add_argument('--product',choices=tuple(PRODUCTS),required=True)
  74. ap.add_argument('--bitstream',type=Path,required=True);ap.add_argument('--td-receipt',type=Path,required=True)
  75. ap.add_argument('--output-dir',type=Path,required=True);args=ap.parse_args()
  76. if sys.platform!='win32':ap.error('Windows x64 Python/PyInstaller is required')
  77. product=fixed_product or args.product
  78. metadata=prepare_identity(product,args.bitstream.resolve(),args.td_receipt.resolve())
  79. out=args.output_dir.resolve()
  80. if out==ROOT or ROOT in out.parents:ap.error('output-dir must be outside the source checkout')
  81. out.mkdir(parents=True,exist_ok=True)
  82. name=f"Prod2U-{product}-GUI-{metadata['commit'][:8]}-{metadata['contract_sha256'][:8]}"
  83. exe=out/(name+'.exe')
  84. if exe.exists():raise ValueError('GUI artifact already exists; use a new output directory')
  85. meta_path=out/'gui-build-metadata.json';meta_bytes=(json.dumps(metadata,indent=2)+'\n').encode()
  86. if meta_path.exists() and meta_path.read_bytes()!=meta_bytes:raise ValueError('different GUI metadata already exists in output-dir')
  87. meta_path.write_bytes(meta_bytes)
  88. generated=ROOT/'generated'/PRODUCTS[product]['generated']
  89. assets=[(meta_path,'.')]
  90. if product=='6400-front-rear':
  91. assets += [(generated/'manual-uart-contract.json','generated/6400'),(generated/'golden-vectors.json','generated/6400'),(ROOT/'contracts/ct7428-format.json','generated/6400')]
  92. else:assets.append((generated/'snapshot-layout.json','.'))
  93. with tempfile.TemporaryDirectory(prefix='pyinstaller-',dir=out) as directory:
  94. work=Path(directory).resolve()
  95. if work.parent!=out:raise ValueError('unexpected build workspace')
  96. command=[sys.executable,'-m','PyInstaller','--noconfirm','--clean','--onefile','--windowed','--name',name,
  97. '--distpath',str(out),'--workpath',str(work/'work'),'--specpath',str(work),
  98. '--paths',str(ROOT),'--paths',str(ROOT/'tools/_vendor'),'--hidden-import','hth_protocol','--hidden-import','prod2u_status']
  99. for path,destination in assets:command+=['--add-data',str(path)+';'+destination]
  100. subprocess.run(command+[str(ROOT/'tools'/PRODUCTS[product]['script'])],cwd=ROOT,check=True)
  101. validation=validate_executable(exe,metadata,assets)
  102. (out/'GUI-VALIDATION.json').write_text(json.dumps(validation,indent=2)+'\n')
  103. print(json.dumps({'exe':str(exe),'sha256':sha(exe),'bytes':exe.stat().st_size,**metadata},indent=2))
  104. return 0
  105. if __name__=='__main__':raise SystemExit(main())