changelog.ts 10 KB

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