fix(cli): support Homebrew Core upgrades (#52753)

This commit is contained in:
Shoubhit Dash
2026-10-02 20:27:14 +05:30
committed by GitHub
Unverified
parent 661853903b
commit f902a0fae7
5 changed files with 95 additions and 41 deletions
@@ -20,7 +20,7 @@ export default Runtime.handler(
)
log.info(`Using method: ${method}`)
const target = Option.getOrUndefined(input.target) ?? (yield* updater.latest())
const target = Option.getOrUndefined(input.target) ?? (yield* updater.latest(method))
const version = target.trim().replace(/^v/, "")
if (version === OPENCODE_VERSION) {
log.warn(`OpenCode upgrade skipped: ${version} is already installed`)
+33 -27
View File
@@ -98,7 +98,7 @@ export interface Interface {
readonly check: () => Effect.Effect<CheckResult | undefined, Error>
readonly apply: (version: string) => Effect.Effect<void, Error>
readonly method: () => Effect.Effect<Method | undefined>
readonly latest: () => Effect.Effect<string, Error>
readonly latest: (method?: Method) => Effect.Effect<string, Error>
readonly upgrade: (method: Method, version: string) => Effect.Effect<void, Error>
readonly removal: (
method: Method,
@@ -131,8 +131,8 @@ const make = Effect.gen(function* () {
const flock = yield* EffectFlock.Service
const installedVersion = yield* Ref.make(OPENCODE_VERSION)
const channel = OPENCODE_CHANNEL.replace(/[^a-zA-Z0-9._-]/g, "-")
const executable = yield* fs.realPath(process.execPath).pipe(Effect.orElseSucceed(() => process.execPath))
const installedPackage = yield* Effect.gen(function* () {
const executable = yield* fs.realPath(process.execPath)
const directory = path.dirname(path.dirname(executable))
const manifest: { name: string; bin?: Record<string, string> } = yield* fs
.readFileString(path.join(directory, "package.json"))
@@ -142,6 +142,10 @@ const make = Effect.gen(function* () {
if (Object.values(manifest.bin ?? {}).some((bin) => path.resolve(directory, bin) === executable))
return manifest.name
}).pipe(Effect.orElseSucceed(() => undefined))
// "opencode" is Homebrew Core's formula; the others are published to anomalyco/tap.
const installedFormula = ["opencode", "opencode-beta", "opencode-v2"].find((name) =>
executable.includes(`${path.sep}Cellar${path.sep}${name}${path.sep}`),
)
const readPolicy = Effect.fnUntraced(function* () {
const values = yield* Effect.forEach(["config.json", "opencode.json", "opencode.jsonc"], (name) =>
@@ -178,13 +182,7 @@ const make = Effect.gen(function* () {
const method = Effect.fnUntraced(function* () {
if (path.resolve(process.execPath) === curlBinary) return "curl"
const executable = yield* fs.realPath(process.execPath).pipe(Effect.orElseSucceed(() => process.execPath))
if (
["opencode-beta", "opencode-v2"].some((name) =>
executable.includes(`${path.sep}Cellar${path.sep}${name}${path.sep}`),
)
)
return "brew"
if (installedFormula) return "brew"
if (!installedPackage) return
const checks: ReadonlyArray<{ method: Method; command: string[] }> = [
@@ -236,10 +234,14 @@ const make = Effect.gen(function* () {
const release = Effect.fnUntraced(function* (method?: Method) {
const distribution = method === "brew" ? "homebrew" : "npm"
// Homebrew Core builds its formula on its own schedule, so the tap release does not describe it.
const core = method === "brew" && installedFormula === "opencode"
const response = yield* Effect.tryPromise({
try: (signal) =>
fetch(
`https://opencode.ai/update/api/${encodeURIComponent(channel)}/${encodeURIComponent(OPENCODE_ARTIFACT)}/${distribution}?current=${encodeURIComponent(OPENCODE_VERSION)}`,
core
? "https://formulae.brew.sh/api/formula/opencode.json"
: `https://opencode.ai/update/api/${encodeURIComponent(channel)}/${encodeURIComponent(OPENCODE_ARTIFACT)}/${distribution}?current=${encodeURIComponent(OPENCODE_VERSION)}`,
{
signal: AbortSignal.any([signal, AbortSignal.timeout(10_000)]),
},
@@ -262,19 +264,22 @@ const make = Effect.gen(function* () {
retry: "Try again in a few minutes.",
}),
)
const data: { version: string; metadata?: { package?: string } } = yield* Effect.tryPromise({
try: () => response.json(),
catch: (cause) =>
new UpgradeError(
{
title: "Could not read the OpenCode update information",
detail: errorDetail(cause),
retry: "Try again in a few minutes.",
},
{ cause },
),
})
if (!data.metadata?.package)
const data: { version?: string; metadata?: { package?: string }; versions?: { stable?: string } } =
yield* Effect.tryPromise({
try: () => response.json(),
catch: (cause) =>
new UpgradeError(
{
title: "Could not read the OpenCode update information",
detail: errorDetail(cause),
retry: "Try again in a few minutes.",
},
{ cause },
),
})
const version = core ? data.versions?.stable : data.version
const packageName = core ? "opencode" : data.metadata?.package
if (!version || !packageName)
return yield* Effect.fail(
new UpgradeError({
title: "Could not read the OpenCode update information",
@@ -282,11 +287,11 @@ const make = Effect.gen(function* () {
retry: "Try again in a few minutes.",
}),
)
return { package: data.metadata.package, version: data.version }
return { package: packageName, version }
})
const latest = () =>
method().pipe(
const latest = (selected?: Method) =>
(selected ? Effect.succeed(selected) : method()).pipe(
Effect.flatMap(release),
Effect.map((data) => data.version),
)
@@ -346,7 +351,8 @@ const make = Effect.gen(function* () {
const upgrade = Effect.fnUntraced(function* (method: Method, input: string) {
if (!parseReleaseVersion(input)) return yield* Effect.fail(new Error(`Invalid version: ${input}`))
const version = input.trim().replace(/^v/, "")
const packageName = (yield* release(method)).package
const packageName =
method === "brew" && installedFormula === "opencode" ? "opencode" : (yield* release(method)).package
const target = `${packageName}@${version}`
if (installedPackage && packageName !== installedPackage && (method === "pnpm" || method === "yarn")) {
return yield* Effect.fail(new Error(`Reinstall ${target} with ${method} to migrate from ${installedPackage}.`))
+2 -2
View File
@@ -21,9 +21,9 @@ await Effect.runPromise(
record("method")
return Updater.methods.find((method) => method === (process.env.UPGRADE_TEST_METHOD ?? "npm"))
}),
latest: () =>
latest: (method) =>
Effect.suspend(() => {
record("latest")
record({ latest: method })
return process.env.UPGRADE_TEST_LATEST_ERROR
? Effect.fail(new Error("Update check failed"))
: Effect.succeed("0.0.0-beta-new")
+51 -9
View File
@@ -22,6 +22,7 @@ function fixture(
name = "@opencode/cli",
failCleanup = false,
releasePackage = name,
formula?: string,
) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem
@@ -29,20 +30,30 @@ function fixture(
const root = yield* fs.makeTempDirectoryScoped({ prefix: "opencode-updater-" })
const execPath = process.execPath
const modules = path.join(root, "node_modules")
const executable = path.join(modules, "@opencode", "cli", "bin", "opencode")
const executable = formula
? path.join(root, "Cellar", formula, "2.0.20", "bin", "opencode")
: path.join(modules, "@opencode", "cli", "bin", "opencode")
yield* fs.makeDirectory(path.dirname(executable), { recursive: true })
yield* fs.writeFileString(executable, "binary")
yield* fs.writeFileString(
path.join(modules, "@opencode", "cli", "package.json"),
JSON.stringify({ name, bin: { opencode: "bin/opencode" } }),
)
if (!formula)
yield* fs.writeFileString(
path.join(modules, "@opencode", "cli", "package.json"),
JSON.stringify({ name, bin: { opencode: "bin/opencode" } }),
)
const requests: string[] = []
// The updater uses global fetch; scope this replacement to each install test.
yield* Effect.acquireRelease(
Effect.sync(() =>
spyOn(globalThis, "fetch").mockImplementation(
Object.assign(async () => Response.json({ version: "2.3.4", metadata: { package: releasePackage } }), {
preconnect: fetch.preconnect,
}),
Object.assign(
async (input: string | URL | Request) => {
const url = input instanceof Request ? input.url : input.toString()
requests.push(url)
if (new URL(url).hostname === "formulae.brew.sh") return Response.json({ versions: { stable: "2.0.21" } })
return Response.json({ version: "2.3.4", metadata: { package: releasePackage } })
},
{ preconnect: fetch.preconnect },
),
),
),
(request) => Effect.sync(() => request.mockRestore()),
@@ -106,7 +117,7 @@ function fixture(
}),
),
)
return { updater, commands, global, fs, executable }
return { updater, commands, requests, global, fs, executable }
})
}
@@ -281,6 +292,37 @@ it.live("vp detection ignores no-match output that repeats the package name", ()
}),
)
it.live("Homebrew Core installs check and upgrade the Core formula", () =>
Effect.gen(function* () {
const test = yield* fixture(() => ({}), "@opencode/cli", false, "anomalyco/tap/opencode-v2", "opencode")
expect(yield* test.updater.method()).toBe("brew")
expect(yield* test.updater.latest()).toBe("2.0.21")
yield* test.updater.upgrade("brew", "2.0.21")
expect(test.commands).toEqual([["brew", "upgrade", "opencode"]])
// An explicitly selected method keeps its own release source.
expect(yield* test.updater.latest("npm")).toBe("2.3.4")
expect(test.requests).toEqual([
"https://formulae.brew.sh/api/formula/opencode.json",
"https://opencode.ai/update/api/local/cli/npm?current=local",
])
}),
)
;["opencode-v2", "opencode-beta"].forEach((formula) => {
it.live(`Homebrew tap installs of ${formula} use the published tap formula`, () =>
Effect.gen(function* () {
const test = yield* fixture(() => ({}), "@opencode/cli", false, `anomalyco/tap/${formula}`, formula)
expect(yield* test.updater.method()).toBe("brew")
expect(yield* test.updater.latest()).toBe("2.3.4")
yield* test.updater.upgrade("brew", "2.3.4")
expect(test.commands).toEqual([["brew", "upgrade", `anomalyco/tap/${formula}`]])
expect(test.requests).toEqual([
"https://opencode.ai/update/api/local/cli/homebrew?current=local",
"https://opencode.ai/update/api/local/cli/homebrew?current=local",
])
}),
)
})
// Links are named opencode-upgrade-<pid>-<random>.exe; read them from inside the installer run.
const links = (directory: string) =>
existsSync(directory) ? readdirSync(directory).filter((name) => name.startsWith("opencode-")) : []
+8 -2
View File
@@ -18,10 +18,16 @@ describe("upgrade command", () => {
test("detects the installation method and resolves the latest version", async () => {
const result = await cli([])
expect(result.exitCode).toBe(0)
expect(result.events).toEqual(["method", "latest", { method: "npm", version: "0.0.0-beta-new" }])
expect(result.events).toEqual(["method", { latest: "npm" }, { method: "npm", version: "0.0.0-beta-new" }])
expect(result.stdout).toContain("Upgrade complete")
})
test("resolves the latest version for an explicit method without detection", async () => {
const result = await cli(["--method", "pnpm"], { UPGRADE_TEST_METHOD: "brew" })
expect(result.exitCode).toBe(0)
expect(result.events).toEqual([{ latest: "pnpm" }, { method: "pnpm", version: "0.0.0-beta-new" }])
})
test("accepts an explicit version and method without detection or a version lookup", async () => {
const result = await cli(["v0.0.0-beta-target", "--method", "pnpm"])
expect(result.exitCode).toBe(0)
@@ -64,7 +70,7 @@ describe("upgrade command", () => {
test("reports version lookup failures without installing", async () => {
const result = await cli([], { UPGRADE_TEST_LATEST_ERROR: "1" })
expect(result.exitCode).toBe(1)
expect(result.events).toEqual(["method", "latest"])
expect(result.events).toEqual(["method", { latest: "npm" }])
expect(result.stdout).toContain("Update check failed")
})