gunk-dev/the-valley

change.go

source60ad80d5a5a5main's published tip history
15.9 KiB
1package cmd
2
3import (
4 "context"
5 "errors"
6 "fmt"
7 "slices"
8 "sort"
9 "strings"
10
11 "the-valley/flow/internal/git"
12 "the-valley/flow/internal/integration"
13 "the-valley/flow/internal/run"
14 "the-valley/flow/internal/valley"
15)
16
17// changeTarget is the change a --change launch continues.
18type changeTarget struct {
19 ID string // the change ID
20 Name string // how launch names it: its handle, else its ID
21 Repo string // the change's repo, as integration.RepoName names it; "" when unknown
22 Branch string // the branch its work is on; "" when none is known
23 Head string // that branch's last known head
24 Tip string // origin's tip of the branch, which the worktree starts from; set by checkBranch
25 Runs []*run.State // klaus's runs on the change, newest first
26}
27
28// changeSources is what resolveChange reads.
29type changeSources struct {
30 Runs []*run.State // every recorded run, from every session
31 // Repo is the target repo's identity, named as integration.RepoName names
32 // a run's: the short name of the new run's target repo (targetName).
33 // Only runs it names count; "" is an error.
34 Repo string
35 // Valley lists the changes of the target repo, as `valley changes
36 // --json` does, or returns errNoValley when no valley serves it. nil
37 // means no valley. resolveChange calls it at most once.
38 Valley func() (*valley.Changes, error)
39 // Slug is the target repo's GitHub owner/repo, "" when its origin isn't
40 // on GitHub.
41 Slug string
42 // PRs lists the URLs of the GitHub PRs, open or not, whose head is a
43 // branch of the target repo, newest first. nil when its origin isn't on
44 // GitHub.
45 PRs func(branch string) ([]string, error)
46}
47
48// errNoValley is changeSources.Valley's answer when no valley serves the
49// target repo.
50var errNoValley = errors.New("no valley serves the repo")
51
52// resolveChange finds the change ref names, for a launch that continues it.
53// ref is a run ID, a full change ID or a valley handle:
54//
55// - a run ID names that run's change;
56// - a change ID or handle names the change of the runs in the target repo
57// whose change ID it is, or starts with it, or whose recorded valley
58// handle it is;
59// - when no run matches, the valley's listing of the target repo names the
60// change whose ID or handle it is, or whose ID starts with it.
61//
62// A ref that names more than one change is an error listing them. A run is
63// in the target repo only when its integration.RepoName is the target's
64// identity: a run whose valley names its repo otherwise is in that other
65// repo, whatever its own target repo was called.
66//
67// The change's branch and head are its active version's when the valley
68// lists one with a branch, else those the newest run on it pushed; its name
69// is the valley's handle, else the newest recorded one, else its ID.
70func resolveChange(ref string, src changeSources) (*changeTarget, error) {
71 if src.Repo == "" {
72 return nil, errors.New("can't tell which repo the launch targets; name it with --repo")
73 }
74 var (
75 asked bool
76 listing *valley.Changes
77 listErr = errNoValley
78 )
79 list := func() (*valley.Changes, error) {
80 if !asked && src.Valley != nil {
81 listing, listErr = src.Valley()
82 }
83 asked = true
84 return listing, listErr
85 }
86 inRepo := func(s *run.State) bool {
87 return s.Type != "session" && integration.RepoName(s) == src.Repo
88 }
89 where := src.Repo
90
91 var id string
92 if s := findRun(src.Runs, ref); s != nil {
93 if !run.ValidChangeID(s.ChangeID) {
94 return nil, fmt.Errorf("run %s has no change ID (its state predates change IDs); --resume-from %s continues its conversation on a new branch", s.ID, s.ID)
95 }
96 if !inRepo(s) {
97 other := integration.RepoName(s)
98 if other == "" {
99 other = "another repo"
100 }
101 return nil, fmt.Errorf("run %s is in %s, not %s; target its repo with --repo", s.ID, other, src.Repo)
102 }
103 id = s.ChangeID
104 } else {
105 named := make(map[string]*run.State) // change ID → its newest run that ref names
106 handles := make(map[string]string) // change ID → a handle recorded for it
107 for _, s := range src.Runs {
108 if !inRepo(s) || !run.ValidChangeID(s.ChangeID) || !refersTo(ref, s.ChangeID, recordedHandles(s)...) {
109 continue
110 }
111 if prev, ok := named[s.ChangeID]; !ok || createdBefore(prev, s) {
112 named[s.ChangeID] = s
113 }
114 if h := handleOf(s); h != "" {
115 handles[s.ChangeID] = h
116 }
117 }
118 switch len(named) {
119 case 1:
120 for k := range named {
121 id = k
122 }
123 case 0:
124 l, err := list()
125 if err != nil {
126 msg := fmt.Sprintf("no run on a change %q is recorded in %s", ref, where)
127 if errors.Is(err, errNoValley) {
128 return nil, errors.New(msg)
129 }
130 return nil, fmt.Errorf("%s, and the valley couldn't be asked: %w", msg, err)
131 }
132 found := make(map[string]valley.Change)
133 for _, vr := range l.Repos {
134 for _, ch := range vr.Changes {
135 if vr.Err() == "" && refersTo(ref, ch.ChangeID, ch.Handle) {
136 found[ch.ChangeID] = ch
137 }
138 }
139 }
140 if len(found) == 0 {
141 return nil, fmt.Errorf("no change %q: no run in %s records it, and the valley doesn't list it", ref, where)
142 }
143 if len(found) > 1 {
144 var lines []string
145 for _, ch := range found {
146 lines = append(lines, changeName(ch.ChangeID, ch.Handle))
147 }
148 return nil, ambiguous(ref, where, lines)
149 }
150 for k := range found {
151 id = k
152 }
153 default:
154 var lines []string
155 for _, s := range named {
156 line := changeName(s.ChangeID, handles[s.ChangeID]) + ", latest run " + s.ID
157 if title := firstLine(runTitle(s)); title != "" {
158 line += ": " + title
159 }
160 lines = append(lines, line)
161 }
162 return nil, ambiguous(ref, where, lines)
163 }
164 }
165
166 t := &changeTarget{ID: id}
167 for _, s := range src.Runs {
168 if s.ChangeID == id && inRepo(s) {
169 t.Runs = append(t.Runs, s)
170 }
171 }
172 sort.SliceStable(t.Runs, func(a, b int) bool { return createdBefore(t.Runs[b], t.Runs[a]) })
173
174 // The valley's view of the change's active version comes first: it may
175 // have been marked ready elsewhere, after klaus's newest run.
176 if l, err := list(); err == nil {
177 if vr, ch, v, ok := activeVersionOf(l, id); ok {
178 t.Repo, t.Name = vr, ch.Handle
179 if v.Branch != "" {
180 t.Branch, t.Head = v.Branch, v.Head
181 }
182 }
183 }
184 for _, s := range t.Runs {
185 if t.Repo == "" {
186 t.Repo = integration.RepoName(s)
187 }
188 if t.Name == "" {
189 t.Name = handleOf(s)
190 }
191 if t.Branch == "" && s.PushedBranch != nil && *s.PushedBranch != "" {
192 t.Branch = *s.PushedBranch
193 if s.PushedSHA != nil {
194 t.Head = *s.PushedSHA
195 }
196 }
197 }
198 if t.Name == "" {
199 t.Name = id
200 }
201 return t, nil
202}
203
204// resumeTarget decides whether a --resume-from launch that names no branch
205// of its own (no --pr, --change or --branch) continues the branch of the
206// run it resumes, priorID, as --change continues a change. It does when
207// that run pushed its branch without a PR, the branch is still its
208// change's, and nothing took the change further:
209//
210// - the run is in the target repo, by name and, where both are known, by
211// GitHub owner;
212// - no run of the change has a PR;
213// - origin has the branch;
214// - no run of another change worked on the branch, and origin's tip
215// carries no other change's Change-Id;
216// - the change's branch as resolveChange finds it (its valley's active
217// version's, else its newest push's) is still that branch;
218// - origin's branch has the run's push in its history, or a later head of
219// the change that rewrote it, as restacking the change onto main does:
220// the push of a later run of the change on the branch, or the head
221// resolveChange finds;
222// - on GitHub, no PR, open or not, has the branch as its head.
223//
224// Otherwise it returns nil and why the launch gets a new branch instead, or
225// "" when the run is unknown, has no change ID or pushed no branch: then a
226// new branch is all there is.
227func resumeTarget(ctx context.Context, repoRoot, priorID string, src changeSources) (*changeTarget, string) {
228 prior := findRun(src.Runs, priorID)
229 if prior == nil || !run.ValidChangeID(prior.ChangeID) {
230 return nil, ""
231 }
232 if prior.PRURL != nil && *prior.PRURL != "" {
233 return nil, fmt.Sprintf("run %s opened PR %s; --pr continues its branch", prior.ID, formatPR(prior))
234 }
235 if prior.PushedBranch == nil || *prior.PushedBranch == "" || prior.PushedSHA == nil {
236 return nil, ""
237 }
238 if repo := integration.RepoName(prior); repo != src.Repo {
239 return nil, fmt.Sprintf("run %s is in %s, not %s", prior.ID, repo, src.Repo)
240 }
241 owner, _, _ := strings.Cut(src.Slug, "/")
242 if o := repoOwner(prior); owner != "" && o != "" && !strings.EqualFold(o, owner) {
243 return nil, fmt.Sprintf("run %s is in %s's %s, not %s", prior.ID, o, src.Repo, src.Slug)
244 }
245 // inRepo is whether a run is in the target repo: by name, and by
246 // GitHub owner where both are known.
247 inRepo := func(s *run.State) bool {
248 o := repoOwner(s)
249 return s.Type != "session" && integration.RepoName(s) == src.Repo && (owner == "" || o == "" || strings.EqualFold(o, owner))
250 }
251 branch, head := *prior.PushedBranch, *prior.PushedSHA
252 var pr *run.State // the newest run of the change with a PR
253 for _, s := range src.Runs {
254 if inRepo(s) && s.ChangeID == prior.ChangeID && s.PRURL != nil && *s.PRURL != "" && (pr == nil || createdBefore(pr, s)) {
255 pr = s
256 }
257 }
258 if pr != nil {
259 return nil, fmt.Sprintf("its change went on in PR %s (run %s); --pr continues that branch", formatPR(pr), pr.ID)
260 }
261 origin := "refs/remotes/origin/" + branch
262 if !git.RefExists(ctx, repoRoot, origin) {
263 return nil, fmt.Sprintf("run %s's branch %s is gone from origin", prior.ID, branch)
264 }
265 for _, s := range src.Runs {
266 if inRepo(s) && s.ChangeID != prior.ChangeID && (s.Branch == branch || s.PushedBranch != nil && *s.PushedBranch == branch) {
267 return nil, fmt.Sprintf("branch %s is also run %s's, of another change", branch, s.ID)
268 }
269 }
270 if id, err := git.CommitChangeID(ctx, repoRoot, origin); err == nil && run.ValidChangeID(id) && id != prior.ChangeID {
271 return nil, fmt.Sprintf("origin's %s ends in a commit of another change, %s", branch, id)
272 }
273 // The change's branch, from its runs in this repo alone.
274 mine := src
275 mine.Runs = nil
276 for _, s := range src.Runs {
277 if inRepo(s) {
278 mine.Runs = append(mine.Runs, s)
279 }
280 }
281 t, err := resolveChange(prior.ID, mine)
282 if err != nil {
283 return nil, err.Error()
284 }
285 if t.Branch != branch {
286 return nil, fmt.Sprintf("change %s moved on to branch %s; --change continues it there", t.Name, t.Branch)
287 }
288 heads := []string{head, t.Head}
289 for _, s := range t.Runs {
290 if createdBefore(prior, s) && s.PushedBranch != nil && *s.PushedBranch == branch && s.PushedSHA != nil {
291 heads = append(heads, *s.PushedSHA)
292 }
293 }
294 if !slices.ContainsFunc(heads, func(h string) bool { return h != "" && git.IsAncestor(ctx, repoRoot, h, origin) }) {
295 return nil, fmt.Sprintf("origin's %s has diverged from run %s's push %s", branch, prior.ID, shortSHA(head))
296 }
297 if src.PRs != nil {
298 prs, err := src.PRs(branch)
299 switch {
300 case err != nil:
301 return nil, fmt.Sprintf("couldn't ask GitHub whether branch %s has a PR: %v", branch, err)
302 case len(prs) > 0:
303 return nil, fmt.Sprintf("branch %s has PR #%s on GitHub; --pr continues it", branch, extractPRNumberFromURL(prs[0]))
304 }
305 }
306 return t, ""
307}
308
309// checkBranch reports an error unless the change's branch is on origin, as
310// fetched into repoRoot: the worktree tracks origin's branch. It records
311// that branch's tip as t.Tip.
312func (t *changeTarget) checkBranch(ctx context.Context, repoRoot string) error {
313 if t.Branch == "" {
314 return fmt.Errorf("change %s has no known branch or head: no run on it recorded a pushed branch, and no valley lists one", t.Name)
315 }
316 t.Tip = git.RefCommit(ctx, repoRoot, "refs/remotes/origin/"+t.Branch)
317 if t.Tip == "" {
318 head := t.Head
319 if head == "" {
320 head = "unknown"
321 }
322 return fmt.Errorf("change %s's branch %s is not on origin (last known head %s)", t.Name, t.Branch, head)
323 }
324 return nil
325}
326
327// checkContinuation rejects launch flags that pick a branch two ways: --pr
328// works on the PR's branch and --change on the change's, and --branch names
329// a new one.
330func checkContinuation(pr, change string, branchSet bool) error {
331 switch {
332 case pr != "" && change != "":
333 return fmt.Errorf("--pr and --change are mutually exclusive: --pr continues a PR, --change a change without one")
334 case branchSet && pr != "":
335 return fmt.Errorf("--branch and --pr are mutually exclusive: --pr works on the PR's branch")
336 case branchSet && change != "":
337 return fmt.Errorf("--branch and --change are mutually exclusive: --change works on the change's branch")
338 }
339 return nil
340}
341
342// liveHolder returns a run that running says is live and that holds what a
343// continuing launch is about to work on, in the target repo: branch, or the
344// change changeID. repos are the names the target repo goes by, compared
345// with integration.RepoName; a run no name matches is in another repo.
346func liveHolder(states []*run.State, running func(*run.State) bool, branch, changeID string, repos ...string) *run.State {
347 for _, s := range states {
348 repo := integration.RepoName(s)
349 if s.Type == "session" || repo == "" || !slices.Contains(repos, repo) {
350 continue
351 }
352 onBranch := branch != "" && s.Branch == branch
353 onChange := run.ValidChangeID(changeID) && s.ChangeID == changeID
354 if (onBranch || onChange) && running(s) {
355 return s
356 }
357 }
358 return nil
359}
360
361// targetName is the short name of a target repo, as integration.RepoName
362// names a run by it: its last path component, without ".git".
363func targetName(target *string) string {
364 return integration.RepoName(&run.State{TargetRepo: target})
365}
366
367// findRun returns the run with ID id, or nil.
368func findRun(states []*run.State, id string) *run.State {
369 for _, s := range states {
370 if s.ID == id && s.Type != "session" {
371 return s
372 }
373 }
374 return nil
375}
376
377// refersTo reports whether ref names the change with ID changeID and the
378// given handles: it is the ID, or starts it, or is one of the handles.
379func refersTo(ref, changeID string, handles ...string) bool {
380 if strings.HasPrefix(changeID, ref) {
381 return true
382 }
383 for _, h := range handles {
384 if h != "" && h == ref {
385 return true
386 }
387 }
388 return false
389}
390
391// recordedHandles are the valley handles klaus recorded for a run's change:
392// finalize's `valley ready` and launch's `valley unready`.
393func recordedHandles(s *run.State) []string {
394 var hs []string
395 if s.Valley != nil {
396 hs = append(hs, s.Valley.Handle)
397 }
398 if h := s.UnreadyHandle(); h != "" {
399 hs = append(hs, h)
400 }
401 return hs
402}
403
404// handleOf is the handle recorded for a run's change, or "".
405func handleOf(s *run.State) string {
406 for _, h := range recordedHandles(s) {
407 if h != "" {
408 return h
409 }
410 }
411 return ""
412}
413
414// runTitle is what a run is about: the subject of the head it pushed, else
415// its prompt.
416func runTitle(s *run.State) string {
417 if s.Valley != nil && s.Valley.Title != "" {
418 return s.Valley.Title
419 }
420 if s.PushedSubject != "" {
421 return s.PushedSubject
422 }
423 return s.Prompt
424}
425
426// firstLine is s up to its first newline.
427func firstLine(s string) string {
428 line, _, _ := strings.Cut(strings.TrimSpace(s), "\n")
429 return line
430}
431
432// changeName names a change by its ID and, when known, its handle.
433func changeName(id, handle string) string {
434 if handle == "" {
435 return id
436 }
437 return id + " (" + handle + ")"
438}
439
440// ambiguous is the error for a ref that names several changes, one per line.
441func ambiguous(ref, where string, lines []string) error {
442 sort.Strings(lines)
443 return fmt.Errorf("%q names %d changes in %s:\n %s\nname one by its change ID or a run ID", ref, len(lines), where, strings.Join(lines, "\n "))
444}
445
446// activeVersionOf finds change id in a valley listing and returns the repo
447// it is listed in, the change and its active version. A repo the valley
448// couldn't read is skipped; where several records hold the ID, one that
449// isn't withdrawn wins.
450func activeVersionOf(l *valley.Changes, id string) (repo string, ch valley.Change, v valley.Version, ok bool) {
451 for _, vr := range l.Repos {
452 if vr.Err() != "" {
453 continue
454 }
455 for _, c := range vr.Changes {
456 if c.ChangeID != id || (ok && ch.State != valley.StateWithdrawn) {
457 continue
458 }
459 for _, cv := range c.Versions {
460 if cv.N == c.Active {
461 repo, ch, v, ok = vr.Repo, c, cv, true
462 }
463 }
464 }
465 }
466 return
467}