mirror of
https://github.com/Such-Software/hash-wallet.git
synced 2026-11-25 11:03:55 +01:00
ci(release): stage Hash Bags desktop builds from one tag
This commit is contained in:
committed by
John Winter Murphy
parent
13a2908e8a
commit
9bb2a519ac
@@ -0,0 +1,161 @@
|
||||
"""Stage and check a Hash Bags desktop release without publishing the draft."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
REPO = "Such-Software/hash-wallet"
|
||||
BUILDS = "Builds/hash-wallet"
|
||||
SOURCE_BRANCH = "refs/heads/dev"
|
||||
SCRIPT = "scripts/release/desktop-release.py"
|
||||
REMOTE_URLS = {
|
||||
"origin": {f"git@github.com:{REPO}.git", f"https://github.com/{REPO}.git"},
|
||||
"gitea-builds": {
|
||||
f"such-git@git.such.software:{BUILDS}.git",
|
||||
f"ssh://such-git@git.such.software:2222/{BUILDS}.git",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args, text=True).strip()
|
||||
|
||||
|
||||
def verify_remote(name):
|
||||
allowed = {url.lower() for url in REMOTE_URLS[name]}
|
||||
for direction in ([], ["--push"]):
|
||||
urls = command("git", "remote", "get-url", *direction, "--all", name).splitlines()
|
||||
if len(urls) != 1 or urls[0].lower() not in allowed:
|
||||
raise ValueError(f"{name} does not have the expected fetch and push destinations")
|
||||
|
||||
|
||||
def remote_refs(remote, *refs):
|
||||
return {
|
||||
ref: sha
|
||||
for sha, ref in (line.split() for line in command("git", "ls-remote", remote, *refs).splitlines())
|
||||
}
|
||||
|
||||
|
||||
def remote_tag(remote, ref):
|
||||
peeled = f"{ref}^{{}}"
|
||||
refs = remote_refs(remote, ref, peeled)
|
||||
return refs.get(peeled, refs.get(ref))
|
||||
|
||||
|
||||
def release_for(tag):
|
||||
raw = command("gh", "api", "--paginate", f"repos/{REPO}/releases?per_page=100")
|
||||
decoder = json.JSONDecoder()
|
||||
matches = []
|
||||
while raw:
|
||||
page, end = decoder.raw_decode(raw)
|
||||
matches.extend(release for release in page if release["tag_name"] == tag)
|
||||
raw = raw[end:].lstrip()
|
||||
if len(matches) > 1:
|
||||
raise ValueError(f"GitHub returned more than one release for {tag}")
|
||||
return matches[0] if matches else None
|
||||
|
||||
|
||||
def verify_assets(release, names):
|
||||
assets = {asset["name"]: asset for asset in release["assets"]}
|
||||
missing = []
|
||||
for name in names:
|
||||
asset = assets.get(name, {})
|
||||
if (asset.get("state") != "uploaded" or asset.get("size", 0) <= 0
|
||||
or not re.fullmatch(r"sha256:[0-9a-f]{64}", asset.get("digest") or "")):
|
||||
missing.append(name)
|
||||
else:
|
||||
print(f"{name} {asset['digest']}")
|
||||
if missing:
|
||||
raise ValueError("Desktop assets are missing or unverified: " + ", ".join(missing))
|
||||
|
||||
|
||||
def has_release_driver(commit):
|
||||
source = subprocess.run(
|
||||
["git", "show", f"{commit}:{SCRIPT}"], capture_output=True, text=True,
|
||||
)
|
||||
return source.returncode == 0 and source.stdout.strip() == Path(__file__).read_text().strip()
|
||||
|
||||
|
||||
def stage(commit, tag, version, ref, canonical, builds, release):
|
||||
if not has_release_driver(commit):
|
||||
raise ValueError("The exact release commit does not contain this desktop release automation")
|
||||
if release is not None and not release["draft"]:
|
||||
raise ValueError(f"GitHub release {tag} is already public")
|
||||
if builds is not None and (canonical is None or release is None):
|
||||
raise ValueError(f"Builds tag {tag} already exists without its expected GitHub tag and draft")
|
||||
if canonical is None:
|
||||
subprocess.run(["git", "push", "origin", f"{commit}:{ref}"], check=True)
|
||||
if release is None:
|
||||
subprocess.run(
|
||||
["gh", "release", "create", tag, "--repo", REPO, "--draft", "--verify-tag",
|
||||
"--title", f"Hash Bags {version}", "--notes", ""],
|
||||
check=True,
|
||||
)
|
||||
release = release_for(tag)
|
||||
if release is None or not release["draft"] or remote_tag("origin", ref) != commit:
|
||||
raise ValueError("GitHub did not confirm the exact release tag and draft")
|
||||
if builds is None:
|
||||
subprocess.run(["git", "push", "gitea-builds", f"{commit}:{ref}"], check=True)
|
||||
if remote_tag("gitea-builds", ref) != commit:
|
||||
raise ValueError(f"Builds did not confirm tag {tag} at {commit}")
|
||||
print(f"Desktop build tag confirmed: {tag}")
|
||||
print(release["html_url"])
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("commit", help="Full reviewed canonical Git commit")
|
||||
operation = parser.add_mutually_exclusive_group()
|
||||
operation.add_argument("--start", action="store_true", help="Create the draft and start the desktop tag builds")
|
||||
operation.add_argument("--verify", action="store_true", help="Check the three GitHub asset names and digests")
|
||||
args = parser.parse_args()
|
||||
if not re.fullmatch(r"[0-9a-f]{40}", args.commit):
|
||||
parser.error("commit must be a full lowercase Git SHA")
|
||||
|
||||
for remote in REMOTE_URLS:
|
||||
verify_remote(remote)
|
||||
head = remote_refs("origin", SOURCE_BRANCH).get(SOURCE_BRANCH)
|
||||
if head is None:
|
||||
raise ValueError("Canonical dev did not return a commit")
|
||||
ancestry = subprocess.run(["git", "merge-base", "--is-ancestor", args.commit, head])
|
||||
if ancestry.returncode != 0:
|
||||
raise ValueError("The commit is not on locally available canonical dev history. Fetch origin dev if it moved.")
|
||||
|
||||
spec = command("git", "show", f"{args.commit}:pubspec_description.yaml")
|
||||
match = re.search(r"^version:\s+([0-9]+\.[0-9]+\.[0-9]+)\+([1-9][0-9]*)$", spec, re.MULTILINE)
|
||||
if not match:
|
||||
raise ValueError("Expected a version and positive build number in pubspec_description.yaml")
|
||||
version, build = match.groups()
|
||||
tag = f"hash-bags-{version}-build{build}"
|
||||
ref = f"refs/tags/{tag}"
|
||||
canonical = remote_tag("origin", ref)
|
||||
builds = remote_tag("gitea-builds", ref)
|
||||
if any(sha is not None and sha != args.commit for sha in (canonical, builds)):
|
||||
raise ValueError(f"Tag {tag} already points at a different commit")
|
||||
release = release_for(tag)
|
||||
names = [f"{tag}-macos.zip", f"HashBags-windows-{tag}.zip", "Hash_Bags-x86_64.AppImage"]
|
||||
print(f"{tag} at {args.commit}")
|
||||
if args.start:
|
||||
stage(args.commit, tag, version, ref, canonical, builds, release)
|
||||
elif args.verify:
|
||||
if canonical is None or builds is None or release is None:
|
||||
raise ValueError("The GitHub tag, Builds tag, and GitHub release must all exist")
|
||||
verify_assets(release, names)
|
||||
print(release["html_url"])
|
||||
else:
|
||||
print("Desktop assets: " + ", ".join(names))
|
||||
if has_release_driver(args.commit):
|
||||
print("Use --start to stage the draft and trigger the desktop tag builds.")
|
||||
else:
|
||||
print("This commit predates the desktop tag workflow or carries a different release command.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (ValueError, OSError, subprocess.SubprocessError) as error:
|
||||
sys.exit(f"Desktop release failed: {error}")
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Attach an immutable desktop asset to an existing Hash Bags release."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
REPO = "Such-Software/hash-wallet"
|
||||
API = f"https://api.github.com/repos/{REPO}"
|
||||
|
||||
|
||||
def request(url, *, asset=None):
|
||||
token = os.environ.get("GH_TOKEN")
|
||||
if not token:
|
||||
raise ValueError("GH_RELEASE_TOKEN is missing")
|
||||
headers = {
|
||||
"Accept": "application/vnd.github+json",
|
||||
"User-Agent": "hash-bags-ci",
|
||||
}
|
||||
if asset is None:
|
||||
attempt = Request(url, headers=headers)
|
||||
attempt.add_unredirected_header("Authorization", f"Bearer {token}")
|
||||
with urlopen(attempt, timeout=30) as response:
|
||||
return json.load(response)
|
||||
headers["Content-Type"] = "application/octet-stream"
|
||||
headers["Content-Length"] = str(asset.stat().st_size)
|
||||
with asset.open("rb") as handle:
|
||||
attempt = Request(url, data=handle, headers=headers)
|
||||
attempt.add_unredirected_header("Authorization", f"Bearer {token}")
|
||||
with urlopen(attempt, timeout=600) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def find_release(tag):
|
||||
page = 1
|
||||
while True:
|
||||
releases = request(f"{API}/releases?per_page=100&page={page}")
|
||||
for release in releases:
|
||||
if release["tag_name"] == tag:
|
||||
return release
|
||||
if len(releases) < 100:
|
||||
raise ValueError(f"GitHub release {tag} does not exist")
|
||||
page += 1
|
||||
|
||||
|
||||
def verify_tag(tag):
|
||||
ref = f"refs/tags/{tag}"
|
||||
output = subprocess.check_output(
|
||||
["git", "ls-remote", f"https://github.com/{REPO}.git", ref, f"{ref}^{{}}"],
|
||||
text=True,
|
||||
timeout=30,
|
||||
)
|
||||
refs = dict(reversed(line.split()) for line in output.splitlines())
|
||||
sha = refs.get(f"{ref}^{{}}", refs.get(ref))
|
||||
if sha is None or sha != os.environ.get("GITHUB_SHA"):
|
||||
raise ValueError(f"GitHub tag {tag} does not point to the build commit")
|
||||
|
||||
|
||||
def publish(tag, asset):
|
||||
if not asset.is_file() or asset.stat().st_size == 0:
|
||||
raise ValueError(f"Desktop asset is missing or empty: {asset}")
|
||||
release = find_release(tag)
|
||||
if os.environ.get("GITHUB_EVENT_NAME") == "push":
|
||||
verify_tag(tag)
|
||||
if not release["draft"]:
|
||||
raise ValueError(f"Tag builds may only attach assets to a draft release: {tag}")
|
||||
|
||||
digest = hashlib.sha256()
|
||||
with asset.open("rb") as handle:
|
||||
for block in iter(lambda: handle.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
expected_digest = f"sha256:{digest.hexdigest()}"
|
||||
|
||||
existing = next((item for item in release["assets"] if item["name"] == asset.name), None)
|
||||
if existing is not None:
|
||||
if existing.get("state") != "uploaded" or existing.get("digest") != expected_digest:
|
||||
raise ValueError(f"GitHub already has a different or incomplete asset named {asset.name}")
|
||||
print(f"{asset.name} is already uploaded with the expected digest")
|
||||
return
|
||||
|
||||
upload_url = f"https://uploads.github.com/repos/{REPO}/releases/{release['id']}/assets"
|
||||
uploaded = request(f"{upload_url}?{urlencode({'name': asset.name})}", asset=asset)
|
||||
if uploaded.get("state") != "uploaded" or uploaded.get("digest") != expected_digest:
|
||||
raise ValueError(f"GitHub did not confirm the expected digest for {asset.name}")
|
||||
print(f"Uploaded {asset.name} to GitHub release {tag}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
tag, filename = sys.argv[1:]
|
||||
publish(tag, Path(filename))
|
||||
except HTTPError as error:
|
||||
sys.exit(f"Desktop asset upload refused by GitHub (HTTP {error.code})")
|
||||
except (ValueError, URLError, OSError, subprocess.SubprocessError) as error:
|
||||
sys.exit(f"Desktop asset upload failed: {error}")
|
||||
@@ -0,0 +1,89 @@
|
||||
import contextlib
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
def load_script(name):
|
||||
spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(f"{name}.py"))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
release = load_script("desktop-release")
|
||||
publisher = load_script("publish-desktop-asset")
|
||||
|
||||
|
||||
class DesktopReleaseTests(unittest.TestCase):
|
||||
def test_lookup_finds_draft_on_later_github_page(self):
|
||||
draft = {"tag_name": "target", "draft": True}
|
||||
paginated_output = json.dumps([{"tag_name": "previous"}]) + json.dumps([draft])
|
||||
with patch.object(release, "command", return_value=paginated_output):
|
||||
self.assertEqual(release.release_for("target"), draft)
|
||||
|
||||
def test_staging_creates_draft_before_pushing_the_builds_tag(self):
|
||||
commit = "a" * 40
|
||||
tag = "hash-bags-1.2.3-build4"
|
||||
draft = {"draft": True, "html_url": "https://example.invalid/draft"}
|
||||
with (
|
||||
patch.object(release, "has_release_driver", return_value=True),
|
||||
patch.object(release, "release_for", return_value=draft),
|
||||
patch.object(release, "remote_tag", return_value=commit),
|
||||
patch.object(release.subprocess, "run") as run,
|
||||
contextlib.redirect_stdout(io.StringIO()),
|
||||
):
|
||||
release.stage(commit, tag, "1.2.3", f"refs/tags/{tag}", None, None, None)
|
||||
actions = [call.args[0] for call in run.call_args_list]
|
||||
self.assertEqual([action[0] for action in actions], ["git", "gh", "git"])
|
||||
self.assertIn("--draft", actions[1])
|
||||
self.assertIn("origin", actions[0])
|
||||
self.assertIn("gitea-builds", actions[2])
|
||||
|
||||
def test_verification_refuses_a_missing_desktop_asset(self):
|
||||
with self.assertRaisesRegex(ValueError, "AppImage"):
|
||||
release.verify_assets({"assets": []}, ["Hash_Bags-x86_64.AppImage"])
|
||||
|
||||
|
||||
class DesktopPublisherTests(unittest.TestCase):
|
||||
def test_tag_build_refuses_public_release(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
artifact = Path(directory) / "desktop.zip"
|
||||
artifact.write_bytes(b"fixture")
|
||||
with (
|
||||
patch.dict(publisher.os.environ, {"GITHUB_EVENT_NAME": "push"}),
|
||||
patch.object(publisher, "find_release", return_value={"draft": False}),
|
||||
patch.object(publisher, "verify_tag"),
|
||||
patch.object(publisher, "request") as request,
|
||||
self.assertRaisesRegex(ValueError, "draft release"),
|
||||
):
|
||||
publisher.publish("target", artifact)
|
||||
request.assert_not_called()
|
||||
|
||||
def test_retry_accepts_identical_asset_and_refuses_replacement(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
artifact = Path(directory) / "desktop.zip"
|
||||
artifact.write_bytes(b"fixture")
|
||||
digest = "sha256:" + hashlib.sha256(artifact.read_bytes()).hexdigest()
|
||||
asset = {"name": artifact.name, "state": "uploaded", "digest": digest}
|
||||
draft = {"draft": True, "assets": [asset]}
|
||||
with (
|
||||
patch.dict(publisher.os.environ, {"GITHUB_EVENT_NAME": "workflow_dispatch"}),
|
||||
patch.object(publisher, "find_release", return_value=draft),
|
||||
patch.object(publisher, "request") as request,
|
||||
contextlib.redirect_stdout(io.StringIO()),
|
||||
):
|
||||
publisher.publish("target", artifact)
|
||||
artifact.write_bytes(b"different fixture")
|
||||
with self.assertRaisesRegex(ValueError, "different or incomplete asset"):
|
||||
publisher.publish("target", artifact)
|
||||
request.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user