changelog.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. #!/usr/bin/env bun
  2. import { $ } from "bun"
  3. import { createOpencode } from "@opencode-ai/sdk"
  4. import { parseArgs } from "util"
  5. export const team = [
  6. "actions-user",
  7. "opencode",
  8. "rekram1-node",
  9. "thdxr",
  10. "kommander",
  11. "jayair",
  12. "fwang",
  13. "adamdotdevin",
  14. "iamdavidhill",
  15. "opencode-agent[bot]",
  16. ]
  17. export async function getLatestRelease() {
  18. return fetch("https://api.github.com/repos/anomalyco/opencode/releases/latest")
  19. .then((res) => {
  20. if (!res.ok) throw new Error(res.statusText)
  21. return res.json()
  22. })
  23. .then((data: any) => data.tag_name.replace(/^v/, ""))
  24. }
  25. type Commit = {
  26. hash: string
  27. author: string | null
  28. message: string
  29. areas: Set<string>
  30. }
  31. export async function getCommits(from: string, to: string): Promise<Commit[]> {
  32. const fromRef = from.startsWith("v") ? from : `v${from}`
  33. const toRef = to === "HEAD" ? to : to.startsWith("v") ? to : `v${to}`
  34. // Get commit data with GitHub usernames from the API
  35. const compare =
  36. await $`gh api "/repos/anomalyco/opencode/compare/${fromRef}...${toRef}" --jq '.commits[] | {sha: .sha, login: .author.login, message: .commit.message}'`.text()
  37. const commitData = new Map<string, { login: string | null; message: string }>()
  38. for (const line of compare.split("\n").filter(Boolean)) {
  39. const data = JSON.parse(line) as { sha: string; login: string | null; message: string }
  40. commitData.set(data.sha, { login: data.login, message: data.message.split("\n")[0] ?? "" })
  41. }
  42. // Get commits that touch the relevant packages
  43. const log =
  44. await $`git log ${fromRef}..${toRef} --oneline --format="%H" -- packages/opencode packages/sdk packages/plugin packages/desktop packages/app sdks/vscode packages/extensions github`.text()
  45. const hashes = log.split("\n").filter(Boolean)
  46. const commits: Commit[] = []
  47. for (const hash of hashes) {
  48. const data = commitData.get(hash)
  49. if (!data) continue
  50. const message = data.message
  51. if (message.match(/^(ignore:|test:|chore:|ci:|release:)/i)) continue
  52. const files = await $`git diff-tree --no-commit-id --name-only -r ${hash}`.text()
  53. const areas = new Set<string>()
  54. for (const file of files.split("\n").filter(Boolean)) {
  55. if (file.startsWith("packages/opencode/src/cli/cmd/")) areas.add("tui")
  56. else if (file.startsWith("packages/opencode/")) areas.add("core")
  57. else if (file.startsWith("packages/desktop/src-tauri/")) areas.add("tauri")
  58. else if (file.startsWith("packages/desktop/")) areas.add("app")
  59. else if (file.startsWith("packages/app/")) areas.add("app")
  60. else if (file.startsWith("packages/sdk/")) areas.add("sdk")
  61. else if (file.startsWith("packages/plugin/")) areas.add("plugin")
  62. else if (file.startsWith("packages/extensions/")) areas.add("extensions/zed")
  63. else if (file.startsWith("sdks/vscode/")) areas.add("extensions/vscode")
  64. else if (file.startsWith("github/")) areas.add("github")
  65. }
  66. if (areas.size === 0) continue
  67. commits.push({
  68. hash: hash.slice(0, 7),
  69. author: data.login,
  70. message,
  71. areas,
  72. })
  73. }
  74. return filterRevertedCommits(commits)
  75. }
  76. function filterRevertedCommits(commits: Commit[]): Commit[] {
  77. const revertPattern = /^Revert "(.+)"$/
  78. const seen = new Map<string, Commit>()
  79. for (const commit of commits) {
  80. const match = commit.message.match(revertPattern)
  81. if (match) {
  82. // It's a revert - remove the original if we've seen it
  83. const original = match[1]!
  84. if (seen.has(original)) seen.delete(original)
  85. else seen.set(commit.message, commit) // Keep revert if original not in range
  86. } else {
  87. // Regular commit - remove if its revert exists, otherwise add
  88. const revertMsg = `Revert "${commit.message}"`
  89. if (seen.has(revertMsg)) seen.delete(revertMsg)
  90. else seen.set(commit.message, commit)
  91. }
  92. }
  93. return [...seen.values()]
  94. }
  95. const sections = {
  96. core: "Core",
  97. tui: "TUI",
  98. app: "Desktop",
  99. tauri: "Desktop",
  100. sdk: "SDK",
  101. plugin: "SDK",
  102. "extensions/zed": "Extensions",
  103. "extensions/vscode": "Extensions",
  104. github: "Extensions",
  105. } as const
  106. function getSection(areas: Set<string>): string {
  107. // Priority order for multi-area commits
  108. const priority = ["core", "tui", "app", "tauri", "sdk", "plugin", "extensions/zed", "extensions/vscode", "github"]
  109. for (const area of priority) {
  110. if (areas.has(area)) return sections[area as keyof typeof sections]
  111. }
  112. return "Core"
  113. }
  114. async function summarizeCommit(opencode: Awaited<ReturnType<typeof createOpencode>>, message: string): Promise<string> {
  115. console.log("summarizing commit:", message)
  116. const session = await opencode.client.session.create()
  117. const result = await opencode.client.session
  118. .prompt({
  119. path: { id: session.data!.id },
  120. body: {
  121. model: { providerID: "opencode", modelID: "claude-sonnet-4-5" },
  122. tools: {
  123. "*": false,
  124. },
  125. parts: [
  126. {
  127. type: "text",
  128. text: `Summarize this commit message for a changelog entry. Return ONLY a single line summary starting with a capital letter. Be concise but specific. If the commit message is already well-written, just clean it up (capitalize, fix typos, proper grammar). Do not include any prefixes like "fix:" or "feat:".
  129. Commit: ${message}`,
  130. },
  131. ],
  132. },
  133. signal: AbortSignal.timeout(120_000),
  134. })
  135. .then((x) => x.data?.parts?.find((y) => y.type === "text")?.text ?? message)
  136. return result.trim()
  137. }
  138. export async function generateChangelog(commits: Commit[], opencode: Awaited<ReturnType<typeof createOpencode>>) {
  139. // Summarize commits in parallel with max 10 concurrent requests
  140. const BATCH_SIZE = 10
  141. const summaries: string[] = []
  142. for (let i = 0; i < commits.length; i += BATCH_SIZE) {
  143. const batch = commits.slice(i, i + BATCH_SIZE)
  144. const results = await Promise.all(batch.map((c) => summarizeCommit(opencode, c.message)))
  145. summaries.push(...results)
  146. }
  147. const grouped = new Map<string, string[]>()
  148. for (let i = 0; i < commits.length; i++) {
  149. const commit = commits[i]!
  150. const section = getSection(commit.areas)
  151. const attribution = commit.author && !team.includes(commit.author) ? ` (@${commit.author})` : ""
  152. const entry = `- ${summaries[i]}${attribution}`
  153. if (!grouped.has(section)) grouped.set(section, [])
  154. grouped.get(section)!.push(entry)
  155. }
  156. const sectionOrder = ["Core", "TUI", "Desktop", "SDK", "Extensions"]
  157. const lines: string[] = []
  158. for (const section of sectionOrder) {
  159. const entries = grouped.get(section)
  160. if (!entries || entries.length === 0) continue
  161. lines.push(`## ${section}`)
  162. lines.push(...entries)
  163. }
  164. return lines
  165. }
  166. export async function getContributors(from: string, to: string) {
  167. const fromRef = from.startsWith("v") ? from : `v${from}`
  168. const toRef = to === "HEAD" ? to : to.startsWith("v") ? to : `v${to}`
  169. const compare =
  170. await $`gh api "/repos/anomalyco/opencode/compare/${fromRef}...${toRef}" --jq '.commits[] | {login: .author.login, message: .commit.message}'`.text()
  171. const contributors = new Map<string, Set<string>>()
  172. for (const line of compare.split("\n").filter(Boolean)) {
  173. const { login, message } = JSON.parse(line) as { login: string | null; message: string }
  174. const title = message.split("\n")[0] ?? ""
  175. if (title.match(/^(ignore:|test:|chore:|ci:|release:)/i)) continue
  176. if (login && !team.includes(login)) {
  177. if (!contributors.has(login)) contributors.set(login, new Set())
  178. contributors.get(login)!.add(title)
  179. }
  180. }
  181. return contributors
  182. }
  183. export async function buildNotes(from: string, to: string) {
  184. const commits = await getCommits(from, to)
  185. if (commits.length === 0) {
  186. return []
  187. }
  188. console.log("generating changelog since " + from)
  189. const opencode = await createOpencode({ port: 5044 })
  190. const notes: string[] = []
  191. try {
  192. const lines = await generateChangelog(commits, opencode)
  193. notes.push(...lines)
  194. console.log("---- Generated Changelog ----")
  195. console.log(notes.join("\n"))
  196. console.log("-----------------------------")
  197. } catch (error) {
  198. if (error instanceof Error && error.name === "TimeoutError") {
  199. console.log("Changelog generation timed out, using raw commits")
  200. for (const commit of commits) {
  201. const attribution = commit.author && !team.includes(commit.author) ? ` (@${commit.author})` : ""
  202. notes.push(`- ${commit.message}${attribution}`)
  203. }
  204. } else {
  205. throw error
  206. }
  207. } finally {
  208. opencode.server.close()
  209. }
  210. const contributors = await getContributors(from, to)
  211. if (contributors.size > 0) {
  212. notes.push("")
  213. notes.push(`**Thank you to ${contributors.size} community contributor${contributors.size > 1 ? "s" : ""}:**`)
  214. for (const [username, userCommits] of contributors) {
  215. notes.push(`- @${username}:`)
  216. for (const c of userCommits) {
  217. notes.push(` - ${c}`)
  218. }
  219. }
  220. }
  221. return notes
  222. }
  223. // CLI entrypoint
  224. if (import.meta.main) {
  225. const { values } = parseArgs({
  226. args: Bun.argv.slice(2),
  227. options: {
  228. from: { type: "string", short: "f" },
  229. to: { type: "string", short: "t", default: "HEAD" },
  230. help: { type: "boolean", short: "h", default: false },
  231. },
  232. })
  233. if (values.help) {
  234. console.log(`
  235. Usage: bun script/changelog.ts [options]
  236. Options:
  237. -f, --from <version> Starting version (default: latest GitHub release)
  238. -t, --to <ref> Ending ref (default: HEAD)
  239. -h, --help Show this help message
  240. Examples:
  241. bun script/changelog.ts # Latest release to HEAD
  242. bun script/changelog.ts --from 1.0.200 # v1.0.200 to HEAD
  243. bun script/changelog.ts -f 1.0.200 -t 1.0.205
  244. `)
  245. process.exit(0)
  246. }
  247. const to = values.to!
  248. const from = values.from ?? (await getLatestRelease())
  249. console.log(`Generating changelog: v${from} -> ${to}\n`)
  250. const notes = await buildNotes(from, to)
  251. console.log("\n=== Final Notes ===")
  252. console.log(notes.join("\n"))
  253. }