beta.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #!/usr/bin/env bun
  2. import { $ } from "bun"
  3. interface PR {
  4. number: number
  5. title: string
  6. author: { login: string }
  7. labels: Array<{ name: string }>
  8. }
  9. interface FailedPR {
  10. number: number
  11. title: string
  12. reason: string
  13. }
  14. async function commentOnPR(prNumber: number, reason: string) {
  15. const body = `⚠️ **Blocking Beta Release**
  16. This PR cannot be merged into the beta branch due to: **${reason}**
  17. Please resolve this issue to include this PR in the next beta release.`
  18. try {
  19. await $`gh pr comment ${prNumber} --body ${body}`
  20. console.log(` Posted comment on PR #${prNumber}`)
  21. } catch (err) {
  22. console.log(` Failed to post comment on PR #${prNumber}: ${err}`)
  23. }
  24. }
  25. async function conflicts() {
  26. const out = await $`git diff --name-only --diff-filter=U`.text().catch(() => "")
  27. return out
  28. .split("\n")
  29. .map((x) => x.trim())
  30. .filter(Boolean)
  31. }
  32. async function cleanup() {
  33. try {
  34. await $`git merge --abort`
  35. } catch {}
  36. try {
  37. await $`git checkout -- .`
  38. } catch {}
  39. try {
  40. await $`git clean -fd`
  41. } catch {}
  42. }
  43. async function fix(pr: PR, files: string[], prs: PR[], applied: number[], idx: number) {
  44. console.log(` Trying to auto-resolve ${files.length} conflict(s) with opencode...`)
  45. const done =
  46. prs
  47. .filter((x) => applied.includes(x.number))
  48. .map((x) => `- #${x.number}: ${x.title}`)
  49. .join("\n") || "(none yet)"
  50. const next =
  51. prs
  52. .slice(idx + 1)
  53. .map((x) => `- #${x.number}: ${x.title}`)
  54. .join("\n") || "(none)"
  55. const prompt = [
  56. `Resolve the current git merge conflicts while merging PR #${pr.number} into the beta branch.`,
  57. `PR #${pr.number}: ${pr.title}`,
  58. `Only touch these files: ${files.join(", ")}.`,
  59. `Merged PRs on HEAD:\n${done}`,
  60. `Pending PRs after this one (context only):\n${next}`,
  61. "IMPORTANT: The conflict resolution must be consistent with already-merged PRs.",
  62. "Pending PRs are context only; do not introduce their changes unless they are already present on HEAD.",
  63. "Prefer already-merged PRs over the base branch when resolving stacked conflicts.",
  64. "If a PR already deleted a file/directory, do not re-add it, instead apply changes in the new semantic location.",
  65. "If a PR already changed an import, keep that change.",
  66. "Keep the merge in progress, do not abort the merge, and do not create a commit.",
  67. "When done, leave the working tree with no unmerged files.",
  68. ].join("\n")
  69. try {
  70. await $`opencode run -m opencode/gpt-5.3-codex ${prompt}`
  71. } catch (err) {
  72. console.log(` opencode failed: ${err}`)
  73. return false
  74. }
  75. const left = await conflicts()
  76. if (left.length > 0) {
  77. console.log(` Conflicts remain: ${left.join(", ")}`)
  78. return false
  79. }
  80. console.log(" Conflicts resolved with opencode")
  81. return true
  82. }
  83. async function main() {
  84. console.log("Fetching open PRs with beta label...")
  85. const stdout =
  86. await $`gh pr list --state open --draft=false --label beta --json number,title,author,labels --limit 100`.text()
  87. const prs: PR[] = JSON.parse(stdout).sort((a: PR, b: PR) => a.number - b.number)
  88. console.log(`Found ${prs.length} open PRs with beta label`)
  89. if (prs.length === 0) {
  90. console.log("No team PRs to merge")
  91. return
  92. }
  93. console.log("Fetching latest dev branch...")
  94. await $`git fetch origin dev`
  95. console.log("Checking out beta branch...")
  96. await $`git checkout -B beta origin/dev`
  97. const applied: number[] = []
  98. const failed: FailedPR[] = []
  99. for (const [idx, pr] of prs.entries()) {
  100. console.log(`\nProcessing PR #${pr.number}: ${pr.title}`)
  101. console.log(" Fetching PR head...")
  102. try {
  103. await $`git fetch origin pull/${pr.number}/head:pr/${pr.number}`
  104. } catch (err) {
  105. console.log(` Failed to fetch: ${err}`)
  106. failed.push({ number: pr.number, title: pr.title, reason: "Fetch failed" })
  107. await commentOnPR(pr.number, "Fetch failed")
  108. continue
  109. }
  110. console.log(" Merging...")
  111. try {
  112. await $`git merge --no-commit --no-ff pr/${pr.number}`
  113. } catch {
  114. const files = await conflicts()
  115. if (files.length > 0) {
  116. console.log(" Failed to merge (conflicts)")
  117. if (!(await fix(pr, files, prs, applied, idx))) {
  118. await cleanup()
  119. failed.push({ number: pr.number, title: pr.title, reason: "Merge conflicts" })
  120. await commentOnPR(pr.number, "Merge conflicts with dev branch")
  121. continue
  122. }
  123. } else {
  124. console.log(" Failed to merge")
  125. await cleanup()
  126. failed.push({ number: pr.number, title: pr.title, reason: "Merge failed" })
  127. await commentOnPR(pr.number, "Merge failed")
  128. continue
  129. }
  130. }
  131. try {
  132. await $`git rev-parse -q --verify MERGE_HEAD`.text()
  133. } catch {
  134. console.log(" No changes, skipping")
  135. continue
  136. }
  137. try {
  138. await $`git add -A`
  139. } catch {
  140. console.log(" Failed to stage changes")
  141. failed.push({ number: pr.number, title: pr.title, reason: "Staging failed" })
  142. await commentOnPR(pr.number, "Failed to stage changes")
  143. continue
  144. }
  145. const commitMsg = `Apply PR #${pr.number}: ${pr.title}`
  146. try {
  147. await $`git commit -m ${commitMsg}`
  148. } catch (err) {
  149. console.log(` Failed to commit: ${err}`)
  150. failed.push({ number: pr.number, title: pr.title, reason: "Commit failed" })
  151. await commentOnPR(pr.number, "Failed to commit changes")
  152. continue
  153. }
  154. console.log(" Applied successfully")
  155. applied.push(pr.number)
  156. }
  157. console.log("\n--- Summary ---")
  158. console.log(`Applied: ${applied.length} PRs`)
  159. applied.forEach((num) => console.log(` - PR #${num}`))
  160. if (failed.length > 0) {
  161. console.log(`Failed: ${failed.length} PRs`)
  162. failed.forEach((f) => console.log(` - PR #${f.number}: ${f.reason}`))
  163. throw new Error(`${failed.length} PR(s) failed to merge`)
  164. }
  165. console.log("\nChecking if beta branch has changes...")
  166. await $`git fetch origin beta`
  167. const localTree = await $`git rev-parse beta^{tree}`.text()
  168. const remoteTrees = (await $`git log origin/dev..origin/beta --format=%T`.text()).split("\n")
  169. const matchIdx = remoteTrees.indexOf(localTree.trim())
  170. if (matchIdx !== -1) {
  171. if (matchIdx !== 0) {
  172. console.log(`Beta branch contains this sync, but additional commits exist after it. Leaving beta branch as is.`)
  173. } else {
  174. console.log("Beta branch has identical contents, no push needed")
  175. }
  176. return
  177. }
  178. console.log("Force pushing beta branch...")
  179. await $`git push origin beta --force --no-verify`
  180. console.log("Successfully synced beta branch")
  181. }
  182. main().catch((err) => {
  183. console.error("Error:", err)
  184. process.exit(1)
  185. })