100 lines
5.8 KiB
Python
100 lines
5.8 KiB
Python
"""Publish this project's source and immutable release assets to the owner's Gitea.
|
|
|
|
Credentials are read through Git's configured credential helper and never printed.
|
|
No release, tag, repository, or existing asset is overwritten.
|
|
"""
|
|
import argparse
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('action', choices=['create-repository', 'publish-release', 'verify-release'])
|
|
parser.add_argument('--host', default='git.knickqueue.win')
|
|
parser.add_argument('--owner', default='Knick')
|
|
parser.add_argument('--repository', default='WindowsVolumeSteps')
|
|
args = parser.parse_args()
|
|
root = Path(__file__).resolve().parents[1]
|
|
env = dict(os.environ, GIT_TERMINAL_PROMPT='0', GCM_INTERACTIVE='never')
|
|
result = subprocess.run(['git', 'credential', 'fill'], input=f'protocol=https\nhost={args.host}\n\n',
|
|
text=True, capture_output=True, env=env, check=True)
|
|
credential = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line)
|
|
authorization = 'Basic ' + base64.b64encode((credential['username'] + ':' + credential['password']).encode()).decode()
|
|
base = f'https://{args.host}/api/v1'
|
|
repo_path = f'/repos/{urllib.parse.quote(args.owner, safe="")}/{urllib.parse.quote(args.repository, safe="")}'
|
|
|
|
def api(path, method='GET', data=None, headers=None, raw=False):
|
|
body = data if isinstance(data, bytes) else json.dumps(data).encode() if data is not None else None
|
|
request_headers = {'Authorization': authorization, 'Accept': 'application/json'}
|
|
if data is not None and not isinstance(data, bytes): request_headers['Content-Type'] = 'application/json'
|
|
if headers: request_headers.update(headers)
|
|
request = urllib.request.Request(base + path, method=method, data=body, headers=request_headers)
|
|
with urllib.request.urlopen(request, timeout=120) as response:
|
|
content = response.read()
|
|
return content if raw else json.loads(content) if content else None
|
|
|
|
def maybe(path):
|
|
try: return api(path)
|
|
except urllib.error.HTTPError as error:
|
|
if error.code != 404: raise
|
|
return None
|
|
|
|
user = api('/user')
|
|
if user['login'].lower() != args.owner.lower(): raise RuntimeError('The credential belongs to another owner.')
|
|
repo = maybe(repo_path)
|
|
if args.action == 'create-repository':
|
|
if repo:
|
|
print(json.dumps({'existing_repository': repo['html_url']})); return
|
|
repo = api('/user/repos', 'POST', {'name':args.repository, 'private':True, 'auto_init':False,
|
|
'default_branch':'main', 'description':'Two-point snapping for native Windows 11 volume sliders, with a per-user installer.'})
|
|
print(json.dumps({'created_repository':repo['html_url'], 'private':repo['private']})); return
|
|
if not repo: raise RuntimeError('Create the repository and push source before publishing.')
|
|
tag = 'v0.1.1'
|
|
sha = subprocess.check_output(['git','rev-parse','HEAD'], cwd=root, text=True).strip()
|
|
branch = api(repo_path + '/branches/main')
|
|
if branch['commit']['id'] != sha: raise RuntimeError('Remote source does not match the local release commit.')
|
|
release = maybe(repo_path + '/releases/tags/' + tag)
|
|
if args.action == 'publish-release' and release is None:
|
|
notes = (root / 'RELEASE_NOTES.md').read_text(encoding='utf-8')
|
|
release = api(repo_path + '/releases', 'POST', {'tag_name':tag,'target_commitish':sha,
|
|
'name':'Windows Volume Steps 0.1.1', 'body':notes, 'draft':False, 'prerelease':True})
|
|
if release is None: raise RuntimeError('Release not found.')
|
|
reference = api(repo_path + '/git/refs/tags/' + tag)
|
|
if isinstance(reference, list): reference = reference[0]
|
|
if reference['object']['sha'] != sha: raise RuntimeError('Existing release tag belongs to another commit.')
|
|
names = ['WindowsVolumeSteps-0.1.1-Setup.exe', 'WindowsVolumeSteps-0.1.1-win-x64.zip',
|
|
'WindowsVolumeSteps-0.1.1-source.zip', 'SHA256SUMS.txt']
|
|
verified = []
|
|
for name in names:
|
|
content = (root / 'dist' / name).read_bytes()
|
|
expected = hashlib.sha256(content).hexdigest()
|
|
assets = api(repo_path + f'/releases/{release["id"]}/assets')
|
|
existing = next((a for a in assets if a['name'] == name), None)
|
|
if not existing and args.action == 'publish-release':
|
|
boundary = 'VolumeSteps-' + uuid.uuid4().hex
|
|
body = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\n'
|
|
'Content-Type: application/octet-stream\r\n\r\n').encode() + content + f'\r\n--{boundary}--\r\n'.encode()
|
|
existing = api(repo_path + f'/releases/{release["id"]}/assets?name=' + urllib.parse.quote(name),
|
|
'POST', body, {'Content-Type':f'multipart/form-data; boundary={boundary}'})
|
|
if not existing: raise RuntimeError('Missing release asset: ' + name)
|
|
download_url = f'https://{args.host}/{args.owner}/{args.repository}/releases/download/{tag}/{urllib.parse.quote(name)}'
|
|
request = urllib.request.Request(download_url, headers={'Authorization':authorization})
|
|
with urllib.request.urlopen(request, timeout=120) as response: downloaded = response.read()
|
|
if hashlib.sha256(downloaded).hexdigest() != expected: raise RuntimeError('Downloaded asset checksum mismatch: ' + name)
|
|
verified.append({'name':name,'bytes':len(downloaded),'sha256':expected,'url':download_url})
|
|
print(json.dumps({'repository':repo['html_url'],'release':f'https://{args.host}/{args.owner}/{args.repository}/releases/tag/{tag}',
|
|
'commit':sha,'assets':verified}, indent=2))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|