#!/usr/bin/env python3 """Build in a fresh source copy using pinned Quartus; leave source/IP untouched.""" import argparse, datetime, hashlib, json, re, shutil, subprocess from pathlib import Path,PurePosixPath ROOT=Path(__file__).resolve().parents[1] def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest() def main(): p=argparse.ArgumentParser(description=__doc__) p.add_argument('--quartus',type=Path,required=True,help='Full path to quartus_sh.exe (17.0.2 Build602)') p.add_argument('--output',type=Path,default=ROOT/'build/fpga') p.add_argument('--prepare-only',action='store_true') a=p.parse_args();a.output=a.output.resolve() if not a.output.is_relative_to(ROOT/'build') or a.output.exists():raise RuntimeError('Use a fresh repository build/ directory') version=subprocess.check_output([str(a.quartus.resolve()),'--version'],stderr=subprocess.STDOUT).decode() if not re.search(r'17\.0\.2\s+Build\s+602',version):raise RuntimeError('Expected Quartus17.0.2 Build602: '+version) inventory=json.loads((ROOT/'tools/project_inputs.json').read_text()) names=inventory['files'] if len(names)!=len(set(names)):raise RuntimeError('Duplicate project input') for name in names: relative=PurePosixPath(name) if relative.is_absolute() or '..' in relative.parts or '\\' in name or ':' in name:raise RuntimeError('Unsafe project input: '+name) if not (ROOT/name).is_file() or (ROOT/name).is_symlink():raise RuntimeError('Missing/nonregular project input: '+name) # New HDL/IP/constraint files must not silently disappear from the build copy. extensions={'.sv','.v','.vh','.vhd','.qip','.sdc','.mif','.hex','.qsys','.ip','.tcl'} candidates=[p for folder in (ROOT/'rtl',ROOT/'sys') for p in folder.rglob('*') if p.is_file() and p.suffix.lower() in extensions] candidates += [p for p in ROOT.iterdir() if p.is_file() and p.suffix.lower() in extensions] missing=sorted(p.relative_to(ROOT).as_posix() for p in candidates if p.relative_to(ROOT).as_posix() not in names) if missing:raise RuntimeError('Add new project dependencies to tools/project_inputs.json: '+', '.join(missing)) seeds=re.findall(r'^set_global_assignment\s+-name\s+SEED\s+(\d+)\s*$',(ROOT/'CoCo3.qsf').read_text(),re.M) if len(seeds)!=1:raise RuntimeError('Require one literal SEED assignment in CoCo3.qsf') seed=int(seeds[0]) project=a.output/'project';project.mkdir(parents=True) inputs={} for name in names: source=ROOT/name;target=project/name;target.parent.mkdir(parents=True,exist_ok=True) shutil.copyfile(source,target) if name not in ('README.md','.gitignore','changes.txt'):inputs[name]=sha(source) # The unchanged upstream flow generates build_id.v in this copy only. receipt=dict(source_commit_at_build=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT).decode().strip(),source_state='Working tree with individually hashed project inputs',quartus=version.strip(),seed=seed,project_inventory_sha256=sha(ROOT/'tools/project_inputs.json'),inputs=inputs,prepared_utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),scope='Prepared source only') (a.output/'build.json').write_text(json.dumps(receipt,indent=2)+'\n') if a.prepare_only:print('Prepared '+str(project));return command=[str(a.quartus.resolve()),'--flow','compile','CoCo3'] with (a.output/'compile.log').open('w') as log: result=subprocess.run(command,cwd=project,stdout=log,stderr=subprocess.STDOUT) receipt['command']=['quartus_sh','--flow','compile','CoCo3'];receipt['exit_code']=result.returncode rbf=project/'output_files/CoCo3.rbf' if result.returncode or not rbf.exists():raise RuntimeError('Compilation failed; inspect '+str(a.output/'compile.log')) summary=project/'output_files/CoCo3.sta.summary' text=summary.read_text(errors='replace') slack=[float(x) for x in re.findall(r'Slack\s*:\s*([-+\d.]+)',text,re.I)] if not slack or min(slack)<0:raise RuntimeError('Missing or negative timing summary; inspect '+str(summary)) if any(sha(ROOT/n)!=h for n,h in inputs.items()):raise RuntimeError('Source changed during compilation') receipt.update(scope='Full native fit and timing summary; detailed path audits and hardware are separate',rbf_sha256=sha(rbf),rbf_bytes=rbf.stat().st_size,summary_sha256=sha(summary),slack_ns=slack,passed=True) (a.output/'build.json').write_text(json.dumps(receipt,indent=2)+'\n');print(json.dumps({k:v for k,v in receipt.items() if k!='inputs'},indent=2)) if __name__=='__main__':main()