beta.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #!/usr/bin/env bun
  2. import { Script } from "@opencode-ai/script"
  3. import { parseArgs } from "util"
  4. interface PR {
  5. number: number
  6. title: string
  7. author: { login: string }
  8. }
  9. interface RunResult {
  10. exitCode: number
  11. stdout: string
  12. stderr: string
  13. }
  14. interface FailedPR {
  15. number: number
  16. title: string
  17. reason: string
  18. }
  19. async function postToDiscord(failures: FailedPR[], webhookUrl?: string) {
  20. const url = webhookUrl || process.env.DISCORD_ISSUES_WEBHOOK_URL
  21. if (!url) {
  22. console.log("Warning: No Discord webhook URL provided, skipping notification")
  23. return
  24. }
  25. const message = `**Beta Branch Merge Failures**
  26. The following team PRs failed to merge into the beta branch:
  27. ${failures.map((f) => `- **#${f.number}**: ${f.title} - ${f.reason}`).join("\n")}
  28. Please resolve these conflicts manually.`
  29. const content = JSON.stringify({ content: message })
  30. const response = await fetch(url, {
  31. method: "POST",
  32. headers: { "Content-Type": "application/json" },
  33. body: content,
  34. })
  35. if (!response.ok) {
  36. console.error("Failed to post to Discord:", await response.text())
  37. } else {
  38. console.log("Posted failures to Discord")
  39. }
  40. }
  41. async function main() {
  42. const { values } = parseArgs({
  43. args: Bun.argv.slice(2),
  44. options: {
  45. "discord-webhook": { type: "string", short: "d" },
  46. },
  47. })
  48. const discordWebhook = values["discord-webhook"] as string | undefined
  49. console.log("Fetching open PRs from team members...")
  50. const allPrs: PR[] = []
  51. for (const member of Script.team) {
  52. const result = await $`gh pr list --state open --author ${member} --json number,title,author --limit 100`.nothrow()
  53. if (result.exitCode !== 0) continue
  54. const memberPrs: PR[] = JSON.parse(result.stdout)
  55. allPrs.push(...memberPrs)
  56. }
  57. const seen = new Set<number>()
  58. const prs = allPrs.filter((pr) => {
  59. if (seen.has(pr.number)) return false
  60. seen.add(pr.number)
  61. return true
  62. })
  63. console.log(`Found ${prs.length} open PRs from team members`)
  64. if (prs.length === 0) {
  65. console.log("No team PRs to merge")
  66. return
  67. }
  68. console.log("Fetching latest dev branch...")
  69. const fetchDev = await $`git fetch origin dev`.nothrow()
  70. if (fetchDev.exitCode !== 0) {
  71. throw new Error(`Failed to fetch dev branch: ${fetchDev.stderr}`)
  72. }
  73. console.log("Checking out beta branch...")
  74. const checkoutBeta = await $`git checkout -B beta origin/dev`.nothrow()
  75. if (checkoutBeta.exitCode !== 0) {
  76. throw new Error(`Failed to checkout beta branch: ${checkoutBeta.stderr}`)
  77. }
  78. const applied: number[] = []
  79. const failed: FailedPR[] = []
  80. for (const pr of prs) {
  81. console.log(`\nProcessing PR #${pr.number}: ${pr.title}`)
  82. console.log(" Fetching PR head...")
  83. const fetch = await run(["git", "fetch", "origin", `pull/${pr.number}/head:pr/${pr.number}`])
  84. if (fetch.exitCode !== 0) {
  85. console.log(` Failed to fetch: ${fetch.stderr}`)
  86. failed.push({ number: pr.number, title: pr.title, reason: "Fetch failed" })
  87. continue
  88. }
  89. console.log(" Merging...")
  90. const merge = await run(["git", "merge", "--no-commit", "--no-ff", `pr/${pr.number}`])
  91. if (merge.exitCode !== 0) {
  92. console.log(" Failed to merge (conflicts)")
  93. await $`git merge --abort`.nothrow()
  94. await $`git checkout -- .`.nothrow()
  95. await $`git clean -fd`.nothrow()
  96. failed.push({ number: pr.number, title: pr.title, reason: "Merge conflicts" })
  97. continue
  98. }
  99. const mergeHead = await $`git rev-parse -q --verify MERGE_HEAD`.nothrow()
  100. if (mergeHead.exitCode !== 0) {
  101. console.log(" No changes, skipping")
  102. continue
  103. }
  104. const add = await $`git add -A`.nothrow()
  105. if (add.exitCode !== 0) {
  106. console.log(" Failed to stage changes")
  107. failed.push({ number: pr.number, title: pr.title, reason: "Staging failed" })
  108. continue
  109. }
  110. const commitMsg = `Apply PR #${pr.number}: ${pr.title}`
  111. const commit = await run(["git", "commit", "-m", commitMsg])
  112. if (commit.exitCode !== 0) {
  113. console.log(` Failed to commit: ${commit.stderr}`)
  114. failed.push({ number: pr.number, title: pr.title, reason: "Commit failed" })
  115. continue
  116. }
  117. console.log(" Applied successfully")
  118. applied.push(pr.number)
  119. }
  120. console.log("\n--- Summary ---")
  121. console.log(`Applied: ${applied.length} PRs`)
  122. applied.forEach((num) => console.log(` - PR #${num}`))
  123. if (failed.length > 0) {
  124. console.log(`Failed: ${failed.length} PRs`)
  125. failed.forEach((f) => console.log(` - PR #${f.number}: ${f.reason}`))
  126. await postToDiscord(failed, discordWebhook)
  127. throw new Error(`${failed.length} PR(s) failed to merge. Check Discord for details.`)
  128. }
  129. console.log("\nForce pushing beta branch...")
  130. const push = await $`git push origin beta --force --no-verify`.nothrow()
  131. if (push.exitCode !== 0) {
  132. throw new Error(`Failed to push beta branch: ${push.stderr}`)
  133. }
  134. console.log("Successfully synced beta branch")
  135. }
  136. main().catch((err) => {
  137. console.error("Error:", err)
  138. process.exit(1)
  139. })
  140. async function run(args: string[], stdin?: Uint8Array): Promise<RunResult> {
  141. const proc = Bun.spawn(args, {
  142. stdin: stdin ?? "inherit",
  143. stdout: "pipe",
  144. stderr: "pipe",
  145. })
  146. const exitCode = await proc.exited
  147. const stdout = await new Response(proc.stdout).text()
  148. const stderr = await new Response(proc.stderr).text()
  149. return { exitCode, stdout, stderr }
  150. }
  151. function $(strings: TemplateStringsArray, ...values: unknown[]) {
  152. const cmd = strings.reduce((acc, str, i) => acc + str + (values[i] ?? ""), "")
  153. return {
  154. async nothrow() {
  155. const proc = Bun.spawn(cmd.split(" "), {
  156. stdout: "pipe",
  157. stderr: "pipe",
  158. })
  159. const exitCode = await proc.exited
  160. const stdout = await new Response(proc.stdout).text()
  161. const stderr = await new Response(proc.stderr).text()
  162. return { exitCode, stdout, stderr }
  163. },
  164. }
  165. }