gunk-dev/the-valley

walk.go

source795c933f9c5emain's published tip history
13.4 KiB
1package main
2
3// valley review with no change: a walk through what needs the operator.
4// bin/valley runs valley-go walk for it.
5//
6// The walk reads the queue once, as valley pending reads it
7// (operatorQueue, queue.go), across every project the serving host
8// publishes, or the one --repo names, and steps through its rows that wait
9// on an approval in landing order. A project that did not read, and a
10// discovery that failed and left the walk with the current project alone,
11// are said before the first step and again in the summary, and nothing
12// says that nothing needs the operator while either stands.
13//
14// Each step prints a header naming the row's project, handle, version,
15// stack and checks, then runs the single-change review as a child:
16//
17// $VALLEY_COMMAND review [-v] [--build-here] <change ID>
18//
19// in the row's repository root: the current checkout's top level, or the
20// cache clone a project other than the current one is read through
21// (cacheRepo, list.go), with cacheEnvironment's environment. The child has
22// the walker's stdin, stdout and stderr. A cache clone's configuration is
23// its own, so the child is given the current checkout's valley.principal,
24// user.name and user.email through GIT_CONFIG_COUNT, for each key the
25// clone's own configuration does not set, and nothing is written into the
26// clone. Two variables tell the child it is a step of a walk:
27//
28// VALLEY_WALK_QUEUED <change ID> <version> <head>, as the queue held it
29// VALLEY_WALK_OUTCOME the file the child writes how the step ended to
30//
31// The outcome is one line of tab-separated fields, its first field one of:
32//
33// approved <change ID> <handle> <version> <head> what the step approved
34// rejected <branch> the branch was deleted from origin
35// kept <branch> the rejection was not confirmed
36// skipped
37// refused an answer was refused, then the change skipped
38// moved it moved while it was shown
39// not-reviewed <reason> it landed, is not ready, or has no branch now
40// interrupted
41// error
42//
43// A child that leaves no outcome the walker reads ended in error. While a
44// child runs, the walker catches SIGINT rather than ignoring it, so the
45// child, which a terminal's Ctrl-C reaches too, keeps its own handling.
46// A step interrupted, by the child exiting 130 or by SIGINT reaching the
47// walker, ends the walk: the summary so far is printed and the walk exits
48// 130.
49//
50// The summary is one line per row walked, then what still needs the
51// operator, read again from every project, and what either read did not
52// cover.
53
54import (
55 "fmt"
56 "io"
57 "os"
58 "os/exec"
59 "os/signal"
60 "path/filepath"
61 "slices"
62 "strconv"
63 "strings"
64
65 "the-valley/change"
66)
67
68// walkConfigKeys are the settings a review in a cache clone borrows from
69// the current checkout: who approves and rebases, and who commits.
70var walkConfigKeys = []string{"valley.principal", "user.name", "user.email"}
71
72// walkQueue is one read of the queue for a walk.
73type walkQueue struct {
74 repos []listed
75 h handleMap
76 rows, moving []*entry
77 gaps []string // what the read did not cover, one line each
78 drafts, branches int
79}
80
81// stepOutcome is how one step ended, as its outcome file says.
82type stepOutcome struct {
83 kind string
84 fields []string
85}
86
87// walkStep is one row walked and how its step ended.
88type walkStep struct {
89 row *entry
90 outcome stepOutcome
91}
92
93func runWalk(g git, args []string, stdout, stderr io.Writer) int {
94 l := listing{all: true}
95 var child []string // the flags each step's review is given
96 for i := 0; i < len(args); i++ {
97 switch a := args[i]; {
98 case a == "-v" || a == "--build-here":
99 child = append(child, a)
100 case a == "--repo" && i+1 < len(args):
101 i++
102 l.repo = args[i]
103 case strings.HasPrefix(a, "--repo="):
104 l.repo = strings.TrimPrefix(a, "--repo=")
105 default:
106 fmt.Fprintf(stderr, "valley: walk does not take %s\n", a)
107 return 2
108 }
109 }
110 if l.repo != "" && !change.ValidPrincipal(l.repo) {
111 fmt.Fprintf(stderr, "valley: --repo %s: not a project name\n", l.repo)
112 return 1
113 }
114 valley, err := walkCommand()
115 if err != nil {
116 fmt.Fprintf(stderr, "valley: %s\n", err)
117 return 1
118 }
119 q, err := readWalkQueue(g, l, stderr)
120 if err != nil {
121 fmt.Fprintf(stderr, "valley: %s\n", err)
122 return 1
123 }
124 warnUnverified(q.repos, stderr)
125 t := terminalOf(stdout)
126 p := func(format string, args ...any) { fmt.Fprintf(stdout, format, args...) }
127 if len(q.rows) == 0 {
128 for _, line := range q.gapLines(t) {
129 p("%s\n", line)
130 }
131 if len(q.gaps) > 0 {
132 return 1
133 }
134 p("%s\n", q.nothing())
135 return 0
136 }
137 p("needs you (%d, in landing order)\n", len(q.rows))
138 for _, line := range q.gapLines(t) {
139 p("%s\n", line)
140 }
141
142 scratch, err := os.MkdirTemp("", "valley-walk-")
143 if err != nil {
144 fmt.Fprintf(stderr, "valley: no scratch directory for the walk's outcomes: %v\n", err)
145 return 1
146 }
147 defer os.RemoveAll(scratch)
148 top, _ := g.output(true, "rev-parse", "--show-toplevel")
149 repos := map[string]listed{}
150 for _, r := range q.repos {
151 repos[r.name] = r
152 }
153 interrupts := make(chan os.Signal, 1)
154 signal.Notify(interrupts, os.Interrupt)
155 var walked []walkStep
156 interrupted, broken := false, false
157 for i, e := range q.rows {
158 if interrupted = interrupted || caught(interrupts); interrupted || broken {
159 break
160 }
161 p("\n%s\n", stepHeader(t, i+1, len(q.rows), e))
162 step := walkStep{row: e}
163 r := repos[e.repo]
164 dir := r.g.dir
165 if dir == "" {
166 dir = top
167 }
168 if dir == "" {
169 step.outcome = stepOutcome{kind: "error", fields: []string{"no work tree here to review it in"}}
170 walked = append(walked, step)
171 continue
172 }
173 outcome := filepath.Join(scratch, fmt.Sprintf("step-%d", i+1))
174 cmd := exec.Command(valley, append(append([]string{"review"}, child...), e.id)...)
175 cmd.Dir = dir
176 cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, stdout, stderr
177 env := os.Environ()
178 if r.g.dir != "" {
179 env = withConfig(cacheEnvironment(env), borrowedConfig(g, r.g))
180 }
181 cmd.Env = append(env,
182 fmt.Sprintf("VALLEY_WALK_QUEUED=%s %d %s", e.id, e.version, e.head),
183 "VALLEY_WALK_OUTCOME="+outcome)
184 end := phase("steps")
185 processStarted()
186 if err := cmd.Start(); err != nil {
187 end()
188 step.outcome = stepOutcome{kind: "error", fields: []string{fmt.Sprintf("could not run %s: %v", valley, err)}}
189 walked, broken = append(walked, step), true
190 continue
191 }
192 _ = cmd.Wait()
193 end()
194 interrupted = caught(interrupts) || cmd.ProcessState.ExitCode() == 130
195 var ok bool
196 if step.outcome, ok = readOutcome(outcome); !ok {
197 step.outcome = stepOutcome{kind: "error"}
198 if interrupted {
199 step.outcome.kind = "interrupted"
200 }
201 }
202 walked = append(walked, step)
203 }
204 signal.Stop(interrupts)
205
206 status := 0
207 p("\nwalked (%d of %d)\n", len(walked), len(q.rows))
208 for _, s := range walked {
209 p("%s\n", s.line(t, q.h))
210 if s.outcome.kind == "error" {
211 status = 1
212 }
213 }
214 if interrupted {
215 return 130
216 }
217 again, err := readWalkQueue(g, l, io.Discard)
218 if err != nil {
219 fmt.Fprintf(stderr, "valley: the queue did not read again: %s\n", err)
220 return 1
221 }
222 // The summary repeats what the first read did not cover, since the walk
223 // left it out, and adds what the second read did not.
224 for _, gap := range again.gaps {
225 if !slices.Contains(q.gaps, gap) {
226 q.gaps = append(q.gaps, gap)
227 }
228 }
229 p("\n")
230 for _, line := range q.gapLines(t) {
231 p("%s\n", line)
232 }
233 switch {
234 case len(again.rows) > 0:
235 var names []string
236 for _, e := range again.rows {
237 names = append(names, e.repo+" "+e.ref)
238 }
239 p("still needs you (%d): %s\n", len(again.rows), strings.Join(names, ", "))
240 case len(again.gaps) == 0:
241 p("%s\n", again.nothing())
242 }
243 if len(q.gaps) > 0 {
244 status = 1
245 }
246 return status
247}
248
249// caught reports whether a signal is waiting on c, and takes it.
250func caught(c chan os.Signal) bool {
251 select {
252 case <-c:
253 return true
254 default:
255 return false
256 }
257}
258
259// walkCommand is the valley command each step runs, as an absolute path,
260// since a step runs in another directory: VALLEY_COMMAND, which bin/valley
261// sets to its own path, or valley on PATH.
262func walkCommand() (string, error) {
263 v := os.Getenv("VALLEY_COMMAND")
264 if v == "" {
265 v = "valley"
266 }
267 if !strings.Contains(v, "/") {
268 found, err := exec.LookPath(v)
269 if err != nil {
270 return "", fmt.Errorf("no %s command to review each change with: %v", v, err)
271 }
272 v = found
273 }
274 return filepath.Abs(v)
275}
276
277// readWalkQueue reads the queue across the repositories l covers, and
278// what the read did not cover.
279func readWalkQueue(g git, l listing, stderr io.Writer) (walkQueue, error) {
280 list, _, gap, err := findSources(g, l)
281 if err != nil {
282 return walkQueue{}, err
283 }
284 q := walkQueue{repos: readSources(list, newVerifier())}
285 q.h = handles(q.repos)
286 if gap != nil {
287 q.gaps = append(q.gaps, fmt.Sprintf("discovery is unavailable: %v · walking %s only", gap, list[0].name))
288 }
289 for _, r := range q.repos {
290 if r.err != nil {
291 q.gaps = append(q.gaps, fmt.Sprintf("%s did not read: %v", r.name, r.err))
292 }
293 }
294 q.rows, q.moving = operatorQueue(q.repos, q.h, l, newCosts(), stderr, func(_ listed, view jsonRepo) {
295 q.drafts, q.branches = q.drafts+len(*view.Drafts), q.branches+len(view.Branches)
296 })
297 return q, nil
298}
299
300// gapLines are the read's gaps, one failed line each.
301func (q walkQueue) gapLines(t terminal) []string {
302 var lines []string
303 for _, gap := range q.gaps {
304 lines = append(lines, t.tint(colourRefused, "✗")+" "+fit(gap, t.width-2))
305 }
306 return lines
307}
308
309// nothing is the line of a queue with no row, with the counts valley
310// pending gives of what else there is.
311func (q walkQueue) nothing() string {
312 parts := []string{"nothing needs you"}
313 if n := len(q.moving); n > 0 {
314 parts = append(parts, fmt.Sprintf("%d moving", n))
315 }
316 if q.drafts > 0 {
317 parts = append(parts, counted(q.drafts, "draft"))
318 }
319 switch q.branches {
320 case 0:
321 case 1:
322 parts = append(parts, "1 branch no change is on")
323 default:
324 parts = append(parts, fmt.Sprintf("%d branches no change is on", q.branches))
325 }
326 return strings.Join(parts, " · ")
327}
328
329// stepHeader is the line that opens step n of all: the row's project, its
330// change, the stack it tops and its checks, as the queue read them.
331func stepHeader(t terminal, n, all int, e *entry) string {
332 parts := []string{fmt.Sprintf("[%d/%d] %s", n, all, e.repo), t.strong(e.name)}
333 if len(e.below) > 0 {
334 parts = append(parts, "stack of "+strconv.Itoa(len(e.below)+1))
335 }
336 if c := checkCount(e.state); c != "" {
337 parts = append(parts, c)
338 }
339 return strings.Join(parts, " · ")
340}
341
342// borrowedConfig is the configuration a review in the cache clone at
343// clone takes from the current checkout here: each of walkConfigKeys that
344// here sets and the clone's own configuration does not.
345func borrowedConfig(here, clone git) [][2]string {
346 var kv [][2]string
347 for _, k := range walkConfigKeys {
348 v, err := here.output(true, "config", "--get", k)
349 if err != nil || v == "" || clone.succeeds(true, "config", "--local", "--get", k) {
350 continue
351 }
352 kv = append(kv, [2]string{k, v})
353 }
354 return kv
355}
356
357// withConfig is env with each pair added to git's configuration through
358// GIT_CONFIG_COUNT, after the entries env gives it already. A count git
359// would refuse has failed every git the walk ran before this.
360func withConfig(env []string, kv [][2]string) []string {
361 if len(kv) == 0 {
362 return env
363 }
364 n := 0
365 var kept []string
366 for _, e := range env {
367 if v, ok := strings.CutPrefix(e, "GIT_CONFIG_COUNT="); ok {
368 n, _ = strconv.Atoi(v)
369 continue
370 }
371 kept = append(kept, e)
372 }
373 for i, p := range kv {
374 kept = append(kept, fmt.Sprintf("GIT_CONFIG_KEY_%d=%s", n+i, p[0]), fmt.Sprintf("GIT_CONFIG_VALUE_%d=%s", n+i, p[1]))
375 }
376 return append(kept, fmt.Sprintf("GIT_CONFIG_COUNT=%d", n+len(kv)))
377}
378
379// outcomeFields is how many fields each outcome takes after its name.
380var outcomeFields = map[string]int{
381 "approved": 4, "rejected": 1, "kept": 1, "skipped": 0, "refused": 0,
382 "moved": 0, "not-reviewed": 1, "interrupted": 0, "error": 0,
383}
384
385// readOutcome reads a step's outcome file. ok is false when there is none,
386// or it is no outcome.
387func readOutcome(path string) (o stepOutcome, ok bool) {
388 b, err := os.ReadFile(path)
389 if err != nil {
390 return o, false
391 }
392 line, _, _ := strings.Cut(string(b), "\n")
393 f := strings.Split(line, "\t")
394 n, known := outcomeFields[f[0]]
395 if !known || len(f)-1 != n {
396 return o, false
397 }
398 return stepOutcome{kind: f[0], fields: f[1:]}, true
399}
400
401// line is the summary's line for a step: its glyph, the row's project,
402// handle and version, and what became of it.
403func (s walkStep) line(t terminal, h handleMap) string {
404 e, f := s.row, s.outcome.fields
405 glyph, colour, says := "◇", colourWaiting, s.outcome.kind
406 switch s.outcome.kind {
407 case "approved":
408 glyph, colour = "✓", colourDone
409 id, handle, version := f[0], f[1], f[2]
410 if known := h[handleKey{e.repo, recordTarget, id}]; known != "" {
411 handle = known
412 }
413 switch {
414 case id != e.id:
415 says = "approved " + handle + " v" + version + ", a layer under it"
416 case version != strconv.Itoa(e.version):
417 says = "approved v" + version
418 }
419 case "rejected":
420 glyph, colour, says = "✓", colourDone, "rejected · branch deleted"
421 case "kept":
422 says = "kept · rejection not confirmed"
423 case "refused":
424 glyph, colour, says = "⊘", colourRefused, "refused, then skipped"
425 case "moved":
426 says = "moved while shown"
427 case "not-reviewed":
428 glyph, colour, says = "⊘", colourRefused, "not reviewed · "+f[0]
429 case "error":
430 glyph, colour = "✗", colourRefused
431 if len(f) > 0 {
432 says += " · " + f[0]
433 }
434 }
435 lead := " " + glyph + " " + e.repo + " "
436 return " " + t.tint(colour, glyph) + " " + e.repo + " " + t.strong(e.name) + " " +
437 fit(says, t.width-columns(lead)-columns(e.name)-2)
438}