#!/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 tempfile import TemporaryDirectory 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 ZIP_DEFLATED, 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' ADDON = 'eventlabs-loop-builder' ADDON_SOURCE = f'addons/{ADDON}/' ADDON_MAIN = f'{ADDON}.php' ADDON_MANIFEST = f'{ADDON}-release.json' 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 def build_loop_builder(ref, output): commit = git('rev-parse', '--verify', '--end-of-options', ref + '^{commit}').decode().strip() source = git('show', commit + ':' + ADDON_SOURCE + ADDON_MAIN).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 {ADDON_MAIN}.') return found[0] version = header('Version', VERSION) tag = 'loop-builder-v' + version if f"const VERSION = '{version}';" not in source: raise ValueError('The Loop Builder version header and constant must match.') if (ref.startswith('refs/tags/') or re.fullmatch('loop-builder-v' + VERSION, ref)) and ref.removeprefix('refs/tags/') != tag: raise ValueError(f'Loop Builder release tag must match its version: {tag}.') core = re.findall(r"^const CORE_MINIMUM = '(" + VERSION + r")';$", source, re.M) if len(core) != 1 or header('Requires Plugins', r'[^\r\n]+') != 'burn-events, elementor': raise ValueError('The Loop Builder must declare its eventLabs and Elementor dependencies.') output.mkdir(parents=True, exist_ok=True) archive = output / f'{ADDON}-v{version}.zip' with TemporaryDirectory(dir=output) as temp: raw = Path(temp) / 'tagged-source.zip' candidate = Path(temp) / archive.name paths = [ADDON_SOURCE + file for file in (ADDON_MAIN, 'README.md', 'includes', 'assets')] subprocess.run( ['git', '-C', str(ROOT), 'archive', '--format=zip', '--output=' + str(raw.resolve()), commit, '--', *paths], check=True, env={**os.environ, 'TZ': 'UTC'}, ) with ZipFile(raw) as tagged, ZipFile(candidate, 'w', ZIP_DEFLATED, compresslevel=9) as package: for entry in tagged.infolist(): if entry.is_dir(): continue path = entry.filename.removeprefix(ADDON_SOURCE) body = tagged.read(entry) entry.filename = f'{ADDON}/{path}' entry.orig_filename = entry.filename package.writestr(entry, body, compress_type=ZIP_DEFLATED, compresslevel=9) with ZipFile(candidate) as package: if package.read(f'{ADDON}/{ADDON_MAIN}').decode() != source or package.testzip() is not None: raise ValueError('The Loop Builder ZIP is incomplete or corrupt.') size = candidate.stat().st_size if not 0 < size <= MAX_ZIP_BYTES: raise ValueError('The WordPress release ZIP must be at most 32 MiB.') data = { 'version': version, 'requires': header('Requires at least', REQUIREMENT), 'requires_php': header('Requires PHP', REQUIREMENT), 'requires_eventlabs': core[0], 'package': archive.name, 'commit': commit, 'size': size, 'sha256': hashlib.sha256(candidate.read_bytes()).hexdigest(), } candidate.replace(archive) manifest = output / ADDON_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, *, addon=False): 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']}`" name = 'eventLabs Loop Builder v' + data['version'] if addon else 'eventLabs ' + tag requirements = ( f"Requires eventLabs {data['requires_eventlabs']} or later and Elementor.\n\n" f"[Setup and usage guide]({HOST}{REPO}/src/tag/{tag}/{ADDON_SOURCE}README.md)\n\n" if addon else '' ) 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': name, 'draft': True, 'prerelease': addon, 'body': f"Install `{archive.name}` through Plugins → Add Plugin → Upload Plugin.\n\n" f"{requirements}Source commit: `{data['commit']}`\n\n{marker}", }) if release.get('tag_name') != tag or release.get('prerelease') is not addon 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('--loop-builder', action='store_true', help='Package the separately installable Loop Builder add-on') parser.add_argument('--publish', action='store_true', help='Publish both assets to the already pushed tag') args = parser.parse_args() prefix = 'loop-builder-v' if args.loop_builder else 'v' if args.publish and not re.fullmatch(prefix + VERSION, args.ref): parser.error(f'--publish requires a {prefix}X.Y.Z tag') ref = 'refs/tags/' + args.ref if args.publish else args.ref try: builder = build_loop_builder if args.loop_builder else build release = builder(ref, args.out) if args.publish: publish(*release, addon=args.loop_builder) 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())