gunk-dev/the-valley

track_change.go

source4cbb5ec9c5dbmain's published tip history
5.3 KiB
1package cmd
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "regexp"
8 "strings"
9 "time"
10
11 "the-valley/flow/internal/integration"
12 "the-valley/flow/internal/project"
13 "the-valley/flow/internal/run"
14 "the-valley/flow/internal/valley"
15)
16
17// changeRefPattern matches a valley change as klaus track and untrack take
18// it: a handle or a full change ID (4 to 32 of the letters k to z a change ID
19// is made of), optionally after "<project>:".
20var changeRefPattern = regexp.MustCompile(`^(?:([^:\s]+):)?([k-z]{4,32})$`)
21
22// parseChangeRef splits a valley change ref into its project ("" when it
23// names none) and its handle or change ID. ok is false when ref isn't one.
24func parseChangeRef(ref string) (project, id string, ok bool) {
25 m := changeRefPattern.FindStringSubmatch(ref)
26 if m == nil {
27 return "", "", false
28 }
29 return m[1], m[2], true
30}
31
32// valleyListings caches the valley's listing of each checkout klaus track
33// asks about, so one command asks once per repo.
34type valleyListings map[string]*valley.Changes
35
36// trackChange tracks the valley change id names (a handle or a change ID) in
37// project, a registered project name, owner/repo or URL with a local
38// checkout, or "" for the repo of the current directory. It asks the valley
39// about that checkout and saves a track record of the change: its ID, the
40// valley's name for its repo, its handle, and its active version's number,
41// title, branch and head. It returns the record, or nil when it saved none:
42// the change is already on the dashboard, tracked or pushed by a run in
43// states, or the valley doesn't list exactly one change id names.
44func trackChange(ctx context.Context, proj, id string, store run.StateStore, states []*run.State, listings valleyListings) (*run.State, error) {
45 dir, err := existingRepoDir(proj)
46 if err != nil {
47 return nil, err
48 }
49 switch {
50 case dir == "" && proj == "":
51 return nil, fmt.Errorf("no project for change %s: name it as <project>:%s, use --repo, or set a session target", id, id)
52 case dir == "":
53 return nil, fmt.Errorf("no checkout of %s on this machine: register it with valley flow project add", proj)
54 }
55 l, ok := listings[dir]
56 if !ok {
57 var err error
58 if l, err = valley.ListRepo(ctx, dir); err != nil {
59 return nil, fmt.Errorf("asking the valley about %s: %w", dir, err)
60 }
61 listings[dir] = l
62 }
63 where := proj
64 if where == "" {
65 where = dir
66 }
67 type found struct {
68 repo string
69 ch valley.Change
70 }
71 var matches []found
72 for _, vr := range l.Repos {
73 if vr.Err() != "" {
74 continue
75 }
76 for _, ch := range vr.Changes {
77 _, prefix, _ := strings.Cut(ch.Handle, ":") // a handle the valley qualifies as <repo>:<prefix>
78 if refersTo(id, ch.ChangeID, ch.Handle, prefix) {
79 matches = append(matches, found{vr.Repo, ch})
80 }
81 }
82 }
83 switch len(matches) {
84 case 0:
85 return nil, fmt.Errorf("the valley lists no change %s in %s", id, where)
86 case 1:
87 default:
88 var lines []string
89 for _, f := range matches {
90 lines = append(lines, changeName(f.ch.ChangeID, f.ch.Handle)+" in "+f.repo)
91 }
92 return nil, ambiguous(id, where, lines)
93 }
94 repo, ch := matches[0].repo, matches[0].ch
95
96 for _, s := range states {
97 if s.Type != "session" && s.ChangeID == ch.ChangeID && integration.RepoName(s) == repo {
98 fmt.Printf("Already tracking change %s (%s)\n", ch.Handle, repo)
99 return nil, nil
100 }
101 }
102
103 var active valley.Version
104 for _, v := range ch.Versions {
105 if v.N == ch.Active {
106 active = v
107 }
108 }
109 switch {
110 case active.Landing == valley.Landed || active.Landing == valley.LandedRecorded:
111 fmt.Fprintf(os.Stderr, "warning: change %s has landed\n", ch.Handle)
112 case ch.State == valley.StateWithdrawn:
113 fmt.Fprintf(os.Stderr, "warning: change %s is withdrawn\n", ch.Handle)
114 }
115 title := active.Title
116 if title == "" {
117 title = "change " + ch.Handle
118 }
119
120 target := repo
121 if proj != "" {
122 reg, err := registryUnlessConflict()
123 if err != nil {
124 return nil, err
125 }
126 target = project.NormalizeRepoName(proj, reg)
127 }
128 runID, err := run.GenID()
129 if err != nil {
130 return nil, err
131 }
132 st := &run.State{
133 ID: runID,
134 Prompt: title,
135 Branch: active.Branch,
136 Type: "track",
137 TargetRepo: &target,
138 CloneDir: &dir,
139 CreatedAt: time.Now().Format(time.RFC3339),
140 ChangeID: ch.ChangeID,
141 HeadSHA: active.Head,
142 RepoKey: "valley:" + repo,
143 Valley: &run.Valley{Repo: repo, Handle: ch.Handle, Version: ch.Active, Title: active.Title},
144 }
145 if err := store.Save(st); err != nil {
146 return nil, fmt.Errorf("saving state: %w", err)
147 }
148 fmt.Printf("Tracking change %s (%s) — %s\n", ch.Handle, repo, title)
149 return st, nil
150}
151
152// trackedChanges returns the tracked valley changes among states that id (a
153// handle or a change ID) names, in project when it isn't "": by the valley's
154// name for the change's repo, or the name its project had when it was
155// tracked. A registry at both its names is an error.
156func trackedChanges(states []*run.State, proj, id string) ([]*run.State, error) {
157 var out []*run.State
158 for _, s := range states {
159 if !integration.TracksChange(s) || !refersTo(id, s.ChangeID, s.Valley.Handle) {
160 continue
161 }
162 if proj != "" && proj != s.Valley.Repo && proj != deref(s.TargetRepo) {
163 reg, err := registryUnlessConflict()
164 if err != nil {
165 return nil, err
166 }
167 if project.NormalizeRepoName(proj, reg) != deref(s.TargetRepo) {
168 continue
169 }
170 }
171 out = append(out, s)
172 }
173 return out, nil
174}