#!/usr/bin/env python3 """Create a Gitea release from a version tag; the .bin is a gzip tar archive.""" from __future__ import annotations import json import os from pathlib import Path import re import subprocess import tempfile from urllib.parse import quote from urllib.request import Request, urlopen import uuid def main() -> None: tag = os.environ['GITHUB_REF_NAME'] if not re.fullmatch(r'v\d+\.\d+\.\d+', tag): raise ValueError('Tag wydania musi mieć postać v1.2.3') if Path('VERSION').read_text(encoding='utf-8').strip() != tag[1:]: raise ValueError('VERSION musi odpowiadać tagowi wydania') server = os.environ['GITHUB_SERVER_URL'].rstrip('/') repo = os.environ['GITHUB_REPOSITORY'] if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', repo): raise ValueError('Nieprawidłowa nazwa repozytorium') token = os.environ['GITEA_RELEASE_TOKEN'] if not token: raise ValueError('Brakuje sekretu GITEA_RELEASE_TOKEN') api = f'{server}/api/v1/repos/{repo}/releases' def request(url: str, method: str, data: bytes, content_type: str) -> dict: req = Request(url, data=data, method=method, headers={'Authorization': f'token {token}', 'Content-Type': content_type}) with urlopen(req, timeout=120) as response: return json.load(response) with tempfile.TemporaryDirectory() as tmp: package = Path(tmp) / f'WGTools-Extended-{tag[1:]}.bin' for required in ('VERSION', 'app/main.py', 'scripts/wgtools-helper', 'scripts/install.sh'): subprocess.run(['git', 'cat-file', '-e', f'HEAD:{required}'], check=True) subprocess.run(['git', 'archive', '--format=tar.gz', f'--output={package}', 'HEAD'], check=True) title = f'WGTools-Extended wersja {tag[1:]}' release = request(api, 'POST', json.dumps({'tag_name': tag, 'name': title, 'body': title, 'draft': True}).encode(), 'application/json') boundary = 'wgtools' + uuid.uuid4().hex body = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{package.name}"\r\nContent-Type: application/octet-stream\r\n\r\n'.encode() + package.read_bytes() + f'\r\n--{boundary}--\r\n'.encode()) request(f'{api}/{int(release["id"])}/assets?name={quote(package.name)}', 'POST', body, f'multipart/form-data; boundary={boundary}') request(f'{api}/{int(release["id"])}', 'PATCH', b'{"draft":false}', 'application/json') if __name__ == '__main__': main()