From f85e1aba88a78d300ca3cc4d2e093b2542afc705 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Sun, 29 Nov 2026 02:00:59 -0700 Subject: [PATCH] ci: add automated GitHub-to-GitCode repo and release mirror sync --- .github/workflows/build-runtime.yml | 19 +++ .github/workflows/sync-gitcode.yml | 66 +++++++++ scripts/sync-gitcode-release.py | 201 ++++++++++++++++++++++++++++ 3 files changed, 286 insertions(+) create mode 100644 .github/workflows/sync-gitcode.yml create mode 100644 scripts/sync-gitcode-release.py diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml index 48dae3a..f61cfb2 100644 --- a/.github/workflows/build-runtime.yml +++ b/.github/workflows/build-runtime.yml @@ -237,6 +237,25 @@ jobs: gh release create "runtime-$c" @assets --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" } + - name: Mirror alpha prerelease to GitCode (best-effort) + if: github.event_name == 'schedule' || inputs.publish + continue-on-error: true + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }} + GITHUB_REPO: ${{ github.repository }} + shell: pwsh + run: | + if (-not $env:GITCODE_TOKEN) { + Write-Host 'GITCODE_TOKEN not set; skipping GitCode mirror' + exit 0 + } + $tag = "runtime-$($env:RELEASE_ID)" + git fetch --tags origin + $auth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("Nwflower:$($env:GITCODE_TOKEN)")) + git -c "http.extraheader=Authorization: Basic $auth" push "https://gitcode.com/Nwflower/Reims-Go.git" "refs/tags/${tag}:refs/tags/${tag}" + python scripts/sync-gitcode-release.py $tag + - name: Prune old alpha prereleases if: github.event_name == 'schedule' || inputs.publish env: diff --git a/.github/workflows/sync-gitcode.yml b/.github/workflows/sync-gitcode.yml new file mode 100644 index 0000000..0fc1b52 --- /dev/null +++ b/.github/workflows/sync-gitcode.yml @@ -0,0 +1,66 @@ +name: Sync Mirror to GitCode + +on: + push: + branches: [main] + release: + types: [published, released, edited, prereleased] + workflow_dispatch: + inputs: + tag: + description: "Specific release tag to sync (empty = latest app release + all runtime-* releases)" + required: false + default: "" + sync_releases: + description: "Also sync Release metadata and assets to GitCode" + type: boolean + default: true + +concurrency: + group: sync-gitcode + cancel-in-progress: false + +jobs: + sync: + runs-on: ubuntu-latest + env: + GITCODE_REPO: Nwflower/Reims-Go + GITCODE_USER: Nwflower + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Push main branch and tags to GitCode + env: + GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }} + run: | + set -euo pipefail + if [ -z "$GITCODE_TOKEN" ]; then + echo "GITCODE_TOKEN secret is not configured; skipping." + exit 0 + fi + git fetch --tags origin + # Configure token via extraheader so it never appears in remote URLs/logs. + auth="$(printf '%s:%s' "$GITCODE_USER" "$GITCODE_TOKEN" | base64 -w0)" + git -c "http.extraheader=Authorization: Basic $auth" push "https://gitcode.com/${GITCODE_REPO}.git" HEAD:refs/heads/main + git -c "http.extraheader=Authorization: Basic $auth" push "https://gitcode.com/${GITCODE_REPO}.git" --tags + + - name: Sync Release and assets to GitCode + if: github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && inputs.sync_releases) + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITCODE_TOKEN: ${{ secrets.GITCODE_TOKEN }} + GITHUB_REPO: ${{ github.repository }} + TARGET_TAG: ${{ github.event.release.tag_name || inputs.tag }} + run: | + set -euo pipefail + if [ -z "$GITCODE_TOKEN" ]; then + echo "GITCODE_TOKEN secret is not configured; skipping release sync." + exit 0 + fi + if [ -n "$TARGET_TAG" ]; then + python3 scripts/sync-gitcode-release.py "$TARGET_TAG" + else + python3 scripts/sync-gitcode-release.py + fi diff --git a/scripts/sync-gitcode-release.py b/scripts/sync-gitcode-release.py new file mode 100644 index 0000000..db5abd0 --- /dev/null +++ b/scripts/sync-gitcode-release.py @@ -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()