299 lines
11 KiB
Python
Executable File
299 lines
11 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Publish or update the rolling Gitea release with desktop, Android, and Firefox assets."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
from datetime import datetime, timezone
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parent.parent
|
|
DIST_DIR = REPO_ROOT / "dist"
|
|
EXT_MANIFEST = REPO_ROOT / "extensions" / "firefox-i2p-torrent" / "manifest.json"
|
|
ANDROID_MANIFEST = REPO_ROOT / "android" / "app" / "src" / "main" / "AndroidManifest.xml"
|
|
|
|
BINARY_ARTIFACTS = [
|
|
("MoonI2P-Browser-x86_64.AppImage", DIST_DIR / "MoonI2P-Browser-x86_64.AppImage"),
|
|
("MoonI2P-Browser-android.apk", DIST_DIR / "MoonI2P-Browser-android.apk"),
|
|
("moon-i2p-firefox-extension.xpi", REPO_ROOT / "extensions" / "firefox-i2p-torrent.xpi"),
|
|
]
|
|
|
|
|
|
def sha256_and_size(path: Path) -> tuple[str, int]:
|
|
h = hashlib.sha256()
|
|
size = 0
|
|
with open(path, "rb") as fp:
|
|
while True:
|
|
chunk = fp.read(1024 * 1024)
|
|
if not chunk:
|
|
break
|
|
h.update(chunk)
|
|
size += len(chunk)
|
|
return h.hexdigest(), size
|
|
|
|
|
|
def fmt_size(num_bytes: int) -> str:
|
|
if num_bytes >= 1024 * 1024:
|
|
return f"{num_bytes / (1024 * 1024):.1f} MiB"
|
|
if num_bytes >= 1024:
|
|
return f"{num_bytes / 1024:.1f} KiB"
|
|
return f"{num_bytes} B"
|
|
|
|
|
|
def git_commit_sha() -> str:
|
|
env_sha = os.environ.get("GITHUB_SHA", "").strip()
|
|
if env_sha:
|
|
return env_sha
|
|
return (
|
|
subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=str(REPO_ROOT), text=True)
|
|
.strip()
|
|
)
|
|
|
|
|
|
def read_apk_manifest_versions() -> tuple[str, str]:
|
|
text = ANDROID_MANIFEST.read_text(encoding="utf-8")
|
|
vc_m = re.search(r'android:versionCode="([^"]+)"', text)
|
|
vn_m = re.search(r'android:versionName="([^"]+)"', text)
|
|
return (vc_m.group(1) if vc_m else "1", vn_m.group(1) if vn_m else "0.1.0")
|
|
|
|
|
|
def api_json(url: str, token: str, method: str = "GET", payload: dict | None = None):
|
|
headers = {
|
|
"Authorization": f"token {token}",
|
|
"Accept": "application/json",
|
|
}
|
|
data = None
|
|
if payload is not None:
|
|
headers["Content-Type"] = "application/json"
|
|
data = json.dumps(payload).encode("utf-8")
|
|
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
raw = resp.read().decode("utf-8", errors="replace").strip()
|
|
return resp.status, (json.loads(raw) if raw else None)
|
|
except urllib.error.HTTPError as exc:
|
|
body = exc.read().decode("utf-8", errors="replace").strip()
|
|
raise RuntimeError(f"Gitea API {method} {url} failed with HTTP {exc.code}: {body}") from None
|
|
|
|
|
|
def upload_asset_curl(upload_url: str, file_path: Path, token: str) -> None:
|
|
cfg_input = f'header = "Authorization: token {token}"\n'
|
|
res = subprocess.run(
|
|
[
|
|
"curl",
|
|
"-fsS",
|
|
"--retry",
|
|
"3",
|
|
"--retry-delay",
|
|
"5",
|
|
"-K",
|
|
"-",
|
|
"-F",
|
|
f"attachment=@{file_path}",
|
|
upload_url,
|
|
],
|
|
input=cfg_input,
|
|
text=True,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
)
|
|
if res.returncode != 0:
|
|
err = (res.stderr or "").strip()
|
|
raise RuntimeError(f"curl upload failed for {file_path.name} (rc={res.returncode}): {err}")
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument(
|
|
"--dry-run",
|
|
action="store_true",
|
|
help="Validate artifacts, generate SHA256SUMS.txt & version.json, and print release metadata without calling remote APIs.",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
tag = (os.environ.get("ROLLING_TAG") or "rolling").strip() or "rolling"
|
|
server = (os.environ.get("GITHUB_SERVER_URL") or "https://git.site.latha.org").strip().rstrip("/")
|
|
repo = (os.environ.get("GITHUB_REPOSITORY") or "experiments/moon-i2p").strip().strip("/")
|
|
commit = git_commit_sha()
|
|
short_commit = commit[:7]
|
|
built_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
run_number = (os.environ.get("GITHUB_RUN_NUMBER") or "local").strip()
|
|
|
|
ext_version = json.loads(EXT_MANIFEST.read_text(encoding="utf-8")).get("version", "0.1.0")
|
|
manifest_vc, manifest_vn = read_apk_manifest_versions()
|
|
apk_version_code = (os.environ.get("MOON_I2P_VERSION_CODE") or "").strip() or manifest_vc
|
|
apk_version_name = (os.environ.get("MOON_I2P_VERSION_NAME") or "").strip() or manifest_vn
|
|
apk_signed_with = (os.environ.get("APK_SIGNED_WITH") or "").strip() or (
|
|
"release" if os.environ.get("ANDROID_KEYSTORE_B64", "").strip() else "debug"
|
|
)
|
|
|
|
DIST_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
missing = [str(path) for _, path in BINARY_ARTIFACTS if not path.is_file()]
|
|
if missing:
|
|
raise FileNotFoundError(f"Missing release artifact(s): {', '.join(missing)}")
|
|
|
|
assets_meta: dict[str, dict[str, object]] = {}
|
|
sum_lines: list[str] = []
|
|
upload_list: list[tuple[str, Path]] = []
|
|
|
|
for name, path in BINARY_ARTIFACTS:
|
|
digest, size = sha256_and_size(path)
|
|
assets_meta[name] = {"size": size, "sha256": digest}
|
|
sum_lines.append(f"{digest} {name}")
|
|
upload_list.append((name, path))
|
|
|
|
sums_path = DIST_DIR / "SHA256SUMS.txt"
|
|
sums_path.write_text("\n".join(sum_lines) + "\n", encoding="utf-8")
|
|
sums_digest, sums_size = sha256_and_size(sums_path)
|
|
assets_meta["SHA256SUMS.txt"] = {"size": sums_size, "sha256": sums_digest}
|
|
upload_list.append(("SHA256SUMS.txt", sums_path))
|
|
|
|
version_info = {
|
|
"tag": tag,
|
|
"commit": commit,
|
|
"short_commit": short_commit,
|
|
"built_at": built_at,
|
|
"run_number": run_number,
|
|
"extension_version": ext_version,
|
|
"apk_version_code": int(apk_version_code) if apk_version_code.isdigit() else apk_version_code,
|
|
"apk_version_name": apk_version_name,
|
|
"apk_signed_with": apk_signed_with,
|
|
"assets": assets_meta,
|
|
}
|
|
version_path = DIST_DIR / "version.json"
|
|
version_path.write_text(json.dumps(version_info, indent=2) + "\n", encoding="utf-8")
|
|
upload_list.append(("version.json", version_path))
|
|
|
|
title = f"Moon I2P Rolling Build ({short_commit})"
|
|
table_rows = "\n".join(
|
|
f"| `{name}` | {fmt_size(int(assets_meta[name]['size']))} | `{assets_meta[name]['sha256']}` |"
|
|
for name, _ in BINARY_ARTIFACTS
|
|
)
|
|
body = (
|
|
f"Automated rolling build from `main` at [`{short_commit}`]({server}/{repo}/commit/{commit}).\n\n"
|
|
f"- **Built at:** `{built_at}` (CI run #{run_number})\n"
|
|
f"- **Firefox Extension:** `v{ext_version}`\n"
|
|
f"- **Android APK:** `v{apk_version_name}` (`versionCode={apk_version_code}`, signed: `{apk_signed_with}`)\n\n"
|
|
"### Downloads\n\n"
|
|
"| Artifact | Size | SHA-256 |\n"
|
|
"| --- | --- | --- |\n"
|
|
f"{table_rows}\n\n"
|
|
"Verify downloads with `sha256sum -c SHA256SUMS.txt`.\n"
|
|
)
|
|
|
|
if args.dry_run:
|
|
print(f"DRY RUN title: {title}")
|
|
print(f"DRY RUN tag: {tag} -> {server}/{repo}/releases/tag/{tag}")
|
|
print(body)
|
|
return 0
|
|
|
|
token = (os.environ.get("GITEA_TOKEN") or os.environ.get("GITHUB_TOKEN") or "").strip()
|
|
if not token:
|
|
raise RuntimeError("Missing GITEA_TOKEN / GITHUB_TOKEN environment variable")
|
|
|
|
api = f"{server}/api/v1/repos/{repo}"
|
|
_, releases = api_json(f"{api}/releases?limit=50", token)
|
|
existing = None
|
|
if isinstance(releases, list):
|
|
for rel in releases:
|
|
if rel.get("tag_name") == tag:
|
|
existing = rel
|
|
break
|
|
|
|
if existing is not None:
|
|
release_id = existing["id"]
|
|
print(f"[publish_rolling_release] Updating existing '{tag}' release (id={release_id})")
|
|
tag_res = subprocess.run(
|
|
["git", "tag", "-f", tag, commit],
|
|
cwd=str(REPO_ROOT),
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
text=True,
|
|
)
|
|
if tag_res.returncode == 0:
|
|
push_res = subprocess.run(
|
|
["git", "push", "-f", "origin", f"refs/tags/{tag}"],
|
|
cwd=str(REPO_ROOT),
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
text=True,
|
|
)
|
|
if push_res.returncode != 0:
|
|
print(
|
|
f"[publish_rolling_release] Warning: could not force-push tag '{tag}' (rc={push_res.returncode}); continuing with release update",
|
|
file=sys.stderr,
|
|
)
|
|
else:
|
|
print(
|
|
f"[publish_rolling_release] Warning: git tag -f failed (rc={tag_res.returncode})",
|
|
file=sys.stderr,
|
|
)
|
|
|
|
_, cur_assets = api_json(f"{api}/releases/{release_id}/assets", token)
|
|
for asset in cur_assets or []:
|
|
asset_id = asset.get("id")
|
|
if asset_id is not None:
|
|
api_json(f"{api}/releases/{release_id}/assets/{asset_id}", token, method="DELETE")
|
|
|
|
api_json(
|
|
f"{api}/releases/{release_id}",
|
|
token,
|
|
method="PATCH",
|
|
payload={
|
|
"name": title,
|
|
"body": body,
|
|
"target_commitish": commit,
|
|
"prerelease": False,
|
|
},
|
|
)
|
|
else:
|
|
print(f"[publish_rolling_release] Creating draft '{tag}' release")
|
|
_, created = api_json(
|
|
f"{api}/releases",
|
|
token,
|
|
method="POST",
|
|
payload={
|
|
"tag_name": tag,
|
|
"target_commitish": commit,
|
|
"name": title,
|
|
"body": body,
|
|
"draft": True,
|
|
"prerelease": False,
|
|
},
|
|
)
|
|
release_id = created["id"]
|
|
|
|
for name, path in upload_list:
|
|
print(f"[publish_rolling_release] Uploading {name} ({path.stat().st_size} bytes)...")
|
|
qname = urllib.parse.quote(name, safe="")
|
|
upload_asset_curl(f"{api}/releases/{release_id}/assets?name={qname}", path, token)
|
|
|
|
api_json(
|
|
f"{api}/releases/{release_id}",
|
|
token,
|
|
method="PATCH",
|
|
payload={
|
|
"draft": False,
|
|
"prerelease": False,
|
|
"name": title,
|
|
"body": body,
|
|
"target_commitish": commit,
|
|
},
|
|
)
|
|
print(f"[publish_rolling_release] Published {tag} release: {server}/{repo}/releases/tag/{tag}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|