2
0

beta.ts 5.5 KB

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