| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "slices" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "the-valley/flow/internal/git" |
| 15 | "the-valley/flow/internal/integration" |
| 16 | "the-valley/flow/internal/location" |
| 17 | "the-valley/flow/internal/run" |
| 18 | ) |
| 19 | |
| 20 | // continuationLockWait is how long a launch that continues a branch waits |
| 21 | // for another such launch in the same clone to register its run. |
| 22 | var continuationLockWait = 5 * time.Minute |
| 23 | |
| 24 | // lockContinuation takes the lock that serialises the launches continuing a |
| 25 | // branch (--pr, --change, or --resume-from on its run's branch) in the |
| 26 | // clone at repoRoot, from the check that no other run holds the branch or |
| 27 | // the change through the new run's registration: a second launch waits, |
| 28 | // then finds the first run registered and refuses. It waits up to |
| 29 | // continuationLockWait, saying so on stderr. The returned func releases it. |
| 30 | func lockContinuation(ctx context.Context, repoRoot string) (func(), error) { |
| 31 | paths, err := continuationLockPaths(ctx, repoRoot) |
| 32 | if err != nil { |
| 33 | return nil, err |
| 34 | } |
| 35 | deadline := time.Now().Add(continuationLockWait) |
| 36 | for said := false; ; said = true { |
| 37 | l, err := location.TryLock(paths...) |
| 38 | if err == nil { |
| 39 | return l.Release, nil |
| 40 | } |
| 41 | if !errors.Is(err, location.ErrBusy) { |
| 42 | return nil, err |
| 43 | } |
| 44 | if !said { |
| 45 | fmt.Fprintf(os.Stderr, "waiting for another launch continuing a branch in %s to start its run...\n", repoRoot) |
| 46 | } |
| 47 | if time.Now().After(deadline) { |
| 48 | return nil, fmt.Errorf("another launch continuing a branch in %s still hasn't started its run after %s", repoRoot, continuationLockWait) |
| 49 | } |
| 50 | select { |
| 51 | case <-ctx.Done(): |
| 52 | return nil, ctx.Err() |
| 53 | case <-time.After(200 * time.Millisecond): |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | // tryLockContinuation takes the lock lockContinuation takes, if no launch |
| 59 | // holds it; ok is false when one does, or the lock can't be taken. |
| 60 | func tryLockContinuation(ctx context.Context, repoRoot string) (release func(), ok bool) { |
| 61 | paths, err := continuationLockPaths(ctx, repoRoot) |
| 62 | if err != nil { |
| 63 | return nil, false |
| 64 | } |
| 65 | l, err := location.TryLock(paths...) |
| 66 | if err != nil { |
| 67 | return nil, false |
| 68 | } |
| 69 | return l.Release, true |
| 70 | } |
| 71 | |
| 72 | // continuationLockPaths are the continuation lock's files, in the clone's |
| 73 | // common git directory, which its worktrees share. |
| 74 | func continuationLockPaths(ctx context.Context, repoRoot string) ([]string, error) { |
| 75 | out, err := exec.CommandContext(ctx, "git", "-C", repoRoot, "rev-parse", "--git-common-dir").Output() |
| 76 | if err != nil { |
| 77 | return nil, fmt.Errorf("finding the git directory of %s: %w", repoRoot, err) |
| 78 | } |
| 79 | dir := strings.TrimSpace(string(out)) |
| 80 | if !filepath.IsAbs(dir) { |
| 81 | dir = filepath.Join(repoRoot, dir) |
| 82 | } |
| 83 | return location.ContinuationLocks(dir), nil |
| 84 | } |
| 85 | |
| 86 | // occupantError is the refusal to create a worktree on branch while the |
| 87 | // worktree at path has it checked out, holding work that origin lacks ("" |
| 88 | // for none): owner is the run that registered it, or nil when none did. |
| 89 | // klaus never removes such a worktree, even for --force-takeover, so the |
| 90 | // operator frees the branch first. |
| 91 | func occupantError(branch, path, work string, owner *run.State) error { |
| 92 | what := path |
| 93 | if work != "" { |
| 94 | what += " (with " + work + ")" |
| 95 | } |
| 96 | if owner == nil { |
| 97 | return fmt.Errorf("branch %s is checked out in %s, which no flow run registered; flow never removes it: check another branch out there, or remove it yourself", branch, what) |
| 98 | } |
| 99 | free := "clean that run up first" |
| 100 | if work != "" { |
| 101 | free = "save that work, then clean that run up" |
| 102 | } |
| 103 | return fmt.Errorf("branch %s is checked out in run %s's worktree %s; flow never removes a worktree, even with --force-takeover: %s (valley flow cleanup %s, with --force while its agent runs) and launch again", branch, owner.ID, what, free, owner.ID) |
| 104 | } |
| 105 | |
| 106 | // worktreeOwner returns the run whose recorded worktree is path, or nil. |
| 107 | func worktreeOwner(states []*run.State, path string) *run.State { |
| 108 | clean := filepath.Clean(path) |
| 109 | for _, s := range states { |
| 110 | if s.Type != "session" && s.Worktree != "" && filepath.Clean(s.Worktree) == clean { |
| 111 | return s |
| 112 | } |
| 113 | } |
| 114 | return nil |
| 115 | } |
| 116 | |
| 117 | // takeoverCandidates are the runs whose attention a run of changeID in repo |
| 118 | // (as integration.RepoName names it) could take on: other runs of the |
| 119 | // change that need attention and pushed their work, and that self doesn't |
| 120 | // already record. |
| 121 | func takeoverCandidates(states []*run.State, self *run.State, changeID string, repos ...string) []*run.State { |
| 122 | var out []*run.State |
| 123 | for _, s := range states { |
| 124 | if s.Type == "session" || s.ID == self.ID || s.ChangeID != changeID || !run.ValidChangeID(changeID) || |
| 125 | !slices.Contains(repos, integration.RepoName(s)) || !needsAttention(s) || s.PushedSHA == nil || |
| 126 | slices.Contains(self.TookOver, s.ID) { |
| 127 | continue |
| 128 | } |
| 129 | out = append(out, s) |
| 130 | } |
| 131 | return out |
| 132 | } |
| 133 | |
| 134 | // recordTakeovers adds to self.TookOver each candidate whose pushed head is |
| 135 | // head or one of its ancestors in the repo at dir: self holds that work. |
| 136 | // It returns the IDs it added. |
| 137 | func recordTakeovers(ctx context.Context, dir, head string, self *run.State, candidates []*run.State) []string { |
| 138 | var added []string |
| 139 | for _, s := range candidates { |
| 140 | if git.IsAncestor(ctx, dir, *s.PushedSHA, head) { |
| 141 | self.TookOver = append(self.TookOver, s.ID) |
| 142 | added = append(added, s.ID) |
| 143 | } |
| 144 | } |
| 145 | return added |
| 146 | } |
| 147 | |
| 148 | // recordFinalTakeovers records, as a run finalizes, the runs of its change |
| 149 | // that need attention and whose pushed heads the head it left on origin |
| 150 | // contains: its pushed head, or for a PR its branch's tip on origin. It |
| 151 | // asks origin only when there is such a run to check. |
| 152 | func recordFinalTakeovers(ctx context.Context, gc git.Client, state *run.State) { |
| 153 | if state.Worktree == "" { |
| 154 | return |
| 155 | } |
| 156 | states, _ := run.ListAllSessions() |
| 157 | candidates := takeoverCandidates(states, state, state.ChangeID, integration.RepoName(state)) |
| 158 | if len(candidates) == 0 { |
| 159 | return |
| 160 | } |
| 161 | var head string |
| 162 | switch { |
| 163 | case state.PushedSHA != nil: |
| 164 | head = *state.PushedSHA |
| 165 | case state.PRURL != nil && *state.PRURL != "": |
| 166 | head, _ = gc.RemoteBranchSHA(ctx, state.Worktree, state.Branch) |
| 167 | } |
| 168 | if head != "" { |
| 169 | recordTakeovers(ctx, state.Worktree, head, state, candidates) |
| 170 | } |
| 171 | } |