gunk-dev/the-valley

walk.go

sourceb115ae7362ffmain's published tip history
15.9 KiB
1package main
2
3// valley review with no change: a walk through what needs the operator
4// (review.go).
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 calls the single-change review (review.go) with
16// a reviewStep for the row: the git handle on the row's repository root,
17// the current checkout's top level or the cache clone a project other
18// than the current one is read through (cacheRepo, list.go), with
19// cacheEnvironment's environment; the change as the queue held it, its ID,
20// version and head; the walk's -v and --build-here; the walk's terminal
21// and streams; and the walk's signer source. Every process the step starts
22// runs in that root and environment, unless it targets a tree of its own,
23// and nothing is set in the walk's own environment or directory. A cache
24// clone's configuration is its own, so the step's environment gives it
25// the current checkout's valley.principal, user.name and user.email
26// through GIT_CONFIG_COUNT, for each key the clone's own configuration
27// does not set, and nothing is written into the clone.
28//
29// The walk's signer source trusts the integrator of the valley the
30// current checkout's main names. A step in a cache clone whose project's
31// main names another valley, or none, is not reviewed with it
32// (walkValley): the step ends in error, saying which valley each names,
33// unless a flag or the environment gives what the walk trusts.
34//
35// The review returns how the step ended (stepOutcome), and the walk goes
36// on to the next row whatever it was, an error included. Each review a
37// step runs is recorded as an untimed review command of its own, from the
38// step's repository and environment, so a step in a cache clone is its
39// project's.
40//
41// Once the queue is first read, until the process exits, the walk
42// catches SIGINT and SIGTERM, and each step's review takes them from the
43// walk's catch while it listens (review.go): SIGINT and SIGTERM end the
44// step interrupted, SIGTERM sent to the walk alone included, and SIGHUP
45// ends it with 129. The review ends the walk through the step's end path:
46// once the step has cleaned up, the summary so far is printed (not for
47// SIGHUP), the step and the walk are recorded, and the process exits with
48// the review's status. One that arrives while no review listens, between
49// steps or while a step cleans up, ends the walk before the next step:
50// the step under way ends as it would and is recorded, the summary so far
51// is printed, and the walk exits 130. One that arrives while the queue is
52// read again ends the walk with 130 once the read has ended.
53//
54// The summary is one line per row walked, then what still needs the
55// operator, read again from every project, and what either read did not
56// cover.
57
58import (
59 "errors"
60 "fmt"
61 "io"
62 "os"
63 "os/signal"
64 "slices"
65 "strconv"
66 "strings"
67 "syscall"
68 "time"
69
70 "the-valley/change"
71)
72
73// walkConfigKeys are the settings a review in a cache clone borrows from
74// the current checkout: who approves and rebases, and who commits.
75var walkConfigKeys = []string{"valley.principal", "user.name", "user.email"}
76
77// walkQueue is one read of the queue for a walk.
78type walkQueue struct {
79 repos []listed
80 h handleMap
81 rows, moving []*entry
82 gaps []string // what the read did not cover, one line each
83 drafts, branches int
84}
85
86// walkStep is one row walked and how its step ended.
87type walkStep struct {
88 row *entry
89 outcome stepOutcome
90}
91
92// runWalk walks the queue. end ends the process when a signal ends a step,
93// after the walk has said what it walked; it does not return.
94func runWalk(g git, args []string, stdout, stderr io.Writer, end func(int)) int {
95 l := listing{all: true}
96 var flags []string // the flags each step's review is recorded with
97 var verbose, buildHere bool
98 var keyFlags approvalFlags
99 for i := 0; i < len(args); i++ {
100 last, isKey, err := keyFlags.take(args, i)
101 if err != nil {
102 fmt.Fprintf(stderr, "valley: %s\n", err)
103 return 2
104 }
105 if isKey {
106 flags = append(flags, args[i:last+1]...)
107 i = last
108 continue
109 }
110 switch a := args[i]; {
111 case a == "-v" || a == "--build-here":
112 flags = append(flags, a)
113 verbose, buildHere = verbose || a == "-v", buildHere || a == "--build-here"
114 case a == "--repo" && i+1 < len(args):
115 i++
116 l.repo = args[i]
117 case strings.HasPrefix(a, "--repo="):
118 l.repo = strings.TrimPrefix(a, "--repo=")
119 default:
120 fmt.Fprintf(stderr, "valley: walk does not take %s\n", a)
121 return 2
122 }
123 }
124 key, err := keyFlags.key()
125 if err != nil {
126 fmt.Fprintf(stderr, "valley: %s\n", err)
127 return 1
128 }
129 if l.repo != "" && !change.ValidPrincipal(l.repo) {
130 fmt.Fprintf(stderr, "valley: --repo %s: not a project name\n", l.repo)
131 return 1
132 }
133 q, err := readWalkQueue(g, l, stderr)
134 if err != nil {
135 fmt.Fprintf(stderr, "valley: %s\n", err)
136 return 1
137 }
138 defer closeSources(q.repos)
139 warnUnverified(q.repos, stderr)
140 t := terminalOf(stdout)
141 p := func(format string, args ...any) { fmt.Fprintf(stdout, format, args...) }
142 if len(q.rows) == 0 {
143 for _, line := range q.gapLines(t) {
144 p("%s\n", line)
145 }
146 if len(q.gaps) > 0 {
147 return 1
148 }
149 p("%s\n", q.nothing())
150 return 0
151 }
152 p("needs you (%d, in landing order)\n", len(q.rows))
153 for _, line := range q.gapLines(t) {
154 p("%s\n", line)
155 }
156
157 top, _ := g.output(true, "rev-parse", "--show-toplevel")
158 repos := map[string]listed{}
159 for _, r := range q.repos {
160 repos[r.name] = r
161 }
162 own := &walkValley{g: g, given: verification.given(), published: map[string]publication{}}
163 var walked []walkStep
164 summary := func() int {
165 status := 0
166 p("\nwalked (%d of %d)\n", len(walked), len(q.rows))
167 for _, s := range walked {
168 p("%s\n", s.line(t, q.h))
169 if s.outcome.kind == "error" {
170 status = 1
171 }
172 }
173 return status
174 }
175 // Never stopped: the process exits holding it.
176 interrupts := make(chan os.Signal, 1)
177 signal.Notify(interrupts, os.Interrupt, syscall.SIGTERM)
178 interrupted := false
179 for i, e := range q.rows {
180 if interrupted = interrupted || caught(interrupts); interrupted {
181 break
182 }
183 p("\n%s\n", stepHeader(t, i+1, len(q.rows), e))
184 r := repos[e.repo]
185 step := git{env: g.env, stderr: g.stderr, dir: top}
186 if r.g.dir != "" {
187 step.dir, step.env = r.g.dir, withConfig(r.g.env, borrowedConfig(g, r.g))
188 }
189 if step.dir == "" {
190 walked = append(walked, walkStep{row: e, outcome: stepOutcome{kind: "error", reason: "no work tree here to review it in"}})
191 continue
192 }
193 if why := own.elsewhere(r.g); why != "" {
194 fmt.Fprintf(stderr, "valley: %s: %s\n", e.repo, why)
195 walked = append(walked, walkStep{row: e, outcome: stepOutcome{kind: "error", reason: why}})
196 continue
197 }
198 inv := &invocation{args: append(append([]string{"review"}, flags...), e.id), since: time.Now(), version: versionStamp}
199 left := phase("steps")
200 o := reviewChange(reviewStep{g: step, queued: &queuedChange{id: e.id, version: e.version, head: e.head},
201 verbose: verbose, buildHere: buildHere, key: key, stdin: os.Stdin, stdout: stdout, stderr: stderr,
202 signers: verification, interrupts: interrupts,
203 end: func(status int, o stepOutcome) {
204 walked = append(walked, walkStep{row: e, outcome: o})
205 if status == interruptedStatus {
206 summary()
207 }
208 inv.record(step, status, false)
209 closeSources(q.repos)
210 verification.done()
211 end(status)
212 }}, e.id)
213 left()
214 inv.record(step, o.status, false)
215 walked = append(walked, walkStep{row: e, outcome: o})
216 interrupted = caught(interrupts)
217 }
218
219 status := summary()
220 if interrupted {
221 return interruptedStatus
222 }
223 again, err := readWalkQueue(g, l, io.Discard)
224 if caught(interrupts) {
225 closeSources(again.repos)
226 return interruptedStatus
227 }
228 if err != nil {
229 fmt.Fprintf(stderr, "valley: the queue did not read again: %s\n", err)
230 return 1
231 }
232 closeSources(again.repos)
233 // The summary repeats what the first read did not cover, since the walk
234 // left it out, and adds what the second read did not.
235 for _, gap := range again.gaps {
236 if !slices.Contains(q.gaps, gap) {
237 q.gaps = append(q.gaps, gap)
238 }
239 }
240 p("\n")
241 for _, line := range q.gapLines(t) {
242 p("%s\n", line)
243 }
244 switch {
245 case len(again.rows) > 0:
246 var names []string
247 for _, e := range again.rows {
248 names = append(names, e.repo+" "+e.ref)
249 }
250 p("still needs you (%d): %s\n", len(again.rows), strings.Join(names, ", "))
251 case len(again.gaps) == 0:
252 p("%s\n", again.nothing())
253 }
254 if len(q.gaps) > 0 {
255 status = 1
256 }
257 return status
258}
259
260// walkValley is the valley the walk's checkout's main names, whose
261// publication the walk's signer source reads, set against the valley each
262// step's cache clone names (instanceOf). A step whose project names
263// another valley, or none, is not verified with the walk's source: the
264// integrator that signs its transfer statements is its own valley's.
265type walkValley struct {
266 g git // the walk's checkout
267 given bool // a flag or the environment gives what the walk trusts
268
269 read bool
270 instance string
271 err error
272 published map[string]publication // what each instance URL read publishes
273}
274
275// publication is the signers tree an instance repository publishes, ""
276// for none, or the error of reading it.
277type publication struct {
278 tree string
279 err error
280}
281
282// elsewhere is why a step in the cache clone c is not reviewed with the
283// walk's signer source, or "" when its project's main names the walk's
284// valley. Two URLs are one valley when they are the same string, or when
285// both read the same signers publication, which holds for two spellings
286// of one repository and makes the trust the same either way. When the
287// operator gave what the walk trusts, every step is reviewed with it.
288func (v *walkValley) elsewhere(c git) string {
289 if v.given || c.dir == "" {
290 return ""
291 }
292 const there = " · review it from a checkout of its own valley"
293 theirs, err := instanceOf(c)
294 var none noInstance
295 switch {
296 case errors.As(err, &none):
297 return "its main names no valley" + there
298 case err != nil:
299 return fmt.Sprintf("could not read which valley its main names: %v", err)
300 }
301 if !v.read {
302 v.read = true
303 v.instance, v.err = instanceOf(v.g)
304 }
305 if v.err != nil {
306 return fmt.Sprintf("could not read which valley this checkout's main names: %v", v.err)
307 }
308 if theirs == v.instance {
309 return ""
310 }
311 if a, b := v.publication(theirs), v.publication(v.instance); a.err == nil && b.err == nil && a.tree == b.tree {
312 return ""
313 }
314 return fmt.Sprintf("its main names the valley %s, not this checkout's %s%s", theirs, v.instance, there)
315}
316
317// publication is what the instance repository at url publishes, read once.
318func (v *walkValley) publication(url string) publication {
319 if p, ok := v.published[url]; ok {
320 return p
321 }
322 tree, err := remoteRef(v.g.restricted(), url, signersRef)
323 p := publication{tree: tree, err: err}
324 v.published[url] = p
325 return p
326}
327
328// caught reports whether a signal is waiting on c, and takes it.
329func caught(c chan os.Signal) bool {
330 select {
331 case <-c:
332 return true
333 default:
334 return false
335 }
336}
337
338// readWalkQueue reads the queue across the repositories l covers, and
339// what the read did not cover. closeSources removes what it read.
340func readWalkQueue(g git, l listing, stderr io.Writer) (walkQueue, error) {
341 list, _, gap, err := findSources(g, l)
342 if err != nil {
343 return walkQueue{}, err
344 }
345 q := walkQueue{repos: readSources(list, newVerifier())}
346 q.h = handles(q.repos)
347 if gap != nil {
348 q.gaps = append(q.gaps, fmt.Sprintf("discovery is unavailable: %v · walking %s only", gap, list[0].name))
349 }
350 for _, r := range q.repos {
351 if r.err != nil {
352 q.gaps = append(q.gaps, fmt.Sprintf("%s did not read: %v", r.name, r.err))
353 }
354 }
355 c := newCosts()
356 q.rows, q.moving = operatorQueue(q.repos, q.h, l, c, nil, assessEvidence, stderr, func(_ listed, view jsonRepo) {
357 q.drafts, q.branches = q.drafts+len(*view.Drafts), q.branches+len(view.Branches)
358 })
359 c.close()
360 return q, nil
361}
362
363// gapLines are the read's gaps, one failed line each.
364func (q walkQueue) gapLines(t terminal) []string {
365 var lines []string
366 for _, gap := range q.gaps {
367 lines = append(lines, t.tint(colourRefused, "✗")+" "+fit(gap, t.width-2))
368 }
369 return lines
370}
371
372// nothing is the line of a queue with no row, with the counts valley
373// pending gives of what else there is.
374func (q walkQueue) nothing() string {
375 parts := []string{"nothing needs you"}
376 if n := len(q.moving); n > 0 {
377 parts = append(parts, fmt.Sprintf("%d moving", n))
378 }
379 if q.drafts > 0 {
380 parts = append(parts, counted(q.drafts, "draft"))
381 }
382 switch q.branches {
383 case 0:
384 case 1:
385 parts = append(parts, "1 branch no change is on")
386 default:
387 parts = append(parts, fmt.Sprintf("%d branches no change is on", q.branches))
388 }
389 return strings.Join(parts, " · ")
390}
391
392// stepHeader is the line that opens step n of all: the row's project, its
393// change, the stack it tops and its checks, as the queue read them.
394func stepHeader(t terminal, n, all int, e *entry) string {
395 parts := []string{fmt.Sprintf("[%d/%d] %s", n, all, e.repo), t.strong(e.name)}
396 if len(e.below) > 0 {
397 parts = append(parts, "stack of "+strconv.Itoa(len(e.below)+1))
398 }
399 if c := checkCount(e.state); c != "" {
400 parts = append(parts, c)
401 }
402 return strings.Join(parts, " · ")
403}
404
405// borrowedConfig is the configuration a review in the cache clone at
406// clone takes from the current checkout here: each of walkConfigKeys that
407// here sets and the clone's own configuration does not.
408func borrowedConfig(here, clone git) [][2]string {
409 var kv [][2]string
410 for _, k := range walkConfigKeys {
411 v, err := here.output(true, "config", "--get", k)
412 if err != nil || v == "" || clone.succeeds(true, "config", "--local", "--get", k) {
413 continue
414 }
415 kv = append(kv, [2]string{k, v})
416 }
417 return kv
418}
419
420// withConfig is env with each pair added to git's configuration through
421// GIT_CONFIG_COUNT, after the entries env gives it already. A count git
422// would refuse has failed every git the walk ran before this.
423func withConfig(env []string, kv [][2]string) []string {
424 if len(kv) == 0 {
425 return env
426 }
427 n := 0
428 var kept []string
429 for _, e := range env {
430 if v, ok := strings.CutPrefix(e, "GIT_CONFIG_COUNT="); ok {
431 n, _ = strconv.Atoi(v)
432 continue
433 }
434 kept = append(kept, e)
435 }
436 for i, p := range kv {
437 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]))
438 }
439 return append(kept, fmt.Sprintf("GIT_CONFIG_COUNT=%d", n+len(kv)))
440}
441
442// line is the summary's line for a step: its glyph, the row's project,
443// handle and version, and what became of it.
444func (s walkStep) line(t terminal, h handleMap) string {
445 e, o := s.row, s.outcome
446 glyph, colour, says := "◇", colourWaiting, o.kind
447 switch o.kind {
448 case "approved":
449 glyph, colour = "✓", colourDone
450 id, handle, version := o.id, o.handle, o.version
451 if known := h[handleKey{e.repo, recordTarget, id}]; known != "" {
452 handle = known
453 }
454 switch {
455 case id != e.id:
456 says = "approved " + handle + " v" + version + ", a layer under it"
457 case version != strconv.Itoa(e.version):
458 says = "approved v" + version
459 }
460 case "rejected":
461 glyph, colour, says = "✓", colourDone, "rejected · branch deleted"
462 case "kept":
463 says = "kept · rejection not confirmed"
464 case "refused":
465 glyph, colour, says = "⊘", colourRefused, "refused, then skipped"
466 case "moved":
467 says = "moved while shown"
468 case "not-reviewed":
469 glyph, colour, says = "⊘", colourRefused, "not reviewed · "+o.reason
470 case "error":
471 glyph, colour = "✗", colourRefused
472 if o.reason != "" {
473 says += " · " + o.reason
474 }
475 }
476 lead := " " + glyph + " " + e.repo + " "
477 return " " + t.tint(colour, glyph) + " " + e.repo + " " + t.strong(e.name) + " " +
478 fit(says, t.width-columns(lead)-columns(e.name)-2)
479}