gunk-dev/the-valley

verdict.go

sourceb9df3fe59e29main's published tip history
13.3 KiB
1package main
2
3// verdict prints what approve and review's prompt say (bin/valley), from
4// the facts bin/valley already holds. An approval ends in one verdict
5// line, the change and what happened to it, with one indented line under
6// it only when the person must act:
7//
8// ✓ nqyw v3 approved · checks passed · landing on main
9// ◇ nqyw v3 approved · waiting for 2 checks (no worker building)
10// run: valley approve --build-here nqyw
11// ⊘ nqyw v3 not approved · change is a draft
12// run: valley ready nqyw
13//
14// The glyphs are plan's (plan.go): ✓ settled, ◐ under way, ◇ waiting on
15// nothing that will move by itself, ⊘ refused, and ? unknown. An approval
16// goes to stdout, a refusal to stderr. On a terminal the glyph has its
17// colour and the change's name is bold; in a pipe, or with NO_COLOR set,
18// the text is the same without them. A verdict never says a change landed:
19// approve files a request and does not watch it land.
20//
21// checking runs the checks approve builds here, as one line redrawn in
22// place on a terminal and as a start line in a pipe, and keeps the
23// builder's output to itself unless a check fails. prompt is review's
24// prompt: a header of clauses about the change, and the keys it takes.
25
26import (
27 "bufio"
28 "fmt"
29 "io"
30 "os"
31 "os/exec"
32 "strconv"
33 "strings"
34 "sync"
35 "syscall"
36 "time"
37)
38
39const verdictUsage = `usage: valley-go verdict approved|refused|unknown --name <name> [--version <n>] [<fact>]...
40 valley-go verdict checking --name <name> [--version <n>] [--of <n>] [--passed <n>] [-v] --check <name>... -- <command>...
41 valley-go verdict prompt <clause>... -- <key>...
42facts: --required <n> --passed <n> --took <duration> --waiting <check> --worker
43 --failed <check> --why <obstruction> --run <command> --see <command>
44 --then <text> --target <branch>`
45
46// The SGR colours of the verdict glyphs, as plan shows its states.
47const (
48 colourDone = "32"
49 colourWorking = "33"
50 colourRefused = "31"
51 colourWaiting = "36"
52)
53
54// verdict is the facts one outcome of approve is told from.
55type verdict struct {
56 outcome string // approved, refused or unknown
57 name string // a change's handle, or a branch
58 version string
59 target string
60 required int // the checks the policy requires; -1 when not given
61 passed int // how many of them have passed; -1 when not known
62 took string
63 waiting []string // required checks no evidence is published for yet
64 worker bool // a check worker builds the waiting checks
65 failed []string
66 why string // what stops the approval, or what is not known
67 run string // the command the person runs next
68 see string // where the person reads more
69 then string // what the person does next, when it is no command
70}
71
72func runVerdict(args []string, stdout, stderr io.Writer) int {
73 if len(args) == 0 {
74 fmt.Fprintln(stderr, verdictUsage)
75 return 2
76 }
77 if args[0] == "prompt" {
78 header, keys, _ := cutArgs(args[1:])
79 fmt.Fprint(stdout, promptLines(terminalOf(stdout), header, keys))
80 return 0
81 }
82 v := verdict{outcome: args[0], target: "main", required: -1, passed: -1}
83 var checks, command []string
84 verbose := false
85 args, command, _ = cutArgs(args[1:])
86 for i := 0; i < len(args); i++ {
87 flag := args[i]
88 if flag == "--worker" || flag == "-v" {
89 v.worker = v.worker || flag == "--worker"
90 verbose = verbose || flag == "-v"
91 continue
92 }
93 if i+1 == len(args) {
94 fmt.Fprintln(stderr, verdictUsage)
95 return 2
96 }
97 i++
98 value := args[i]
99 var err error
100 switch flag {
101 case "--name":
102 v.name = value
103 case "--version":
104 v.version = value
105 case "--target":
106 v.target = value
107 case "--required", "--of":
108 v.required, err = strconv.Atoi(value)
109 case "--passed":
110 v.passed, err = strconv.Atoi(value)
111 case "--took":
112 v.took = value
113 case "--waiting":
114 v.waiting = append(v.waiting, value)
115 case "--failed":
116 v.failed = append(v.failed, value)
117 case "--check":
118 checks = append(checks, value)
119 case "--why":
120 v.why = value
121 case "--run":
122 v.run = value
123 case "--see":
124 v.see = value
125 case "--then":
126 v.then = value
127 default:
128 err = fmt.Errorf("unknown flag %s", flag)
129 }
130 if err != nil {
131 fmt.Fprintf(stderr, "valley: %v\n%s\n", err, verdictUsage)
132 return 2
133 }
134 }
135 if v.name == "" {
136 fmt.Fprintln(stderr, verdictUsage)
137 return 2
138 }
139 switch v.outcome {
140 case "approved", "unknown":
141 fmt.Fprint(stdout, v.lines(terminalOf(stdout)))
142 case "refused":
143 fmt.Fprint(stderr, v.lines(terminalOf(stderr)))
144 return 1
145 case "checking":
146 if len(command) == 0 || len(checks) == 0 {
147 fmt.Fprintln(stderr, verdictUsage)
148 return 2
149 }
150 return v.checking(checks, command, verbose, droppable(stdout), droppable(stderr))
151 default:
152 fmt.Fprintln(stderr, verdictUsage)
153 return 2
154 }
155 return 0
156}
157
158// droppable is w, when it is a file, through a duplicate of its
159// descriptor. Go ends a process whose write to its own standard output or
160// error finds no reader; through a duplicate the write fails with EPIPE
161// and nothing more, so an approval goes on when nobody reads what its
162// checks print, as attest run's own output does.
163func droppable(w io.Writer) io.Writer {
164 f, ok := w.(*os.File)
165 if !ok {
166 return w
167 }
168 syscall.ForkLock.RLock()
169 fd, err := syscall.Dup(int(f.Fd()))
170 if err == nil {
171 syscall.CloseOnExec(fd)
172 }
173 syscall.ForkLock.RUnlock()
174 if err != nil {
175 return w
176 }
177 return os.NewFile(uintptr(fd), f.Name())
178}
179
180// cutArgs splits args at the first "--".
181func cutArgs(args []string) (before, after []string, found bool) {
182 for i, a := range args {
183 if a == "--" {
184 return args[:i], args[i+1:], true
185 }
186 }
187 return args, nil, false
188}
189
190// lines is the verdict: its line, and the action line under it when there
191// is one.
192func (v verdict) lines(t terminal) string {
193 var glyph, colour string
194 var clauses []string
195 action := v.action(t)
196 switch v.outcome {
197 case "refused":
198 glyph, colour = "⊘", colourRefused
199 why := v.why
200 if len(v.failed) > 0 {
201 why = fmt.Sprintf("%d of %s failed", len(v.failed), countOf(v.required, "check"))
202 if v.required < 0 {
203 why = countOf(len(v.failed), "check") + " failed"
204 }
205 action = t.tint(colourRefused, "✗") + " " + strings.Join(v.failed, ", ") + " — see: valley status " + v.name
206 }
207 clauses = []string{"not approved", why}
208 case "unknown":
209 glyph = "?"
210 why := v.why
211 if why == "" {
212 why = "state unknown"
213 }
214 clauses = []string{"approved", why, "see: valley status " + v.name}
215 action = ""
216 case "approved":
217 clauses = []string{"approved"}
218 switch {
219 case v.required == 0:
220 glyph, colour = "✓", colourDone
221 clauses = append(clauses, "no checks required", "landing on "+v.target)
222 case len(v.waiting) == 0:
223 glyph, colour = "✓", colourDone
224 passed := "checks passed"
225 if v.took != "" && v.required > 0 {
226 passed = countOf(v.required, "check") + " passed in " + v.took
227 }
228 clauses = append(clauses, passed, "landing on "+v.target)
229 case v.worker:
230 glyph, colour = "◐", colourWorking
231 if v.passed >= 0 && v.required > 0 {
232 pass := "pass"
233 if len(v.waiting) == 1 {
234 pass = "passes"
235 }
236 clauses = append(clauses, fmt.Sprintf("lands when %s %s (%d/%d passed)", countOf(len(v.waiting), "check"), pass, v.passed, v.required))
237 } else {
238 clauses = append(clauses, "waiting for "+countOf(len(v.waiting), "check"))
239 }
240 default:
241 glyph, colour = "◇", colourWaiting
242 clauses = append(clauses, "waiting for "+countOf(len(v.waiting), "check")+" (no worker building)")
243 }
244 }
245 line := t.tint(colour, glyph) + " " + t.strong(v.label()) + " " + strings.Join(clauses, " · ") + "\n"
246 if action != "" {
247 line += " " + action + "\n"
248 }
249 return line
250}
251
252// action is the line under a verdict that says what the person does next.
253func (v verdict) action(t terminal) string {
254 switch {
255 case v.run != "":
256 return "run: " + v.run
257 case v.see != "":
258 return "see: " + v.see
259 }
260 return v.then
261}
262
263// label is the change as a verdict names it: its handle and version, or
264// a branch's name.
265func (v verdict) label() string {
266 if v.version == "" {
267 return v.name
268 }
269 return v.name + " v" + v.version
270}
271
272// countOf is n of a thing, as "1 check" or "3 checks".
273func countOf(n int, thing string) string {
274 if n == 1 {
275 return "1 " + thing
276 }
277 return strconv.Itoa(n) + " " + thing + "s"
278}
279
280// promptLines is review's prompt: the header, its first clause the
281// change in bold, and the keys, each with its letter in bold on a
282// terminal, left open for the answer.
283func promptLines(t terminal, header, keys []string) string {
284 if len(header) > 0 {
285 header[0] = t.strong(header[0])
286 }
287 shown := make([]string, len(keys))
288 for i, k := range keys {
289 if open, rest, ok := strings.Cut(k, "["); ok {
290 if letter, after, ok := strings.Cut(rest, "]"); ok {
291 k = open + "[" + t.strong(letter) + "]" + after
292 }
293 }
294 shown[i] = k
295 }
296 return strings.Join(header, " · ") + "\n" + strings.Join(shown, " ") + ": "
297}
298
299// logTail is how many lines of a failed check's log are shown, and
300// logKept how many of the last lines of the run's output are kept to find
301// them in. attest run prints a failed check's log after every check has
302// ended, so the logs are at the end of its output.
303const (
304 logTail = 20
305 logKept = 2000
306)
307
308// checking runs command, attest run over the checks named, in order. On a
309// terminal one line says which check is building and for how long, and is
310// redrawn in place; in a pipe one line says the checks started. The
311// command's own output is kept back, unless verbose, and when a check
312// fails the end of its log is shown and the refusal follows. On success
313// nothing more is printed: approve has not filed yet, and its verdict
314// follows. The status is the command's.
315func (v verdict) checking(checks, command []string, verbose bool, stdout, stderr io.Writer) int {
316 t := terminalOf(stdout)
317 began := time.Now()
318 of := v.required
319 if of < len(checks) {
320 of = len(checks)
321 }
322 done := v.passed
323 if done < 0 {
324 done = of - len(checks)
325 }
326
327 cmd := exec.Command(command[0], command[1:]...)
328 cmd.Stdin = os.Stdin
329 var mu sync.Mutex
330 var output []string
331 reported, failed := 0, []string(nil)
332 line := func() string {
333 mu.Lock()
334 defer mu.Unlock()
335 current := ""
336 if reported < len(checks) {
337 current = " · " + checks[reported]
338 }
339 return fmt.Sprintf("%s %s checking %d/%d%s (%s)…", t.tint(colourWorking, "◐"), t.strong(v.label()),
340 min(done+reported+1, of), of, current, time.Since(began).Round(time.Second))
341 }
342 if verbose || !t.live {
343 fmt.Fprintf(stdout, "%s %s checking %s: %s\n", t.tint(colourWorking, "◐"), t.strong(v.label()),
344 countOf(len(checks), "check"), strings.Join(checks, ", "))
345 }
346 // Both streams are read line by line, kept for a failure's log, and
347 // passed through as they come when verbose. A check's result is the
348 // line attest run prints on stdout as each check ends.
349 var cleanup []func()
350 var wg sync.WaitGroup
351 scan := func(echo io.Writer) io.Writer {
352 r, w := io.Pipe()
353 wg.Add(1)
354 go func() {
355 defer wg.Done()
356 s := bufio.NewScanner(r)
357 s.Buffer(make([]byte, 64*1024), 1024*1024)
358 for s.Scan() {
359 text := s.Text()
360 mu.Lock()
361 output = append(output, text)
362 if len(output) > 2*logKept {
363 output = append(output[:0], output[len(output)-logKept:]...)
364 }
365 if f := strings.Fields(text); len(f) == 4 && f[0] == "check" {
366 reported++
367 if f[3] != "passed" {
368 failed = append(failed, f[1])
369 }
370 }
371 if verbose {
372 fmt.Fprintln(echo, text)
373 }
374 mu.Unlock()
375 }
376 io.Copy(io.Discard, r)
377 }()
378 cleanup = append(cleanup, func() { w.Close() })
379 return w
380 }
381 cmd.Stdout, cmd.Stderr = scan(stdout), scan(stderr)
382 cleanup = append(cleanup, wg.Wait)
383 if t.live && !verbose {
384 // The clock in the line moves once a second; what it shows
385 // otherwise changes only as the command reports a check.
386 stop := make(chan struct{})
387 ticked := make(chan struct{})
388 go func() {
389 defer close(ticked)
390 tick := time.NewTicker(time.Second)
391 defer tick.Stop()
392 for {
393 fmt.Fprint(stdout, "\r\x1b[K"+t.fit(line(), ""))
394 select {
395 case <-stop:
396 return
397 case <-tick.C:
398 }
399 }
400 }()
401 cleanup = append([]func(){func() { close(stop); <-ticked; fmt.Fprint(stdout, "\r\x1b[K") }}, cleanup...)
402 }
403 err := cmd.Run()
404 for _, f := range cleanup {
405 f()
406 }
407 if err == nil {
408 return 0
409 }
410 status := 1
411 if exit, ok := err.(*exec.ExitError); ok && exit.ExitCode() > 0 {
412 status = exit.ExitCode()
413 }
414 if !verbose {
415 fmt.Fprint(stderr, failedLogs(output, failed))
416 }
417 r := v
418 r.outcome, r.failed = "refused", failed
419 if len(failed) == 0 {
420 r.why, r.see = "the checks did not run", "the output above"
421 if !verbose {
422 r.run = "valley approve -v " + v.name
423 }
424 }
425 fmt.Fprint(stderr, r.lines(terminalOf(stderr)))
426 return status
427}
428
429// failedLogs is the end of each failed check's log, as attest run prints
430// a failed check's log after a "--- <check> ---" line, or the end of the
431// whole output when no check's log is in it.
432func failedLogs(output, failed []string) string {
433 var b strings.Builder
434 shown := false
435 for _, name := range failed {
436 start := -1
437 for i, l := range output {
438 if l == "--- "+name+" ---" {
439 start = i + 1
440 }
441 }
442 if start < 0 {
443 continue
444 }
445 end := start
446 for end < len(output) && !strings.HasPrefix(output[end], "--- ") {
447 end++
448 }
449 fmt.Fprintf(&b, "--- %s ---\n", name)
450 for _, l := range output[max(start, end-logTail):end] {
451 b.WriteString(l + "\n")
452 }
453 shown = true
454 }
455 if !shown {
456 for _, l := range output[max(0, len(output)-logTail):] {
457 b.WriteString(l + "\n")
458 }
459 }
460 return b.String()
461}