Add GitHub Release self-update support for standalone binary
This commit is contained in:
1 parent
c86ee6a235
commit
ce06d8f600
4 files changed
+265
-81
No files matched your search
@@ -50,6 +50,9 @@ jobs:
|
||||
- name: macos-arm64
|
||||
os: macos-latest
|
||||
ext: ""
|
||||
- name: macos-x64
|
||||
os: macos-13
|
||||
ext: ""
|
||||
- name: windows-x64
|
||||
os: windows-latest
|
||||
ext: ".exe"
|
||||
@@ -87,6 +90,7 @@ jobs:
|
||||
with:
|
||||
name: seal-home-${{ matrix.name }}
|
||||
path: |
|
||||
dist/bin/seal-home-${{ matrix.name }}${{ matrix.ext }}
|
||||
dist/bin/seal-home-${{ matrix.name }}.tar.gz
|
||||
dist/bin/seal-home-${{ matrix.name }}.zip
|
||||
if-no-files-found: error
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { isNewerVersion } from "./update.js";
|
||||
|
||||
describe("update version comparator", () => {
|
||||
test("correctly identifies newer semantic versions", () => {
|
||||
expect(isNewerVersion("0.7.0", "0.6.0")).toBe(true);
|
||||
expect(isNewerVersion("1.0.0", "0.6.0")).toBe(true);
|
||||
expect(isNewerVersion("0.6.1", "0.6.0")).toBe(true);
|
||||
expect(isNewerVersion("0.6.0", "0.6.0")).toBe(false);
|
||||
expect(isNewerVersion("0.5.9", "0.6.0")).toBe(false);
|
||||
expect(isNewerVersion("0.6.0", "0.7.0")).toBe(false);
|
||||
});
|
||||
});
|
||||
+243
-80
@@ -1,4 +1,5 @@
|
||||
import { chmodSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { isCompiledBinary } from "../../core/runtime.js";
|
||||
import { VERSION } from "../../version.js";
|
||||
@@ -9,8 +10,16 @@ import type { CliRuntime } from "../types.js";
|
||||
|
||||
const DEFAULT_GITHUB_REPO = "yunyingk/seal-home";
|
||||
const UPDATE_URL_ENV = "SEAL_HOME_UPDATE_URL";
|
||||
const GITHUB_REPO_ENV = "SEAL_HOME_GITHUB_REPO";
|
||||
|
||||
export async function handleUpdateCommand(runtime: CliRuntime, options: { checkOnly?: boolean } = {}) {
|
||||
export type UpdateOptions = {
|
||||
checkOnly?: boolean;
|
||||
force?: boolean;
|
||||
targetVersion?: string;
|
||||
repo?: string;
|
||||
};
|
||||
|
||||
export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOptions = {}) {
|
||||
const serviceConfig = {
|
||||
appRoot: runtime.appRoot,
|
||||
entryFile: runtime.entryFile,
|
||||
@@ -19,6 +28,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: { checkO
|
||||
launcher: runtime.launcher
|
||||
};
|
||||
|
||||
// 1. Source development mode (running via bun/node)
|
||||
if (!isCompiledBinary()) {
|
||||
const wasRunning = serviceStatus(serviceConfig).running;
|
||||
if (wasRunning) await runServiceCommand("stop", serviceConfig);
|
||||
@@ -37,125 +47,278 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: { checkO
|
||||
return;
|
||||
}
|
||||
|
||||
// Standalone binary update
|
||||
const currentPlatform = detectPlatformArch();
|
||||
const updateInfo = await fetchLatestReleaseInfo();
|
||||
// 2. Standalone binary mode: check GitHub Releases
|
||||
const repo = options.repo || process.env[GITHUB_REPO_ENV]?.trim() || DEFAULT_GITHUB_REPO;
|
||||
const platform = detectPlatform();
|
||||
const arch = detectArch();
|
||||
|
||||
if (!updateInfo) {
|
||||
const release = await fetchGitHubRelease(repo, options.targetVersion);
|
||||
if (!release) {
|
||||
printJson({
|
||||
updated: false,
|
||||
version: VERSION,
|
||||
currentVersion: VERSION,
|
||||
mode: "binary",
|
||||
message: "No update source configured or release server unreachable"
|
||||
message: `Failed to query releases from GitHub repository '${repo}'`
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (isNewerVersion(updateInfo.version, VERSION)) {
|
||||
if (options.checkOnly) {
|
||||
printJson({
|
||||
updated: false,
|
||||
updateAvailable: true,
|
||||
currentVersion: VERSION,
|
||||
latestVersion: updateInfo.version,
|
||||
downloadUrl: updateInfo.downloads[currentPlatform]?.url
|
||||
});
|
||||
return;
|
||||
const latestVersion = release.version;
|
||||
const isUpgrade = isNewerVersion(latestVersion, VERSION);
|
||||
const shouldUpdate = options.force || Boolean(options.targetVersion) || isUpgrade;
|
||||
|
||||
if (options.checkOnly) {
|
||||
printJson({
|
||||
updated: false,
|
||||
updateAvailable: isUpgrade,
|
||||
currentVersion: VERSION,
|
||||
latestVersion,
|
||||
releaseNotes: release.notes,
|
||||
releaseUrl: release.htmlUrl,
|
||||
mode: "binary"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!shouldUpdate) {
|
||||
printJson({
|
||||
updated: false,
|
||||
currentVersion: VERSION,
|
||||
latestVersion,
|
||||
mode: "binary",
|
||||
message: `seal-home is already up to date (v${VERSION})`
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Find matching asset
|
||||
const asset = matchAssetForPlatform(release.assets, platform, arch);
|
||||
if (!asset) {
|
||||
throw new Error(
|
||||
`No compatible binary found for ${platform}-${arch} in release v${latestVersion}. ` +
|
||||
`Available assets: ${release.assets.map((a) => a.name).join(", ")}`
|
||||
);
|
||||
}
|
||||
|
||||
// Download binary or archive
|
||||
const wasRunning = serviceStatus(serviceConfig).running;
|
||||
if (wasRunning) await runServiceCommand("stop", serviceConfig);
|
||||
|
||||
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);
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
const downloadUrl = updateInfo.downloads[currentPlatform]?.url;
|
||||
if (!downloadUrl) {
|
||||
throw new Error(`No prebuilt binary available for platform: ${currentPlatform} in release ${updateInfo.version}`);
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
const wasRunning = serviceStatus(serviceConfig).running;
|
||||
if (wasRunning) await runServiceCommand("stop", serviceConfig);
|
||||
|
||||
const tmpBinary = `${process.execPath}.tmp.${Date.now()}`;
|
||||
const response = await fetch(downloadUrl);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download binary update: ${response.status} ${response.statusText}`);
|
||||
// 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 buffer = Buffer.from(await response.arrayBuffer());
|
||||
writeFileSync(tmpBinary, buffer);
|
||||
chmodSync(tmpBinary, 0o755);
|
||||
renameSync(tmpBinary, process.execPath);
|
||||
|
||||
if (wasRunning) await runServiceCommand("start", serviceConfig);
|
||||
|
||||
printJson({
|
||||
updated: true,
|
||||
fromVersion: VERSION,
|
||||
toVersion: updateInfo.version,
|
||||
toVersion: latestVersion,
|
||||
serviceRestarted: wasRunning,
|
||||
mode: "binary"
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
printJson({
|
||||
updated: false,
|
||||
version: VERSION,
|
||||
mode: "binary",
|
||||
message: "seal-home is already up to date"
|
||||
});
|
||||
}
|
||||
|
||||
function detectPlatformArch(): string {
|
||||
const platform = process.platform === "darwin" ? "darwin" : process.platform === "win32" ? "windows" : "linux";
|
||||
const arch = process.arch === "arm64" ? "arm64" : "x64";
|
||||
return `${platform}-${arch}`;
|
||||
}
|
||||
|
||||
type ReleaseInfo = {
|
||||
version: string;
|
||||
downloads: Record<string, { url: string; sha256?: string }>;
|
||||
};
|
||||
|
||||
async function fetchLatestReleaseInfo(): Promise<ReleaseInfo | undefined> {
|
||||
const customUrl = process.env[UPDATE_URL_ENV]?.trim();
|
||||
if (customUrl) {
|
||||
} finally {
|
||||
try {
|
||||
const res = await fetch(customUrl);
|
||||
if (res.ok) {
|
||||
return (await res.json()) as ReleaseInfo;
|
||||
}
|
||||
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";
|
||||
}
|
||||
|
||||
type GitHubAsset = {
|
||||
name: string;
|
||||
downloadUrl: string;
|
||||
size: number;
|
||||
};
|
||||
|
||||
type GitHubRelease = {
|
||||
version: string;
|
||||
tagName: string;
|
||||
notes: string;
|
||||
htmlUrl: string;
|
||||
assets: GitHubAsset[];
|
||||
};
|
||||
|
||||
async function fetchGitHubRelease(repo: string, targetVersion?: string): Promise<GitHubRelease | undefined> {
|
||||
const url = targetVersion
|
||||
? `https://api.github.com/repos/${repo}/releases/tags/${targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`}`
|
||||
: `https://api.github.com/repos/${repo}/releases/latest`;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
"User-Agent": `seal-home/${VERSION}`,
|
||||
Accept: "application/vnd.github.v3+json"
|
||||
};
|
||||
|
||||
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
||||
if (token) {
|
||||
headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
// Fallback to GitHub API
|
||||
try {
|
||||
const res = await fetch(`https://api.github.com/repos/${DEFAULT_GITHUB_REPO}/releases/latest`, {
|
||||
headers: {
|
||||
"User-Agent": `seal-home/${VERSION}`
|
||||
}
|
||||
});
|
||||
const res = await fetch(url, { headers });
|
||||
if (!res.ok) return undefined;
|
||||
const json = (await res.json()) as {
|
||||
tag_name?: string;
|
||||
assets?: Array<{ name: string; browser_download_url: string }>;
|
||||
body?: string;
|
||||
html_url?: string;
|
||||
assets?: Array<{ name: string; browser_download_url: string; size?: number }>;
|
||||
};
|
||||
const version = (json.tag_name ?? "").replace(/^v/, "");
|
||||
|
||||
const tagName = json.tag_name ?? "";
|
||||
const version = tagName.replace(/^v/, "");
|
||||
if (!version) return undefined;
|
||||
|
||||
const downloads: Record<string, { url: string }> = {};
|
||||
for (const asset of json.assets ?? []) {
|
||||
for (const target of ["darwin-arm64", "darwin-x64", "linux-x64", "linux-arm64", "windows-x64"]) {
|
||||
if (asset.name.includes(target)) {
|
||||
downloads[target] = { url: asset.browser_download_url };
|
||||
}
|
||||
}
|
||||
}
|
||||
const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({
|
||||
name: item.name,
|
||||
downloadUrl: item.browser_download_url,
|
||||
size: item.size ?? 0
|
||||
}));
|
||||
|
||||
return { version, downloads };
|
||||
return {
|
||||
version,
|
||||
tagName,
|
||||
notes: json.body ?? "",
|
||||
htmlUrl: json.html_url ?? "",
|
||||
assets
|
||||
};
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function isNewerVersion(latest: string, current: string): boolean {
|
||||
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", "win"]
|
||||
};
|
||||
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];
|
||||
}
|
||||
|
||||
async function downloadFile(url: string, destPath: string) {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to download asset from ${url}: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
const buffer = Buffer.from(await res.arrayBuffer());
|
||||
writeFileSync(destPath, buffer);
|
||||
}
|
||||
|
||||
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(`Failed to extract tar archive: ${result.stderr.toString()}`);
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
// Look for executable in targetDir
|
||||
const expectedName = platform === "windows" ? "seal-home.exe" : "seal-home";
|
||||
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(`Failed to extract zip archive: ${result.stderr.toString()}`);
|
||||
}
|
||||
unlinkSync(archivePath);
|
||||
|
||||
const expectedName = platform === "windows" ? "seal-home.exe" : "seal-home";
|
||||
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 isNewerVersion(latest: string, current: string): boolean {
|
||||
const lParts = latest.split(".").map(Number);
|
||||
const cParts = current.split(".").map(Number);
|
||||
for (let i = 0; i < Math.max(lParts.length, cParts.length); i++) {
|
||||
|
||||
+5
-1
@@ -162,8 +162,12 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
}
|
||||
|
||||
if (area === "update") {
|
||||
const targetVersion = stringOption(args.options.version) ?? stringOption(args.options.tag) ?? (action && !action.startsWith("-") ? action : undefined);
|
||||
await handleUpdateCommand(runtime, {
|
||||
checkOnly: booleanOption(args.options.check) ?? booleanOption(args.options["check-only"])
|
||||
checkOnly: booleanOption(args.options.check) ?? booleanOption(args.options["check-only"]),
|
||||
force: booleanOption(args.options.force),
|
||||
targetVersion,
|
||||
repo: stringOption(args.options.repo)
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user