From 21eef18f7bea75bd89c900eb5a66b0b7ed70d4fb 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 23:10:27 -0700 Subject: [PATCH] refactor(runtime,ci): remove GitCode mirror sync and download source --- .github/workflows/build-runtime.yml | 18 -- .github/workflows/sync-gitcode.yml | 75 -------- README.en.md | 2 +- README.md | 2 +- docs/architecture.md | 2 +- docs/plugin-architecture.md | 2 +- docs/portable-runtime-spec.md | 2 +- docs/roadmap.md | 2 +- frontend/src/App.tsx | 7 +- frontend/src/components/HostView.tsx | 7 +- frontend/src/components/RuntimeOnline.tsx | 31 +--- frontend/src/components/Setup.tsx | 7 +- frontend/src/i18n.ts | 14 +- frontend/src/types.ts | 4 - frontend/wailsjs/go/app/App.d.ts | 2 - frontend/wailsjs/go/app/App.js | 4 - frontend/wailsjs/go/models.ts | 4 - internal/app/runtime_bindings.go | 48 ++---- internal/cli/runtime_fetch.go | 28 ++- internal/config/config.go | 4 - internal/runtime/remote.go | 153 +++------------- internal/runtime/remote_test.go | 58 ------- internal/version/version.go | 86 ++------- scripts/sync-gitcode-release.py | 201 ---------------------- 24 files changed, 69 insertions(+), 694 deletions(-) delete mode 100644 .github/workflows/sync-gitcode.yml delete mode 100644 scripts/sync-gitcode-release.py diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml index 659355b..40234aa 100644 --- a/.github/workflows/build-runtime.yml +++ b/.github/workflows/build-runtime.yml @@ -239,24 +239,6 @@ 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 - git -c credential.helper= push "https://Nwflower:$($env:GITCODE_TOKEN)@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 deleted file mode 100644 index 7fa6967..0000000 --- a/.github/workflows/sync-gitcode.yml +++ /dev/null @@ -1,75 +0,0 @@ -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 - # Use GIT_ASKPASS so the token never appears in URLs or process argv. - askpass="$(mktemp)" - chmod 700 "$askpass" - cat > "$askpass" <<'EOF' - #!/bin/sh - case "$1" in - *Username*) printf '%s\n' "$GITCODE_USER" ;; - *) printf '%s\n' "$GITCODE_TOKEN" ;; - esac - EOF - trap 'rm -f "$askpass"' EXIT - GIT_TERMINAL_PROMPT=0 GIT_ASKPASS="$askpass" git -c credential.helper= push "https://gitcode.com/${GITCODE_REPO}.git" HEAD:refs/heads/main - GIT_TERMINAL_PROMPT=0 GIT_ASKPASS="$askpass" git -c credential.helper= 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/README.en.md b/README.en.md index 845ee80..34753d6 100644 --- a/README.en.md +++ b/README.en.md @@ -54,7 +54,7 @@ Reims-Go is a Windows desktop app for [reims-vgpu](https://github.com/steelbrain ## Highlights - **GPU acceleration**: macOS Metal graphics run on your Windows GPU through Vulkan. -- **Nothing to compile**: download one exe and run it. The app installs the runtime for you, and switches to the GitCode mirror when GitHub is unreachable. +- **Nothing to compile**: download one exe and run it. The app installs the runtime for you, with system proxy support and local archive import. - **No typing during install**: installers come straight from Apple. One click in Recovery types the install command, which erases the disk and starts installing. Once macOS is running: diff --git a/README.md b/README.md index ff8b722..907b9d7 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ Reims-Go 是 [reims-vgpu](https://github.com/steelbrain/reims-vgpu) 的 Windows ## 特点 - **显卡加速**:macOS 的 Metal 图形经 Vulkan 交给 Windows 独显执行。 -- **免编译**:下载一个 exe 就能用。运行时在应用里一键安装,GitHub 连不上时自动改用 GitCode 镜像。 +- **免编译**:下载一个 exe 就能用。运行时在应用里一键安装,支持系统代理和本地压缩包导入。 - **装机不用敲命令**:安装包直接从 Apple 下载;在恢复模式里点一下,装机命令会自动键入,抹盘和安装随即开始。 装好之后: diff --git a/docs/architecture.md b/docs/architecture.md index 010158b..f7e6f63 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -57,7 +57,7 @@ flowchart TB | `internal/vmstart` | GUI 与 CLI 共用的启动前准备:提交内存预检、离线辅助盘、恢复模式引导、客体语言重放、WHPX 兼容处理、启动后 CPU 绑核 | | `internal/cli` | 命令行子命令实现、单实例参数解析与向界面进程交接 `vm start` | | `internal/host` | 宿主机体检与硬件调优:WHPX 检测与 UAC 启用、提交内存预检、Vulkan ICD 扫描、三层大小核拓扑与实时绑核、显示器 HiDPI 推荐、音频与磁盘总线探测、窗口置前、IME 文本钩子 | -| `internal/runtime` | 便携运行时拉取(GitHub 主源 + GitCode 国内镜像回退)、原子解压、多版本切换与子进程环境变量构造 | +| `internal/runtime` | 便携运行时拉取(GitHub Releases)、原子解压、多版本切换与子进程环境变量构造 | | `internal/fetch` | 发布附件下载:HTTP `Range` 续传与按发布页 `SHA256SUMS.txt` 强制校验,运行时安装与应用内更新共用 | | `internal/selfupdate` | 应用内更新:把已校验的新版 `reims-go.exe` 换入运行中程序的位置、重新拉起与残留清理 | | `internal/installer` | 包装 `reims-util --json` 实现 macOS 离线安装包查询、宿主机直连下载、断点续传、互斥锁保护与缓存清理 | diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index e2d4eb1..95e2bed 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -378,7 +378,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card` - **安装来源**:本地包导入(首批)、市场索引(后续)、开发者模式本地目录链接。 - **随主程序附带的插件**:需要时可以标准插件包形式嵌入 `reims-go.exe`,信任等级为 `official`,版本跟随主程序;可启用/停用,不可卸载。 - **事务安装**:下载到 `tmp` → 校验 `SHA256SUMS` 与签名 → 核对包内 `id` / `version` 与预期一致(防偷换)→ 兼容预检 → 原子 rename 到 `pkgs//` → 提交 `state.json`。任一步失败都不改变现状。 -- **市场索引**:独立仓库发布静态 `index.json`(GitHub 主源 + GitCode 镜像,复用运行时下载源的回退与代理逻辑),含版本、`engines`、下载地址、SHA-256 与签名者;主程序内嵌兜底副本。 +- **市场索引**:独立仓库发布静态 `index.json`(GitHub Releases,复用运行时下载的代理逻辑),含版本、`engines`、下载地址、SHA-256 与签名者;主程序内嵌兜底副本。 - **更新与回滚**:新旧版本并存、切换指针,保留最近若干版本;插件同样区分 `alpha` / `stable` 通道,默认只取 `stable`。 - **安全模式**:`reims-go --safe-mode` 跳过全部第三方插件,界面顶部显示横幅与插件管理入口;以启动哨兵文件检测上次插件初始化阶段异常退出,下次启动询问是否进入安全模式。 - **市场红线**:拒收含 Apple 专有文件、SMBIOS 真值或闭源固件的包;运行时包必须附源码与许可证。 diff --git a/docs/portable-runtime-spec.md b/docs/portable-runtime-spec.md index 5fa2eb8..b737c8b 100644 --- a/docs/portable-runtime-spec.md +++ b/docs/portable-runtime-spec.md @@ -94,7 +94,7 @@ reims-runtime-/ > **CI 边界**:GitHub 托管的 Windows Server runner 不提供 WHPX,也无法复现 Windows 10 兼容性问题。CI 只验证可编译与控制面基本可用,实际能否启动 macOS 桌面必须经过第 5 节的真机冒烟。 ### 3.3 客户端下载与安装 -`internal/runtime` 默认从 GitHub Releases(tag `runtime-`)拉取,并支持官方镜像源 [GitCode `Nwflower/Reims-Go`](https://gitcode.com/Nwflower/Reims-Go) 自动回退(`auto` / `github` / `gitcode`),沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。 +`internal/runtime` 默认从 GitHub Releases(tag `runtime-`)拉取,沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。 --- diff --git a/docs/roadmap.md b/docs/roadmap.md index 9921929..4622840 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -12,7 +12,7 @@ ## 已实现能力(截至 v0.2.6) ### 1. 免编译与环境初始化 -- **便携运行时体系**:剥离 MSYS2 / Rust / 源码仓库依赖,支持 GitHub Release(含 GitCode 国内镜像回退与系统代理)在线下载、断点续传、SHA-256 校验、原子切换与本地 `.tar.zst` 导入。 +- **便携运行时体系**:剥离 MSYS2 / Rust / 源码仓库依赖,支持 GitHub Release(含系统代理)在线下载、断点续传、SHA-256 校验、原子切换与本地 `.tar.zst` 导入。 - **宿主机体检与引导**:免提权检测 WHPX(缺失时支持 UAC 一键开启)、物理与可用提交内存预检、Vulkan 独立显卡识别、大小核(P/E/LP-E)拓扑与处理器计划检查、数据盘总线类型风险提示。 - **统一发布物**:桌面界面与命令行共用单个 `reims-go.exe`,支持浅色/深色外观与中英双语。 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index b207a97..494503d 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -18,7 +18,7 @@ import { macOSMajor } from './lib/macosRelease' import { currentTask, finishedTaskTTL, pruneFinishedTasks, upsertTask } from './lib/tasks' import { applyActiveTheme, type UIStateSnapshot } from './lib/themeEngine' import { latestVMStats } from './lib/vmStats' -import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, RuntimeSource, Task, VMDetail } from './types' +import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types' import { Button, Tip, TooltipProvider } from './ui/controls' import { Modal } from './ui/dialog' import { Toaster, useToasts } from './ui/toast' @@ -338,9 +338,6 @@ export const App: React.FC = () => { const setChannel = (alpha: boolean) => { api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(() => refresh()).catch((e) => fail(tr('failGeneric'), e)) } - const setSource = (source: RuntimeSource) => { - api.SetRuntimeSource(source).then(() => refresh()).catch((e) => fail(tr('failGeneric'), e)) - } const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) } // In-app update: one task per release; its state drives the sidebar capsule @@ -875,7 +872,6 @@ export const App: React.FC = () => { onFinish={() => setSetupStage(null)} onError={fail} onChannel={setChannel} - onSource={setSource} onInstallRuntime={installRuntime} onCancelTask={cancelTask} onImportRuntime={importRuntime} @@ -1025,7 +1021,6 @@ export const App: React.FC = () => { onToast={(title) => toasts.push({ kind: 'ok', title })} runtimeTask={runtimeTask} onChannel={setChannel} - onSource={setSource} onInstallRuntime={installRuntime} onCancelTask={cancelTask} /> diff --git a/frontend/src/components/HostView.tsx b/frontend/src/components/HostView.tsx index 82ecdaa..030ec44 100644 --- a/frontend/src/components/HostView.tsx +++ b/frontend/src/components/HostView.tsx @@ -2,7 +2,7 @@ import { Cpu, HardDrive, MemoryStick, Plus, RefreshCw, ShieldCheck, Trash } from import React, { useEffect, useState } from 'react' import { I18nKey, t } from '../i18n' import { formatBytes, gpuCompatHint, gpuKey, gpuMetaLine, sameGPU } from '../lib/format' -import { AppState, Locale, RuntimeSource, StorageBreakdown, Task } from '../types' +import { AppState, Locale, StorageBreakdown, Task } from '../types' import { Button, IconButton } from '../ui/controls' import { api } from '../wails' import { RuntimeOnline } from './RuntimeOnline' @@ -16,12 +16,11 @@ interface Props { onToast?: (title: string) => void runtimeTask: Task | null onChannel: (alpha: boolean) => void - onSource: (source: RuntimeSource) => void onInstallRuntime: (commit: string) => void onCancelTask: (id: string) => void } -export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, onError, onToast, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask }) => { +export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, onError, onToast, runtimeTask, onChannel, onInstallRuntime, onCancelTask }) => { const [importing, setImporting] = useState(false) const [enabling, setEnabling] = useState(false) const [confirmDelete, setConfirmDelete] = useState('') @@ -191,11 +190,9 @@ export const HostView: React.FC = ({ state, locale, onRefresh, onNewVM, o diff --git a/frontend/src/components/RuntimeOnline.tsx b/frontend/src/components/RuntimeOnline.tsx index f338053..a98b95d 100644 --- a/frontend/src/components/RuntimeOnline.tsx +++ b/frontend/src/components/RuntimeOnline.tsx @@ -2,19 +2,17 @@ import { Download, LoaderCircle, Pause, RefreshCw } from 'lucide-react' import React, { useEffect, useState } from 'react' import { I18nKey, t } from '../i18n' import { taskDetail } from '../lib/tasks' -import { InstalledRuntime, Locale, RemoteRuntime, RuntimeSource, Task } from '../types' +import { InstalledRuntime, Locale, RemoteRuntime, Task } from '../types' import { Button, IconButton } from '../ui/controls' -import { Segmented, Switch } from '../ui/settings' +import { Switch } from '../ui/settings' import { api } from '../wails' interface Props { locale: Locale channel: 'stable' | 'alpha' - source: RuntimeSource installed: InstalledRuntime[] task: Task | null onChannel: (alpha: boolean) => void - onSource: (source: RuntimeSource) => void onInstall: (commit: string) => void onCancel: (taskId: string) => void } @@ -26,9 +24,9 @@ const shortQemu = (v: string) => v.replace(/^QEMU emulator version\s*/i, 'QEMU ' /** * The runtime rows: the active runtime and whether it is current (or, with - * none installed, the newest release to install), then download source and alpha switches. + * none installed, the newest release to install), then the alpha switch. */ -export const RuntimeOnline: React.FC = ({ locale, channel, source, installed, task, onChannel, onSource, onInstall, onCancel }) => { +export const RuntimeOnline: React.FC = ({ locale, channel, installed, task, onChannel, onInstall, onCancel }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const [remote, setRemote] = useState(null) const [error, setError] = useState('') @@ -42,7 +40,7 @@ export const RuntimeOnline: React.FC = ({ locale, channel, source, instal .then((list) => { if (live) setRemote(list ?? []) }) .catch((e) => { if (live) setError(String(e).replace(/^Error:\s*/, '')) }) return () => { live = false } - }, [channel, source, task?.status === 'done', reload]) + }, [channel, task?.status === 'done', reload]) const active = installed.find((i) => i.active) ?? installed[0] const latest = remote?.[0] @@ -79,12 +77,10 @@ export const RuntimeOnline: React.FC = ({ locale, channel, source, instal } else if (!latest) { sub =
{tr('runtimeNoneOnChannel')}
} else { - const srcLabel = latest.source === 'gitcode' ? 'GitCode' : latest.source === 'github' ? 'GitHub' : '' sub = (
{active ? tr('runtimeNewer', { v: latest.commit }) : tr('runtimeLatest', { v: latest.commit })} {' · '}{tr(`runtimeChannel_${latest.channel}` as I18nKey)} - {srcLabel ? ` · ${srcLabel}` : ''} {latest.archive_size > 0 ? ` · ${gb(latest.archive_size)}` : ''}
) @@ -115,23 +111,6 @@ export const RuntimeOnline: React.FC = ({ locale, channel, source, instal ) : null} -
-
-
{tr('runtimeSource')}
-
{tr('runtimeSourceHint')}
-
-
- ({ - value: s, - label: tr(`runtimeSource_${s}` as I18nKey), - }))} - /> -
-
{tr('runtimeAlpha')}
diff --git a/frontend/src/components/Setup.tsx b/frontend/src/components/Setup.tsx index 388b33c..29f7811 100644 --- a/frontend/src/components/Setup.tsx +++ b/frontend/src/components/Setup.tsx @@ -1,7 +1,7 @@ import { FolderOpen, HardDrive } from 'lucide-react' import React, { useEffect, useState } from 'react' import { getLocaleOptions, I18nKey, joinNotices, t } from '../i18n' -import { AppState, DataRootCheck, DataRootChoice, Locale, ResolvedLocalePack, RuntimeSource, Task } from '../types' +import { AppState, DataRootCheck, DataRootChoice, Locale, ResolvedLocalePack, Task } from '../types' import { Button } from '../ui/controls' import { PopupSelect } from '../ui/settings' import { gpuCompatHint, recommendedMemoryGB, shortGPUName } from '../lib/format' @@ -19,7 +19,6 @@ interface Props { onFinish: () => void onError: (title: string, e: unknown) => void onChannel: (alpha: boolean) => void - onSource: (source: RuntimeSource) => void onInstallRuntime: (commit: string) => void onCancelTask: (id: string) => void onImportRuntime: () => void @@ -155,7 +154,7 @@ const FolderStep: React.FC = ({ locale, locales, tr, onLocale, onFold ) } -const RuntimeStep: React.FC = ({ locale, tr, state, runtimeTask, onChannel, onSource, onInstallRuntime, onCancelTask, onImportRuntime, onFinish, onError }) => { +const RuntimeStep: React.FC = ({ locale, tr, state, runtimeTask, onChannel, onInstallRuntime, onCancelTask, onImportRuntime, onFinish, onError }) => { const ready = !!state.active_runtime const { host } = state const [enabling, setEnabling] = useState(false) @@ -235,11 +234,9 @@ const RuntimeStep: React.FC = ({ locale, tr, state, runtimeTask, onCh diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index 9ee3231..4c7e80e 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -303,13 +303,8 @@ const dict = { runtimeChannel_alpha: 'Alpha 版', runtimeChannel_stable: '稳定版', runtimeLookupFailed: '无法读取运行时列表', - runtimeLookupRateLimit: 'GitHub 接口限流(HTTP 403),可切换 GitCode 镜像、稍后重试或手动导入', + runtimeLookupRateLimit: 'GitHub 接口限流(HTTP 403),请稍后重试或手动导入', runtimeRetry: '重试', - runtimeSource: '下载源', - runtimeSourceHint: '自动模式优先 GitHub,连不上时自动切换 GitCode 国内镜像', - runtimeSource_auto: '自动', - runtimeSource_github: 'GitHub', - runtimeSource_gitcode: 'GitCode', // Toasts & dialogs toastStopped: '{name} 已关机', @@ -1096,13 +1091,8 @@ const dict = { runtimeChannel_alpha: 'Alpha', runtimeChannel_stable: 'Stable', runtimeLookupFailed: 'Couldn’t read the runtime list', - runtimeLookupRateLimit: 'GitHub API rate limit reached (HTTP 403); switch to GitCode mirror, retry later, or import a local bundle', + runtimeLookupRateLimit: 'GitHub API rate limit reached (HTTP 403); retry later or import a local bundle', runtimeRetry: 'Retry', - runtimeSource: 'Download source', - runtimeSourceHint: 'Auto tries GitHub first and falls back to the GitCode mirror if unreachable', - runtimeSource_auto: 'Auto', - runtimeSource_github: 'GitHub', - runtimeSource_gitcode: 'GitCode', toastStopped: '{name} shut down', toastEjected: 'Installer ejected', diff --git a/frontend/src/types.ts b/frontend/src/types.ts index fbb1aff..829bbb0 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -9,12 +9,9 @@ type Model = Omit export type BuiltinLocale = 'zh-CN' | 'en-US' export type Locale = BuiltinLocale | (string & {}) -export type RuntimeSource = 'auto' | 'github' | 'gitcode' - export type Config = Model & { locale: Locale runtime_channel?: 'stable' | 'alpha' | '' - runtime_source?: RuntimeSource | '' } export type DisplayInfo = host.DisplayInfo @@ -48,7 +45,6 @@ export type InstalledRuntime = Model export type RemoteRuntime = Model & { channel: 'stable' | 'alpha' - source?: 'github' | 'gitcode' } export type VMListItem = Model & { diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index 405f315..181dad2 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -193,8 +193,6 @@ export function SetPluginSettings(arg1:string,arg2:string,arg3:Record; -export function SetRuntimeSource(arg1:string):Promise; - export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise; export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 9ac5a7f..7385a11 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -370,10 +370,6 @@ export function SetRuntimeChannel(arg1) { return window['go']['app']['App']['SetRuntimeChannel'](arg1); } -export function SetRuntimeSource(arg1) { - return window['go']['app']['App']['SetRuntimeSource'](arg1); -} - export function SetVMAffinity(arg1, arg2) { return window['go']['app']['App']['SetVMAffinity'](arg1, arg2); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 69d26e4..c7e1ba0 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -433,7 +433,6 @@ export namespace config { auto_pin_pcores: boolean; default_gpu?: string; runtime_channel?: string; - runtime_source?: string; minimize_to_tray?: boolean; static createFrom(source: any = {}) { @@ -448,7 +447,6 @@ export namespace config { this.auto_pin_pcores = source["auto_pin_pcores"]; this.default_gpu = source["default_gpu"]; this.runtime_channel = source["runtime_channel"]; - this.runtime_source = source["runtime_source"]; this.minimize_to_tray = source["minimize_to_tray"]; } } @@ -2095,7 +2093,6 @@ export namespace runtime { commit: string; tag: string; channel: string; - source?: string; published_at: string; page_url: string; archive_name: string; @@ -2114,7 +2111,6 @@ export namespace runtime { this.commit = source["commit"]; this.tag = source["tag"]; this.channel = source["channel"]; - this.source = source["source"]; this.published_at = source["published_at"]; this.page_url = source["page_url"]; this.archive_name = source["archive_name"]; diff --git a/internal/app/runtime_bindings.go b/internal/app/runtime_bindings.go index f98265f..c9b18eb 100644 --- a/internal/app/runtime_bindings.go +++ b/internal/app/runtime_bindings.go @@ -32,43 +32,35 @@ func (a *App) includeAlpha() bool { return rt.NormalizeChannel(a.cfg.RuntimeChannel) == rt.ChannelAlpha } -func (a *App) runtimeSource() string { - a.mu.Lock() - defer a.mu.Unlock() - return rt.NormalizeSource(a.cfg.RuntimeSource) -} - // remoteCache keeps the release list for a while: GitHub allows 60 // unauthenticated API requests an hour, and the host page, first launch and // the CLI all ask for it. var remoteCache struct { sync.Mutex - at time.Time - alpha bool - source string - list []rt.Remote + at time.Time + alpha bool + list []rt.Remote } const remoteCacheTTL = 10 * time.Minute -// ListRemoteRuntimes lists published runtimes for the configured channel and source. +// ListRemoteRuntimes lists published runtimes for the configured channel. func (a *App) ListRemoteRuntimes() ([]rt.Remote, error) { alpha := a.includeAlpha() - source := a.runtimeSource() remoteCache.Lock() defer remoteCache.Unlock() - if remoteCache.list != nil && remoteCache.alpha == alpha && remoteCache.source == source && time.Since(remoteCache.at) < remoteCacheTTL { + if remoteCache.list != nil && remoteCache.alpha == alpha && time.Since(remoteCache.at) < remoteCacheTTL { return remoteCache.list, nil } - list, err := rt.DefaultSourceFor(source).ListRemote(a.baseCtx(), alpha) + list, err := rt.DefaultSource().ListRemote(a.baseCtx(), alpha) if err != nil { return nil, err } - remoteCache.at, remoteCache.alpha, remoteCache.source, remoteCache.list = time.Now(), alpha, source, list + remoteCache.at, remoteCache.alpha, remoteCache.list = time.Now(), alpha, list return list, nil } -// forgetRemoteRuntimes drops the cached list (after an install or a channel/source change). +// forgetRemoteRuntimes drops the cached list (after an install or a channel change). func forgetRemoteRuntimes() { remoteCache.Lock() remoteCache.list = nil @@ -91,25 +83,6 @@ func (a *App) SetRuntimeChannel(channel string) error { return config.Save("", a.cfg) } -// SetRuntimeSource picks "auto", "github", or "gitcode" for online runtime and -// app update lookups. -func (a *App) SetRuntimeSource(source string) error { - switch strings.ToLower(strings.TrimSpace(source)) { - case "", rt.SourceAuto, rt.SourceGitHub, rt.SourceGitCode: - source = rt.NormalizeSource(source) - default: - return fmt.Errorf("unknown runtime source %q", source) - } - a.mu.Lock() - defer a.mu.Unlock() - a.cfg.RuntimeSource = source - forgetRemoteRuntimes() - appUpdateCache.Lock() - appUpdateCache.info = nil - appUpdateCache.Unlock() - return config.Save("", a.cfg) -} - // InstallRuntimeOnline downloads, verifies and installs a published runtime // ("" or "latest" for the newest on the channel) and makes it active. It runs // in the background and returns the task ID; CancelTask pauses the download, @@ -156,7 +129,7 @@ func (a *App) InstallRuntimeOnline(commit string) (string, error) { } func (a *App) installRuntime(ctx context.Context, cfg *config.Config, commit, taskID string) (string, error) { - src := rt.DefaultSourceFor(cfg.RuntimeSource) + src := rt.DefaultSource() step := func(msg string) { a.emitLog("runtime", msg) tasks.update(taskID, installer.Update{Kind: installer.KindStep, Message: msg, Percent: -1}) @@ -220,13 +193,12 @@ var appUpdateCache struct { // CheckAppUpdate checks GitHub Releases for a newer stable Reims-Go version. // Results are cached for 10 minutes unless force is true. func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) { - source := a.runtimeSource() appUpdateCache.Lock() defer appUpdateCache.Unlock() if !force && appUpdateCache.info != nil && time.Since(appUpdateCache.at) < remoteCacheTTL { return *appUpdateCache.info, nil } - info, err := version.DefaultSourceFor(source).CheckUpdate(a.baseCtx(), version.Version) + info, err := version.DefaultSource().CheckUpdate(a.baseCtx(), version.Version) if err != nil { return info, err } diff --git a/internal/cli/runtime_fetch.go b/internal/cli/runtime_fetch.go index 9b79d2e..e6634a9 100644 --- a/internal/cli/runtime_fetch.go +++ b/internal/cli/runtime_fetch.go @@ -14,15 +14,14 @@ import ( rt "github.com/Nwflower/reims-go/internal/runtime" ) -// runtime available [--alpha] [--source auto|github|gitcode]: published runtimes. +// runtime available [--alpha]: published runtimes. func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) error { fs := flag.NewFlagSet("runtime available", flag.ContinueOnError) alpha := alphaFlag(fs, cfg, "Include alpha runtimes") - source := fs.String("source", rt.NormalizeSource(cfg.RuntimeSource), "Download source: auto, github, or gitcode") if err := fs.Parse(flagsFirst(args)); err != nil { return err } - list, err := rt.DefaultSourceFor(*source).ListRemote(context.Background(), *alpha) + list, err := rt.DefaultSource().ListRemote(context.Background(), *alpha) if err != nil { return err } @@ -30,7 +29,7 @@ func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) err fmt.Println(i18n.T(loc, "runtime.remote.empty")) return nil } - fmt.Printf("%-12s %-10s %-8s %-11s %9s %s\n", "COMMIT", "CHANNEL", "SOURCE", "PUBLISHED", "SIZE", "INSTALLED") + fmt.Printf("%-12s %-10s %-11s %9s %s\n", "COMMIT", "CHANNEL", "PUBLISHED", "SIZE", "INSTALLED") for _, r := range list { mark := "" if rt.IsInstalled(cfg, r.Commit) { @@ -40,16 +39,15 @@ func cmdRuntimeAvailable(cfg *config.Config, loc i18n.Locale, args []string) err if len(date) >= 10 { date = date[:10] } - fmt.Printf("%-12s %-10s %-8s %-11s %9s %s\n", r.Commit, r.Channel, r.Source, date, humanBytes(r.ArchiveSize), mark) + fmt.Printf("%-12s %-10s %-11s %9s %s\n", r.Commit, r.Channel, date, humanBytes(r.ArchiveSize), mark) } return nil } -// runtime fetch [commit|latest] [--alpha] [--source auto|github|gitcode]: download, verify, install, activate. +// runtime fetch [commit|latest] [--alpha]: download, verify, install, activate. func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error { fs := flag.NewFlagSet("runtime fetch", flag.ContinueOnError) alpha := alphaFlag(fs, cfg, "Allow alpha runtimes for \"latest\"") - source := fs.String("source", rt.NormalizeSource(cfg.RuntimeSource), "Download source: auto, github, or gitcode") if err := fs.Parse(flagsFirst(args)); err != nil { return err } @@ -58,7 +56,7 @@ func cmdRuntimeFetch(cfg *config.Config, loc i18n.Locale, args []string) error { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() - src := rt.DefaultSourceFor(*source) + src := rt.DefaultSource() list, err := src.ListRemote(ctx, *alpha || explicit) if err != nil { return err @@ -108,20 +106,14 @@ func alphaFlag(fs *flag.FlagSet, cfg *config.Config, usage string) *bool { return v } -// flagsFirst moves "-x" arguments (and their values for value flags like -// --source) before positional ones, so "fetch latest --source gitcode --alpha" -// works like "fetch --source gitcode --alpha latest" (the flag package stops -// at the first positional argument). +// flagsFirst moves "-x" arguments before positional ones, so +// "fetch latest --alpha" works like "fetch --alpha latest" (the flag package +// stops at the first positional argument). func flagsFirst(args []string) []string { var flags, rest []string - for i := 0; i < len(args); i++ { - a := args[i] + for _, a := range args { if len(a) > 1 && a[0] == '-' { flags = append(flags, a) - if (a == "-source" || a == "--source") && i+1 < len(args) { - i++ - flags = append(flags, args[i]) - } } else { rest = append(rest, a) } diff --git a/internal/config/config.go b/internal/config/config.go index 3034647..0a68667 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -20,10 +20,6 @@ type Config struct { // whether online install offers alpha runtimes (portable-runtime-spec.md §6). // "candidate", the name used before 2026-11-28, is read as "alpha". RuntimeChannel string `json:"runtime_channel,omitempty"` - // RuntimeSource chooses where online runtimes and app updates are fetched: - // "auto" (default, also when empty: try GitHub first, fall back to GitCode), - // "github", or "gitcode". - RuntimeSource string `json:"runtime_source,omitempty"` // MinimizeToTray keeps Reims-Go running in the Windows system tray when the // main window is closed so Guest Tools bridges stay alive. Defaults to true. MinimizeToTray *bool `json:"minimize_to_tray,omitempty"` diff --git a/internal/runtime/remote.go b/internal/runtime/remote.go index 1713ba9..144004e 100644 --- a/internal/runtime/remote.go +++ b/internal/runtime/remote.go @@ -34,35 +34,13 @@ import ( ) const ( - DefaultReleasesRepo = "Nwflower/reims-go" - DefaultAPIBase = "https://api.github.com" - DefaultWebBase = "https://github.com" - DefaultGitCodeRepo = "Nwflower/Reims-Go" - DefaultGitCodeAPIBase = "https://api.gitcode.com/api/v5" - DefaultGitCodeWebBase = "https://gitcode.com" - runtimeTagPrefix = "runtime-" - sumsAsset = fetch.SumsAsset + DefaultReleasesRepo = "Nwflower/reims-go" + DefaultAPIBase = "https://api.github.com" + DefaultWebBase = "https://github.com" + runtimeTagPrefix = "runtime-" + sumsAsset = fetch.SumsAsset ) -const ( - SourceAuto = "auto" - SourceGitHub = "github" - SourceGitCode = "gitcode" -) - -// NormalizeSource maps a stored or user-given source name to SourceAuto, -// SourceGitHub, or SourceGitCode. Empty or unknown values default to SourceAuto. -func NormalizeSource(s string) string { - switch strings.ToLower(strings.TrimSpace(s)) { - case SourceGitHub: - return SourceGitHub - case SourceGitCode: - return SourceGitCode - default: - return SourceAuto - } -} - var errRateLimited = errors.New("GitHub API rate limit reached") const ( @@ -89,72 +67,26 @@ func NormalizeChannel(s string) string { // app releases and (until pruned) daily alpha runtimes. const maxReleasePages = 10 -// fallbackProbeTimeout bounds how long a primary source query may block when a -// mirror fallback is configured, so unreachable hosts fail over quickly. -const fallbackProbeTimeout = 8 * time.Second - -// Source is where runtime releases are listed. REIMS_GO_RELEASES_REPO and -// REIMS_GO_GITCODE_REPO override the repositories (for forks and testing). +// Source is where runtime releases are listed. REIMS_GO_RELEASES_REPO overrides +// the repository (for forks and testing). type Source struct { - Provider string - APIBase string - WebBase string - Repo string - Client *http.Client - Fallbacks []Source + APIBase string + WebBase string + Repo string + Client *http.Client } -func githubSource(client *http.Client) Source { +// DefaultSource returns the default GitHub runtime source. +func DefaultSource() Source { repo := os.Getenv("REIMS_GO_RELEASES_REPO") if repo == "" { repo = DefaultReleasesRepo } return Source{ - Provider: SourceGitHub, - APIBase: DefaultAPIBase, - WebBase: DefaultWebBase, - Repo: repo, - Client: client, - } -} - -func gitcodeSource(client *http.Client) Source { - repo := os.Getenv("REIMS_GO_GITCODE_REPO") - if repo == "" { - repo = DefaultGitCodeRepo - } - return Source{ - Provider: SourceGitCode, - APIBase: DefaultGitCodeAPIBase, - WebBase: DefaultGitCodeWebBase, - Repo: repo, - Client: client, - } -} - -// DefaultSource returns the default runtime source (SourceAuto unless -// REIMS_GO_SOURCE overrides it). -func DefaultSource() Source { - return DefaultSourceFor("") -} - -// DefaultSourceFor returns a Source configured for mode ("auto", "github", or -// "gitcode"). When mode is empty, REIMS_GO_SOURCE is consulted before falling -// back to "auto" (GitHub primary, GitCode fallback). -func DefaultSourceFor(mode string) Source { - if strings.TrimSpace(mode) == "" { - mode = os.Getenv("REIMS_GO_SOURCE") - } - client := netproxy.NewClient() - switch NormalizeSource(mode) { - case SourceGitHub: - return githubSource(client) - case SourceGitCode: - return gitcodeSource(client) - default: - gh := githubSource(client) - gh.Fallbacks = []Source{gitcodeSource(client)} - return gh + APIBase: DefaultAPIBase, + WebBase: DefaultWebBase, + Repo: repo, + Client: netproxy.NewClient(), } } @@ -163,7 +95,6 @@ type Remote struct { Commit string `json:"commit"` Tag string `json:"tag"` Channel string `json:"channel"` - Source string `json:"source,omitempty"` PublishedAt string `json:"published_at"` PageURL string `json:"page_url"` ArchiveName string `json:"archive_name"` @@ -186,9 +117,7 @@ type ghRelease struct { } // isAlphaRelease treats either an explicit prerelease flag or an "(alpha)" / -// "(candidate)" marker in the release title as alpha. GitCode API v5 currently -// returns prerelease=false even when created with prerelease=true, while -// preserving the mirrored GitHub release title. +// "(candidate)" marker in the release title as alpha. func isAlphaRelease(prerelease bool, name string) bool { if prerelease { return true @@ -214,16 +143,6 @@ func newRequest(ctx context.Context, url string) (*http.Request, error) { return fetch.NewRequest(ctx, url) } -func (s Source) providerName() string { - if s.Provider != "" { - return s.Provider - } - if strings.Contains(strings.ToLower(s.APIBase), "gitcode.com") { - return SourceGitCode - } - return SourceGitHub -} - func (s Source) webBase() string { if s.WebBase != "" { return strings.TrimRight(s.WebBase, "/") @@ -231,49 +150,19 @@ func (s Source) webBase() string { if strings.TrimRight(s.APIBase, "/") == DefaultAPIBase { return DefaultWebBase } - if strings.TrimRight(s.APIBase, "/") == DefaultGitCodeAPIBase { - return DefaultGitCodeWebBase - } return "" } // ListRemote lists published runtime packages, newest first. Alpha runtimes -// are included only when includeAlpha is set. When Fallbacks are configured, -// a failing primary source automatically fails over to the next mirror. +// are included only when includeAlpha is set. func (s Source) ListRemote(ctx context.Context, includeAlpha bool) ([]Remote, error) { - primaryCtx := ctx - var cancel context.CancelFunc - if len(s.Fallbacks) > 0 { - primaryCtx, cancel = context.WithTimeout(ctx, fallbackProbeTimeout) - defer cancel() - } - out, err := s.listRemoteSingle(primaryCtx, includeAlpha) - if err == nil { - return out, nil - } - if ctx.Err() != nil || len(s.Fallbacks) == 0 { - return nil, err - } - var lastErr error - for _, fb := range s.Fallbacks { - fbOut, fbErr := fb.listRemoteSingle(ctx, includeAlpha) - if fbErr == nil { - return fbOut, nil - } - lastErr = fbErr - } - return nil, fmt.Errorf("%w (mirror fallback failed: %v)", err, lastErr) -} - -func (s Source) listRemoteSingle(ctx context.Context, includeAlpha bool) ([]Remote, error) { base := strings.TrimRight(s.APIBase, "/") url := fmt.Sprintf("%s/repos/%s/releases?per_page=100", base, s.Repo) - provider := s.providerName() var rels []ghRelease for page := 0; url != "" && page < maxReleasePages; page++ { batch, next, err := s.releasesPage(ctx, url) if err != nil { - if errors.Is(err, errRateLimited) && provider == SourceGitHub && s.webBase() != "" { + if errors.Is(err, errRateLimited) && s.webBase() != "" { if fb, ferr := s.listRemoteWeb(ctx, includeAlpha); ferr == nil { return fb, nil } @@ -304,7 +193,6 @@ func (s Source) listRemoteSingle(ctx context.Context, includeAlpha bool) ([]Remo rem := Remote{ Commit: commit, Tag: r.TagName, - Source: provider, PublishedAt: pub, PageURL: pageURL, Channel: ChannelStable, @@ -445,7 +333,6 @@ func (s Source) listRemoteWeb(ctx context.Context, includeAlpha bool) ([]Remote, Commit: commit, Tag: tag, Channel: channel, - Source: SourceGitHub, PublishedAt: e.Updated, PageURL: pageURL, } diff --git a/internal/runtime/remote_test.go b/internal/runtime/remote_test.go index 4154d8e..922fd74 100644 --- a/internal/runtime/remote_test.go +++ b/internal/runtime/remote_test.go @@ -296,61 +296,3 @@ func TestListRemoteFallsBackToWebOnRateLimit(t *testing.T) { t.Fatalf("all fallback = %+v", all) } } - -func TestListRemoteAutoFallsBackToGitCode(t *testing.T) { - badPrimary := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Error(w, "gateway down", http.StatusBadGateway) - })) - defer badPrimary.Close() - - var gcSrv *httptest.Server - gcSrv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/api/v5/repos/o/r/releases" { - http.NotFound(w, r) - return - } - // Matches real GitCode API v5 shape: created_at (+08:00), no published_at or html_url, - // and prerelease=false even on mirrored alpha prereleases whose title carries "(alpha)". - fmt.Fprintf(w, `[ - {"tag_name":"runtime-3731afd-p2","name":"Portable Runtime runtime-3731afd-p2 (alpha)","prerelease":false,"created_at":"2026-11-29T17:39:03+08:00","assets":[ - {"name":"reims-runtime-win-x64-3731afd-p2.tar.zst","size":169000000,"browser_download_url":"%s/dl/rt-p2"}, - {"name":"reims-runtime-src-3731afd-p2.tar.zst","size":500,"browser_download_url":"%s/dl/src-p2"}, - {"name":"SHA256SUMS.txt","size":100,"browser_download_url":"%s/dl/sums-p2"} - ]}, - {"tag_name":"runtime-3731afd","name":"Runtime 3731afd","prerelease":false,"created_at":"2026-11-28T19:03:04+08:00","assets":[ - {"name":"reims-runtime-win-x64-3731afd.tar.zst","size":168000000,"browser_download_url":"%s/dl/rt"}, - {"name":"reims-runtime-src-3731afd.tar.zst","size":500,"browser_download_url":"%s/dl/src"}, - {"name":"SHA256SUMS.txt","size":100,"browser_download_url":"%s/dl/sums"} - ]} -]`, gcSrv.URL, gcSrv.URL, gcSrv.URL, gcSrv.URL, gcSrv.URL, gcSrv.URL) - })) - defer gcSrv.Close() - - src := Source{ - Provider: SourceGitHub, - APIBase: badPrimary.URL, - Repo: "o/r", - Client: badPrimary.Client(), - Fallbacks: []Source{{ - Provider: SourceGitCode, - APIBase: gcSrv.URL + "/api/v5", - WebBase: "https://gitcode.com", - Repo: "o/r", - Client: gcSrv.Client(), - }}, - } - list, err := src.ListRemote(context.Background(), false) - if err != nil { - t.Fatal(err) - } - if len(list) != 1 || list[0].Commit != "3731afd" || list[0].Channel != ChannelStable || list[0].Source != SourceGitCode || list[0].PageURL != "https://gitcode.com/o/r/releases/tag/runtime-3731afd" { - t.Fatalf("gitcode fallback stable = %+v", list) - } - all, err := src.ListRemote(context.Background(), true) - if err != nil { - t.Fatal(err) - } - if len(all) != 2 || all[0].Commit != "3731afd-p2" || all[0].Channel != ChannelAlpha { - t.Fatalf("gitcode fallback with alpha = %+v", all) - } -} diff --git a/internal/version/version.go b/internal/version/version.go index a38b177..8d8123a 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -8,7 +8,6 @@ import ( "os" "strconv" "strings" - "time" "github.com/Nwflower/reims-go/internal/netproxy" ) @@ -20,26 +19,20 @@ import ( var Version = "v0.2.8" const ( - DefaultReleasesRepo = "Nwflower/Reims-Go" - DefaultAPIBase = "https://api.github.com" - DefaultWebBase = "https://github.com" - DefaultGitCodeRepo = "Nwflower/Reims-Go" - DefaultGitCodeAPIBase = "https://api.gitcode.com/api/v5" - DefaultGitCodeWebBase = "https://gitcode.com" + DefaultReleasesRepo = "Nwflower/Reims-Go" + DefaultAPIBase = "https://api.github.com" + DefaultWebBase = "https://github.com" ) -const fallbackProbeTimeout = 8 * time.Second - // Source configures where app releases are checked. type Source struct { - APIBase string - WebBase string - Repo string - Client *http.Client - Fallbacks []Source + APIBase string + WebBase string + Repo string + Client *http.Client } -func githubSource(client *http.Client) Source { +func DefaultSource() Source { repo := os.Getenv("REIMS_GO_RELEASES_REPO") if repo == "" { repo = DefaultReleasesRepo @@ -48,41 +41,7 @@ func githubSource(client *http.Client) Source { APIBase: DefaultAPIBase, WebBase: DefaultWebBase, Repo: repo, - Client: client, - } -} - -func gitcodeSource(client *http.Client) Source { - repo := os.Getenv("REIMS_GO_GITCODE_REPO") - if repo == "" { - repo = DefaultGitCodeRepo - } - return Source{ - APIBase: DefaultGitCodeAPIBase, - WebBase: DefaultGitCodeWebBase, - Repo: repo, - Client: client, - } -} - -func DefaultSource() Source { - return DefaultSourceFor("") -} - -func DefaultSourceFor(mode string) Source { - if strings.TrimSpace(mode) == "" { - mode = os.Getenv("REIMS_GO_SOURCE") - } - client := netproxy.NewClient() - switch strings.ToLower(strings.TrimSpace(mode)) { - case "github": - return githubSource(client) - case "gitcode": - return gitcodeSource(client) - default: - gh := githubSource(client) - gh.Fallbacks = []Source{gitcodeSource(client)} - return gh + Client: netproxy.NewClient(), } } @@ -175,32 +134,9 @@ func Compare(a, b string) int { return 0 } -// CheckUpdate queries GitHub/GitCode Releases for the newest stable (non-draft, -// non-prerelease) application release tagged "vX.Y.Z", failing over to -// Fallbacks when the primary source is unreachable. +// CheckUpdate queries GitHub Releases for the newest stable (non-draft, +// non-prerelease) application release tagged "vX.Y.Z". func (s Source) CheckUpdate(ctx context.Context, current string) (UpdateInfo, error) { - primaryCtx := ctx - var cancel context.CancelFunc - if len(s.Fallbacks) > 0 { - primaryCtx, cancel = context.WithTimeout(ctx, fallbackProbeTimeout) - defer cancel() - } - info, err := s.checkUpdateSingle(primaryCtx, current) - if err == nil { - return info, nil - } - if ctx.Err() != nil || len(s.Fallbacks) == 0 { - return info, err - } - for _, fb := range s.Fallbacks { - if fbInfo, fbErr := fb.checkUpdateSingle(ctx, current); fbErr == nil { - return fbInfo, nil - } - } - return info, err -} - -func (s Source) checkUpdateSingle(ctx context.Context, current string) (UpdateInfo, error) { if current == "" { current = Version } diff --git a/scripts/sync-gitcode-release.py b/scripts/sync-gitcode-release.py deleted file mode 100644 index db5abd0..0000000 --- a/scripts/sync-gitcode-release.py +++ /dev/null @@ -1,201 +0,0 @@ -#!/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()