gunk-dev/the-valley

verdict.go

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