gunk-dev/the-valley

merge.go

source6a7605f70901main's published tip history
20.0 KiB
1package cmd
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "fmt"
8 "io"
9 "log/slog"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "strings"
14 "time"
15
16 "the-valley/flow/internal/config"
17 "the-valley/flow/internal/git"
18 gh "the-valley/flow/internal/github"
19 "the-valley/flow/internal/location"
20 "the-valley/flow/internal/run"
21 "github.com/spf13/cobra"
22)
23
24// mergeRunner holds the dependencies for the merge workflow.
25// Fields are functions to allow testing with mocks.
26type mergeRunner struct {
27 out io.Writer
28 in io.Reader
29 getPRTitle func(string, string) string
30 getPRCI func(string, string) string
31 getPRConflicts func(string, string) string
32 getPRBehind func(string, string) int
33 getPRReviewDecision func(string, string) string
34 rebaseAndPush func(string, string) error
35 mergePR func(string, string, bool, string) error
36 updateBranch func(string, string) error
37 pollCI func(string, string) error
38 markMerged func(prNumber string)
39 resolveRepo func(prNumber string) string
40 checkApproval func(prNumber string) bool
41 forceApproval bool
42 yesFlag bool
43}
44
45func newMergeRunner(out io.Writer, in io.Reader, store run.StateStore, repoFlag string) *mergeRunner {
46 ctx := context.TODO()
47 r := &mergeRunner{
48 out: out,
49 in: in,
50 getPRTitle: func(pr, repo string) string {
51 return gh.NewGHCLIClient(repo).GetTitle(ctx, pr)
52 },
53 getPRCI: func(pr, repo string) string {
54 return gh.NewGHCLIClient(repo).GetCI(ctx, pr)
55 },
56 getPRConflicts: func(pr, repo string) string {
57 return gh.NewGHCLIClient(repo).GetConflicts(ctx, pr)
58 },
59 getPRBehind: func(pr, repo string) int {
60 return gh.NewGHCLIClient(repo).GetCommitsBehind(ctx, pr)
61 },
62 getPRReviewDecision: func(pr, repo string) string {
63 return gh.NewGHCLIClient(repo).GetReviewDecision(ctx, pr)
64 },
65 rebaseAndPush: rebaseAndPush,
66 mergePR: func(prNumber, mergeMethod string, deleteBranch bool, repo string) error {
67 return gh.NewGHCLIClient(repo).Merge(ctx, prNumber, mergeMethod, deleteBranch)
68 },
69 updateBranch: func(prNumber, repo string) error {
70 return gh.NewGHCLIClient(repo).UpdateBranch(ctx, prNumber)
71 },
72 pollCI: defaultPollCI,
73 markMerged: markRunsMerged(store),
74 checkApproval: buildApprovalChecker(store),
75 }
76 r.resolveRepo = buildRepoResolver(store, repoFlag)
77 return r
78}
79
80// buildRepoResolver returns a function that resolves the target repo for a given PR number.
81// Priority: run state pr_url match > --repo flag > session target > "" (existing behavior).
82func buildRepoResolver(store run.StateStore, repoFlag string) func(string) string {
83 // Pre-load states and session target once from the provided store.
84 var states []*run.State
85 if store != nil {
86 states, _ = store.List()
87 }
88
89 var sessionTarget string
90 if store != nil {
91 sessionTarget, _ = run.LoadTarget(filepath.Dir(store.StateDir()))
92 }
93
94 return func(prNumber string) string {
95 // 1. Check run states for matching pr_url
96 for _, s := range states {
97 if extractPRNumber(s) == prNumber && s.PRURL != nil {
98 if repo := repoFromPRURL(*s.PRURL); repo != "" && repo != "(unknown)" {
99 return repo
100 }
101 }
102 }
103 // 2. --repo flag
104 if repoFlag != "" {
105 return repoFlag
106 }
107 // 3. Session target
108 if sessionTarget != "" {
109 return sessionTarget
110 }
111 // 4. Empty string — gh will use the current git repo
112 return ""
113 }
114}
115
116// buildApprovalChecker returns a function that checks if a PR number
117// has been approved in the run state or via GitHub review. Returns true if approved.
118func buildApprovalChecker(store run.StateStore) func(string) bool {
119 return func(prNumber string) bool {
120 // Check internal approval state first.
121 var states []*run.State
122 if store != nil {
123 states, _ = store.List()
124 }
125
126 repo := ""
127 isApproved := false
128 for _, s := range states {
129 if extractPRNumber(s) == prNumber {
130 if s.Approved != nil && *s.Approved {
131 isApproved = true
132 }
133 if repo == "" && s.PRURL != nil {
134 repo = repoFromPRURL(*s.PRURL)
135 if repo == "(unknown)" {
136 repo = ""
137 }
138 }
139 }
140 }
141
142 if isApproved {
143 return true
144 }
145
146 // Fall back to checking GitHub review decision.
147 decision := gh.NewGHCLIClient(repo).GetReviewDecision(context.TODO(), prNumber)
148 if strings.EqualFold(decision, "APPROVED") {
149 // Persist the approval into run state so future checks are fast.
150 for _, s := range states {
151 if extractPRNumber(s) == prNumber {
152 markApproved(s, store)
153 break
154 }
155 }
156 return true
157 }
158 return false
159 }
160}
161
162// markRunsMerged returns a function that finds run states matching a PR number
163// and updates their MergedAt field. This triggers the dashboard's fsnotify
164// watcher so it can reflect the merge immediately.
165func markRunsMerged(store run.StateStore) func(string) {
166 return func(prNumber string) {
167 if store == nil {
168 return
169 }
170 states, err := store.List()
171 if err != nil {
172 return
173 }
174 now := time.Now().UTC().Format(time.RFC3339)
175 for _, s := range states {
176 if extractPRNumber(s) == prNumber {
177 s.MergedAt = &now
178 if err := store.Save(s); err != nil {
179 slog.Warn("failed to save merged state", "id", s.ID, "err", err)
180 }
181 }
182 }
183 }
184}
185
186var mergeCmd = &cobra.Command{
187 Use: "merge <pr1> <pr2> ...",
188 Short: "Merge PRs sequentially with automatic rebasing",
189 Long: `Merges a list of PRs in the given order. For each PR:
190
1911. Resolves the target repo (from run state, --repo flag, or session target)
1922. Checks merge readiness (CI, conflicts, review approval)
1933. If conflicts exist, rebases onto main and re-pushes
1944. Merges with the specified method (default: squash)
1955. Moves to the next PR
196
197A branch that is merely behind main is merged as-is: rebasing it would rewrite
198history and dismiss the approval the merge depends on. If GitHub refuses the
199merge because the branch must be up to date, flow runs GitHub's "Update
200branch" (a merge from main, not a rebase), waits for CI, and merges again.
201
202If a rebase fails or CI times out, stops and reports the stuck PR. The rebase
203runs in a worktree of its own; while another worktree, such as a fix agent's,
204has the PR's branch checked out, merge stops rather than remove it.
205
206Use --repo to specify the target repository when running outside a git repo
207(e.g. from a flow session workspace). If PRs were created by flow agents,
208the repo is auto-detected from run state. Rebasing needs a checkout: flow
209uses the current repo, a registered project, or clones under
210worktree_base/.repos, so merge does not have to run inside a clone.`,
211 Args: cobra.MinimumNArgs(1),
212 RunE: func(cmd *cobra.Command, args []string) error {
213 dryRun, _ := cmd.Flags().GetBool("dry-run")
214 mergeMethod, _ := cmd.Flags().GetString("merge-method")
215 noDeleteBranch, _ := cmd.Flags().GetBool("no-delete-branch")
216 repoFlag, _ := cmd.Flags().GetString("repo")
217 force, _ := cmd.Flags().GetBool("force")
218 yes, _ := cmd.Flags().GetBool("yes")
219
220 if err := validateMergeMethod(mergeMethod); err != nil {
221 return err
222 }
223
224 // Best-effort: get the session store so we can update run states
225 // after merge. If not in a session, store will be nil and
226 // markMerged will be a no-op.
227 store, _ := sessionStore()
228
229 runner := newMergeRunner(os.Stdout, os.Stdin, store, repoFlag)
230 runner.forceApproval = force
231 runner.yesFlag = yes
232
233 // Load config (require_approval, merge_verify_command) from the target
234 // repo rather than the current directory, so merging another repo's PRs
235 // from a klaus session workspace still honours that repo's settings.
236 // existingRepoDir never clones: when the repo has no local checkout,
237 // repoDir is empty and only global config applies.
238 repoDir, err := existingRepoDir(runner.resolveRepo(args[0]))
239 if err != nil {
240 return err
241 }
242 cfg, err := config.Load(repoDir)
243 if err != nil {
244 return fmt.Errorf("could not load configuration: %w", err)
245 }
246 if !cfg.RequiresApproval() {
247 runner.forceApproval = true // approval not required by config
248 }
249
250 if dryRun {
251 return runner.dryRun(args)
252 }
253 return runner.run(args, mergeMethod, !noDeleteBranch)
254 },
255}
256
257func validateMergeMethod(method string) error {
258 switch method {
259 case "squash", "merge", "rebase":
260 return nil
261 default:
262 return fmt.Errorf("invalid merge method %q: must be squash, merge, or rebase", method)
263 }
264}
265
266// rebaseAndPush rebases a PR branch onto origin/main, verifies compilation,
267// and force-pushes using a temporary worktree.
268func rebaseAndPush(prNumber string, repo string) error {
269 ctx := context.TODO()
270 branch, err := gh.NewGHCLIClient(repo).GetBranch(ctx, prNumber)
271 if err != nil {
272 return fmt.Errorf("getting branch: %w", err)
273 }
274
275 // The rebase needs a real checkout to build a worktree from. Resolve it
276 // from the PR's repo (current checkout, registered project, or a clone
277 // under worktree_base/.repos) so merge works outside a git directory.
278 repoRoot, err := resolveRepoDir(ctx, repo)
279 if err != nil {
280 return fmt.Errorf("could not find a checkout to rebase in: %w", err)
281 }
282
283 gitClient := git.NewExecClient()
284
285 if err := gitClient.FetchBranch(ctx, repoRoot, "main"); err != nil {
286 return fmt.Errorf("fetching main: %w", err)
287 }
288 if err := gitClient.FetchBranch(ctx, repoRoot, branch); err != nil {
289 return fmt.Errorf("fetching %s: %w", branch, err)
290 }
291
292 tmpDir, err := os.MkdirTemp("", location.TempPattern("merge-*"))
293 if err != nil {
294 return fmt.Errorf("creating temp dir: %w", err)
295 }
296 worktreePath := filepath.Join(tmpDir, "rebase")
297 var tracking bool
298 defer func() {
299 if err := gitClient.WorktreeRemove(ctx, repoRoot, worktreePath); err != nil {
300 fmt.Fprintf(os.Stderr, "warning: failed to remove worktree: %v\n", err)
301 }
302 // The local branch started at origin's tip and holds only this
303 // rebase; drop it, so a rebase that wasn't pushed doesn't read as
304 // work origin lacks when the next worktree tracks the branch.
305 if tracking {
306 _ = gitClient.BranchDelete(ctx, repoRoot, branch)
307 }
308 if err := os.RemoveAll(tmpDir); err != nil {
309 fmt.Fprintf(os.Stderr, "warning: failed to remove temp directory: %v\n", err)
310 }
311 }()
312
313 if err := gitClient.WorktreeAddTrack(ctx, repoRoot, worktreePath, branch, false); err != nil {
314 return fmt.Errorf("creating worktree: %w", err)
315 }
316 tracking = true
317
318 rebaseCmd := exec.Command("git", "rebase", "origin/main")
319 rebaseCmd.Dir = worktreePath
320 var stderr bytes.Buffer
321 rebaseCmd.Stderr = &stderr
322 if err := rebaseCmd.Run(); err != nil {
323 abortCmd := exec.Command("git", "rebase", "--abort")
324 abortCmd.Dir = worktreePath
325 if abortErr := abortCmd.Run(); abortErr != nil {
326 slog.Warn("failed to abort rebase", "pr", prNumber, "worktree", worktreePath, "err", abortErr)
327 }
328 return fmt.Errorf("rebase conflicts: %s", strings.TrimSpace(stderr.String()))
329 }
330
331 cfg, _ := config.Load(repoRoot)
332 if err := verifyRebasedWorktree(worktreePath, cfg.MergeVerifyCmd()); err != nil {
333 return err
334 }
335
336 pushCmd := exec.Command("git", "push", "--force-with-lease")
337 pushCmd.Dir = worktreePath
338 var pushStderr bytes.Buffer
339 pushCmd.Stderr = &pushStderr
340 if err := pushCmd.Run(); err != nil {
341 return fmt.Errorf("force push failed: %s", strings.TrimSpace(pushStderr.String()))
342 }
343
344 return nil
345}
346
347// verifyRebasedWorktree sanity-checks the rebased branch before force-push.
348// Precedence: configured merge_verify_command (via sh -c) > `go build ./...`
349// iff a go.mod exists > skip (non-Go repo with no command — rely on CI).
350func verifyRebasedWorktree(worktreePath string, verifyCmd *string) error {
351 var cmd *exec.Cmd
352 switch {
353 case verifyCmd != nil:
354 cmd = exec.Command("sh", "-c", *verifyCmd)
355 case fileExists(filepath.Join(worktreePath, "go.mod")):
356 cmd = exec.Command("go", "build", "./...")
357 default:
358 return nil
359 }
360 cmd.Dir = worktreePath
361 var stderr bytes.Buffer
362 cmd.Stderr = &stderr
363 if err := cmd.Run(); err != nil {
364 return fmt.Errorf("merge verification failed after rebase: %s", strings.TrimSpace(stderr.String()))
365 }
366 return nil
367}
368
369// fileExists reports whether path exists.
370func fileExists(path string) bool {
371 _, err := os.Stat(path)
372 return err == nil
373}
374
375// defaultPollCI polls CI checks until they pass or timeout.
376func defaultPollCI(prNumber string, repo string) error {
377 timeout := 10 * time.Minute
378 interval := 30 * time.Second
379 deadline := time.Now().Add(timeout)
380 client := gh.NewGHCLIClient(repo)
381 ctx := context.TODO()
382
383 for {
384 ci := client.GetCI(ctx, prNumber)
385 switch ci {
386 case "passing":
387 return nil
388 case "failing":
389 return fmt.Errorf("CI checks failed")
390 }
391 if time.Now().After(deadline) {
392 return fmt.Errorf("CI timed out after %v", timeout)
393 }
394 time.Sleep(interval)
395 }
396}
397
398// formatRepoLabel returns the repo string for display, defaulting to "(local)".
399func formatRepoLabel(repo string) string {
400 if repo == "" {
401 return "(local)"
402 }
403 return repo
404}
405
406// dryRun prints the merge plan without executing.
407func (r *mergeRunner) dryRun(prNumbers []string) error {
408 fmt.Fprintf(r.out, "Merge plan (dry run):\n\n")
409 for i, prNum := range prNumbers {
410 repo := r.resolveRepo(prNum)
411 title := r.getPRTitle(prNum, repo)
412 ci := r.getPRCI(prNum, repo)
413 conflicts := r.getPRConflicts(prNum, repo)
414 behind := r.getPRBehind(prNum, repo)
415 review := r.getPRReviewDecision(prNum, repo)
416 status := computeMergeStatus(ci, conflicts, review, behind)
417
418 repoLabel := formatRepoLabel(repo)
419 fmt.Fprintf(r.out, " %d. PR #%s [%s]: %s\n", i+1, prNum, repoLabel, title)
420 fmt.Fprintf(r.out, " CI: %s | Conflicts: %s | Behind: %d | Review: %s | Merge: %s\n",
421 ci, conflicts, behind, review, status)
422 }
423 return nil
424}
425
426// run merges PRs sequentially.
427func (r *mergeRunner) run(prNumbers []string, mergeMethod string, deleteBranch bool) error {
428 scanner := bufio.NewScanner(r.in)
429 for i, prNum := range prNumbers {
430 repo := r.resolveRepo(prNum)
431 repoLabel := formatRepoLabel(repo)
432 fmt.Fprintf(r.out, "\n[%d/%d] PR #%s [%s]\n", i+1, len(prNumbers), prNum, repoLabel)
433
434 title := r.getPRTitle(prNum, repo)
435 fmt.Fprintf(r.out, " Title: %s\n", title)
436
437 ci := r.getPRCI(prNum, repo)
438 conflicts := r.getPRConflicts(prNum, repo)
439 behind := r.getPRBehind(prNum, repo)
440 review := r.getPRReviewDecision(prNum, repo)
441
442 fmt.Fprintf(r.out, " CI: %s | Conflicts: %s | Behind: %d | Review: %s\n",
443 ci, conflicts, behind, review)
444
445 // Check approval gate
446 if !r.forceApproval && r.checkApproval != nil && !r.checkApproval(prNum) {
447 if r.yesFlag {
448 fmt.Fprintf(r.out, " Skipping PR #%s: not approved\n", prNum)
449 continue
450 }
451 // Interactive prompt
452 fmt.Fprintf(r.out, " PR #%s is not approved. Approve and merge? [y/n/s(kip)] ", prNum)
453 if scanner.Scan() {
454 answer := strings.ToLower(strings.TrimSpace(scanner.Text()))
455 switch answer {
456 case "y", "yes":
457 // Continue with merge
458 case "s", "skip":
459 fmt.Fprintf(r.out, " Skipped PR #%s\n", prNum)
460 continue
461 default:
462 return r.stopQueue(prNum, "not approved", prNumbers[i+1:])
463 }
464 } else {
465 return r.stopQueue(prNum, "merge not confirmed", prNumbers[i+1:])
466 }
467 }
468
469 // Unfixable blocker: changes requested
470 if strings.EqualFold(review, "CHANGES_REQUESTED") {
471 return r.stopQueue(prNum, "changes requested in review", prNumbers[i+1:])
472 }
473
474 // Conflicts are the only reason to rewrite history. The rebase
475 // force-push creates a new head, and under a policy that dismisses
476 // reviews on new commits that costs the PR the very approval the merge
477 // depends on — so a branch that is merely behind main is left alone.
478 // GitHub merges a behind branch as-is unless the repo requires branches
479 // to be up to date; that refusal is handled below by a server-side
480 // branch update, which preserves approvals where policy allows.
481 // CI-failing-without-conflicts stops first: don't rebase a broken branch.
482 if conflicts == "yes" {
483 fmt.Fprintf(r.out, " Rebasing onto main...\n")
484 if err := r.rebaseAndPush(prNum, repo); err != nil {
485 return r.stopQueue(prNum, fmt.Sprintf("rebase failed: %v", err), prNumbers[i+1:])
486 }
487 behind = 0 // the rebased head sits on top of main
488 fmt.Fprintf(r.out, " Waiting for CI after rebase...\n")
489 if err := r.pollCI(prNum, repo); err != nil {
490 return r.stopQueue(prNum, fmt.Sprintf("CI after rebase: %v", err), prNumbers[i+1:])
491 }
492 } else if ci == "failing" {
493 // CI failing without conflicts — can't fix automatically
494 return r.stopQueue(prNum, "CI is failing", prNumbers[i+1:])
495 } else if ci != "passing" {
496 // CI pending or unknown — wait
497 fmt.Fprintf(r.out, " Waiting for CI...\n")
498 if err := r.pollCI(prNum, repo); err != nil {
499 return r.stopQueue(prNum, fmt.Sprintf("CI: %v", err), prNumbers[i+1:])
500 }
501 }
502
503 if err := r.mergeWithBranchUpdate(prNum, mergeMethod, deleteBranch, repo, behind); err != nil {
504 return r.stopQueue(prNum, fmt.Sprintf("merge failed: %v", err), prNumbers[i+1:])
505 }
506 fmt.Fprintf(r.out, " Merged PR #%s.\n", prNum)
507 if r.markMerged != nil {
508 r.markMerged(prNum)
509 }
510 }
511
512 fmt.Fprintf(r.out, "\nAll %d PRs merged successfully.\n", len(prNumbers))
513 return nil
514}
515
516// mergeWithBranchUpdate merges a PR, retrying once through GitHub's
517// "Update branch" when the merge is refused because the branch is behind its
518// base. The update merges main into the head server-side, so unlike a rebase
519// and force-push it does not rewrite history — which is what lets an existing
520// approval survive on repos that dismiss reviews for rewritten heads.
521func (r *mergeRunner) mergeWithBranchUpdate(prNum, mergeMethod string, deleteBranch bool, repo string, behind int) error {
522 fmt.Fprintf(r.out, " Merging (%s)...\n", mergeMethod)
523 err := r.mergePR(prNum, mergeMethod, deleteBranch, repo)
524 if err == nil {
525 return nil
526 }
527 // Only worth retrying when the branch really is behind: an update-branch
528 // call on an up-to-date PR is rejected, and the original refusal is the
529 // more useful error to report.
530 if behind <= 0 || r.updateBranch == nil || !mergeRefusedForStaleBranch(err) {
531 return err
532 }
533
534 fmt.Fprintf(r.out, " Merge refused while %d commit(s) behind main; updating branch from main...\n", behind)
535 if updateErr := r.updateBranch(prNum, repo); updateErr != nil {
536 return fmt.Errorf("%w (updating branch from main also failed: %v)", err, updateErr)
537 }
538 fmt.Fprintf(r.out, " Waiting for CI after branch update...\n")
539 if ciErr := r.pollCI(prNum, repo); ciErr != nil {
540 return fmt.Errorf("CI after branch update: %w", ciErr)
541 }
542 fmt.Fprintf(r.out, " Merging (%s)...\n", mergeMethod)
543 return r.mergePR(prNum, mergeMethod, deleteBranch, repo)
544}
545
546// mergeRefusedForStaleBranch reports whether a merge failure looks like one an
547// "Update branch" would clear. GitHub does not always name the stale branch: a
548// PR blocked by "require branches to be up to date" surfaces through gh as the
549// same generic base-branch-policy message as any other blocked merge, so that
550// text is matched too. Callers gate on the PR actually being behind, which is
551// what keeps the generic match from firing on unrelated blocks.
552func mergeRefusedForStaleBranch(err error) bool {
553 msg := strings.ToLower(err.Error())
554 for _, phrase := range []string{
555 "not up to date",
556 "out of date",
557 "base branch policy prohibits the merge",
558 "base branch was modified",
559 } {
560 if strings.Contains(msg, phrase) {
561 return true
562 }
563 }
564 return false
565}
566
567// stopQueue reports which PR is stuck and lists remaining unmerged PRs.
568func (r *mergeRunner) stopQueue(stuckPR, reason string, remaining []string) error {
569 fmt.Fprintf(r.out, "\nStopped: PR #%s — %s\n", stuckPR, reason)
570 if len(remaining) > 0 {
571 fmt.Fprintf(r.out, "Remaining PRs: %s\n", formatPRList(remaining))
572 }
573 return fmt.Errorf("PR #%s: %s", stuckPR, reason)
574}
575
576// formatPRList formats a list of PR numbers for display.
577func formatPRList(prs []string) string {
578 formatted := make([]string, len(prs))
579 for i, pr := range prs {
580 formatted[i] = "#" + pr
581 }
582 return strings.Join(formatted, ", ")
583}
584
585func init() {
586 mergeCmd.Flags().Bool("dry-run", false, "Print the merge plan without executing")
587 mergeCmd.Flags().String("merge-method", "squash", "Merge method: squash, merge, or rebase")
588 mergeCmd.Flags().Bool("no-delete-branch", false, "Skip --delete-branch on gh pr merge")
589 mergeCmd.Flags().String("repo", "", "Default target repo (owner/repo) for all PRs")
590 mergeCmd.Flags().Bool("force", false, "Bypass approval check")
591 mergeCmd.Flags().BoolP("yes", "y", false, "Skip interactive prompts (skips unapproved PRs with a warning)")
592 rootCmd.AddCommand(mergeCmd)
593}