From 839aa25c3ed07ef814a5126bef097e3b42848bb6 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Sat, 19 Sep 2026 04:37:36 -0400 Subject: [PATCH] feat(cli): publish Homebrew formula --- packages/cli/script/publish-homebrew.ts | 120 ++++++++++++++++++++++++ packages/cli/script/publish.ts | 4 + packages/cli/src/services/updater.ts | 27 ++++-- packages/cli/test/upgrade.test.ts | 2 +- 4 files changed, 145 insertions(+), 8 deletions(-) create mode 100644 packages/cli/script/publish-homebrew.ts diff --git a/packages/cli/script/publish-homebrew.ts b/packages/cli/script/publish-homebrew.ts new file mode 100644 index 00000000000..a9a7ed2f47a --- /dev/null +++ b/packages/cli/script/publish-homebrew.ts @@ -0,0 +1,120 @@ +#!/usr/bin/env bun +import { Script } from "@opencode/script" +import { $ } from "bun" +import { mkdir, rm } from "node:fs/promises" +import path from "node:path" +import { fileURLToPath } from "node:url" +import { UpdateArtifact } from "../../../script/update-artifact" + +if (Script.channel !== "beta" && Script.channel !== "latest") { + throw new Error("Homebrew publishing requires the beta or latest channel") +} +const valid = + Script.channel === "beta" + ? /^\d+\.\d+\.\d+-beta[.-]\d+(?:\.\d+)?$/.test(Script.version) + : /^\d+\.\d+\.\d+$/.test(Script.version) +if (!valid) throw new Error(`Expected a ${Script.channel} release version`) + +const dir = fileURLToPath(new URL("..", import.meta.url)) +const root = path.resolve(process.env.OPENCODE_CLI_DIST ?? path.join(dir, "dist")) +const outdir = path.join(root, "homebrew-tap") +const dryRun = process.argv.includes("--dry-run") +const name = Script.channel === "beta" ? "opencode-beta" : "opencode-v2" +const formulaClass = Script.channel === "beta" ? "OpencodeBeta" : "OpencodeV2" + +const targets = await Promise.all( + [ + { name: "darwin-arm64", archive: "zip" }, + { name: "darwin-x64-baseline", archive: "zip" }, + { name: "linux-arm64", archive: "tar.gz" }, + { name: "linux-x64-baseline", archive: "tar.gz" }, + ].map(async (target) => { + const filename = `opencode-${target.name}.${target.archive}` + const file = Bun.file(path.join(root, filename)) + if (!(await file.exists()) || !file.size) throw new Error(`Missing Homebrew archive: ${filename}`) + const sha256 = new Bun.CryptoHasher("sha256") + for await (const chunk of file.stream()) sha256.update(chunk) + return { + ...target, + url: `https://opencode.ai/files/bin/${encodeURIComponent(Script.version)}/${filename}`, + sha256: sha256.digest("hex"), + } + }), +) + +await rm(outdir, { recursive: true, force: true }) +if (dryRun) await mkdir(outdir, { recursive: true }) +if (!dryRun) { + const token = process.env.GITHUB_TOKEN + if (!token) throw new Error("GITHUB_TOKEN is required to update the Homebrew tap") + await $`git clone ${`https://x-access-token:${token}@github.com/anomalyco/homebrew-tap.git`} ${outdir}` + await $`git checkout -B master`.cwd(outdir) +} + +const target = (name: string) => { + const result = targets.find((item) => item.name === name) + if (!result) throw new Error(`Missing Homebrew target: ${name}`) + return result +} +const macArm = target("darwin-arm64") +const macIntel = target("darwin-x64-baseline") +const linuxArm = target("linux-arm64") +const linuxIntel = target("linux-x64-baseline") + +await Bun.write( + path.join(outdir, `${name}.rb`), + [ + "# typed: false", + "# frozen_string_literal: true", + "", + `class ${formulaClass} < Formula`, + ` desc "OpenCode V2${Script.channel === "beta" ? " beta" : ""} - the AI coding agent for the terminal"`, + ' homepage "https://github.com/anomalyco/opencode"', + ` version "${Script.version}"`, + ' license "MIT"', + "", + ' depends_on "ripgrep"', + ' conflicts_with "opencode", because: "both install an opencode binary"', + "", + " on_macos do", + " if Hardware::CPU.arm?", + ` url "${macArm.url}"`, + ` sha256 "${macArm.sha256}"`, + " else", + ` url "${macIntel.url}"`, + ` sha256 "${macIntel.sha256}"`, + " end", + " end", + "", + " on_linux do", + " if Hardware::CPU.arm?", + ` url "${linuxArm.url}"`, + ` sha256 "${linuxArm.sha256}"`, + " else", + ` url "${linuxIntel.url}"`, + ` sha256 "${linuxIntel.sha256}"`, + " end", + " end", + "", + " def install", + ' bin.install "opencode"', + " end", + "end", + "", + ].join("\n"), +) +console.log(`Prepared ${name} ${Script.version} in ${outdir}`) +if (dryRun) process.exit(0) + +await $`git add ${name + ".rb"}`.cwd(outdir) +if ((await $`git diff --cached --quiet`.cwd(outdir).nothrow()).exitCode !== 0) { + await $`git commit -m ${`chore: update ${name} to ${Script.version}`}`.cwd(outdir) + await $`git push origin master`.cwd(outdir) +} +await UpdateArtifact.publish({ + channel: Script.channel, + name: "cli", + distribution: "homebrew", + version: Script.version, + metadata: { package: `anomalyco/tap/${name}` }, +}) diff --git a/packages/cli/script/publish.ts b/packages/cli/script/publish.ts index b16fe642e1b..b5ca32787eb 100755 --- a/packages/cli/script/publish.ts +++ b/packages/cli/script/publish.ts @@ -149,6 +149,10 @@ if (Script.channel === "latest" && Script.release && !dryRun) { if ((Script.channel === "beta" || Script.channel === "latest") && Script.release) { await $`bun ./script/publish-aur.ts ${dryRun ? ["--dry-run"] : []}`.env({ ...process.env, OPENCODE_CLI_DIST: root }) + await $`bun ./script/publish-homebrew.ts ${dryRun ? ["--dry-run"] : []}`.env({ + ...process.env, + OPENCODE_CLI_DIST: root, + }) } async function archive(bin: string, target: string, binary: string, directory: string) { diff --git a/packages/cli/src/services/updater.ts b/packages/cli/src/services/updater.ts index b1a85db1fd8..689b235c323 100644 --- a/packages/cli/src/services/updater.ts +++ b/packages/cli/src/services/updater.ts @@ -7,7 +7,7 @@ import { parse, type ParseError } from "jsonc-parser" import path from "node:path" import { action, parseReleaseVersion, type Policy } from "./updater-action" -export const methods = ["curl", "npm", "pnpm", "bun", "yarn"] as const +export const methods = ["curl", "npm", "pnpm", "bun", "yarn", "brew"] as const export type Method = (typeof methods)[number] export type RunResult = { readonly type: "available" | "installed"; readonly version: string } export type CheckResult = RunResult | { readonly type: "unavailable"; readonly message: string } @@ -96,6 +96,13 @@ const make = Effect.gen(function* () { process.platform === "win32" ? "opencode.exe" : "opencode", ) if (path.resolve(process.execPath) === path.resolve(binary)) 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 (!installedPackage) return const checks: ReadonlyArray<{ method: Method; command: string[] }> = [ @@ -113,7 +120,7 @@ const make = Effect.gen(function* () { }) const removal = (method: Method) => { - if (method === "curl" || !installedPackage) return undefined + if (method === "curl" || method === "brew" || !installedPackage) return undefined const commands = { npm: ["npm", "uninstall", "--global", installedPackage], pnpm: ["pnpm", "remove", "--global", installedPackage], @@ -133,11 +140,12 @@ const make = Effect.gen(function* () { } } - const release = Effect.fnUntraced(function* () { + const release = Effect.fnUntraced(function* (method?: Method) { + const distribution = method === "brew" ? "homebrew" : "npm" const response = yield* Effect.tryPromise({ try: (signal) => fetch( - `https://opencode.ai/update/api/${encodeURIComponent(channel)}/${encodeURIComponent(OPENCODE_ARTIFACT)}/npm?current=${encodeURIComponent(OPENCODE_VERSION)}`, + `https://opencode.ai/update/api/${encodeURIComponent(channel)}/${encodeURIComponent(OPENCODE_ARTIFACT)}/${distribution}?current=${encodeURIComponent(OPENCODE_VERSION)}`, { signal: AbortSignal.any([signal, AbortSignal.timeout(10_000)]), }, @@ -153,7 +161,11 @@ const make = Effect.gen(function* () { return { package: data.metadata.package, version: data.version } }) - const latest = () => release().pipe(Effect.map((data) => data.version)) + const latest = () => + method().pipe( + Effect.flatMap(release), + Effect.map((data) => data.version), + ) const temporaryDirectory = (prefix: string) => Effect.acquireRelease(fs.makeTempDirectory({ directory: global.cache, prefix }), (directory) => @@ -163,12 +175,12 @@ 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()).package + const packageName = (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}.`)) } - const commands: Record, string[]> = { + const commands: Record, string[]> = { // Keep the old package: uninstalling it can unlink the replacement command. npm: [ "npm", @@ -202,6 +214,7 @@ const make = Effect.gen(function* () { if (download.code !== 0) return download return yield* exec(["bash", installer, "--version", version, "--no-modify-path"], "5 minutes") } + if (method === "brew") return yield* exec(["brew", "upgrade", packageName], "5 minutes") return yield* exec(commands[method], "5 minutes") }), ).pipe(Effect.mapError((cause) => new Error(`Failed to update with ${method}`, { cause }))) diff --git a/packages/cli/test/upgrade.test.ts b/packages/cli/test/upgrade.test.ts index a9b773db5a0..a8714b716be 100644 --- a/packages/cli/test/upgrade.test.ts +++ b/packages/cli/test/upgrade.test.ts @@ -50,7 +50,7 @@ describe("upgrade command", () => { }) test("rejects unsupported methods before attempting an upgrade", async () => { - const result = await cli(["--method", "brew"]) + const result = await cli(["--method", "apt"]) expect(result.exitCode).not.toBe(0) expect(result.events).toEqual([]) })