"""Check that an APK really is the release it is published as. Used by package_release.py before staging, and by CI against the checked-in distribution: a stale or debug APK must not pass because its checksum and manifest were regenerated around it. """ import argparse, hashlib, json, os, pathlib, re, shutil, subprocess, sys ROOT=pathlib.Path(__file__).resolve().parents[1] PACKAGE='tv.kaleido.app' def properties(): return dict(l.split('=',1) for l in (ROOT/'version.properties').read_text(encoding='utf-8').splitlines() if '=' in l) def aapt2(): names=['aapt2.exe','aapt2'] if os.name=='nt' else ['aapt2'] roots=[ROOT/'.tools/sdk']+[pathlib.Path(os.environ[k]) for k in ('ANDROID_HOME','ANDROID_SDK_ROOT') if os.environ.get(k)] for root in roots: tools=sorted((root/'build-tools').glob('*'),key=lambda p:[int(x) if x.isdigit() else 0 for x in p.name.split('.')],reverse=True) if (root/'build-tools').is_dir() else [] for folder in tools: for name in names: if (folder/name).is_file():return str(folder/name) found=shutil.which('aapt2') if found:return found raise SystemExit('aapt2 was not found. Install Android build-tools or set ANDROID_HOME.') def badging(apk): """(package, versionName, versionCode, debuggable) from the APK's own manifest.""" out=subprocess.run([aapt2(),'dump','badging',str(apk)],capture_output=True,text=True,check=True).stdout m=re.search(r"^package: name='([^']+)' versionCode='(\d+)' versionName='([^']+)'",out,re.M) if not m:raise SystemExit(f'Could not read the version of {apk}.') return m.group(1),m.group(3),int(m.group(2)),'application-debuggable' in out def check_apk(apk,version_name,version_code): package,name,code,debuggable=badging(apk) problems=[] if package!=PACKAGE:problems.append(f'package is {package}, expected {PACKAGE}') if (name,code)!=(version_name,version_code):problems.append(f'APK is {name} ({code}), expected {version_name} ({version_code}); rebuild it') if debuggable:problems.append('APK is a debuggable build, not the release') if problems:raise SystemExit(f'{apk}: '+'; '.join(problems)+'.') def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--release',action='store_true',help='also require the distribution to match version.properties (tag builds)') args=parser.parse_args() out=ROOT/'distribution';apk=out/'Kaleido.apk' if not apk.exists():print('No distribution to verify.');return digest=hashlib.sha256(apk.read_bytes()).hexdigest() if (out/'Kaleido.apk.sha256').read_text().split()[0]!=digest:raise SystemExit('Kaleido.apk does not match Kaleido.apk.sha256.') manifest=json.loads((out/'latest.json').read_text(encoding='utf-8')) check_apk(apk,manifest['version'],int(manifest['versionCode'])) if args.release: version=properties() if (manifest['version'],int(manifest['versionCode']))!=(version['versionName'],int(version['versionCode'])): raise SystemExit('distribution/latest.json does not match version.properties; run scripts/package_release.py.') print('Distribution verified:',manifest['version'],f"({manifest['versionCode']})",'SHA-256',digest) if __name__=='__main__':main()