gunk-dev/the-valley

ready.go

sourcecaaa5bee5e11main's published tip history
8.6 KiB
1package cmd
2
3import (
4 "errors"
5 "fmt"
6 "regexp"
7 "strings"
8
9 "the-valley/flow/internal/event"
10 "the-valley/flow/internal/git"
11 "the-valley/flow/internal/integration"
12 "the-valley/flow/internal/run"
13 "the-valley/flow/internal/tmux"
14 "the-valley/flow/internal/valley"
15 "github.com/spf13/cobra"
16)
17
18var readyCmd = &cobra.Command{
19 Use: "ready <run-id|handle> [--head <sha>]",
20 Short: "Mark a valley change ready for approval once its review passes",
21 Long: `Marks a valley change ready for approval: typically the draft that
22finalize leaves awaiting review when "ready_at_finalize" is false in
23~/.klaus/config.json or the project's .klaus/config.json. Run it once the
24change's review passes; until then approve refuses the change, and valley flow
25status and the dashboard show it awaiting review.
26
27<run-id|handle> is a run ID, which names that run's change, or the change's
28valley handle, its change ID or a prefix of it, as the runs of this session
29record them. A ref that names several changes is an error listing them.
30
31It marks the change's current head ready: its active version's when the
32valley lists the change, else the head the newest run on it, in any session,
33pushed. With --head <sha>, the head you reviewed (its full ID or at least 7
34hex digits of it), it marks exactly that head ready, and refuses, naming the
35current head, when the change's current head is another: a push after your
36review has not been reviewed. With --head the change's current head is the
37tip of its branch on origin when that differs from the one above, as when a
38follow-up's push isn't a version yet; if origin can't be asked, it refuses. That is 'valley ready --change <change-id>
39--head <head> <branch>', run in the run's clone, within 30 seconds. A draft
40at its active version's head is ready again at that version. valley flow ready then
41records the version on the run of this session that pushed the head, if any,
42emits agent:change-ready, with "via": "klaus ready", as finalize does when it
43marks a change ready, and prints the version and the head it marked ready,
44e.g. "widget nxvp v2 ready at <head> (run <run-id>)".
45
46It refuses while an agent in any session is running on the change, as a
47follow-up replacing its head is, and when the run's repo doesn't deliver to a
48valley. It takes the lock that launches continuing a change in the same clone
49take, so a follow-up launch can't start between that check and the ready.`,
50 Args: cobra.ExactArgs(1),
51 RunE: func(cmd *cobra.Command, args []string) error {
52 ctx := cmd.Context()
53 reviewed, _ := cmd.Flags().GetString("head")
54 if reviewed != "" && !headArg.MatchString(reviewed) {
55 return fmt.Errorf("--head takes the commit you reviewed, as its full ID or at least 7 hex digits of it, and %q is not one", reviewed)
56 }
57 store, err := sessionStore()
58 if err != nil {
59 return err
60 }
61 states, err := store.List()
62 if err != nil {
63 return err
64 }
65 s, err := readyTarget(states, args[0])
66 if err != nil {
67 return err
68 }
69 if !run.ValidChangeID(s.ChangeID) {
70 return fmt.Errorf("run %s has no change ID (its state predates change IDs)", s.ID)
71 }
72 repo, dir := integration.RepoName(s), branchDir(s)
73 if repo == "" {
74 return fmt.Errorf("can't tell which repo run %s is in", s.ID)
75 }
76 // A follow-up launch in this clone takes the same lock from its
77 // check for a running holder through its run's registration, so it
78 // either returns the change to draft after this, or is seen here.
79 // The change's head is read under it, from the runs as they stand
80 // now: a follow-up may have pushed a newer head since.
81 unlock, err := lockContinuation(ctx, dir)
82 if err != nil {
83 return err
84 }
85 defer unlock()
86 if states, err = store.List(); err != nil {
87 return err
88 }
89 // Every session's runs, this one's first, as launch reads them.
90 runs := append([]*run.State(nil), states...)
91 mine := make(map[string]bool)
92 for _, c := range states {
93 mine[c.ID] = true
94 }
95 all, _ := run.ListAllSessions()
96 for _, c := range all {
97 if !mine[c.ID] {
98 runs = append(runs, c)
99 }
100 }
101 t, err := resolveChange(s.ID, changeSources{
102 Runs: runs,
103 Repo: repo,
104 Valley: func() (*valley.Changes, error) { return valley.ListRepo(ctx, dir) },
105 })
106 if err != nil {
107 return err
108 }
109 if t.Branch == "" || t.Head == "" {
110 return fmt.Errorf("change %s has no known head: no run on it recorded a pushed branch, and no valley lists one", t.Name)
111 }
112 deps := run.TmuxDepsFor(ctx, tmux.NewExecClient())
113 running := func(r *run.State) bool { return r.IsAgentRunningWith(deps) }
114 if h := liveHolder(runs, running, "", t.ID, repo); h != nil {
115 return fmt.Errorf("run %s is still running on change %s; ready the change once it has pushed and its review has passed", h.ID, t.Name)
116 }
117 if reviewed != "" {
118 // A push the valley doesn't hold as a version yet, as when a
119 // follow-up's ready failed, moves the change on too.
120 head, where := t.Head, ""
121 tip, err := git.RemoteBranchSHA(ctx, dir, t.Branch)
122 if err != nil {
123 return fmt.Errorf("couldn't check origin's %s for a push newer than %s: %w", t.Branch, shortSHA(t.Head), err)
124 }
125 if tip != "" && tip != head {
126 head, where = tip, fmt.Sprintf(" (origin's %s, a push the valley doesn't hold as a version yet)", t.Branch)
127 }
128 if !strings.HasPrefix(head, strings.ToLower(reviewed)) {
129 return fmt.Errorf("change %s's current head is %s%s, not %s: it has moved on since the head you reviewed; review %s, then valley flow ready %s --head %s",
130 t.Name, head, where, reviewed, shortSHA(head), args[0], head)
131 }
132 t.Head = head
133 }
134 if !valley.Detect(ctx, dir, t.Branch, t.Head) {
135 return fmt.Errorf("change %s isn't on a valley flow can mark changes ready on: %s's origin isn't one, its head carries no valley policy, or valley isn't on PATH", t.Name, dir)
136 }
137 r, err := valley.Ready(ctx, dir, t.ID, t.Head, t.Branch)
138 if err != nil {
139 return err
140 }
141
142 // The run that pushed the head holds the version, when it is this
143 // session's; one marked ready elsewhere, or pushed by a run of
144 // another session, is recorded on none here.
145 var pusher *run.State
146 for _, c := range t.Runs {
147 if mine[c.ID] && c.PushedSHA != nil && *c.PushedSHA == t.Head {
148 pusher = c
149 break
150 }
151 }
152 title := ""
153 if pusher != nil {
154 rec := pusher.Valley
155 if rec == nil {
156 rec = &run.Valley{Title: commitSubject(ctx, dir, t.Head)}
157 pusher.Valley = rec
158 }
159 rec.Repo, rec.Handle, rec.Version, rec.Draft, rec.Error = r.Repo, r.Handle, r.Version, false, ""
160 title = rec.Title
161 if err := store.Save(pusher); err != nil {
162 return fmt.Errorf("%s %s v%d is ready, but recording it on run %s failed: %w", r.Repo, r.Handle, r.Version, pusher.ID, err)
163 }
164 } else {
165 title = commitSubject(ctx, dir, t.Head)
166 }
167 on := s
168 if pusher != nil {
169 on = pusher
170 }
171 if hds, ok := store.(*run.HomeDirStore); ok {
172 emitRunEvent(hds.BaseDir(), on, event.AgentChangeReady, map[string]interface{}{
173 "id": on.ID,
174 "repo": r.Repo,
175 "change_id": t.ID,
176 "handle": r.Handle,
177 "version": r.Version,
178 "title": title,
179 "head": t.Head,
180 "via": "klaus ready",
181 })
182 }
183 fmt.Printf("%s %s v%d ready at %s (run %s)\n", r.Repo, r.Handle, r.Version, t.Head, on.ID)
184 return nil
185 },
186}
187
188// headArg is what --head takes: a commit ID, full or at least 7 hex digits.
189var headArg = regexp.MustCompile(`^[0-9a-fA-F]{7,40}$`)
190
191// readyTarget finds the run whose change ref names, among a session's runs:
192// the run whose ID ref is, or else the newest run on the change whose
193// recorded valley handle ref is, or whose change ID starts with ref.
194func readyTarget(states []*run.State, ref string) (*run.State, error) {
195 if ref == "" {
196 return nil, errors.New("name a run ID, a valley handle or a change ID")
197 }
198 if s := findRun(states, ref); s != nil {
199 return s, nil
200 }
201 newest := make(map[integration.ChangeKey]*run.State)
202 for _, s := range states {
203 if s.Type == "session" || !run.ValidChangeID(s.ChangeID) || !refersTo(ref, s.ChangeID, recordedHandles(s)...) {
204 continue
205 }
206 k := integration.ChangeKey{Repo: integration.RepoName(s), ChangeID: s.ChangeID}
207 if prev, ok := newest[k]; !ok || createdBefore(prev, s) {
208 newest[k] = s
209 }
210 }
211 var lines []string
212 for k, s := range newest {
213 if len(newest) == 1 {
214 return s, nil
215 }
216 lines = append(lines, changeName(k.ChangeID, handleOf(s))+" in "+k.Repo+", latest run "+s.ID)
217 }
218 if len(lines) == 0 {
219 return nil, fmt.Errorf("no run in this session is on a change %q: name a run ID, a valley handle or a change ID", ref)
220 }
221 return nil, ambiguous(ref, "this session", lines)
222}
223
224func init() {
225 readyCmd.Flags().String("head", "", "The head you reviewed: mark exactly it ready, and refuse when the change's current head is another")
226 rootCmd.AddCommand(readyCmd)
227}