gunk-dev/the-valley

track_change.go

source28abc5737165main's published tip history
5.1 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 := existingRepoDir(proj)
46 switch {
47 case dir == "" && proj == "":
48 return nil, fmt.Errorf("no project for change %s: name it as <project>:%s, use --repo, or set a session target", id, id)
49 case dir == "":
50 return nil, fmt.Errorf("no checkout of %s on this machine: register it with valley flow project add", proj)
51 }
52 l, ok := listings[dir]
53 if !ok {
54 var err error
55 if l, err = valley.ListRepo(ctx, dir); err != nil {
56 return nil, fmt.Errorf("asking the valley about %s: %w", dir, err)
57 }
58 listings[dir] = l
59 }
60 where := proj
61 if where == "" {
62 where = dir
63 }
64 type found struct {
65 repo string
66 ch valley.Change
67 }
68 var matches []found
69 for _, vr := range l.Repos {
70 if vr.Err() != "" {
71 continue
72 }
73 for _, ch := range vr.Changes {
74 _, prefix, _ := strings.Cut(ch.Handle, ":") // a handle the valley qualifies as <repo>:<prefix>
75 if refersTo(id, ch.ChangeID, ch.Handle, prefix) {
76 matches = append(matches, found{vr.Repo, ch})
77 }
78 }
79 }
80 switch len(matches) {
81 case 0:
82 return nil, fmt.Errorf("the valley lists no change %s in %s", id, where)
83 case 1:
84 default:
85 var lines []string
86 for _, f := range matches {
87 lines = append(lines, changeName(f.ch.ChangeID, f.ch.Handle)+" in "+f.repo)
88 }
89 return nil, ambiguous(id, where, lines)
90 }
91 repo, ch := matches[0].repo, matches[0].ch
92
93 for _, s := range states {
94 if s.Type != "session" && s.ChangeID == ch.ChangeID && integration.RepoName(s) == repo {
95 fmt.Printf("Already tracking change %s (%s)\n", ch.Handle, repo)
96 return nil, nil
97 }
98 }
99
100 var active valley.Version
101 for _, v := range ch.Versions {
102 if v.N == ch.Active {
103 active = v
104 }
105 }
106 switch {
107 case active.Landing == valley.Landed || active.Landing == valley.LandedRecorded:
108 fmt.Fprintf(os.Stderr, "warning: change %s has landed\n", ch.Handle)
109 case ch.State == valley.StateWithdrawn:
110 fmt.Fprintf(os.Stderr, "warning: change %s is withdrawn\n", ch.Handle)
111 }
112 title := active.Title
113 if title == "" {
114 title = "change " + ch.Handle
115 }
116
117 target := repo
118 if proj != "" {
119 reg, _ := project.Load()
120 target = project.NormalizeRepoName(proj, reg)
121 }
122 runID, err := run.GenID()
123 if err != nil {
124 return nil, err
125 }
126 st := &run.State{
127 ID: runID,
128 Prompt: title,
129 Branch: active.Branch,
130 Type: "track",
131 TargetRepo: &target,
132 CloneDir: &dir,
133 CreatedAt: time.Now().Format(time.RFC3339),
134 ChangeID: ch.ChangeID,
135 HeadSHA: active.Head,
136 RepoKey: "valley:" + repo,
137 Valley: &run.Valley{Repo: repo, Handle: ch.Handle, Version: ch.Active, Title: active.Title},
138 }
139 if err := store.Save(st); err != nil {
140 return nil, fmt.Errorf("saving state: %w", err)
141 }
142 fmt.Printf("Tracking change %s (%s) — %s\n", ch.Handle, repo, title)
143 return st, nil
144}
145
146// trackedChanges returns the tracked valley changes among states that id (a
147// handle or a change ID) names, in project when it isn't "": by the valley's
148// name for the change's repo, or the name its project had when it was
149// tracked.
150func trackedChanges(states []*run.State, proj, id string) []*run.State {
151 var out []*run.State
152 for _, s := range states {
153 if !integration.TracksChange(s) || !refersTo(id, s.ChangeID, s.Valley.Handle) {
154 continue
155 }
156 if proj != "" && proj != s.Valley.Repo && proj != deref(s.TargetRepo) {
157 reg, _ := project.Load()
158 if project.NormalizeRepoName(proj, reg) != deref(s.TargetRepo) {
159 continue
160 }
161 }
162 out = append(out, s)
163 }
164 return out
165}