gunk-dev/the-valley

verdict.go

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