Files
metin2-server/tools/ava2-itemshop/build_isolated.py
T

97 lines
4.8 KiB
Python

#!/usr/bin/env python3
"""Build a bound source snapshot in fresh per-target directories; never install it."""
import argparse
import hashlib
import json
from pathlib import Path
import platform
import re
import shutil
import subprocess
import sys
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def source_digest(source):
h=hashlib.sha256()
for part in ('server','extern'):
for path in sorted((source/part).rglob('*')):
if not path.is_file() or any(p in ('.obj','OBJDIR','obj','.git') for p in path.parts):continue
if path.suffix in ('.o','.a','.so','.d'):continue
h.update(str(path.relative_to(source)).encode()+b'\0'+path.read_bytes()+b'\0')
return h.hexdigest()
def validate_dependencies(source, manifest, revision):
if manifest.get('source_sha256')!=revision:raise ValueError('dependency manifest source mismatch')
archives=manifest.get('archives',{})
actual={str(p.relative_to(source)):digest(p) for p in source.rglob('*.a')}
if not actual or archives!=actual:raise ValueError('all dependency archives must match the reviewed source-bound manifest')
for name, expected in manifest.get('system_archives',{}).items():
dependency=Path(name)
if not dependency.is_absolute() or not dependency.is_file() or digest(dependency)!=expected:
raise ValueError('system dependency archive mismatch: '+name)
def prepare(source, output, target, dependency_manifest, warnings=False):
production=Path('/usr/metin2/server')
if output==production or production in output.parents or source==output or source in output.parents:
raise ValueError('output must be outside source and production trees')
revision=source_digest(source)
validate_dependencies(source,dependency_manifest,revision)
output.mkdir(parents=True,exist_ok=True)
state=output/'source-binding.json'
binding={'source':str(source),'sha256':revision,'dependencies':dependency_manifest}
if state.exists():
if json.loads(state.read_text())!=binding:raise ValueError('output belongs to another source/dependency set')
elif any(output.iterdir()):raise ValueError('unbound output must be empty')
else:state.write_text(json.dumps(binding,indent=2)+'\n')
run=output/(target+('-warnings' if warnings else '-release'))
run.mkdir() # Never silently reuse objects, even after a failed build.
snapshot=run/'source'
snapshot.mkdir()
for name in ('server','extern'):
shutil.copytree(source/name,snapshot/name,ignore=shutil.ignore_patterns('*.o','.obj','OBJDIR','*.d'))
for target_dir in (snapshot/'server/game/src',snapshot/'server/db/src'):
makefile=target_dir/'Makefile'
text=makefile.read_bytes().decode('latin1')
# Depend paths must follow this target's OBJDIR, not the original checkout.
text=re.sub(r'(?<![\w])(?:\.obj|OBJDIR)/', '$(OBJDIR)/',text)
if warnings:
text=re.sub(r'(?<!\S)-w(?!\S)','',text)
text+='\nCFLAGS += -Wall -Wextra -Wformat=2 -Wconversion -Wsign-conversion -Werror=format -Werror=implicit-int-conversion -Werror=shorten-64-to-32\n'
makefile.write_bytes(text.encode('latin1'))
for name in ('bin','work','obj'):(run/name).mkdir()
return run,snapshot,revision
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--source',type=Path,required=True)
p.add_argument('--output',type=Path,required=True)
p.add_argument('--target',choices=['game','db'],required=True)
p.add_argument('--jobs',type=int,default=1)
p.add_argument('--dependency-manifest',type=Path,required=True,help='reviewed archive hashes bound to source_sha256')
p.add_argument('--warnings',action='store_true')
a=p.parse_args()
if platform.system()!='FreeBSD':p.error('FreeBSD target build requires a FreeBSD host (not PASS)')
try:run,snapshot,revision=prepare(a.source.resolve(),a.output.resolve(),a.target,json.loads(a.dependency_manifest.read_text()),a.warnings)
except (ValueError,OSError) as e:p.error(str(e))
cmd=['gmake','-j%d'%max(1,a.jobs),'BINDIR='+str(run/'work'),'GAMEDIR='+str(run/'bin'),'DBDIR='+str(run/'bin'),'OBJDIR='+str(run/'obj')]
record={'source_sha256':revision,'command':cmd,'warnings':a.warnings,'status':'FAIL'}
try:
record['compiler']=subprocess.check_output(['clang++-devel','--version'],text=True)
with (run/'build.log').open('w') as log:
subprocess.run(cmd,cwd=snapshot/'server'/a.target/'src',stdout=log,stderr=subprocess.STDOUT,check=True)
binary=run/'bin'/a.target
if not binary.is_file():raise RuntimeError('missing binary')
record.update(status='PASS',binary=str(binary),binary_sha256=digest(binary))
finally:(run/'result.json').write_text(json.dumps(record,indent=2)+'\n')
print(a.target+' PASS')
if __name__=='__main__':main()