ci: add rolling Gitea release workflow and release publisher
Rolling Release / Build & Publish Rolling Release (push) Canceled after 0s
Rolling Release / Build & Publish Rolling Release (push) Canceled after 0s
This commit is contained in:
1 parent
7139a64544
commit
80c16ad6ad
5 files changed
+477
-33
No files matched your search
@@ -0,0 +1,86 @@
|
||||
name: Rolling Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: moon-i2p-rolling-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
build-and-release:
|
||||
name: Build & Publish Rolling Release
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: git.site.latha.org/cluster-services/android-sdk:latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Install native & packaging dependencies
|
||||
run: |
|
||||
apt-get update -qq
|
||||
apt-get install -y -qq --no-install-recommends gcc libc6-dev squashfs-tools librsvg2-bin >/dev/null
|
||||
|
||||
- name: Install MoonBit toolchain
|
||||
run: |
|
||||
curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash
|
||||
echo "$HOME/.moon/bin" >> "$GITHUB_PATH"
|
||||
"$HOME/.moon/bin/moon" version --all
|
||||
|
||||
- name: Run MoonBit tests & script/extension checks
|
||||
run: |
|
||||
moon update
|
||||
moon test --target wasm
|
||||
moon test --target js
|
||||
moon test --target native
|
||||
node --check \
|
||||
extensions/firefox-i2p-torrent/background.js \
|
||||
extensions/firefox-i2p-torrent/content.js \
|
||||
extensions/firefox-i2p-torrent/ui.js \
|
||||
extensions/firefox-i2p-torrent/start.js
|
||||
python3 -m json.tool extensions/firefox-i2p-torrent/manifest.json >/dev/null
|
||||
python3 -m py_compile \
|
||||
scripts/build_appimage.py \
|
||||
scripts/build_apk.py \
|
||||
scripts/moon_i2p_native_host.py \
|
||||
scripts/publish_rolling_release.py
|
||||
|
||||
- name: Compute release version metadata
|
||||
if: github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch')
|
||||
run: |
|
||||
ext_ver=$(python3 -c 'import json; print(json.load(open("extensions/firefox-i2p-torrent/manifest.json"))["version"])')
|
||||
short_sha="${GITHUB_SHA:0:7}"
|
||||
ver_code=$(( $(date +%s) / 60 ))
|
||||
{
|
||||
echo "MOON_I2P_VERSION_CODE=$ver_code"
|
||||
echo "MOON_I2P_VERSION_NAME=${ext_ver}-rolling.${short_sha}"
|
||||
} >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build Linux x86_64 AppImage & Firefox XPI
|
||||
if: github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch')
|
||||
run: |
|
||||
python3 scripts/build_appimage.py
|
||||
bash -n .cache/appimage/AppDir/AppRun
|
||||
|
||||
- name: Build Android APK
|
||||
if: github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch')
|
||||
env:
|
||||
ANDROID_KEYSTORE_B64: ${{ secrets.ANDROID_KEYSTORE_B64 }}
|
||||
ANDROID_KEYSTORE_PASS: ${{ secrets.ANDROID_KEYSTORE_PASS }}
|
||||
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
ANDROID_KEY_PASS: ${{ secrets.ANDROID_KEY_PASS }}
|
||||
run: python3 scripts/build_apk.py
|
||||
|
||||
- name: Publish rolling release
|
||||
if: github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch')
|
||||
env:
|
||||
GITEA_TOKEN: ${{ github.token }}
|
||||
APK_SIGNED_WITH: ${{ secrets.ANDROID_KEYSTORE_B64 != '' && 'release' || 'debug' }}
|
||||
run: python3 scripts/publish_rolling_release.py
|
||||
@@ -97,6 +97,14 @@ curl -x http://127.0.0.1:4444 http://zzz.i2p/
|
||||
./_build/native/debug/build/cmd/client/client.exe http-get kqypgjpjwrphnzebod5ev3ts2vtii6e5tntrg4rnfijqc7rypldq.b32.i2p /
|
||||
```
|
||||
|
||||
## Rolling Releases (CI)
|
||||
|
||||
Every push to `main` runs Gitea Actions ([rolling-release.yml](.gitea/workflows/rolling-release.yml)) to test and publish/update the `rolling` release at <https://git.site.latha.org/experiments/moon-i2p/releases/tag/rolling>:
|
||||
- `MoonI2P-Browser-x86_64.AppImage` — standalone Linux x86_64 Firefox ESR + native `moon-i2p` router bundle
|
||||
- `MoonI2P-Browser-android.apk` — standalone Android (`arm64-v8a` + `x86_64`) WebView browser + bundled router
|
||||
- `moon-i2p-firefox-extension.xpi` — standalone Firefox WebExtension
|
||||
- `SHA256SUMS.txt` & `version.json` — checksums and build metadata
|
||||
|
||||
## Running the Local MoonBit Router & SAMv3 Client
|
||||
|
||||
```bash
|
||||
|
||||
+54
-25
@@ -7,6 +7,7 @@ lib/<abi>/libmoon_i2p_router.so, compiles the Java WebView + ForegroundService
|
||||
shell using Android SDK build-tools (no Gradle required), aligns, and signs.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
@@ -196,6 +197,24 @@ def ensure_debug_keystore(keytool_bin: str) -> Path:
|
||||
return ks
|
||||
|
||||
|
||||
def resolve_signing_config(keytool_bin: str, build_dir: Path) -> tuple[Path, str, str, str]:
|
||||
ks_b64 = os.environ.get("ANDROID_KEYSTORE_B64", "").strip()
|
||||
if ks_b64:
|
||||
ks_pass = os.environ.get("ANDROID_KEYSTORE_PASS", "")
|
||||
key_alias = os.environ.get("ANDROID_KEY_ALIAS", "").strip()
|
||||
key_pass = os.environ.get("ANDROID_KEY_PASS", "") or ks_pass
|
||||
if not ks_pass:
|
||||
raise ValueError("ANDROID_KEYSTORE_PASS is required when ANDROID_KEYSTORE_B64 is set")
|
||||
if not key_alias:
|
||||
raise ValueError("ANDROID_KEY_ALIAS is required when ANDROID_KEYSTORE_B64 is set")
|
||||
ks_path = build_dir / "ci-signing.keystore"
|
||||
ks_path.write_bytes(base64.b64decode(ks_b64))
|
||||
os.chmod(ks_path, stat.S_IRUSR | stat.S_IWUSR)
|
||||
print("[build_apk] Using CI keystore from ANDROID_KEYSTORE_B64")
|
||||
return ks_path, ks_pass, key_alias, key_pass
|
||||
return ensure_debug_keystore(keytool_bin), "android", "androiddebugkey", "android"
|
||||
|
||||
|
||||
def main():
|
||||
tools = find_sdk_paths()
|
||||
DIST_DIR.mkdir(parents=True, exist_ok=True)
|
||||
@@ -223,26 +242,33 @@ def main():
|
||||
java_gen = BUILD_DIR / "gen"
|
||||
java_gen.mkdir(parents=True)
|
||||
base_apk = BUILD_DIR / "base.apk"
|
||||
run(
|
||||
[
|
||||
str(tools["build_tools"] / "aapt2"),
|
||||
"link",
|
||||
"-o",
|
||||
str(base_apk),
|
||||
"-I",
|
||||
str(tools["android_jar"]),
|
||||
"--manifest",
|
||||
str(ANDROID_SRC / "AndroidManifest.xml"),
|
||||
"--min-sdk-version",
|
||||
"24",
|
||||
"--target-sdk-version",
|
||||
"34",
|
||||
"--java",
|
||||
str(java_gen),
|
||||
"--auto-add-overlay",
|
||||
str(flat_zip),
|
||||
]
|
||||
)
|
||||
version_code = os.environ.get("MOON_I2P_VERSION_CODE", "").strip()
|
||||
version_name = os.environ.get("MOON_I2P_VERSION_NAME", "").strip()
|
||||
aapt_link_cmd = [
|
||||
str(tools["build_tools"] / "aapt2"),
|
||||
"link",
|
||||
"-o",
|
||||
str(base_apk),
|
||||
"-I",
|
||||
str(tools["android_jar"]),
|
||||
"--manifest",
|
||||
str(ANDROID_SRC / "AndroidManifest.xml"),
|
||||
"--min-sdk-version",
|
||||
"24",
|
||||
"--target-sdk-version",
|
||||
"34",
|
||||
"--java",
|
||||
str(java_gen),
|
||||
"--auto-add-overlay",
|
||||
]
|
||||
if version_code:
|
||||
if not version_code.isdigit() or int(version_code) <= 0:
|
||||
raise ValueError(f"Invalid MOON_I2P_VERSION_CODE: {version_code!r}")
|
||||
aapt_link_cmd.extend(["--version-code", version_code])
|
||||
if version_name:
|
||||
aapt_link_cmd.extend(["--version-name", version_name])
|
||||
aapt_link_cmd.append(str(flat_zip))
|
||||
run(aapt_link_cmd)
|
||||
|
||||
# 4. Compile Java sources -> class files -> classes.dex via d8
|
||||
classes_dir = BUILD_DIR / "classes"
|
||||
@@ -304,8 +330,11 @@ def main():
|
||||
aligned_apk = BUILD_DIR / "aligned.apk"
|
||||
run([str(tools["build_tools"] / "zipalign"), "-f", "-p", "4", str(unaligned_apk), str(aligned_apk)])
|
||||
|
||||
keystore = ensure_debug_keystore(tools["keytool"])
|
||||
keystore, ks_pass, key_alias, key_pass = resolve_signing_config(tools["keytool"], BUILD_DIR)
|
||||
tmp_signed = OUTPUT_APK.with_suffix(".apk.part")
|
||||
sign_env = dict(d8_env)
|
||||
sign_env["MOON_I2P_KS_PASS"] = ks_pass
|
||||
sign_env["MOON_I2P_KEY_PASS"] = key_pass
|
||||
subprocess.run(
|
||||
[
|
||||
str(tools["build_tools"] / "apksigner"),
|
||||
@@ -313,16 +342,16 @@ def main():
|
||||
"--ks",
|
||||
str(keystore),
|
||||
"--ks-pass",
|
||||
"pass:android",
|
||||
"env:MOON_I2P_KS_PASS",
|
||||
"--ks-key-alias",
|
||||
"androiddebugkey",
|
||||
key_alias,
|
||||
"--key-pass",
|
||||
"pass:android",
|
||||
"env:MOON_I2P_KEY_PASS",
|
||||
"--out",
|
||||
str(tmp_signed),
|
||||
str(aligned_apk),
|
||||
],
|
||||
env=d8_env,
|
||||
env=sign_env,
|
||||
check=True,
|
||||
)
|
||||
tmp_signed.replace(OUTPUT_APK)
|
||||
|
||||
@@ -15,6 +15,8 @@ import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
@@ -48,14 +50,35 @@ def download_cached(url: str, dest: Path, min_bytes: int = 100_000) -> Path:
|
||||
print(f"[build_appimage] Using cached {dest} ({dest.stat().st_size} bytes)")
|
||||
return dest
|
||||
tmp = dest.with_suffix(dest.suffix + ".part")
|
||||
print(f"[build_appimage] Downloading {url} -> {dest}")
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "moon-i2p-appimage-builder/1.0"})
|
||||
with urllib.request.urlopen(req, timeout=180) as resp, open(tmp, "wb") as fp:
|
||||
shutil.copyfileobj(resp, fp, length=1024 * 256)
|
||||
if tmp.stat().st_size < min_bytes:
|
||||
raise RuntimeError(f"Downloaded file too small: {tmp} ({tmp.stat().st_size} bytes)")
|
||||
tmp.replace(dest)
|
||||
return dest
|
||||
max_attempts = 3
|
||||
last_err = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
print(
|
||||
f"[build_appimage] Downloading {url} -> {dest} (attempt {attempt}/{max_attempts})"
|
||||
)
|
||||
req = urllib.request.Request(
|
||||
url, headers={"User-Agent": "moon-i2p-appimage-builder/1.0"}
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=180) as resp, open(tmp, "wb") as fp:
|
||||
shutil.copyfileobj(resp, fp, length=1024 * 256)
|
||||
if tmp.stat().st_size < min_bytes:
|
||||
raise RuntimeError(
|
||||
f"Downloaded file too small: {tmp} ({tmp.stat().st_size} bytes)"
|
||||
)
|
||||
tmp.replace(dest)
|
||||
return dest
|
||||
except (urllib.error.URLError, OSError, RuntimeError) as exc:
|
||||
last_err = exc
|
||||
if tmp.exists():
|
||||
tmp.unlink(missing_ok=True)
|
||||
if attempt < max_attempts:
|
||||
delay = attempt * 2
|
||||
print(
|
||||
f"[build_appimage] Download attempt {attempt} failed ({exc}); retrying in {delay}s..."
|
||||
)
|
||||
time.sleep(delay)
|
||||
raise RuntimeError(f"Failed downloading {url} after {max_attempts} attempts: {last_err}")
|
||||
|
||||
|
||||
def build_router_binary() -> Path:
|
||||
|
||||
Executable
+298
@@ -0,0 +1,298 @@
|
||||
#!/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())
|
||||
Reference in new issue
Block a user