Files
cutdex/tool/gitea/stage-release.py
T

288 lines
13 KiB
Python

"""Upload platform builds to a commit-bound draft, then verify and publish it."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import importlib.util
import io
import json
import os
from pathlib import Path
import urllib.error
import urllib.parse
import zipfile
from release_artifacts import AUDIT, FEED, INSTALLER, PORTABLE, app_versions, validate_metadata
import release_transport as transport
request = transport.request
fingerprint = transport.fingerprint
def context():
base = f"{transport.SERVER}/api/v1/repos/{os.environ['GITEA_REPOSITORY']}"
sha, tag = os.environ['GITEA_SHA'], os.environ['RELEASE_TAG']
version, windows_version = app_versions('pubspec.yaml')
if tag != f'v{version}':
raise ValueError('Release tag must match pubspec version')
remote_tag = request(f'{base}/tags/{urllib.parse.quote(tag, safe="")}')
if remote_tag['commit']['sha'] != sha:
raise ValueError('Release tag no longer matches the checked-out commit')
if os.environ.get('CI_RUN_ID'):
successful_ci(base, sha, int(os.environ['CI_RUN_ID']))
return base, sha, tag, version, windows_version
def marker(sha):
return f'<!-- cutdex-source-commit:{sha} -->'
def check_draft(release, sha, tag):
if not release.get('draft'):
raise ValueError('Release already published; choose a new version')
if release.get('tag_name') != tag or marker(sha) not in (release.get('body') or '').splitlines():
raise ValueError('Draft Release belongs to a different commit or release flow')
def ci_marker(run_id):
return f'<!-- cutdex-ci-run:{run_id} -->'
def successful_ci(base, sha, run_id=None):
runs = request(f'{base}/actions/runs?limit=100')['workflow_runs']
matches = [run for run in runs if run['head_sha'] == sha
and run['path'].endswith('@refs/heads/main')
and Path(run['path'].split('@')[0]).name == 'ci.yml'
and run['conclusion'] == 'success'
and (run_id is None or run['id'] == run_id)]
if not matches:
raise ValueError('No successful main CI for this exact commit; run CI before releasing')
return max(matches, key=lambda run: run['id'])
def ci_artifacts(base, run_id):
return [item for item in request(f'{base}/actions/runs/{run_id}/artifacts')['artifacts']
if not item.get('expired', False)]
def artifact_named(artifacts, name):
matches = [item for item in artifacts if item['name'] == name]
if len(matches) != 1:
raise ValueError('Expected one unexpired CI artifact: ' + name)
return matches[0]
def prepare_ci(base, sha, tag, version, windows_version):
# Keep retries bound to the original run, even if another same-commit CI
# succeeds later with different build bytes.
try:
existing = request(f'{base}/releases/tags/{urllib.parse.quote(tag, safe="")}')
except urllib.error.HTTPError as error:
if error.code != 404:
raise
existing = None
run_id = None
if existing is not None:
check_draft(existing, sha, tag)
import re
matches = re.findall(r'^<!-- cutdex-ci-run:(\d+) -->$', existing.get('body') or '', re.M)
if len(matches) != 1:
raise ValueError('Existing draft is not bound to a main CI run')
run_id = int(matches[0])
run = successful_ci(base, sha, run_id)
artifacts = ci_artifacts(base, run['id'])
verification = artifact_named(artifacts, 'cutdex-release-metadata')
selected = {platform: artifact_named(artifacts, f'cutdex-{platform}-build')
for platform in ('android', 'windows')}
release = prepare(base, sha, tag, version, windows_version, ci_run=run['id'])
if os.environ.get('GITHUB_OUTPUT'):
with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as stream:
stream.write(f"sha={sha}\nci-run-id={run['id']}\nartifact-id={verification['id']}\n")
for platform, artifact in selected.items():
stream.write(f"{platform}-artifact-id={artifact['id']}\n")
return release
def prepare(base, sha, tag, version, windows_version, *, ci_run=None):
try:
release = request(f'{base}/releases/tags/{urllib.parse.quote(tag, safe="")}')
except urllib.error.HTTPError as error:
if error.code != 404:
raise
release = request(f'{base}/releases', {
'tag_name': tag, 'target_commitish': sha, 'name': f'Cutdex {version}',
'draft': True, 'prerelease': False,
'body': f'{marker(sha)}\n' + (f'{ci_marker(ci_run)}\n' if ci_run is not None else '')
+ 'Windows x64 installer, Portable ZIP and full update package; '
f'Android ARM64/x86_64 APK. Windows update version: {windows_version}. '
'Packages are reused from successful main CI and uploaded independently. '
'Publication waits for all checks. '
'Android currently uses the project debug signing key. '
'Processing workers and models are distributed separately.'}, 'POST')
check_draft(release, sha, tag)
if ci_run is not None and ci_marker(ci_run) not in (release.get('body') or '').splitlines():
raise ValueError('Draft Release belongs to a different CI run')
if os.environ.get('GITHUB_OUTPUT'):
with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as stream:
stream.write(f"release-id={release['id']}\n")
return release
def upload_platform(base, release, contents):
"""Confirm upload presence; defer all byte verification to publication."""
transport.upload_contents(base, release['id'], contents, transport=request)
assets = request(f"{base}/releases/{release['id']}/assets")
names = [asset['name'] for asset in assets]
if len(set(names)) != len(names):
raise ValueError('Duplicate Release attachments')
if not set(contents) <= set(names):
raise ValueError('Missing uploaded platform attachments')
def asset_snapshot(assets):
return sorted((asset['id'], asset['name']) for asset in assets)
def verify_remote(base, release, metadata, manifest):
expected = dict(manifest['files'])
for name in ('SHA256SUMS', 'release-manifest.json'):
expected[name] = hashlib.sha256(metadata[name]).hexdigest()
assets = request(f"{base}/releases/{release['id']}/assets")
names = [asset['name'] for asset in assets]
if len(set(names)) != len(names) or set(names) != set(expected):
raise ValueError('Draft Release attachments differ from the validated artifact')
full = json.loads(metadata[FEED])['Assets'][0]
def verify(asset):
name = asset['name']
actual = fingerprint(asset)
if actual['sha256'] != expected[name]:
raise ValueError('Release attachment verification failed: ' + name)
if name == full['FileName'] and (actual['sha1'] != full['SHA1'].lower() or actual['size'] != full['Size']):
raise ValueError('Update index checksums do not match the full package')
with ThreadPoolExecutor(max_workers=2) as executor:
list(executor.map(verify, assets))
return asset_snapshot(assets)
def platform_contents(platform, path, version, windows_version):
if platform == 'android':
if path.is_dir():
expected = f'cutdex-{version}-android.apk'
if set(read_directory(path)) != {expected}:
raise ValueError('Expected exactly one Android APK')
path = path / expected
# Import lazily: assembling/uploading Windows must not require an APK.
spec = importlib.util.spec_from_file_location('package_app', Path(__file__).with_name('package-app.py'))
packaging = importlib.util.module_from_spec(spec)
spec.loader.exec_module(packaging)
packaging.validate_apk(path)
return {f'cutdex-{version}-android.apk': path.read_bytes()}
contents = read_directory(path)
# Validate the Windows feed/version/full-package hashes using the same
# complete-artifact validator before any bytes are uploaded.
required = {AUDIT, FEED, INSTALLER, PORTABLE}
if not required <= set(contents):
raise ValueError('Incomplete Windows packages')
dummy_apk = f'cutdex-{version}-android.apk'
if dummy_apk in contents or 'release-manifest.json' in contents or 'SHA256SUMS' in contents:
raise ValueError('Windows artifact contains unexpected release metadata')
validation = dict(contents)
validation[dummy_apk] = b''
spec = importlib.util.spec_from_file_location('package_app', Path(__file__).with_name('package-app.py'))
packaging = importlib.util.module_from_spec(spec)
spec.loader.exec_module(packaging)
packaging.assemble(validation, version, windows_version)
return contents
def read_directory(path):
paths = list(path.iterdir())
if any(not item.is_file() or item.is_symlink() for item in paths):
raise ValueError('Expected a flat package directory with regular files')
return {item.name: item.read_bytes() for item in paths}
def fetch_ci_artifact(base, command, path, version, windows_version):
run_id = int(os.environ['CI_RUN_ID'])
artifact_id = int(os.environ['CI_ARTIFACT_ID'])
artifacts = ci_artifacts(base, run_id)
matches = [item for item in artifacts if item['id'] == artifact_id]
if len(matches) != 1:
raise ValueError('Artifact does not belong to the selected CI run or has expired')
artifact = matches[0]
platform = command.removeprefix('fetch-')
expected = 'cutdex-release-metadata' if platform == 'release' else f'cutdex-{platform}-build'
if artifact['name'] != expected:
raise ValueError('Unexpected CI artifact type')
data = request(f'{base}/actions/artifacts/{artifact_id}/zip')
with zipfile.ZipFile(io.BytesIO(data)) as archive:
entries = [item for item in archive.infolist() if not item.is_dir()]
names = [item.filename for item in entries]
if len(set(names)) != len(names) or any('/' in name or '\\' in name for name in names):
raise ValueError('CI artifact requires unique flat filenames')
contents = {item.filename: archive.read(item) for item in entries}
apk_name = f'cutdex-{version}-android.apk'
if artifact['name'] == 'cutdex-release-metadata':
validate_metadata(contents, version, windows_version)
elif platform == 'android':
if set(contents) != {'app-production-release.apk'}:
raise ValueError('Unexpected Android build artifact')
contents = {apk_name: contents['app-production-release.apk']}
if path.exists() and any(path.iterdir()):
raise ValueError('CI artifact output directory must be empty')
path.mkdir(parents=True, exist_ok=True)
for name, body in contents.items():
(path / name).write_bytes(body)
if platform in {'android', 'windows'}:
platform_contents(platform, path, version, windows_version)
return artifact_id
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('command', choices=['prepare', 'prepare-ci', 'fetch-android', 'fetch-windows',
'fetch-release', 'android', 'windows', 'publish'])
parser.add_argument('--path', type=Path)
args = parser.parse_args()
if args.command not in {'prepare', 'prepare-ci'} and args.path is None:
parser.error('--path is required for uploading or publishing')
base, sha, tag, version, windows_version = context()
if args.command.startswith('fetch-'):
fetch_ci_artifact(base, args.command, args.path, version, windows_version)
return
if args.command == 'prepare-ci':
release = prepare_ci(base, sha, tag, version, windows_version)
elif args.command == 'prepare':
release = prepare(base, sha, tag, version, windows_version)
else:
release = request(f"{base}/releases/{int(os.environ['RELEASE_ID'])}")
check_draft(release, sha, tag)
if os.environ.get('CI_RUN_ID') and ci_marker(int(os.environ['CI_RUN_ID'])) not in (release.get('body') or '').splitlines():
raise ValueError('Draft Release belongs to a different CI run')
if args.command == 'publish':
contents = read_directory(args.path)
manifest = validate_metadata(contents, version, windows_version)
# Platform binaries must already have been independently uploaded.
metadata = {'SHA256SUMS', 'release-manifest.json'}
assets = request(f"{base}/releases/{release['id']}/assets")
if {asset['name'] for asset in assets} - metadata != set(manifest['files']):
raise ValueError('Not all platform packages have been uploaded')
transport.upload_contents(base, release['id'], {name: contents[name] for name in metadata}, transport=request)
snapshot = verify_remote(base, release, contents, manifest)
# Recheck tag binding and draft status immediately before publishing.
context()
check_draft(request(f"{base}/releases/{release['id']}"), sha, tag)
if snapshot != asset_snapshot(request(f"{base}/releases/{release['id']}/assets")):
raise ValueError('Release attachments changed during verification')
request(f"{base}/releases/{release['id']}", {'draft': False, 'prerelease': False}, 'PATCH')
else:
contents = platform_contents(args.command, args.path, version, windows_version)
upload_platform(base, release, contents)
print(json.dumps({'releaseId': release['id'], 'tag': tag, 'command': args.command}))
if __name__ == '__main__':
main()