publish-start.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. #!/usr/bin/env bun
  2. import { $ } from "bun"
  3. import { createOpencode } from "@opencode-ai/sdk"
  4. import { Script } from "@opencode-ai/script"
  5. const notes = [] as string[]
  6. const team = [
  7. "actions-user",
  8. "opencode",
  9. "rekram1-node",
  10. "thdxr",
  11. "kommander",
  12. "jayair",
  13. "fwang",
  14. "adamdotdevin",
  15. "iamdavidhill",
  16. "opencode-agent[bot]",
  17. ]
  18. function getAreaFromPath(file: string): string {
  19. if (file.startsWith("packages/")) {
  20. const parts = file.replace("packages/", "").split("/")
  21. if (parts[0] === "extensions" && parts[1]) return `extensions/${parts[1]}`
  22. return parts[0] || "other"
  23. }
  24. if (file.startsWith("sdks/")) {
  25. const name = file.replace("sdks/", "").split("/")[0] || "other"
  26. return `extensions/${name}`
  27. }
  28. const rootDir = file.split("/")[0]
  29. if (rootDir && !rootDir.includes(".")) return rootDir
  30. return "other"
  31. }
  32. console.log("=== publishing ===\n")
  33. if (!Script.preview) {
  34. const previous = await fetch("https://registry.npmjs.org/opencode-ai/latest")
  35. .then((res) => {
  36. if (!res.ok) throw new Error(res.statusText)
  37. return res.json()
  38. })
  39. .then((data: any) => data.version)
  40. // Fetch commit authors from GitHub API (hash -> login)
  41. const compare =
  42. await $`gh api "/repos/sst/opencode/compare/v${previous}...HEAD" --jq '.commits[] | {sha: .sha, login: .author.login, message: .commit.message}'`.text()
  43. const authorByHash = new Map<string, string>()
  44. const contributors = new Map<string, string[]>()
  45. for (const line of compare.split("\n").filter(Boolean)) {
  46. const { sha, login, message } = JSON.parse(line) as { sha: string; login: string | null; message: string }
  47. const shortHash = sha.slice(0, 7)
  48. if (login) authorByHash.set(shortHash, login)
  49. const title = message.split("\n")[0] || ""
  50. if (title.match(/^(ignore:|test:|chore:|ci:|release:)/i)) continue
  51. if (login && !team.includes(login)) {
  52. if (!contributors.has(login)) contributors.set(login, [])
  53. contributors.get(login)?.push(title)
  54. }
  55. }
  56. // Batch-fetch files for all commits (hash -> areas)
  57. const diffLog = await $`git log v${previous}..HEAD --name-only --format="%h"`.text()
  58. const areasByHash = new Map<string, Set<string>>()
  59. let currentHash: string | null = null
  60. for (const rawLine of diffLog.split("\n")) {
  61. const line = rawLine.trim()
  62. if (!line) continue
  63. if (/^[0-9a-f]{7}$/i.test(line)) {
  64. currentHash = line
  65. if (!areasByHash.has(currentHash)) areasByHash.set(currentHash, new Set())
  66. continue
  67. }
  68. if (currentHash) {
  69. areasByHash.get(currentHash)!.add(getAreaFromPath(line))
  70. }
  71. }
  72. // Build commit lines with author and areas
  73. const log = await $`git log v${previous}..HEAD --oneline --format="%h %s"`.text()
  74. const commitLines = log.split("\n").filter((line) => line && !line.match(/^\w+ (ignore:|test:|chore:|ci:|release:)/i))
  75. const commitsWithMeta = commitLines
  76. .map((line) => {
  77. const hash = line.split(" ")[0]
  78. if (!hash) return null
  79. const author = authorByHash.get(hash)
  80. const authorStr = author ? ` [author: ${author}]` : ""
  81. const areas = areasByHash.get(hash)
  82. const areaStr = areas && areas.size > 0 ? ` [areas: ${[...areas].join(", ")}]` : " [areas: other]"
  83. return `${line}${authorStr}${areaStr}`
  84. })
  85. .filter(Boolean) as string[]
  86. const commits = commitsWithMeta.join("\n")
  87. const opencode = await createOpencode()
  88. const session = await opencode.client.session.create()
  89. console.log("generating changelog since " + previous)
  90. const raw = await opencode.client.session
  91. .prompt({
  92. path: {
  93. id: session.data!.id,
  94. },
  95. body: {
  96. model: {
  97. providerID: "opencode",
  98. modelID: "gemini-3-flash",
  99. },
  100. parts: [
  101. {
  102. type: "text",
  103. text: `
  104. Analyze these commits and generate a changelog of all notable user facing changes, grouped by area.
  105. Each commit below includes:
  106. - [author: username] showing the GitHub username of the commit author
  107. - [areas: ...] showing which areas of the codebase were modified
  108. Commits between ${previous} and HEAD:
  109. ${commits}
  110. Group the changes into these categories based on the [areas: ...] tags (omit any category with no changes):
  111. - **TUI**: Changes to "opencode" area (the terminal/CLI interface)
  112. - **Desktop**: Changes to "desktop" or "tauri" areas (the desktop application)
  113. - **SDK**: Changes to "sdk" or "plugin" areas (the SDK and plugin system)
  114. - **Extensions**: Changes to "extensions/zed", "extensions/vscode", or "github" areas (editor extensions and GitHub Action)
  115. - **Other**: Any user-facing changes that don't fit the above categories
  116. Excluded areas (omit these entirely unless they contain user-facing changes like refactors that may affect behavior):
  117. - "nix", "infra", "script" - CI/build infrastructure
  118. - "ui", "docs", "web", "console", "enterprise", "function", "util", "identity", "slack" - internal packages
  119. Rules:
  120. - Use the [areas: ...] tags to determine the correct category. If a commit touches multiple areas, put it in the most relevant user-facing category.
  121. - ONLY include commits that have user-facing impact. Omit purely internal changes (CI, build scripts, internal tooling).
  122. - However, DO include refactors that touch user-facing code - refactors can introduce bugs or change behavior.
  123. - Do NOT make general statements about "improvements", be very specific about what was changed.
  124. - For commits that are already well-written and descriptive, avoid rewording them. Simply capitalize the first letter, fix any misspellings, and ensure proper English grammar.
  125. - DO NOT read any other commits than the ones listed above (THIS IS IMPORTANT TO AVOID DUPLICATING THINGS IN OUR CHANGELOG).
  126. - If a commit was made and then reverted do not include it in the changelog. If the commits only include a revert but not the original commit, then include the revert in the changelog.
  127. - Omit categories that have no changes.
  128. - For community contributors: if the [author: username] is NOT in the team list, add (@username) at the end of the changelog entry. This is REQUIRED for all non-team contributors.
  129. - The team members are: ${team.join(", ")}. Do NOT add @ mentions for team members.
  130. IMPORTANT: ONLY return the grouped changelog, do not include any other information. Do not include a preamble like "Based on my analysis..." or "Here is the changelog..."
  131. <example>
  132. ## TUI
  133. - Added experimental support for the Ty language server (@OpeOginni)
  134. - Added /fork slash command for keyboard-friendly session forking (@ariane-emory)
  135. - Increased retry attempts for failed requests
  136. - Fixed model validation before executing slash commands (@devxoul)
  137. ## Desktop
  138. - Added shell mode support
  139. - Fixed prompt history navigation and optimistic prompt duplication
  140. - Disabled pinch-to-zoom on Linux (@Brendonovich)
  141. ## Extensions
  142. - Added OIDC_BASE_URL support for custom GitHub App installations (@elithrar)
  143. </example>
  144. `,
  145. },
  146. ],
  147. },
  148. })
  149. .then((x) => x.data?.parts?.find((y) => y.type === "text")?.text)
  150. for (const line of raw?.split("\n") ?? []) {
  151. if (line.startsWith("## ")) {
  152. if (notes.length > 0) notes.push("")
  153. notes.push(line)
  154. } else if (line.startsWith("- ")) {
  155. notes.push(line)
  156. }
  157. }
  158. console.log("---- Generated Changelog ----")
  159. console.log(notes.join("\n"))
  160. console.log("-----------------------------")
  161. opencode.server.close()
  162. if (contributors.size > 0) {
  163. notes.push("")
  164. notes.push(`**Thank you to ${contributors.size} community contributor${contributors.size > 1 ? "s" : ""}:**`)
  165. for (const username of contributors.keys()) {
  166. notes.push(`- @${username}`)
  167. }
  168. }
  169. }
  170. const pkgjsons = await Array.fromAsync(
  171. new Bun.Glob("**/package.json").scan({
  172. absolute: true,
  173. }),
  174. ).then((arr) => arr.filter((x) => !x.includes("node_modules") && !x.includes("dist")))
  175. for (const file of pkgjsons) {
  176. let pkg = await Bun.file(file).text()
  177. pkg = pkg.replaceAll(/"version": "[^"]+"/g, `"version": "${Script.version}"`)
  178. console.log("updated:", file)
  179. await Bun.file(file).write(pkg)
  180. }
  181. const extensionToml = new URL("../packages/extensions/zed/extension.toml", import.meta.url).pathname
  182. let toml = await Bun.file(extensionToml).text()
  183. toml = toml.replace(/^version = "[^"]+"/m, `version = "${Script.version}"`)
  184. toml = toml.replaceAll(/releases\/download\/v[^/]+\//g, `releases/download/v${Script.version}/`)
  185. console.log("updated:", extensionToml)
  186. await Bun.file(extensionToml).write(toml)
  187. await $`bun install`
  188. console.log("\n=== opencode ===\n")
  189. await import(`../packages/opencode/script/publish.ts`)
  190. console.log("\n=== sdk ===\n")
  191. await import(`../packages/sdk/js/script/publish.ts`)
  192. console.log("\n=== plugin ===\n")
  193. await import(`../packages/plugin/script/publish.ts`)
  194. const dir = new URL("..", import.meta.url).pathname
  195. process.chdir(dir)
  196. if (!Script.preview) {
  197. await $`git commit -am "release: v${Script.version}"`
  198. await $`git tag v${Script.version}`
  199. await $`git fetch origin`
  200. await $`git cherry-pick HEAD..origin/dev`.nothrow()
  201. await $`git push origin HEAD --tags --no-verify --force-with-lease`
  202. await new Promise((resolve) => setTimeout(resolve, 5_000))
  203. await $`gh release create v${Script.version} -d --title "v${Script.version}" --notes ${notes.join("\n") || "No notable changes"} ./packages/opencode/dist/*.zip ./packages/opencode/dist/*.tar.gz`
  204. const release = await $`gh release view v${Script.version} --json id,tagName`.json()
  205. if (process.env.GITHUB_OUTPUT) {
  206. await Bun.write(process.env.GITHUB_OUTPUT, `releaseId=${release.id}\ntagName=${release.tagName}\n`)
  207. }
  208. }