feat(update): 实现多镜像源自更新机制 (update/upgrade) 并升级版本至 v0.2.1
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
🚀 Release / 🚀 Build & Publish Multi-Platform Binaries (push) Has been cancelled
This commit is contained in:
1 parent
6e73de697b
commit
2dfcf67b00
12 files changed
+1021
-9
No files matched your search
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { compareSemVer, isNewerVersion, matchAssetForPlatform, type GitHubAsset } from "./update.js";
|
||||
|
||||
describe("update version comparator", () => {
|
||||
test("correctly identifies newer semantic versions", () => {
|
||||
expect(isNewerVersion("0.2.1", "0.2.0")).toBe(true);
|
||||
expect(isNewerVersion("1.0.0", "0.2.0")).toBe(true);
|
||||
expect(isNewerVersion("0.3.0", "0.2.1")).toBe(true);
|
||||
expect(isNewerVersion("0.2.0", "0.2.0")).toBe(false);
|
||||
expect(isNewerVersion("0.1.9", "0.2.0")).toBe(false);
|
||||
expect(isNewerVersion("0.2.0", "0.2.1")).toBe(false);
|
||||
});
|
||||
|
||||
test("compareSemVer handles tags, major, minor, and patch", () => {
|
||||
expect(compareSemVer("v0.2.1", "0.2.0")).toBe(1);
|
||||
expect(compareSemVer("0.2.0", "v0.2.1")).toBe(-1);
|
||||
expect(compareSemVer("v0.2.1", "v0.2.1")).toBe(0);
|
||||
expect(compareSemVer("1.0.0", "0.9.9")).toBe(1);
|
||||
expect(compareSemVer("0.1.0", "0.2.1")).toBe(-1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("matchAssetForPlatform", () => {
|
||||
const assets: GitHubAsset[] = [
|
||||
{ name: "hose-use-darwin-arm64", downloadUrl: "https://example.com/darwin-arm64", size: 100 },
|
||||
{ name: "hose-use-darwin-x64", downloadUrl: "https://example.com/darwin-x64", size: 100 },
|
||||
{ name: "hose-use-linux-x64.tar.gz", downloadUrl: "https://example.com/linux-x64.tar.gz", size: 100 },
|
||||
{ name: "hose-use-linux-arm64", downloadUrl: "https://example.com/linux-arm64", size: 100 },
|
||||
{ name: "hose-use-windows-x64.zip", downloadUrl: "https://example.com/win-x64.zip", size: 100 },
|
||||
];
|
||||
|
||||
test("matches darwin arm64", () => {
|
||||
const matched = matchAssetForPlatform(assets, "darwin", "arm64");
|
||||
expect(matched?.name).toBe("hose-use-darwin-arm64");
|
||||
});
|
||||
|
||||
test("matches darwin x64", () => {
|
||||
const matched = matchAssetForPlatform(assets, "darwin", "x64");
|
||||
expect(matched?.name).toBe("hose-use-darwin-x64");
|
||||
});
|
||||
|
||||
test("matches linux x64 archive", () => {
|
||||
const matched = matchAssetForPlatform(assets, "linux", "x64");
|
||||
expect(matched?.name).toBe("hose-use-linux-x64.tar.gz");
|
||||
});
|
||||
|
||||
test("matches windows x64 archive", () => {
|
||||
const matched = matchAssetForPlatform(assets, "windows", "x64");
|
||||
expect(matched?.name).toBe("hose-use-windows-x64.zip");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,812 @@
|
||||
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { isCompiledBinary, resolveAppRoot } from "../../core/runtime.js";
|
||||
import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, printKeyValue } from "../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRunOptions, CliRuntime } from "../types.js";
|
||||
|
||||
const DEFAULT_GITHUB_REPO = "yunyingk/hose-use";
|
||||
const GITHUB_REPO_ENV = "HOSE_USE_GITHUB_REPO";
|
||||
|
||||
export type UpdateOptions = {
|
||||
checkOnly?: boolean;
|
||||
changelogOnly?: boolean;
|
||||
limit?: number;
|
||||
force?: boolean;
|
||||
targetVersion?: string;
|
||||
repo?: string;
|
||||
};
|
||||
|
||||
export async function handleUpdateCommand(
|
||||
parsed: CliParsedArgs,
|
||||
runtime: CliRuntime,
|
||||
runOptions: CliRunOptions = {}
|
||||
): Promise<CliResult> {
|
||||
const isChangelog =
|
||||
parsed.area === "changelog" ||
|
||||
parsed.action === "changelog" ||
|
||||
parsed.action === "log" ||
|
||||
parsed.action === "history" ||
|
||||
booleanOption(parsed.options, ["changelog", "log", "l"]);
|
||||
|
||||
const isCheck =
|
||||
parsed.action === "check" ||
|
||||
booleanOption(parsed.options, ["check", "check-only", "c"]);
|
||||
|
||||
const targetVersionRaw =
|
||||
stringOption(parsed.options, ["version", "tag", "target", "t"]) ||
|
||||
(!isChangelog && !isCheck && parsed.action && !parsed.action.startsWith("-")
|
||||
? parsed.action
|
||||
: undefined);
|
||||
|
||||
const targetVersion =
|
||||
targetVersionRaw && targetVersionRaw.toLowerCase() !== "latest"
|
||||
? targetVersionRaw.replace(/^v/, "")
|
||||
: undefined;
|
||||
|
||||
const repo =
|
||||
stringOption(parsed.options, ["repo"]) ||
|
||||
process.env[GITHUB_REPO_ENV]?.trim() ||
|
||||
DEFAULT_GITHUB_REPO;
|
||||
|
||||
const options: UpdateOptions = {
|
||||
checkOnly: isCheck,
|
||||
changelogOnly: isChangelog,
|
||||
limit: numberOption(parsed.options, ["limit", "n"]),
|
||||
force: booleanOption(parsed.options, ["force", "f"]),
|
||||
targetVersion,
|
||||
repo,
|
||||
};
|
||||
|
||||
const appRoot = runOptions.appRoot || resolveAppRoot(runOptions.entryFile);
|
||||
|
||||
// Validate targetVersion: prevent downgrade to older versions
|
||||
if (targetVersion) {
|
||||
const cmp = compareSemVer(targetVersion, VERSION);
|
||||
if (cmp < 0 && !options.force) {
|
||||
const msg = `无法降级 hose-use(当前版本 v${VERSION},目标版本 v${targetVersion})。如需强制重装请使用 --force。`;
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
updated: false,
|
||||
currentVersion: VERSION,
|
||||
targetVersion,
|
||||
mode: isCompiledBinary() ? "binary" : "source",
|
||||
message: msg,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] ${msg}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
if (cmp === 0 && !options.force) {
|
||||
const msg = `hose-use 当前已是版本 v${VERSION}。如需强制重装请添加 --force。`;
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
updated: false,
|
||||
currentVersion: VERSION,
|
||||
targetVersion,
|
||||
mode: isCompiledBinary() ? "binary" : "source",
|
||||
message: msg,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: `ℹ️ ${msg}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Changelog / Release History query
|
||||
if (options.changelogOnly) {
|
||||
const releases = await fetchGitHubReleases(repo, options.limit ?? 10);
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
currentVersion: VERSION,
|
||||
totalQueried: releases.length,
|
||||
releases: releases.map((r) => ({
|
||||
version: r.version,
|
||||
tagName: r.tagName,
|
||||
publishedAt: r.publishedAt,
|
||||
author: r.author,
|
||||
releaseNotes: r.notes,
|
||||
releaseUrl: r.htmlUrl,
|
||||
isCurrent: r.version === VERSION,
|
||||
isNewer: isNewerVersion(r.version, VERSION),
|
||||
})),
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const lines: string[] = [
|
||||
`====== hose-use 版本发布记录 (当前版本: v${VERSION}) ======`,
|
||||
"",
|
||||
];
|
||||
for (const r of releases) {
|
||||
const badge = r.version === VERSION ? " [当前版本]" : isNewerVersion(r.version, VERSION) ? " [新版本 ✨]" : "";
|
||||
lines.push(`• v${r.version} (${r.publishedAt ? r.publishedAt.slice(0, 10) : "未知日期"})${badge}`);
|
||||
if (r.notes) {
|
||||
const snippet = r.notes.trim().split("\n").map((l) => ` ${l}`).join("\n");
|
||||
lines.push(snippet);
|
||||
}
|
||||
lines.push("");
|
||||
}
|
||||
return {
|
||||
stdout: lines.join("\n"),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 2. Source development mode (running via bun/node)
|
||||
if (!isCompiledBinary()) {
|
||||
if (options.checkOnly) {
|
||||
const releases = await fetchGitHubReleases(repo, 30);
|
||||
const latestRelease = releases[0];
|
||||
const latestVersion = latestRelease?.version ?? VERSION;
|
||||
const currentRelease = releases.find((r) => r.version === VERSION);
|
||||
const isUpgrade = isNewerVersion(latestVersion, VERSION);
|
||||
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
updated: false,
|
||||
updateAvailable: isUpgrade,
|
||||
currentVersion: VERSION,
|
||||
currentVersionPublishedAt: currentRelease?.publishedAt,
|
||||
latestVersion,
|
||||
latestVersionPublishedAt: latestRelease?.publishedAt,
|
||||
behindCount: pendingReleases.length,
|
||||
pendingReleases: pendingReleases.map((r) => ({
|
||||
version: r.version,
|
||||
tagName: r.tagName,
|
||||
publishedAt: r.publishedAt,
|
||||
author: r.author,
|
||||
releaseNotes: r.notes,
|
||||
releaseUrl: r.htmlUrl,
|
||||
})),
|
||||
releaseNotes: latestRelease?.notes ?? "",
|
||||
releaseUrl: latestRelease?.htmlUrl ?? "",
|
||||
mode: "source",
|
||||
message: "当前运行于源码开发模式。运行 'hose-use update' 执行 git pull 与依赖更新。",
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const out = printKeyValue({
|
||||
"运行模式": "源码开发模式 (Source Mode)",
|
||||
"当前版本": `v${VERSION}`,
|
||||
"最新版本": `v${latestVersion} ${isUpgrade ? "(可升级 ✨)" : "(已是最新 ✅)"}`,
|
||||
"待更新版本数": pendingReleases.length,
|
||||
"源码路径": appRoot,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== hose-use 版本检查 ======\n${out}\n\n${isUpgrade ? `可运行 hose-use update 执行 git pull 与依赖同步` : "已经是最新版本"}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
runCommand("git", ["-C", appRoot, "pull", "--ff-only"]);
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
console.error(`git pull 提示: ${msg}`);
|
||||
}
|
||||
|
||||
runCommand("bun", ["install"], { cwd: appRoot });
|
||||
const skillSync = syncGlobalSkillIfPresent();
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
updated: true,
|
||||
version: VERSION,
|
||||
mode: "source",
|
||||
skillSynced: skillSync.synced ? skillSync.targetDir : false,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] hose-use 源码与依赖更新成功!\n版本: v${VERSION}\n技能同步: ${skillSync.synced ? "已同步至全局 ✅" : "未同步"}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// 3. Standalone binary mode: check GitHub Releases
|
||||
const platform = detectPlatform();
|
||||
const arch = detectArch();
|
||||
|
||||
const releases = await fetchGitHubReleases(repo, 30);
|
||||
const release = targetVersion
|
||||
? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ??
|
||||
await fetchGitHubRelease(repo, targetVersion))
|
||||
: (releases[0] ?? await fetchGitHubRelease(repo));
|
||||
|
||||
if (!release) {
|
||||
const errorMsg = `无法从 GitHub 仓库 '${repo}' 获取 Release 列表`;
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
updated: false,
|
||||
currentVersion: VERSION,
|
||||
mode: "binary",
|
||||
message: errorMsg,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] ${errorMsg}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const latestVersion = release.version;
|
||||
const currentRelease = releases.find((r) => r.version === VERSION);
|
||||
const isUpgrade = isNewerVersion(latestVersion, VERSION);
|
||||
const shouldUpdate = isUpgrade || Boolean(options.force);
|
||||
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
|
||||
|
||||
if (options.checkOnly) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
updated: false,
|
||||
updateAvailable: isUpgrade,
|
||||
currentVersion: VERSION,
|
||||
currentVersionPublishedAt: currentRelease?.publishedAt,
|
||||
latestVersion,
|
||||
latestVersionPublishedAt: release.publishedAt,
|
||||
behindCount: pendingReleases.length,
|
||||
pendingReleases: pendingReleases.map((r) => ({
|
||||
version: r.version,
|
||||
tagName: r.tagName,
|
||||
publishedAt: r.publishedAt,
|
||||
author: r.author,
|
||||
releaseNotes: r.notes,
|
||||
releaseUrl: r.htmlUrl,
|
||||
})),
|
||||
releaseNotes: release.notes,
|
||||
releaseUrl: release.htmlUrl,
|
||||
mode: "binary",
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const out = printKeyValue({
|
||||
"运行模式": "独立二进制 (Binary Mode)",
|
||||
"当前版本": `v${VERSION}`,
|
||||
"最新版本": `v${latestVersion} ${isUpgrade ? "(可升级 ✨)" : "(已是最新 ✅)"}`,
|
||||
"发布时间": release.publishedAt ? release.publishedAt.slice(0, 10) : "未知",
|
||||
"平台架构": `${platform}-${arch}`,
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: `====== hose-use 版本检查 ======\n${out}\n\n${isUpgrade ? `运行 hose-use update 升级至 v${latestVersion}` : "已经是最新版本"}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
if (!shouldUpdate) {
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
updated: false,
|
||||
currentVersion: VERSION,
|
||||
currentVersionPublishedAt: currentRelease?.publishedAt,
|
||||
latestVersion,
|
||||
latestVersionPublishedAt: release.publishedAt,
|
||||
mode: "binary",
|
||||
message: `hose-use 当前已是最新版本 (v${VERSION})`,
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: `ℹ️ hose-use 当前已是最新版本 (v${VERSION})。如需重装请添加 --force。\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Find matching asset
|
||||
const asset = matchAssetForPlatform(release.assets, platform, arch);
|
||||
if (!asset) {
|
||||
const errorMsg = `未找到适用于 ${platform}-${arch} 平台的 Release 资产 (v${latestVersion})。可用文件: ${release.assets.map((a) => a.name).join(", ")}`;
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({ updated: false, error: true, message: errorMsg }),
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
return {
|
||||
stdout: "",
|
||||
stderr: `[ERROR] ${errorMsg}\n`,
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const execPath = process.execPath;
|
||||
const execDir = dirname(execPath);
|
||||
const tmpDir = join(execDir, `.tmp-update-${Date.now()}`);
|
||||
mkdirSync(tmpDir, { recursive: true });
|
||||
|
||||
try {
|
||||
const downloadedFile = join(tmpDir, asset.name);
|
||||
await downloadFile(asset.downloadUrl, downloadedFile, release.tagName, asset.name);
|
||||
|
||||
let newBinaryPath = downloadedFile;
|
||||
if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) {
|
||||
newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform);
|
||||
} else if (asset.name.endsWith(".zip")) {
|
||||
newBinaryPath = extractZip(downloadedFile, tmpDir, platform);
|
||||
}
|
||||
|
||||
chmodSync(newBinaryPath, 0o755);
|
||||
|
||||
// Re-sign on macOS ad-hoc if codesign exists
|
||||
if (process.platform === "darwin") {
|
||||
try {
|
||||
spawnSync("/usr/bin/codesign", ["--remove-signature", newBinaryPath], { stdio: "ignore" });
|
||||
spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", newBinaryPath], { stdio: "ignore" });
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
// Atomic replace
|
||||
if (process.platform === "win32") {
|
||||
const oldBinary = `${execPath}.old.${Date.now()}`;
|
||||
try {
|
||||
renameSync(execPath, oldBinary);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
renameSync(newBinaryPath, execPath);
|
||||
} else {
|
||||
renameSync(newBinaryPath, execPath);
|
||||
}
|
||||
|
||||
const skillSync = syncGlobalSkillIfPresent();
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson({
|
||||
updated: true,
|
||||
fromVersion: VERSION,
|
||||
toVersion: latestVersion,
|
||||
skillSynced: skillSync.synced ? skillSync.targetDir : false,
|
||||
mode: "binary",
|
||||
}),
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: `[SUCCESS] ✨ hose-use 已成功升级至 v${latestVersion}!\n可执行文件: ${execPath}\nAgent 技能: ${skillSync.synced ? "已自动同步最新版 ✅" : "未同步"}\n`,
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
};
|
||||
} finally {
|
||||
try {
|
||||
rmSync(tmpDir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function detectPlatform(): "darwin" | "linux" | "windows" {
|
||||
if (process.platform === "darwin") return "darwin";
|
||||
if (process.platform === "win32") return "windows";
|
||||
return "linux";
|
||||
}
|
||||
|
||||
function detectArch(): "arm64" | "x64" {
|
||||
return process.arch === "arm64" ? "arm64" : "x64";
|
||||
}
|
||||
|
||||
export type GitHubAsset = {
|
||||
name: string;
|
||||
downloadUrl: string;
|
||||
size: number;
|
||||
};
|
||||
|
||||
export type GitHubRelease = {
|
||||
version: string;
|
||||
tagName: string;
|
||||
name?: string;
|
||||
publishedAt?: string;
|
||||
author?: string;
|
||||
notes: string;
|
||||
htmlUrl: string;
|
||||
assets: GitHubAsset[];
|
||||
};
|
||||
|
||||
export async function fetchGitHubReleases(repo: string, limit = 20): Promise<GitHubRelease[]> {
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
const headers: Record<string, string> = {
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
Accept: "application/vnd.github.v3+json",
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
|
||||
const urls = [
|
||||
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases?per_page=${limit}`,
|
||||
`https://api.github.com/repos/${repo}/releases?per_page=${limit}`,
|
||||
];
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as Array<{
|
||||
tag_name?: string;
|
||||
name?: string;
|
||||
body?: string;
|
||||
html_url?: string;
|
||||
published_at?: string;
|
||||
author?: { login?: string };
|
||||
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
|
||||
}>;
|
||||
|
||||
if (!Array.isArray(json) || json.length === 0) continue;
|
||||
|
||||
const list: GitHubRelease[] = [];
|
||||
for (const item of json) {
|
||||
const tagName = item.tag_name ?? "";
|
||||
const version = tagName.replace(/^v/, "");
|
||||
if (!version) continue;
|
||||
const assets: GitHubAsset[] = (item.assets ?? []).map((a) => ({
|
||||
name: a.name,
|
||||
downloadUrl: a.browser_download_url,
|
||||
size: a.size ?? 0,
|
||||
}));
|
||||
list.push({
|
||||
version,
|
||||
tagName,
|
||||
name: item.name ?? tagName,
|
||||
publishedAt: item.published_at,
|
||||
author: item.author?.login,
|
||||
notes: item.body ?? "",
|
||||
htmlUrl: item.html_url ?? "",
|
||||
assets,
|
||||
});
|
||||
}
|
||||
if (list.length > 0) return list;
|
||||
} catch {
|
||||
// try next source
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
export async function fetchGitHubRelease(
|
||||
repo: string,
|
||||
targetVersion?: string
|
||||
): Promise<GitHubRelease | undefined> {
|
||||
const tag = targetVersion ? (targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`) : undefined;
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
const headers: Record<string, string> = {
|
||||
"User-Agent": `hose-use/${VERSION}`,
|
||||
Accept: "application/vnd.github.v3+json",
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
|
||||
const urls = tag
|
||||
? [
|
||||
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/tags/${tag}`,
|
||||
`https://api.github.com/repos/${repo}/releases/tags/${tag}`,
|
||||
]
|
||||
: [
|
||||
`https://git.ying-qing.cn/api/v1/repos/gitea/hose-use/releases/latest`,
|
||||
`https://api.github.com/repos/${repo}/releases/latest`,
|
||||
];
|
||||
|
||||
let fallbackRelease: GitHubRelease | undefined;
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) });
|
||||
if (!res.ok) continue;
|
||||
const json = (await res.json()) as {
|
||||
tag_name?: string;
|
||||
name?: string;
|
||||
body?: string;
|
||||
html_url?: string;
|
||||
published_at?: string;
|
||||
author?: { login?: string };
|
||||
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
|
||||
};
|
||||
|
||||
const tagName = json.tag_name ?? "";
|
||||
const version = tagName.replace(/^v/, "");
|
||||
if (!version) continue;
|
||||
|
||||
const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({
|
||||
name: item.name,
|
||||
downloadUrl: item.browser_download_url,
|
||||
size: item.size ?? 0,
|
||||
}));
|
||||
|
||||
const candidateRelease: GitHubRelease = {
|
||||
version,
|
||||
tagName,
|
||||
name: json.name ?? tagName,
|
||||
publishedAt: json.published_at,
|
||||
author: json.author?.login,
|
||||
notes: json.body ?? "",
|
||||
htmlUrl: json.html_url ?? "",
|
||||
assets,
|
||||
};
|
||||
|
||||
if (assets.length > 0) {
|
||||
return candidateRelease;
|
||||
}
|
||||
|
||||
if (!fallbackRelease) {
|
||||
fallbackRelease = candidateRelease;
|
||||
}
|
||||
} catch {
|
||||
// try next source
|
||||
}
|
||||
}
|
||||
|
||||
return fallbackRelease;
|
||||
}
|
||||
|
||||
export function matchAssetForPlatform(
|
||||
assets: GitHubAsset[],
|
||||
platform: "darwin" | "linux" | "windows",
|
||||
arch: "arm64" | "x64"
|
||||
): GitHubAsset | undefined {
|
||||
const platformKeywords: Record<string, string[]> = {
|
||||
darwin: ["darwin", "macos", "osx", "apple"],
|
||||
linux: ["linux"],
|
||||
windows: ["windows", "win32", "win64", ".exe"],
|
||||
};
|
||||
const archKeywords: Record<string, string[]> = {
|
||||
arm64: ["arm64", "aarch64"],
|
||||
x64: ["x64", "x86_64", "amd64"],
|
||||
};
|
||||
|
||||
const pKeys = platformKeywords[platform] || [];
|
||||
const aKeys = archKeywords[arch] || [];
|
||||
|
||||
const matched = assets.filter((asset) => {
|
||||
const lower = asset.name.toLowerCase();
|
||||
const matchesP = pKeys.some((k) => lower.includes(k));
|
||||
const matchesA = aKeys.some((k) => lower.includes(k));
|
||||
return matchesP && matchesA;
|
||||
});
|
||||
|
||||
// Prefer direct raw executable over tar.gz / zip if both exist
|
||||
const directBinary = matched.find(
|
||||
(asset) =>
|
||||
!asset.name.endsWith(".tar.gz") &&
|
||||
!asset.name.endsWith(".tgz") &&
|
||||
!asset.name.endsWith(".zip") &&
|
||||
!asset.name.endsWith(".sha256")
|
||||
);
|
||||
if (directBinary) return directBinary;
|
||||
|
||||
// Fallback to archive
|
||||
const archive = matched.find(
|
||||
(asset) =>
|
||||
asset.name.endsWith(".tar.gz") ||
|
||||
asset.name.endsWith(".tgz") ||
|
||||
asset.name.endsWith(".zip")
|
||||
);
|
||||
return archive || matched[0];
|
||||
}
|
||||
|
||||
function logProgress(msg: string) {
|
||||
try {
|
||||
process.stderr.write(`${msg}\n`);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadFile(url: string, destPath: string, tagName?: string, assetName?: string) {
|
||||
const candidates: string[] = [];
|
||||
const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined;
|
||||
const fileName = assetName || url.split("/").pop() || "";
|
||||
|
||||
// 1. High-speed Gitea direct mirror first
|
||||
if (tag && fileName) {
|
||||
candidates.push(`https://git.ying-qing.cn/gitea/hose-use/releases/download/${tag}/${fileName}`);
|
||||
}
|
||||
if (url.startsWith("https://git.ying-qing.cn")) {
|
||||
candidates.push(url);
|
||||
}
|
||||
|
||||
// 2. Fast GitHub CDN proxies and direct GitHub fallback
|
||||
if (tag && fileName) {
|
||||
const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`;
|
||||
candidates.push(`https://ghfast.top/${ghDirectUrl}`);
|
||||
candidates.push(`https://ghproxy.net/${ghDirectUrl}`);
|
||||
candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`);
|
||||
candidates.push(`https://mirror.ghproxy.com/${ghDirectUrl}`);
|
||||
candidates.push(ghDirectUrl);
|
||||
} else if (url.includes("github.com")) {
|
||||
candidates.push(`https://ghfast.top/${url}`);
|
||||
candidates.push(`https://ghproxy.net/${url}`);
|
||||
candidates.push(`https://gh.ddlc.top/${url}`);
|
||||
candidates.push(`https://mirror.ghproxy.com/${url}`);
|
||||
candidates.push(url);
|
||||
} else {
|
||||
candidates.push(url);
|
||||
}
|
||||
|
||||
const uniqueCandidates = Array.from(new Set(candidates));
|
||||
|
||||
let lastError: Error | undefined;
|
||||
for (let i = 0; i < uniqueCandidates.length; i++) {
|
||||
const candidate = uniqueCandidates[i]!;
|
||||
try {
|
||||
logProgress(`==> [${i + 1}/${uniqueCandidates.length}] 正在下载更新: ${candidate}`);
|
||||
const res = await fetch(candidate, { signal: AbortSignal.timeout(6000) });
|
||||
if (!res.ok) {
|
||||
throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
const totalBytes = Number(res.headers.get("content-length")) || 0;
|
||||
const reader = res.body?.getReader();
|
||||
if (!reader) {
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
if (buffer.length < 1000) {
|
||||
throw new Error(`下载文件异常(大小仅 ${buffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, buffer);
|
||||
logProgress(`✓ 下载完成 (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks: Uint8Array[] = [];
|
||||
let receivedBytes = 0;
|
||||
let lastReport = 0;
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (value) {
|
||||
chunks.push(value);
|
||||
receivedBytes += value.length;
|
||||
const now = Date.now();
|
||||
if (now - lastReport > 200) {
|
||||
lastReport = now;
|
||||
const percent = totalBytes ? Math.round((receivedBytes / totalBytes) * 100) : 0;
|
||||
const receivedMb = (receivedBytes / (1024 * 1024)).toFixed(1);
|
||||
const totalMb = totalBytes ? (totalBytes / (1024 * 1024)).toFixed(1) : "?";
|
||||
try {
|
||||
process.stderr.write(`\r ↳ 进度: ${percent}% (${receivedMb} / ${totalMb} MB)...`);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
process.stderr.write("\n");
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
const completeBuffer = Buffer.concat(chunks);
|
||||
if (completeBuffer.length < 1000) {
|
||||
throw new Error(`下载文件异常(大小仅 ${completeBuffer.length} 字节)`);
|
||||
}
|
||||
writeFileSync(destPath, completeBuffer);
|
||||
logProgress(`✓ 下载完成 (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`);
|
||||
return;
|
||||
} catch (err) {
|
||||
lastError = err instanceof Error ? err : new Error(String(err));
|
||||
logProgress(` ↳ 节点失败: ${lastError.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`所有下载镜像均失败: ${lastError?.message}`);
|
||||
}
|
||||
|
||||
function extractTarGz(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 tar 归档失败: ${result.stderr.toString()}`);
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
return files[0] || archivePath;
|
||||
}
|
||||
|
||||
function extractZip(archivePath: string, targetDir: string, platform: string): string {
|
||||
const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" });
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`解压 zip 归档失败: ${result.stderr.toString()}`);
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const expectedName = platform === "windows" ? "hose-use.exe" : "hose-use";
|
||||
const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" })
|
||||
.stdout.trim()
|
||||
.split("\n")
|
||||
.filter(Boolean);
|
||||
|
||||
const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName));
|
||||
if (exact) return exact;
|
||||
return files[0] || archivePath;
|
||||
}
|
||||
|
||||
export function compareSemVer(v1: string, v2: string): number {
|
||||
const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
|
||||
const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0);
|
||||
for (let i = 0; i < Math.max(p1.length, p2.length); i++) {
|
||||
const a = p1[i] ?? 0;
|
||||
const b = p2[i] ?? 0;
|
||||
if (a > b) return 1;
|
||||
if (a < b) return -1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function isNewerVersion(latest: string, current: string): boolean {
|
||||
return compareSemVer(latest, current) > 0;
|
||||
}
|
||||
|
||||
function runCommand(command: string, args: string[], options: { cwd?: string } = {}) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: options.cwd,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
if (result.stdout) console.error(result.stdout.trimEnd());
|
||||
if (result.stderr) console.error(result.stderr.trimEnd());
|
||||
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`${command} ${args.join(" ")} 执行失败 (退出码 ${result.status})`);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user