|
| 1 | +import { spawnSync } from "node:child_process"; |
| 2 | +import { readFileSync } from "node:fs"; |
| 3 | +import { fileURLToPath } from "node:url"; |
| 4 | +import { dirname, join } from "node:path"; |
| 5 | + |
| 6 | +const PKG = "opencodex"; |
| 7 | +const HERE = dirname(fileURLToPath(import.meta.url)); // .../opencodex/src |
| 8 | + |
| 9 | +type Installer = "bun" | "npm" | "source"; |
| 10 | + |
| 11 | +/** Infer how opencodex is installed from the running module's path. */ |
| 12 | +function detectInstall(): Installer { |
| 13 | + if (!HERE.includes("node_modules")) return "source"; // a git checkout, not a global install |
| 14 | + return HERE.includes(".bun") ? "bun" : "npm"; |
| 15 | +} |
| 16 | + |
| 17 | +function currentVersion(): string { |
| 18 | + try { |
| 19 | + return (JSON.parse(readFileSync(join(HERE, "..", "package.json"), "utf8")).version as string) ?? "?"; |
| 20 | + } catch { |
| 21 | + return "?"; |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +/** Latest published version from the registry (best-effort; null if npm isn't available). */ |
| 26 | +function latestVersion(): string | null { |
| 27 | + const r = spawnSync("npm", ["view", PKG, "version"], { encoding: "utf8", timeout: 12000, windowsHide: true }); |
| 28 | + return r.status === 0 ? r.stdout.trim() : null; |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * `ocx update` — self-update opencodex to the latest published version, using the same package |
| 33 | + * manager it was installed with (bun or npm global). A source checkout is told to `git pull` instead. |
| 34 | + */ |
| 35 | +export function runUpdate(): void { |
| 36 | + const installer = detectInstall(); |
| 37 | + const current = currentVersion(); |
| 38 | + console.log(`opencodex v${current} (installed via ${installer})`); |
| 39 | + |
| 40 | + if (installer === "source") { |
| 41 | + console.log("Running from a source checkout — update with: git pull && bun install"); |
| 42 | + return; |
| 43 | + } |
| 44 | + |
| 45 | + const latest = latestVersion(); |
| 46 | + if (latest && latest === current) { |
| 47 | + console.log(`Already on the latest version (v${latest}).`); |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + const bin = installer === "bun" ? "bun" : "npm"; |
| 52 | + const cmdArgs = installer === "bun" |
| 53 | + ? ["add", "-g", `${PKG}@latest`] |
| 54 | + : ["install", "-g", `${PKG}@latest`]; |
| 55 | + console.log(`Updating${latest ? ` to v${latest}` : ""}…\n$ ${bin} ${cmdArgs.join(" ")}`); |
| 56 | + |
| 57 | + const r = spawnSync(bin, cmdArgs, { stdio: "inherit", timeout: 180000, windowsHide: true }); |
| 58 | + if (r.status === 0) { |
| 59 | + console.log(`\n✅ Updated${latest ? ` to v${latest}` : ""}. Restart the proxy: ocx stop && ocx start`); |
| 60 | + } else { |
| 61 | + console.error(`\n⚠️ Update failed (${bin} exit ${r.status ?? "?"}). Try manually: ${bin} ${cmdArgs.join(" ")}`); |
| 62 | + process.exit(1); |
| 63 | + } |
| 64 | +} |
0 commit comments