gunk-dev/the-valley

merge.go

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