changelog.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. #!/usr/bin/env bun
  2. import { $ } from "bun"
  3. import { createOpencode } from "@opencode-ai/sdk"
  4. const TEAM = [
  5. "actions-user",
  6. "opencode",
  7. "rekram1-node",
  8. "thdxr",
  9. "kommander",
  10. "jayair",
  11. "fwang",
  12. "adamdotdevin",
  13. "iamdavidhill",
  14. "opencode-agent[bot]",
  15. ]
  16. const MODEL = "gemini-3-flash"
  17. function getAreaFromPath(file: string): string {
  18. if (file.startsWith("packages/")) {
  19. const parts = file.replace("packages/", "").split("/")
  20. if (parts[0] === "extensions" && parts[1]) return `extensions/${parts[1]}`
  21. return parts[0] || "other"
  22. }
  23. if (file.startsWith("sdks/")) {
  24. const name = file.replace("sdks/", "").split("/")[0] || "other"
  25. return `extensions/${name}`
  26. }
  27. const rootDir = file.split("/")[0]
  28. if (rootDir && !rootDir.includes(".")) return rootDir
  29. return "other"
  30. }
  31. function buildPrompt(previous: string, commits: string): string {
  32. return `
  33. Analyze these commits and generate a changelog of all notable user facing changes, grouped by area.
  34. Each commit below includes:
  35. - [author: username] showing the GitHub username of the commit author
  36. - [areas: ...] showing which areas of the codebase were modified
  37. Commits between ${previous} and HEAD:
  38. ${commits}
  39. Group the changes into these categories based on the [areas: ...] tags (omit any category with no changes):
  40. - **TUI**: Changes to "opencode" area (the terminal/CLI interface)
  41. - **Desktop**: Changes to "desktop" or "tauri" areas (the desktop application)
  42. - **SDK**: Changes to "sdk" or "plugin" areas (the SDK and plugin system)
  43. - **Extensions**: Changes to "extensions/zed", "extensions/vscode", or "github" areas (editor extensions and GitHub Action)
  44. - **Other**: Any user-facing changes that don't fit the above categories
  45. Excluded areas (omit these entirely unless they contain user-facing changes like refactors that may affect behavior):
  46. - "nix", "infra", "script" - CI/build infrastructure
  47. - "ui", "docs", "web", "console", "enterprise", "function", "util", "identity", "slack" - internal packages
  48. Rules:
  49. - Use the [areas: ...] tags to determine the correct category. If a commit touches multiple areas, put it in the most relevant user-facing category.
  50. - ONLY include commits that have user-facing impact. Omit purely internal changes (CI, build scripts, internal tooling).
  51. - However, DO include refactors that touch user-facing code - refactors can introduce bugs or change behavior.
  52. - Do NOT make general statements about "improvements", be very specific about what was changed.
  53. - 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.
  54. - DO NOT read any other commits than the ones listed above (THIS IS IMPORTANT TO AVOID DUPLICATING THINGS IN OUR CHANGELOG).
  55. - 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.
  56. - Omit categories that have no changes.
  57. - 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.
  58. - The team members are: ${TEAM.join(", ")}. Do NOT add @ mentions for team members.
  59. 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..."
  60. <example>
  61. ## TUI
  62. - Added experimental support for the Ty language server (@OpeOginni)
  63. - Added /fork slash command for keyboard-friendly session forking (@ariane-emory)
  64. - Increased retry attempts for failed requests
  65. - Fixed model validation before executing slash commands (@devxoul)
  66. ## Desktop
  67. - Added shell mode support
  68. - Fixed prompt history navigation and optimistic prompt duplication
  69. - Disabled pinch-to-zoom on Linux (@Brendonovich)
  70. ## Extensions
  71. - Added OIDC_BASE_URL support for custom GitHub App installations (@elithrar)
  72. </example>
  73. `
  74. }
  75. function parseChangelog(raw: string): string[] {
  76. const lines: string[] = []
  77. for (const line of raw.split("\n")) {
  78. if (line.startsWith("## ")) {
  79. if (lines.length > 0) lines.push("")
  80. lines.push(line)
  81. } else if (line.startsWith("- ")) {
  82. lines.push(line)
  83. }
  84. }
  85. return lines
  86. }
  87. function formatContributors(contributors: Map<string, string[]>): string[] {
  88. if (contributors.size === 0) return []
  89. const lines: string[] = []
  90. lines.push("")
  91. lines.push(`**Thank you to ${contributors.size} community contributor${contributors.size > 1 ? "s" : ""}:**`)
  92. for (const username of contributors.keys()) {
  93. lines.push(`- @${username}`)
  94. }
  95. return lines
  96. }
  97. /**
  98. * Generates a changelog for a release.
  99. *
  100. * Uses GitHub API for commit authors, git for file changes,
  101. * and Gemini Flash via opencode SDK for changelog generation.
  102. *
  103. * @param previous - The previous version tag (e.g. "v1.0.167")
  104. * @param current - The current ref (e.g. "HEAD" or "v1.0.168")
  105. * @returns Formatted changelog string ready for GitHub release notes
  106. */
  107. export async function generateChangelog(previous: string, current: string): Promise<string> {
  108. // Fetch commit authors from GitHub API (hash -> login)
  109. const compare =
  110. await $`gh api "/repos/sst/opencode/compare/${previous}...${current}" --jq '.commits[] | {sha: .sha, login: .author.login, message: .commit.message}'`
  111. .text()
  112. .catch(() => "")
  113. const authorByHash = new Map<string, string>()
  114. const contributors = new Map<string, string[]>()
  115. for (const line of compare.split("\n").filter(Boolean)) {
  116. const { sha, login, message } = JSON.parse(line) as { sha: string; login: string | null; message: string }
  117. if (login) authorByHash.set(sha, login)
  118. const title = message.split("\n")[0] || ""
  119. if (title.match(/^(ignore:|test:|chore:|ci:|release:)/i)) continue
  120. if (login && !TEAM.includes(login)) {
  121. if (!contributors.has(login)) contributors.set(login, [])
  122. contributors.get(login)?.push(title)
  123. }
  124. }
  125. function findAuthor(shortHash: string): string | undefined {
  126. for (const [sha, login] of authorByHash) {
  127. if (sha.startsWith(shortHash)) return login
  128. }
  129. }
  130. // Batch-fetch files for all commits (hash -> areas)
  131. const diffLog = await $`git log ${previous}..${current} --name-only --format="%h"`.text()
  132. const areasByHash = new Map<string, Set<string>>()
  133. let currentHash: string | null = null
  134. for (const rawLine of diffLog.split("\n")) {
  135. const line = rawLine.trim()
  136. if (!line) continue
  137. if (/^[0-9a-f]{7,}$/i.test(line) && !line.includes("/")) {
  138. currentHash = line
  139. if (!areasByHash.has(currentHash)) areasByHash.set(currentHash, new Set())
  140. continue
  141. }
  142. if (currentHash) {
  143. areasByHash.get(currentHash)!.add(getAreaFromPath(line))
  144. }
  145. }
  146. // Build commit lines with author and areas
  147. const log = await $`git log ${previous}..${current} --oneline --format="%h %s"`.text()
  148. const commitLines = log.split("\n").filter((line) => line && !line.match(/^\w+ (ignore:|test:|chore:|ci:|release:)/i))
  149. const commitsWithMeta = commitLines
  150. .map((line) => {
  151. const hash = line.split(" ")[0]
  152. if (!hash) return null
  153. const author = findAuthor(hash)
  154. const authorStr = author ? ` [author: ${author}]` : ""
  155. const areas = areasByHash.get(hash)
  156. const areaStr = areas && areas.size > 0 ? ` [areas: ${[...areas].join(", ")}]` : " [areas: other]"
  157. return `${line}${authorStr}${areaStr}`
  158. })
  159. .filter(Boolean) as string[]
  160. const commits = commitsWithMeta.join("\n")
  161. if (!commits.trim()) {
  162. console.error("No commits found to generate changelog")
  163. }
  164. // Generate changelog via LLM
  165. // different port to not conflict with dev running opencode
  166. let raw: string | undefined
  167. try {
  168. const opencode = await createOpencode({ port: 8192 })
  169. try {
  170. const session = await opencode.client.session.create()
  171. if (!session.data?.id) {
  172. console.error("Failed to create session:", session)
  173. throw new Error("Failed to create session")
  174. }
  175. const response = await opencode.client.session.prompt({
  176. path: { id: session.data.id },
  177. body: {
  178. model: { providerID: "opencode", modelID: MODEL },
  179. parts: [{ type: "text", text: buildPrompt(previous, commits) }],
  180. },
  181. })
  182. if (!response.data?.parts) {
  183. console.error("Empty response from LLM:", response)
  184. }
  185. raw = response.data?.parts?.find((y) => y.type === "text")?.text
  186. } finally {
  187. opencode.server.close()
  188. }
  189. } catch (err) {
  190. console.error("Failed to generate changelog via LLM:", err)
  191. }
  192. const notes = parseChangelog(raw ?? "")
  193. notes.push(...formatContributors(contributors))
  194. return notes.join("\n")
  195. }
  196. // Standalone runner for local testing
  197. if (import.meta.main) {
  198. const [previous, current] = process.argv.slice(2)
  199. if (!previous || !current) {
  200. console.error("Usage: bun script/changelog.ts <previous> <current>")
  201. console.error("Example: bun script/changelog.ts v1.0.167 HEAD")
  202. process.exit(1)
  203. }
  204. const changelog = await generateChangelog(previous, current)
  205. console.log(changelog)
  206. process.exit(0)
  207. }