77 lines
4.7 KiB
Python
77 lines
4.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Qualify an exact CMS commit and package application files, never runtime state."""
|
|
import argparse
|
|
import gzip
|
|
import hashlib
|
|
import io
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import tarfile
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
ENTRY = 'server/cms-release.json'
|
|
STEPS = ['frozen-install', 'syntax', 'multisite-tests']
|
|
|
|
def digest(data): return hashlib.sha256(data).hexdigest()
|
|
def run(args): subprocess.run(args, cwd=ROOT, check=True)
|
|
def tracked_payload():
|
|
names = subprocess.check_output(['git','ls-files','-z','admin','server','package.json','package-lock.json'], cwd=ROOT).decode().split('\0')
|
|
files = {}
|
|
for name in sorted(filter(None,names)):
|
|
path=ROOT/name
|
|
if path.is_symlink() or not path.is_file() or (name not in ('package.json','package-lock.json') and path.suffix not in ('.js','.mjs','.html','.css','.svg')):
|
|
raise ValueError('unsupported runtime path: '+name)
|
|
files[name]=path.read_bytes()
|
|
if not {'admin/index.html','admin/admin.js','admin/admin.css','server/admin-server.mjs'} <= set(files):
|
|
raise ValueError('missing CMS application entrypoints')
|
|
return files
|
|
|
|
def bundle(files, commit, run_id, run_number, foundation):
|
|
if not re.fullmatch('[a-f0-9]{40}',commit) or any(type(n) is not int or n<=0 for n in (run_id,run_number)):
|
|
raise ValueError('full source and positive run identity required')
|
|
for name, data in files.items():
|
|
if (name not in ('package.json','package-lock.json') and not re.fullmatch(r'(?:admin|server)/[a-zA-Z0-9_-]+\.(?:mjs|js|css|html|svg)', name)) or not isinstance(data, bytes):
|
|
raise ValueError('unsupported application payload: '+name)
|
|
if not files:
|
|
raise ValueError('empty application payload')
|
|
identity=f'dc-cms-release-v1-r{run_id}-{commit}'
|
|
descriptor={'schemaVersion':'nodedc.dc-cms.release.v1','releaseId':identity,'repository':'SILVER/DC_CMS','repositoryId':33,'branch':'master','sourceCommit':commit,'runId':run_id,'runNumber':run_number,'qualification':{'status':'qualified','steps':STEPS,'deployed':False},'filesSha256':{k:digest(v) for k,v in files.items()},'foundationSha256':foundation}
|
|
payload=dict(files);payload[ENTRY]=(json.dumps(descriptor,indent=2,sort_keys=True)+'\n').encode()
|
|
members={'manifest.env':f'id={identity}\ncomponent=dc-cms-release\ntype=app-overlay\n'.encode(),'files.txt':('\n'.join(sorted(payload))+'\n').encode()}
|
|
members.update({'payload/'+k:v for k,v in payload.items()})
|
|
output=io.BytesIO()
|
|
with gzip.GzipFile(fileobj=output,mode='wb',mtime=0,filename='') as zipped:
|
|
with tarfile.open(fileobj=zipped,mode='w') as archive:
|
|
for name,data in sorted(members.items()):
|
|
item=tarfile.TarInfo(name);item.size=len(data);item.mode=0o644
|
|
archive.addfile(item,io.BytesIO(data))
|
|
return identity,output.getvalue()
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser();parser.add_argument('--commit',required=True);parser.add_argument('--run-id',type=int,required=True);parser.add_argument('--run-number',type=int,required=True);parser.add_argument('--output-dir',type=Path,required=True);args=parser.parse_args()
|
|
head=subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT).decode().strip()
|
|
dirty=subprocess.check_output(['git','status','--porcelain','--untracked-files=no'],cwd=ROOT)
|
|
if head!=args.commit or dirty: raise ValueError('qualification requires exact clean commit')
|
|
run(['npm','ci','--ignore-scripts'])
|
|
# UI build dependencies never enter the production package foundation.
|
|
run(['npm','ci','--ignore-scripts','--prefix','ui'])
|
|
run(['node','ui/build.mjs','--check'])
|
|
files=tracked_payload()
|
|
for name in files:
|
|
if name.endswith(('.js','.mjs')): run(['node','--check',name])
|
|
run(['node','--test','test/multisite.test.mjs','test/publication.test.mjs','test/backup.test.mjs'])
|
|
run(['python3','-m','unittest','discover','-s','infra/ci','-p','test_*.py'])
|
|
# The ordinary release cannot change its build, dependency or deployment foundation.
|
|
foundation={name:digest((ROOT/name).read_bytes()) for name in ['Dockerfile','package.json','package-lock.json','infra/docker-compose.yml']}
|
|
identity,data=bundle(files,args.commit,args.run_id,args.run_number,foundation)
|
|
args.output_dir.mkdir(parents=True,exist_ok=True)
|
|
name='nodedc-'+identity+'.tgz'
|
|
with (args.output_dir/name).open('xb') as stream:stream.write(data)
|
|
receipt={'artifact':name,'sourceCommit':args.commit,'runId':args.run_id,'runNumber':args.run_number,'deployed':False,'sha256':digest(data)}
|
|
(args.output_dir/'release.json').write_text(json.dumps(receipt,sort_keys=True)+'\n')
|
|
print(json.dumps(receipt))
|
|
|
|
if __name__=='__main__':main()
|