ci: add automated GitHub-to-GitCode repo and release mirror sync
This commit is contained in:
1 parent
a7921e998b
commit
f85e1aba88
3 files changed
+286
No files matched your search
@@ -0,0 +1,201 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Mirror GitHub Releases (metadata + all assets) to GitCode via API v5.
|
||||
|
||||
Used by .github/workflows/sync-gitcode.yml and build-runtime.yml.
|
||||
Requires environment variables:
|
||||
GITCODE_TOKEN Personal access token with repo & release write scope
|
||||
GH_TOKEN GitHub token for `gh release view/download`
|
||||
|
||||
Optional environment variables:
|
||||
GITHUB_REPO Default: Nwflower/reims-go
|
||||
GITCODE_REPO Default: Nwflower/Reims-Go
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
GITHUB_REPO = os.environ.get("GITHUB_REPO", "Nwflower/reims-go")
|
||||
GITCODE_REPO = os.environ.get("GITCODE_REPO", "Nwflower/Reims-Go")
|
||||
GITCODE_API = "https://api.gitcode.com/api/v5"
|
||||
|
||||
|
||||
def gc_request(method: str, path: str, token: str, payload=None):
|
||||
url = f"{GITCODE_API}{path}"
|
||||
data = None
|
||||
headers = {
|
||||
"Authorization": f"Bearer {token}",
|
||||
"User-Agent": "reims-go-sync",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode("utf-8")
|
||||
headers["Content-Type"] = "application/json; charset=utf-8"
|
||||
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
raw = resp.read()
|
||||
return resp.status, json.loads(raw.decode("utf-8")) if raw else None
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read().decode("utf-8", errors="replace")
|
||||
return e.code, body
|
||||
|
||||
|
||||
def list_gitcode_releases(token: str) -> dict:
|
||||
by_tag = {}
|
||||
for page in range(1, 20):
|
||||
status, data = gc_request(
|
||||
"GET",
|
||||
f"/repos/{GITCODE_REPO}/releases?page={page}&per_page=100",
|
||||
token,
|
||||
)
|
||||
if status != 200 or not isinstance(data, list) or not data:
|
||||
break
|
||||
for rel in data:
|
||||
tag = rel.get("tag_name")
|
||||
if tag:
|
||||
by_tag[tag] = rel
|
||||
if len(data) < 100:
|
||||
break
|
||||
return by_tag
|
||||
|
||||
|
||||
def gh_json(args: list[str]):
|
||||
out = subprocess.check_output(["gh", *args], text=True)
|
||||
return json.loads(out)
|
||||
|
||||
|
||||
def ensure_gitcode_release(tag: str, gh_rel: dict, existing: dict | None, token: str) -> dict:
|
||||
payload = {
|
||||
"tag_name": tag,
|
||||
"name": gh_rel.get("name") or tag,
|
||||
"body": gh_rel.get("body") or "",
|
||||
"prerelease": bool(gh_rel.get("isPrerelease")),
|
||||
"target_commitish": "main",
|
||||
}
|
||||
if existing is None:
|
||||
status, res = gc_request("POST", f"/repos/{GITCODE_REPO}/releases", token, payload)
|
||||
if status not in (200, 201):
|
||||
raise RuntimeError(f"create GitCode release {tag} failed (HTTP {status}): {res}")
|
||||
print(f"created GitCode release {tag} (prerelease={payload['prerelease']})")
|
||||
return res if isinstance(res, dict) else {}
|
||||
|
||||
# Update title/body/prerelease (e.g. when an alpha runtime is promoted to stable).
|
||||
enc_tag = urllib.parse.quote(tag, safe="")
|
||||
status, res = gc_request("PATCH", f"/repos/{GITCODE_REPO}/releases/{enc_tag}", token, payload)
|
||||
if status in (200, 201):
|
||||
print(f"updated GitCode release {tag} (prerelease={payload['prerelease']})")
|
||||
if isinstance(res, dict):
|
||||
return res
|
||||
else:
|
||||
print(f"notice PATCH release {tag} returned HTTP {status}; continuing with existing release")
|
||||
return existing
|
||||
|
||||
|
||||
def upload_asset(tag: str, file_path: str, file_name: str, token: str):
|
||||
enc_tag = urllib.parse.quote(tag, safe="")
|
||||
enc_name = urllib.parse.quote(file_name, safe="")
|
||||
status, data = gc_request(
|
||||
"GET",
|
||||
f"/repos/{GITCODE_REPO}/releases/{enc_tag}/upload_url?file_name={enc_name}",
|
||||
token,
|
||||
)
|
||||
if status != 200 or not isinstance(data, dict) or not data.get("url"):
|
||||
raise RuntimeError(f"get upload_url for {tag}/{file_name} failed (HTTP {status}): {data}")
|
||||
|
||||
cmd = ["curl", "-fSL", "--retry", "3", "--retry-delay", "5", "-X", "PUT", "-T", file_path]
|
||||
for k, v in (data.get("headers") or {}).items():
|
||||
cmd.extend(["-H", f"{k}: {v}"])
|
||||
cmd.append(data["url"])
|
||||
subprocess.check_call(cmd)
|
||||
print(f"uploaded {tag}/{file_name}")
|
||||
|
||||
|
||||
def sync_tag(tag: str, gc_releases: dict, token: str):
|
||||
gh_rel = gh_json([
|
||||
"release", "view", tag, "-R", GITHUB_REPO,
|
||||
"--json", "tagName,name,body,isPrerelease,isDraft,assets",
|
||||
])
|
||||
if gh_rel.get("isDraft"):
|
||||
print(f"skip {tag} (draft)")
|
||||
return
|
||||
|
||||
existing = gc_releases.get(tag)
|
||||
rel = ensure_gitcode_release(tag, gh_rel, existing, token)
|
||||
|
||||
# Refresh existing attachment map so idempotent reruns skip matching assets.
|
||||
have = {}
|
||||
for a in (existing or rel).get("assets") or []:
|
||||
if a.get("type") == "attach" and a.get("name"):
|
||||
have[a["name"]] = a.get("size")
|
||||
|
||||
assets = gh_rel.get("assets") or []
|
||||
if not assets:
|
||||
print(f"done {tag} (no assets)")
|
||||
return
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="gc-sync-") as tmp:
|
||||
for asset in assets:
|
||||
name = asset["name"]
|
||||
size = asset.get("size")
|
||||
if name in have and (size is None or have[name] == size):
|
||||
print(f"exists {tag}/{name} ({size} bytes)")
|
||||
continue
|
||||
print(f"fetching {tag}/{name} ({size} bytes) from GitHub...")
|
||||
subprocess.check_call([
|
||||
"gh", "release", "download", tag, "-R", GITHUB_REPO,
|
||||
"-p", name, "-D", tmp, "--clobber",
|
||||
])
|
||||
local_path = os.path.join(tmp, name)
|
||||
try:
|
||||
upload_asset(tag, local_path, name, token)
|
||||
finally:
|
||||
if os.path.exists(local_path):
|
||||
os.remove(local_path)
|
||||
|
||||
|
||||
def default_tags() -> list[str]:
|
||||
rels = gh_json([
|
||||
"release", "list", "-R", GITHUB_REPO, "--limit", "50",
|
||||
"--json", "tagName,isDraft,isPrerelease,isLatest",
|
||||
])
|
||||
tags = []
|
||||
seen_latest_app = False
|
||||
for r in rels:
|
||||
if r.get("isDraft"):
|
||||
continue
|
||||
tag = r["tagName"]
|
||||
if tag.startswith("runtime-"):
|
||||
tags.append(tag)
|
||||
elif tag.startswith("v") and (r.get("isLatest") or not seen_latest_app):
|
||||
tags.append(tag)
|
||||
seen_latest_app = True
|
||||
return tags
|
||||
|
||||
|
||||
def main():
|
||||
token = os.environ.get("GITCODE_TOKEN", "").strip()
|
||||
if not token:
|
||||
print("GITCODE_TOKEN is not set; skipping GitCode release sync.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
tags = [t.strip() for t in sys.argv[1:] if t.strip()]
|
||||
if not tags:
|
||||
tags = default_tags()
|
||||
if not tags:
|
||||
print("No releases to sync.")
|
||||
return
|
||||
|
||||
gc_releases = list_gitcode_releases(token)
|
||||
for tag in tags:
|
||||
sync_tag(tag, gc_releases, token)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user