gunk-dev/the-valley

verdict.go

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