refactor(cli): split commands/update.ts into update/{index,releases}.ts

releases.ts carries the GitHub/Gitea release infrastructure (types,
listing, mirrored download, archive extraction, semver compare);
index.ts keeps handleUpdateCommand and re-exports the previously
public members so update.test.ts stays source-compatible.
Verbatim code moves, no behavior change: tsc clean, 316 tests pass.
This commit is contained in:
gitea committed 2026-10-04 14:12:03 +08:00
1 parent 6f1f2623a3
commit c8450b9908
4 files changed
+510 -471

No files matched your search

+548
View File
@@ -0,0 +1,548 @@
import { chmodSync, existsSync, mkdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
import { isCompiledBinary, resolveAppRoot } from "../../../packaging/runtime.js";
import { syncGlobalSkillIfPresent } from "../../../packaging/embedded-skill.js";
import { loadGlobalConfig } from "../../../core/config/loader.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";
import {
compareSemVer,
detectArch,
detectPlatform,
downloadFile,
extractTarGz,
extractZip,
fetchGitHubRelease,
fetchGitHubReleases,
isNewerVersion,
isValidRepo,
matchAssetForPlatform,
normalizeRepo,
DEFAULT_GITHUB_REPO,
GITHUB_REPO_ENV,
type GitHubAsset,
type GitHubRelease,
type UpdateSourcePreference,
} from "./releases.js";
export type UpdateOptions = {
checkOnly?: boolean;
changelogOnly?: boolean;
limit?: number;
force?: boolean;
targetVersion?: string;
repo: string;
sourcePreference: UpdateSourcePreference;
};
// 维持模块级兼容导出:测试与外部此前均从 "./update.js" 导入这些成员。
export {
compareSemVer,
downloadFile,
fetchGitHubRelease,
fetchGitHubReleases,
isValidRepo,
isNewerVersion,
matchAssetForPlatform,
normalizeRepo,
DEFAULT_GITHUB_REPO,
GITHUB_REPO_ENV,
type GitHubAsset,
type GitHubRelease,
type UpdateSourcePreference,
} from "./releases.js";
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 isGitHub = booleanOption(parsed.options, ["github", "gh"]);
const isGitea = booleanOption(parsed.options, ["gitea", "yingqing", "mirror"]);
const globalConfig = loadGlobalConfig();
const configuredSource = globalConfig.updateSource || "auto";
let sourcePreference: UpdateSourcePreference = "auto";
if (isGitHub) {
sourcePreference = "github";
} else if (isGitea) {
sourcePreference = "gitea";
} else if (configuredSource === "github" || configuredSource === "gitea") {
sourcePreference = configuredSource;
}
const rawRepo =
stringOption(parsed.options, ["repo"]) ||
process.env[GITHUB_REPO_ENV]?.trim() ||
globalConfig.updateRepo?.trim() ||
DEFAULT_GITHUB_REPO;
const repo = normalizeRepo(rawRepo);
if (!isValidRepo(repo)) {
const errorMsg = `非法 GitHub 仓库标识: '${rawRepo}'。应为 'owner/repo' 格式(如 'yunyingk/hose-use')。`;
if (runtime.jsonMode) {
return {
stdout: printJson({ updated: false, error: true, message: errorMsg }),
stderr: "",
exitCode: 1,
};
}
return {
stdout: "",
stderr: `[ERROR] ${errorMsg}\n`,
exitCode: 1,
};
}
const options: UpdateOptions = {
checkOnly: isCheck,
changelogOnly: isChangelog,
limit: numberOption(parsed.options, ["limit", "n"]),
force: booleanOption(parsed.options, ["force", "f"]),
targetVersion,
repo,
sourcePreference,
};
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, options.sourcePreference);
if (runtime.jsonMode) {
return {
stdout: printJson({
currentVersion: VERSION,
repo,
sourcePreference: options.sourcePreference,
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, options.sourcePreference);
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,
repo,
sourcePreference: options.sourcePreference,
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,
"发布仓库": repo,
"通道偏好": options.sourcePreference,
"源码路径": 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, options.sourcePreference);
const release = targetVersion
? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ??
await fetchGitHubRelease(repo, targetVersion, options.sourcePreference))
: (releases[0] ?? await fetchGitHubRelease(repo, undefined, options.sourcePreference));
if (!release) {
const errorMsg = `无法从 GitHub 仓库 '${repo}' 获取 Release 列表`;
if (runtime.jsonMode) {
return {
stdout: printJson({
updated: false,
currentVersion: VERSION,
repo,
sourcePreference: options.sourcePreference,
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,
repo,
sourcePreference: options.sourcePreference,
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}`,
"发布仓库": repo,
"通道偏好": options.sourcePreference,
});
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,
repo,
sourcePreference: options.sourcePreference,
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, repo, options.sourcePreference);
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);
// Ensure Windows hose-aipro.cmd wrapper exists
const cmdWrapper = join(execDir, "hose-aipro.cmd");
if (!existsSync(cmdWrapper)) {
try {
writeFileSync(cmdWrapper, '@echo off\r\n"%~dp0hose-use.exe" %*\r\n', "utf8");
} catch {
// ignore
}
}
} else {
renameSync(newBinaryPath, execPath);
// Ensure Unix hose-aipro symlink exists and points to the main binary
const aiproLink = join(execDir, "hose-aipro");
if (!existsSync(aiproLink)) {
try {
symlinkSync(execPath, aiproLink);
} catch {
// ignore
}
}
}
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 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})`);
}
}