#!/usr/bin/env python3 """Build an installable eventLabs ZIP, and optionally publish its tag to Gitea.""" import argparse import base64 import hashlib import json import os from pathlib import Path import re import subprocess import sys from urllib.error import HTTPError, URLError from urllib.parse import urlencode from urllib.request import HTTPRedirectHandler, Request, build_opener from uuid import uuid4 from zipfile import ZipFile ROOT = Path(__file__).resolve().parent.parent HOST = 'https://git.labs.casa' REPO = '/josh/eventLabs' API = HOST + '/api/v1/repos' + REPO PACKAGE_DIR = 'burn-events/' MANIFEST = 'eventlabs-update.json' VERSION = r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)' REQUIREMENT = r'[0-9]+\.[0-9]+(?:\.[0-9]+)?' RUNTIME = ('burn-events.php', 'assets', 'includes', 'templates') MAX_ZIP_BYTES = 32 * 1024 * 1024 USER_AGENT = 'eventLabs-release' def git(*args): return subprocess.check_output(['git', '-C', str(ROOT), *args]) def build(ref, output): commit = git('rev-parse', '--verify', '--end-of-options', ref + '^{commit}').decode().strip() source = git('show', commit + ':burn-events.php').decode() def header(name, pattern): found = re.findall(r'^\s*\* ' + re.escape(name) + r': (' + pattern + r')\s*$', source, re.M) if len(found) != 1: raise ValueError(f'Expected one valid {name} header in burn-events.php.') return found[0] version = header('Version', VERSION) tag = 'v' + version constants = re.findall(r"^define\( 'BURN_EVENTS_VERSION', '([^']+)' \);$", source, re.M) if constants != [version]: raise ValueError('The plugin version header and BURN_EVENTS_VERSION must match.') if (ref.startswith('refs/tags/') or re.fullmatch('v' + VERSION, ref)) and ref.removeprefix('refs/tags/') != tag: raise ValueError(f'Release tag must match the plugin version: {tag}.') archive_name = f'eventlabs-{tag}.zip' data = { 'version': version, 'requires': header('Requires at least', REQUIREMENT), 'requires_php': header('Requires PHP', REQUIREMENT), 'package': archive_name, 'commit': commit, } if header('Update URI', r'\S+') != HOST + REPO: raise ValueError('The plugin Update URI must point to the eventLabs release repository.') output.mkdir(parents=True, exist_ok=True) archive = output / archive_name temporary = output / (archive_name + '.tmp') try: subprocess.run( ['git', '-C', str(ROOT), 'archive', '--format=zip', '-9', '--prefix=' + PACKAGE_DIR, '--output=' + str(temporary.resolve()), commit, '--', *RUNTIME], check=True, env={**os.environ, 'TZ': 'UTC'}, ) data['size'] = temporary.stat().st_size if not 0 < data['size'] <= MAX_ZIP_BYTES: raise ValueError('The WordPress release ZIP must be at most 32 MiB.') with ZipFile(temporary) as package: if package.read(PACKAGE_DIR + 'burn-events.php').decode() != source or package.testzip() is not None: raise ValueError('The release ZIP is incomplete or corrupt.') data['sha256'] = hashlib.sha256(temporary.read_bytes()).hexdigest() temporary.replace(archive) finally: temporary.unlink(missing_ok=True) manifest = output / MANIFEST manifest.write_text(json.dumps(data, indent=2) + '\n', encoding='utf-8') print(f'Built {archive} and {manifest}', flush=True) return tag, data, archive, manifest class NoRedirect(HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): # API write requests must never forward a repository credential to a redirect target. return None def authorization(): token = os.environ.get('EVENTLABS_RELEASE_TOKEN', '').strip() if token: return 'token ' + token result = subprocess.run( ['git', '-C', str(ROOT), 'credential', 'fill'], input=f'protocol=https\nhost=git.labs.casa\npath={REPO[1:]}.git\n\n', capture_output=True, text=True, env={**os.environ, 'GIT_TERMINAL_PROMPT': '0'}, ) fields = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line) if result.returncode or not fields.get('username') or not fields.get('password'): raise ValueError('Set EVENTLABS_RELEASE_TOKEN or configure Git credentials for git.labs.casa.') encoded = base64.b64encode((fields['username'] + ':' + fields['password']).encode()).decode() return 'Basic ' + encoded def publish(tag, data, archive, manifest): auth = authorization() opener = build_opener(NoRedirect()) def api(method, path, *, payload=None, attachment=None, missing=False): headers = {'Authorization': auth, 'User-Agent': USER_AGENT, 'Accept': 'application/json'} body = None if payload is not None: body = json.dumps(payload).encode() headers['Content-Type'] = 'application/json' if attachment is not None: boundary = uuid4().hex headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary body = ( f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{attachment.name}"\r\n' 'Content-Type: application/octet-stream\r\n\r\n' ).encode() + attachment.read_bytes() + f'\r\n--{boundary}--\r\n'.encode() path += '?' + urlencode({'name': attachment.name}) request = Request(API + path, method=method, data=body, headers=headers) try: with opener.open(request, timeout=90) as response: return json.load(response) except HTTPError as error: if missing and error.code == 404: return None raise ValueError(f'Gitea {method} {path} returned HTTP {error.code}.') from None remote_tag = api('GET', '/tags/' + tag) if remote_tag.get('commit', {}).get('sha') != data['commit']: raise ValueError(f'Push {tag} for this exact commit before publishing.') marker = f"SHA-256: `{data['sha256']}`" release = api('GET', '/releases/tags/' + tag, missing=True) if release is None: release = api('POST', '/releases', payload={ 'tag_name': tag, 'target_commitish': data['commit'], 'name': f'eventLabs {tag}', 'draft': True, 'prerelease': False, 'body': f"Install `{archive.name}` through Plugins → Add Plugin → Upload Plugin.\n\n" f"Source commit: `{data['commit']}`\n\n{marker}", }) if release.get('tag_name') != tag or release.get('prerelease') or marker not in (release.get('body') or ''): raise ValueError(f'An existing release for {tag} does not match this package. Check it on Gitea.') attachments = {asset['name']: asset['size'] for asset in release.get('assets') or []} if release.get('draft'): path = '/releases/' + str(int(release['id'])) for file in (archive, manifest): size = file.stat().st_size if file.name in attachments: if attachments[file.name] != size: raise ValueError(f'Existing draft attachment has the wrong size: {file.name}.') continue uploaded = api('POST', path + '/assets', attachment=file) if uploaded.get('name') != file.name or uploaded.get('size') != size: raise ValueError(f'Gitea did not store the complete attachment: {file.name}.') api('PATCH', path, payload={'draft': False}) # Confirm the same anonymous download URLs WordPress will use. download = HOST + REPO + '/releases/download/' + tag + '/' for file in (archive, manifest): request = Request(download + file.name, headers={'User-Agent': USER_AGENT}) with build_opener().open(request, timeout=45) as response: expected = file.read_bytes() if response.read(len(expected) + 1) != expected: raise ValueError(f'Public release download does not match the build: {file.name}.') print(HOST + REPO + '/releases/tag/' + tag) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('ref', nargs='?', default='HEAD', help='Git ref to package; default HEAD') parser.add_argument('--out', type=Path, default=ROOT / 'dist') parser.add_argument('--publish', action='store_true', help='Publish both assets to the already pushed tag') args = parser.parse_args() if args.publish and not re.fullmatch('v' + VERSION, args.ref): parser.error('--publish requires a stable tag like v0.5.2') ref = 'refs/tags/' + args.ref if args.publish else args.ref try: release = build(ref, args.out) if args.publish: publish(*release) except (ValueError, OSError, subprocess.CalledProcessError, URLError) as error: print(f'Release failed: {error}', file=sys.stderr) return 1 return 0 if __name__ == '__main__': sys.exit(main())