gunk-dev/the-valley

review.go

source88a5a486b52fmain's published tip history
35.2 KiB
1package main
2
3// valley review: a change, or a stack layer by layer, paged for the
4// operator to approve, reject or skip. With no change it walks what needs
5// the operator (walk.go), and each step of the walk is this review of one
6// change, called with the step's repository.
7//
8// A change is resolved before origin is fetched, as approve resolves it,
9// and shown at the head its record names, or a plain branch at its tip on
10// origin. A stack is read first (stack.go), and reviewed one layer at a
11// time (reviewstack.go). Each page is set against the change's approved
12// version (compare.go), paged through the configured diff pager into
13// less, and read back for notes (reviewpage.go). The prompt is verdict.go's.
14// [a]pprove is approve's attempt (approve.go), [b]ase onto main is the
15// rebase verb's (rebase.go), and before either acts, and before
16// [r]eject, the change is read again (standing.go, carry.go).
17//
18// A review is given a reviewStep: the repository it runs in, whose
19// directory and environment every process it starts is given, unless the
20// process targets a tree of its own; what a walk's queue held of the
21// change; the terminal it reads answers from, a byte at a time, and the
22// streams it writes to; the signer source its reads verify a transfer
23// statement with; the caller's catch of SIGINT and SIGTERM; and the path
24// an interrupt ends it by. It returns how it ended as a stepOutcome, the
25// same for a walk's step as for valley review <change>, which turns it
26// into the exit status.
27//
28// The caller catches SIGINT and SIGTERM from before the review starts
29// until the process exits, so neither ever gets the default handling. The
30// review takes them from the caller's catch while it listens, until its
31// cleanup, and acts on each: it ends the review with status 130, its
32// outcome interrupted, through the step's end path, which ends the
33// process: once the command is recorded for valley review <change>, and
34// once the walk's summary so far is printed for a step (walk.go). One that
35// arrives while a program it runs in the foreground has the terminal, such
36// as less or the editor less starts, ends it once that program has ended:
37// less takes Ctrl-C itself. During [a]pprove's attempt, SIGINT is the
38// attempt's to act on: it stops the checks, and the attempt ends the
39// review through the same path. One that arrives during the cleanup stays
40// in the caller's catch, and the caller acts on it once the review has
41// returned: valley review <change> then exits 130. SIGHUP ends the review
42// at once while it listens, with status 129. Every other ending returns, a
43// failure included, so a walk goes on to its next step. However it ends,
44// the review leaves nothing of its own behind: its pages and the
45// background read of the checks.
46
47import (
48 "bytes"
49 "errors"
50 "fmt"
51 "io"
52 "os"
53 "os/signal"
54 "strconv"
55 "strings"
56 "sync"
57 "syscall"
58
59 "the-valley/change"
60)
61
62const reviewUsage = "usage: valley review [-v] [--build-here] [--approval-key <file> | --approval-piv] [<change> | --repo <name>]"
63
64// reviewStep is what one review of a change is given: by valley review
65// <change> for the current checkout, and by the walk for each step.
66type reviewStep struct {
67 // g is the repository the review runs in, at its root for a walk's
68 // step, with the environment every process the review starts is given.
69 g git
70 queued *queuedChange // what the walk's queue held of the change; nil outside a walk
71 verbose, buildHere bool
72 key *approvalKey // what [a]pprove signs with; nil for no signed approval
73 stdin *os.File // the terminal: read a byte at a time, and given to the programs that read it
74 stdout, stderr io.Writer
75 signers *signerSource // what the review's reads verify a transfer statement with
76 // interrupts is the caller's catch of SIGINT and SIGTERM, which it
77 // holds until the process exits. The review takes from it only while
78 // it listens.
79 interrupts <-chan os.Signal
80 // end ends the process once a signal has ended the review and the
81 // review has cleaned up, with the status and how the review ended. It
82 // does not return.
83 end func(status int, o stepOutcome)
84}
85
86// queuedChange is a change as the walk's queue held it.
87type queuedChange struct {
88 id string
89 version int
90 head string
91}
92
93// stepOutcome is how a review ended. kind is approved, rejected, kept,
94// skipped, refused (an answer was refused, then the change skipped),
95// moved (it moved while it was shown), not-reviewed, interrupted or error.
96// status is the exit status valley review <change> gives it.
97type stepOutcome struct {
98 kind string
99 id, handle, version, head string // approved: what was filed, the head alone for a plain branch
100 branch string // rejected and kept: the branch
101 reason string // not-reviewed, and an error that says why
102 status int
103}
104
105// shownChange is the change review acts on: the one it was given, or a
106// layer of its stack (useLayer). For a change with a record, id, handle,
107// version, head, state and owner are its record's, with head the active
108// version's. A plain branch has a name and a branch alone.
109type shownChange struct {
110 name, id, handle, version, head, branch, state, owner string
111}
112
113// review is one review of a change and the stack under it.
114type review struct {
115 step reviewStep
116 g git
117 stdin *os.File
118 stdout, stderr io.Writer
119 verbose, buildHere bool
120 key *approvalKey
121
122 c shownChange
123 approveHead, approveVersion string // what [a]pprove files (bind)
124 carriedVersion, carriedHead string // the version the answer carried to, which lands, and its head
125 checksFailedAt string // the head [a]pprove's checks failed at
126 checksClause string // the checks line for the prompt's header
127 topName string // the name review was given
128 layers []reviewLayer
129 notes []string // taken in the pages since the last layer began
130 does doers
131 checks *checksRead
132
133 said *stepOutcome // how the review ended, once it says; the last said stands
134 refused bool // an answer was refused
135 attempt func(*approval) // runs [a]pprove's attempt: approval.run
136
137 mu sync.Mutex
138 scratch string // the directory holding the page being shown
139 exiting bool
140 foreground int // programs the review waits on with signals held
141 pending bool // a signal held until they end
142}
143
144// reviewEnded is a review that cannot go on, having said why. status is
145// the exit status valley review <change> gives it.
146type reviewEnded struct{ status int }
147
148func (e reviewEnded) Error() string { return "the review ended with status " + strconv.Itoa(e.status) }
149
150// endedStatus is the exit status of a review err ended.
151func endedStatus(err error) int {
152 var ended reviewEnded
153 if errors.As(err, &ended) {
154 return ended.status
155 }
156 return 1
157}
158
159func runReview(g git, args []string, stdout, stderr io.Writer, end func(int)) int {
160 var name, repo string
161 var verbose, buildHere, repoGiven bool
162 var keyFlags approvalFlags
163 var keyArgs []string // the approval-key flags, for the walk
164 for i := 0; i < len(args); i++ {
165 last, isKey, err := keyFlags.take(args, i)
166 if err != nil {
167 fmt.Fprintf(stderr, "valley: %s\n", err)
168 return 1
169 }
170 if isKey {
171 keyArgs = append(keyArgs, args[i:last+1]...)
172 i = last
173 continue
174 }
175 switch a := args[i]; {
176 case a == "-v":
177 verbose = true
178 case a == "--build-here":
179 buildHere = true
180 case a == "--repo":
181 if i+1 >= len(args) {
182 fmt.Fprintf(stderr, "valley: %s\n", reviewUsage)
183 return 1
184 }
185 repo, repoGiven = args[i+1], true
186 i++
187 case strings.HasPrefix(a, "-") || name != "":
188 fmt.Fprintf(stderr, "valley: %s\n", reviewUsage)
189 return 1
190 default:
191 name = a
192 }
193 }
194 key, err := keyFlags.key()
195 if err != nil {
196 fmt.Fprintf(stderr, "valley: %s\n", err)
197 return 1
198 }
199 if name == "" {
200 var walk []string
201 if verbose {
202 walk = append(walk, "-v")
203 }
204 if buildHere {
205 walk = append(walk, "--build-here")
206 }
207 walk = append(walk, keyArgs...)
208 if repoGiven {
209 walk = append(walk, "--repo", repo)
210 }
211 if err := fetchOrigin(g, stdout, stderr); err != nil {
212 return exitCode(err)
213 }
214 return runWalk(g, walk, stdout, stderr, end)
215 }
216 if repoGiven {
217 fmt.Fprintf(stderr, "valley: %s\n", reviewUsage)
218 return 1
219 }
220 commandTimed = false
221 // Never stopped: the process exits holding it.
222 interrupts := make(chan os.Signal, 1)
223 signal.Notify(interrupts, os.Interrupt, syscall.SIGTERM)
224 o := reviewChange(reviewStep{g: g, verbose: verbose, buildHere: buildHere, key: key, stdin: os.Stdin,
225 stdout: stdout, stderr: stderr, signers: verification, interrupts: interrupts,
226 end: func(status int, _ stepOutcome) {
227 verification.done()
228 end(status)
229 }}, name)
230 if caught(interrupts) {
231 return interruptedStatus
232 }
233 return o.status
234}
235
236// reviewChange is one review of the change named, and how it ended. Only
237// a signal ends it any other way: through s.end.
238func reviewChange(s reviewStep, name string) stepOutcome {
239 return newReview(s).review(name)
240}
241
242// newReview is a review given s.
243func newReview(s reviewStep) *review {
244 return &review{step: s, g: s.g, stdin: s.stdin, stdout: s.stdout, stderr: s.stderr,
245 verbose: s.verbose, buildHere: s.buildHere, key: s.key, attempt: func(a *approval) { a.run() }}
246}
247
248// review reviews the change named, and returns how it ended. It stops
249// listening before it cleans up: a signal taken during the cleanup would
250// find the review already ending and leave the listener parked in exit,
251// and stop would wait for it forever. A signal that arrives during the
252// cleanup stays in the caller's catch instead.
253func (r *review) review(name string) stepOutcome {
254 stop := r.listen()
255 defer stop() // for an end that leaves this goroutine rather than the process
256 status := 0
257 if err := r.run(name); err != nil {
258 status = endedStatus(err)
259 }
260 stop()
261 o, _ := r.cleanup(status)
262 return o
263}
264
265// run is the review of the change named. An error is a review that ended
266// without a verdict, having said why.
267func (r *review) run(name string) error {
268 if err := r.resolve(name); err != nil {
269 return r.die(err.Error())
270 }
271 if err := fetchOrigin(r.g, r.stdout, r.stderr); err != nil {
272 return reviewEnded{exitCode(err)}
273 }
274 if !r.queued() {
275 return nil
276 }
277 // Notes are kept under the branch, and [r]eject deletes it. approve
278 // files the head alone, so it approves such a change.
279 if r.c.id != "" && r.c.branch == "" {
280 return r.die(fmt.Sprintf("change %s v%s records no branch, and review acts on a change's branch. Approve its head alone: valley approve --head %s %s",
281 r.c.handle, r.c.version, r.c.head, r.c.handle))
282 }
283 branch := r.c.branch
284 r.topName = name
285 if r.ref("refs/remotes/origin/"+branch) == "" {
286 return r.die("no such branch on origin: " + branch)
287 }
288 r.bind()
289 // The verdict disposes of the change; the notes are what the human made
290 // of it, so they are printed whatever the verdict was. A stack that
291 // cannot be read is reviewed whole against main, as a change with
292 // nothing under it is.
293 if !r.readStack() {
294 fmt.Fprintf(r.stderr, "valley: warning: the stack under %s could not be read; reviewing it whole, against main\n", name)
295 r.layers = nil
296 }
297 r.readDoes()
298 if len(r.layers) > 1 {
299 if err := r.reviewStack(); err != nil {
300 return err
301 }
302 r.printStackNotes()
303 return nil
304 }
305 if err := r.showReview(branch); err != nil {
306 return err
307 }
308 if err := r.decide(branch, "", 0); err != nil {
309 return err
310 }
311 r.printNotes(branch, r.notes)
312 return nil
313}
314
315// fetchOrigin brings this checkout's remote-tracking refs up to date.
316func fetchOrigin(g git, stdout, stderr io.Writer) error {
317 fetch := g.command("fetch", "--prune", "--quiet", "origin")
318 fetch.Stdout, fetch.Stderr = stdout, stderr
319 processStarted()
320 return fetch.Run()
321}
322
323// listen takes SIGINT and SIGTERM from the caller's catch, and SIGHUP,
324// until the stop it returns, which returns once every signal taken has
325// been acted on: one that ends the review ends the process, so nothing of
326// the review acts on a signal once stop has returned. A SIGINT or SIGTERM
327// that arrives after is left in the caller's catch.
328func (r *review) listen() (stop func()) {
329 hup := make(chan os.Signal, 1)
330 signal.Notify(hup, syscall.SIGHUP)
331 quit, done := make(chan struct{}), make(chan struct{})
332 go func() {
333 defer close(done)
334 for {
335 select {
336 case s := <-r.step.interrupts:
337 r.signalled(s)
338 case s := <-hup:
339 r.signalled(s)
340 case <-quit:
341 if caught(hup) {
342 r.signalled(syscall.SIGHUP)
343 }
344 return
345 }
346 }
347 }()
348 var once sync.Once
349 return func() {
350 once.Do(func() {
351 signal.Stop(hup)
352 close(quit)
353 <-done
354 })
355 }
356}
357
358// signalled acts on a signal: SIGHUP ends the review at once, and another
359// ends it now, or once the programs in the foreground have ended.
360func (r *review) signalled(s os.Signal) {
361 if s == syscall.SIGHUP {
362 r.exit(128 + int(syscall.SIGHUP))
363 }
364 r.mu.Lock()
365 held := r.foreground > 0
366 r.pending = r.pending || held
367 r.mu.Unlock()
368 if !held {
369 r.exit(interruptedStatus)
370 }
371}
372
373// inForeground runs f, which runs a program that has the terminal or
374// handles signals itself, holding any signal until it returns.
375func (r *review) inForeground(f func()) {
376 r.mu.Lock()
377 r.foreground++
378 r.mu.Unlock()
379 f()
380 r.mu.Lock()
381 r.foreground--
382 act := r.foreground == 0 && r.pending
383 r.mu.Unlock()
384 if act {
385 r.exit(interruptedStatus)
386 }
387}
388
389// cleanup removes what the review leaves outside the repository, and
390// returns how it ended with status: what it said, or else interrupted for
391// a signal's status and error for any other. Only the first call acts: it
392// reports false to any other, whose caller leaves the ending to the first.
393func (r *review) cleanup(status int) (stepOutcome, bool) {
394 r.mu.Lock()
395 if r.exiting {
396 r.mu.Unlock()
397 return stepOutcome{}, false
398 }
399 r.exiting = true
400 o := stepOutcome{kind: "error"}
401 if r.said != nil {
402 o = *r.said
403 } else if status == interruptedStatus {
404 o.kind = "interrupted"
405 }
406 o.status = status
407 scratch, checks := r.scratch, r.checks
408 r.scratch, r.checks = "", nil
409 r.mu.Unlock()
410 if scratch != "" {
411 os.RemoveAll(scratch)
412 }
413 checks.stop()
414 return o, true
415}
416
417// exit ends the review and the process, from anywhere, with status.
418func (r *review) exit(status int) {
419 o, first := r.cleanup(status)
420 if !first {
421 select {} // the ending under way ends the process
422 }
423 r.step.end(status, o)
424}
425
426// die says what ends the review: nothing is left to offer. It returns the
427// error that ends it, with status 1.
428func (r *review) die(msg string) error {
429 fmt.Fprintf(r.stderr, "valley: %s\n", msg)
430 return reviewEnded{1}
431}
432
433// refuse reports what was not done, without leaving the review: the
434// change is still under review and the operator can still answer. It
435// returns false.
436func (r *review) refuse(msg string) bool {
437 fmt.Fprintf(r.stderr, "valley: %s\n", msg)
438 return false
439}
440
441// newScratch makes the directory the next page is written to.
442func (r *review) newScratch() (string, error) {
443 dir, err := os.MkdirTemp("", "valley-review-")
444 if err != nil {
445 return "", r.die(fmt.Sprintf("no scratch directory for the review: %v", err))
446 }
447 r.mu.Lock()
448 if r.exiting {
449 r.mu.Unlock()
450 os.RemoveAll(dir)
451 select {}
452 }
453 r.scratch = dir
454 r.mu.Unlock()
455 return dir, nil
456}
457
458// dropScratch removes the page's directory.
459func (r *review) dropScratch() {
460 r.mu.Lock()
461 dir := r.scratch
462 r.scratch = ""
463 r.mu.Unlock()
464 if dir != "" {
465 os.RemoveAll(dir)
466 }
467}
468
469// outcome says how the review ended, unless it is already ending and
470// says so itself. The last one said stands.
471func (r *review) outcome(o stepOutcome) {
472 r.mu.Lock()
473 if !r.exiting {
474 r.said = &o
475 }
476 r.mu.Unlock()
477}
478
479// skipped is the outcome of a review that was skipped or stopped: refused
480// when an answer was refused first.
481func (r *review) skipped() {
482 if r.refused {
483 r.outcome(stepOutcome{kind: "refused"})
484 } else {
485 r.outcome(stepOutcome{kind: "skipped"})
486 }
487}
488
489// queued compares a walk's step with what the walker's queue held of it.
490// A change that landed, is no longer ready or has no branch on origin is
491// not reviewed, and the step ends; one at another version is reviewed at
492// it, saying so first. It reports false when the step ends here.
493func (r *review) queued() bool {
494 q := r.step.queued
495 if q == nil {
496 return true
497 }
498 s, _ := r.readStanding()
499 why := ""
500 switch {
501 case s.landed != "":
502 why = "it landed as " + s.landed
503 case r.c.state != "ready":
504 why = "it is " + strings.Replace(r.c.state, "draft", "a draft", 1)
505 case r.c.branch == "" || r.ref("refs/remotes/origin/"+r.c.branch) == "":
506 why = "its branch is gone from origin"
507 }
508 if why != "" {
509 fmt.Fprintf(r.stdout, "%s is not reviewed: %s\n", r.c.handle, why)
510 r.outcome(stepOutcome{kind: "not-reviewed", reason: why})
511 return false
512 }
513 if q.id != r.c.id || strconv.Itoa(q.version) != r.c.version || q.head != r.c.head {
514 fmt.Fprintf(r.stdout, "%s moved to v%s since the queue was read\n", r.c.handle, r.c.version)
515 }
516 return true
517}
518
519// resolve reads the name as approve and rebase read a change's name: a
520// change's ID, handle, or the branch its active version names, or else a
521// plain branch.
522func (r *review) resolve(name string) error {
523 r.c = shownChange{name: name}
524 if !r.g.succeeds(true, "rev-parse", "--git-dir") {
525 return failure("not a git repository")
526 }
527 res, err := resolveRecorded(r.g, name)
528 if err != nil {
529 return err
530 }
531 r.c.branch = res.branch
532 if res.id != "" {
533 r.c.id, r.c.handle, r.c.version, r.c.head = res.id, res.handle, strconv.Itoa(res.version), res.head
534 r.c.state, r.c.owner = res.state, res.owner
535 }
536 return nil
537}
538
539// verifier is what the review's reads verify a transfer statement with:
540// the step's signer source.
541func (r *review) verifier() verifier { return r.step.signers.verifier() }
542
543// ref is the object ID a ref holds, read by its exact name, or "".
544func (r *review) ref(name string) string {
545 oid, ok, err := r.g.ref(name)
546 if err != nil || !ok {
547 return ""
548 }
549 return oid
550}
551
552func (r *review) short(oid string) string {
553 s, _ := r.g.output(false, "rev-parse", "--short", oid)
554 return s
555}
556
557// changeHead is the commit review acts on: the recorded head for a change
558// with a record, and otherwise the branch's head on origin.
559func (r *review) changeHead(branch string) string {
560 if r.c.head != "" {
561 return r.c.head
562 }
563 return r.ref("refs/remotes/origin/" + branch)
564}
565
566// fastForwards reports whether commit fast-forwards from main's tip as the
567// fetch left it. A main that cannot be read is not one it fast-forwards
568// from.
569func (r *review) fastForwards(commit string) bool {
570 tip := r.ref("refs/remotes/origin/main")
571 return tip != "" && r.g.succeeds(false, "merge-base", "--is-ancestor", tip, commit)
572}
573
574// bind binds [a]pprove to the active version's head of a change with a
575// record. A plain branch is bound to the head review pages, when it pages
576// it (showReview, useLayer).
577func (r *review) bind() {
578 r.approveHead, r.approveVersion = "", ""
579 if r.c.id != "" {
580 r.approveHead, r.approveVersion = r.c.head, r.c.version
581 }
582}
583
584// readStanding reads where the change under review stands now. A plain
585// branch has no record, and reads as nothing. It reports false, having
586// said why, when origin cannot be read.
587func (r *review) readStanding() (standing, bool) {
588 if r.c.id == "" {
589 return standing{}, true
590 }
591 s, err := standingOf(r.g, r.c.id)
592 if err != nil {
593 fmt.Fprintf(r.stderr, "valley: %s\n", err)
594 return standing{}, false
595 }
596 return s, true
597}
598
599// notReady is the line review shows for a change whose record is not
600// ready, above its diff and in its prompt, or "" for a ready change and a
601// plain branch. A draft is often a change an agent is still working on,
602// so the prompt then offers only [v]iew diff and [s]kip: [a]pprove would
603// be refused, and [r]eject would delete the branch its owner may still be
604// working on.
605func notReady(handle, version, state, owner string) string {
606 switch state {
607 case "draft":
608 return fmt.Sprintf("%s v%s is a draft: its owner (%s) hasn't marked it ready, so it can't be approved yet.", handle, version, owner)
609 case "withdrawn":
610 return handle + " is withdrawn: there is nothing to approve."
611 }
612 return ""
613}
614
615// answer reads one answer from the terminal, a byte at a time so that
616// nothing after it is taken from whatever reads the input next, with the
617// spaces and tabs around it trimmed. ok is false when the input ends
618// before the line does.
619func (r *review) answer() (string, bool) {
620 var line []byte
621 b := make([]byte, 1)
622 for {
623 n, err := r.stdin.Read(b)
624 if n == 1 {
625 if b[0] == '\n' {
626 return strings.Trim(string(line), " \t"), true
627 }
628 line = append(line, b[0])
629 }
630 if err != nil {
631 return "", false
632 }
633 }
634}
635
636// mustAnswer is answer, ending the review when the input has ended.
637func (r *review) mustAnswer() (string, error) {
638 choice, ok := r.answer()
639 if !ok {
640 return "", r.die("stdin closed before an answer; nothing done")
641 }
642 return choice, nil
643}
644
645// prompt prints review's prompt: the header's clauses, the empty ones
646// left out, and the keys.
647func (r *review) prompt(header []string, keys ...string) {
648 var shown []string
649 for _, h := range header {
650 if h != "" {
651 shown = append(shown, h)
652 }
653 }
654 fmt.Fprint(r.stdout, promptLines(terminalOf(r.stdout), shown, keys))
655}
656
657// decide takes the verdict on a change alone, and on the top of a stack
658// of n, named name. Its prompt is one header line, the change and what
659// stands in its way, and the keys it takes. A change is named by its
660// handle and version, a plain branch by its name, and a change alone
661// carries the checks line review read for it. The top of a stack says that
662// approving it lands all n layers. [v]iew diff pages the change's whole
663// diff, or the top layer's.
664//
665// A change that is not ready says so in its header, and is offered only
666// [v]iew diff and [s]kip, or [s]top. The top of a stack with a layer under
667// it that is not ready says why it can't be approved (layerHeld), as does
668// a change whose checks failed at the head shown, and neither is offered
669// [a]pprove. A change that can be approved and does not fast-forward from
670// main says so (behindMain). Before [a]pprove and [r]eject act, moved
671// reads the change again, and ends its review when it moved.
672func (r *review) decide(branch, name string, n int) error {
673 approve, reject, stop := "[a]pprove", "[r]eject", "[s]kip"
674 stopped := "skipped " + branch + "; nothing done"
675 header := []string{branch}
676 own, held, behind := "", "", ""
677 if r.c.id != "" {
678 header = []string{r.c.handle + " v" + r.c.version}
679 switch r.c.state {
680 case "draft":
681 own = "draft (its owner, " + r.c.owner + ", has not readied it)"
682 case "withdrawn":
683 own = "withdrawn"
684 }
685 }
686 if n > 0 {
687 header = append(header, fmt.Sprintf("stack of %d", n))
688 approve, reject, stop = fmt.Sprintf("[a]pprove all %d", n), "[r]eject "+name, "[s]top"
689 stopped = fmt.Sprintf("stopped reviewing %s at change %d of %d; nothing done", name, n, n)
690 held = r.layerHeld(n - 1)
691 } else if r.checksClause != "" {
692 header = append(header, r.checksClause)
693 }
694 if own == "" && held == "" {
695 behind = r.behindMain(branch)
696 }
697 for {
698 var clause, answers string
699 var keys []string
700 failed := ""
701 switch {
702 case own != "":
703 clause, keys, answers = own, []string{"[v]iew diff", stop}, "v or s"
704 case held != "":
705 clause, keys, answers = held, []string{"[v]iew diff", reject, stop}, "v, r, or s"
706 default:
707 if failed = r.approveFailedAt(branch); failed != "" {
708 clause, keys, answers = "checks failed at "+failed, []string{"[v]iew diff", reject, stop}, "v, r, or s"
709 } else {
710 clause, keys, answers = behind, []string{approve, "[v]iew diff", reject, stop}, "a, v, r, or s"
711 }
712 }
713 r.prompt(append(append([]string{}, header...), clause), keys...)
714 // A refusal from approve is not a verdict: it says what it did not
715 // do and the prompt comes back, so the branch can still be rejected
716 // or skipped. When the checks failed, approving the same head again
717 // is no longer offered, nor is approving a change that is not ready.
718 // A change that moved since it was shown is not acted on, and its
719 // review ends.
720 choice, err := r.mustAnswer()
721 if err != nil {
722 return err
723 }
724 switch choice {
725 case "a":
726 if failed != "" || own != "" || held != "" {
727 fmt.Fprintln(r.stdout, "answer "+answers)
728 continue
729 }
730 moved, err := r.moved(true)
731 if err != nil {
732 return err
733 }
734 if moved || r.approve(branch) {
735 return nil
736 }
737 case "v":
738 var err error
739 if n > 0 {
740 err = r.viewLayer(n - 1)
741 } else {
742 err = r.viewFull(branch)
743 }
744 if err != nil {
745 return err
746 }
747 case "r":
748 if own != "" {
749 fmt.Fprintln(r.stdout, "answer "+answers)
750 continue
751 }
752 moved, err := r.moved(false)
753 if err != nil {
754 return err
755 }
756 if moved {
757 return nil
758 }
759 if done, err := r.reject(branch); err != nil || done {
760 return err
761 }
762 case "s":
763 fmt.Fprintln(r.stdout, stopped)
764 r.skipped()
765 return nil
766 default:
767 fmt.Fprintln(r.stdout, "answer "+answers)
768 }
769 }
770}
771
772// approveFailedAt is the head the checks failed at in this review, short,
773// while the change is still at it, or "". Approving that head again would
774// run the same checks over the same tree and fail the same way, so the
775// prompt stops offering [a]pprove until the change has a new head.
776func (r *review) approveFailedAt(branch string) string {
777 if r.checksFailedAt == "" || r.checksFailedAt != r.changeHead(branch) {
778 return ""
779 }
780 return r.short(r.checksFailedAt)
781}
782
783// behindMain is the clause review's prompt shows for a change that does
784// not fast-forward from main, or "". Being behind main asks nothing of the
785// operator: the integrator applies the change's delta onto main as main
786// stands, with the evidence for the head approved, and the host's
787// restacker rebases ready changes itself. When the restacker reports that
788// rebasing the change conflicted, the clause says so instead, and
789// [a]pprove stays offered: the integrator decides whether the change
790// applies.
791func (r *review) behindMain(branch string) string {
792 if r.fastForwards(r.changeHead(branch)) {
793 return ""
794 }
795 if s, _ := r.readStanding(); s.conflict == "conflict" {
796 return "conflicts with main (owner resolving)"
797 }
798 return "behind main (integrator merges)"
799}
800
801// moved reads a change with a record again before review acts on an
802// answer about it: another principal may return it to draft, ready a new
803// version, or withdraw it while the operator reads, and it may land. When
804// it is no longer what review showed, moved says in one line what changed
805// and what happens next, and the review of that change ends: the prompt's
806// answers were about what was shown, so it is not asked again. A new
807// version the answer carries to does not end it (carried), nor does
808// approving the new version in place, which moved offers for an approval.
809// It reports false when the change is still as shown, the answer carries
810// or the new version is to be approved, and for a plain branch, which
811// approve and reject check themselves.
812func (r *review) moved(approving bool) (bool, error) {
813 h := r.c.handle
814 r.carriedVersion, r.carriedHead = "", ""
815 if r.c.id == "" {
816 return false, nil
817 }
818 s, ok := r.readStanding()
819 switch {
820 case !ok:
821 fmt.Fprintf(r.stdout, "could not read %s again from origin; nothing done\n", h)
822 r.outcome(stepOutcome{kind: "error"})
823 return true, nil
824 case s.state == "withdrawn":
825 fmt.Fprintf(r.stdout, "%s changed while you were reviewing: it was withdrawn (since %s), so there is nothing to approve.\n", h, s.since)
826 case s.state == "draft":
827 fmt.Fprintf(r.stdout, "%s changed while you were reviewing: it was returned to draft (since %s), so there is nothing to approve now. It comes back when it is ready again.\n", h, s.since)
828 case s.landed != "":
829 fmt.Fprintf(r.stdout, "%s landed as %s while you were reviewing; there is nothing left to approve.\n", h, s.landed)
830 case s.version == r.c.version && s.head == r.c.head:
831 return false, nil
832 default:
833 carried, err := r.carriedTo(s, approving)
834 if err != nil || carried {
835 return false, err
836 }
837 }
838 r.outcome(stepOutcome{kind: "moved"})
839 return true, nil
840}
841
842// carriedTo reports whether the answer about the version review showed
843// carries to the version s the change moved to, as carry decides
844// (carry.go). When it does, it says so in one line, with carry's reason,
845// and the answer stays bound to the head shown: an approval names what the
846// reviewer read, and the integrator applies its delta onto main as main
847// stands. The version moved to is what lands, so the approval's verdict
848// names it (carriedVerdict, approve.go). When it does
849// not, it says why in one line and offers to page only what changed since
850// the version shown. Answering an approval, it also offers to approve the
851// version the change moved to, when carry says: at once, or after the
852// page. [a] binds the approval to that version's head, and the attempt
853// reads the record again before it files. It reports false unless the
854// answer carries or [a] is taken.
855func (r *review) carriedTo(s standing, approving bool) (bool, error) {
856 h := r.c.handle
857 r.bind()
858 dir, err := r.newScratch()
859 if err != nil {
860 return false, err
861 }
862 defer r.dropScratch()
863 var out bytes.Buffer
864 verdict, reason, offer, text := "", "", "", ""
865 if err := runCarry(r.g, []string{r.c.id, r.c.version, s.version}, &out); err != nil {
866 fmt.Fprintf(r.stderr, "valley: %s\n", err)
867 } else {
868 first, rest, _ := strings.Cut(out.String(), "\n")
869 f := strings.Fields(first)
870 if len(f) > 0 {
871 verdict = f[0]
872 }
873 if t := strings.Split(first, "\t"); len(t) > 1 {
874 reason = t[1]
875 if len(t) > 2 {
876 offer = t[2]
877 }
878 }
879 text = rest
880 }
881 if !approving {
882 offer = "none"
883 }
884 switch verdict {
885 case "carries":
886 answer := "rejection"
887 if approving {
888 answer = "approval"
889 }
890 fmt.Fprintf(r.stdout, "%s moved to v%s while you were reviewing. %s, so your %s covers it.\n", h, s.version, reason, answer)
891 r.carriedVersion, r.carriedHead = s.version, s.head
892 return true, nil
893 case "review":
894 keys := "[v]iew what changed since v" + r.c.version + ", [s]kip?"
895 switch offer {
896 case "approve":
897 keys = "[a]pprove v" + s.version + ", " + keys
898 case "view":
899 default:
900 offer, keys = "", "review it again to approve it · "+keys
901 }
902 fmt.Fprintf(r.stdout, "%s moved to v%s while you were reviewing (%s) · %s ", h, s.version, reason, keys)
903 choice, _ := r.answer()
904 if choice == "v" {
905 changed := dir + "/changed"
906 if err := os.WriteFile(changed, []byte(text), 0o600); err == nil {
907 r.page(changed)
908 }
909 if offer != "" {
910 offer = "approve"
911 fmt.Fprintf(r.stdout, "[a]pprove v%s, [s]kip? ", s.version)
912 choice, _ = r.answer()
913 }
914 }
915 if choice == "a" && offer == "approve" {
916 r.approveVersion, r.approveHead = s.version, s.head
917 return true, nil
918 }
919 default:
920 fmt.Fprintf(r.stdout, "%s moved to v%s while you were reviewing; review it again to approve what would land.\n", h, s.version)
921 }
922 return false, nil
923}
924
925// approve is review's [a]pprove: one attempt of approve's own for each
926// answer, a stack's layers included (approve.go), told the change and head
927// review bound and the name as typed, which it reads again before filing.
928// It ends approved, with what it filed; checks-failed, with the head the
929// checks failed at, which the prompt stops offering [a]pprove for
930// (approveFailedAt); refused or unknown; or interrupted, when the attempt
931// has ended the review itself. It reports false unless it filed.
932func (r *review) approve(branch string) bool {
933 c := r.c
934 if c.id == "" {
935 c.branch = branch
936 }
937 a := reviewApproval(r, c)
938 r.inForeground(func() {
939 a.watch(os.Interrupt)
940 r.attempt(a)
941 a.unwatch()
942 })
943 result := a.result
944 switch {
945 case len(result) == 5 && result[0] == "approved":
946 r.outcome(stepOutcome{kind: "approved", id: result[1], handle: result[2], version: result[3], head: result[4]})
947 return true
948 case len(result) == 2 && result[0] == "checks-failed":
949 r.checksFailedAt = result[1]
950 case len(result) == 1 && (result[0] == "refused" || result[0] == "unknown"):
951 default:
952 fmt.Fprintln(r.stderr, "valley: warning: the approval left no outcome; taking it as refused")
953 }
954 r.refused = true
955 return false
956}
957
958// reject deletes the change's branch on origin, once the operator confirms
959// it, and withdraws a change with a record (rejected). For a change with a
960// record, what is rejected is the head its record names, so the branch is
961// deleted only while its tip is that head, and the delete is leased on it.
962// When the tip is another commit, reject refuses and names both, and
963// deletes nothing. A plain branch is deleted as it stands. It reports
964// false when it refused.
965func (r *review) reject(branch string) (bool, error) {
966 var lease []string
967 if r.c.head != "" {
968 if !r.recordedTip(branch, "nothing deleted") {
969 r.refused = true
970 return false, nil
971 }
972 lease = []string{"--force-with-lease=refs/heads/" + branch + ":" + r.c.head}
973 }
974 fmt.Fprintf(r.stdout, "really delete origin/%s? [y/N] ", branch)
975 switch choice, _ := r.answer(); choice {
976 case "y", "Y", "yes":
977 // The change may have moved while the confirmation waited: say so,
978 // and delete nothing.
979 if moved, err := r.moved(false); err != nil || moved {
980 return true, err
981 }
982 push := r.g.command(append(append([]string{"push", "--quiet"}, lease...), "origin", "--delete", branch)...)
983 push.Stdout, push.Stderr = r.stdout, r.stderr
984 var err error
985 r.inForeground(func() { err = push.Run() })
986 if err != nil {
987 r.refuse("origin did not delete " + branch + ", which may have moved since the fetch; nothing deleted")
988 r.refused = true
989 return false, nil
990 }
991 r.rejected(branch)
992 default:
993 fmt.Fprintf(r.stdout, "kept %s\n", branch)
994 r.outcome(stepOutcome{kind: "kept", branch: branch})
995 }
996 return true, nil
997}
998
999// rejected says reject deleted the branch. A change with a record is
1000// withdrawn too, by valley withdraw's own code and under its rules, while
1001// its active version is still at the head deleted: a rejection says the
1002// change is not wanted, and withdrawing it voids what is outstanding on it
1003// and takes it off what needs the operator. When the
1004// withdrawal fails, the line says so and names the command to run. The
1005// branch is gone either way, so the outcome is rejected. Signals are held
1006// until the line is printed, so a deleted branch is always reported.
1007func (r *review) rejected(branch string) {
1008 r.inForeground(func() {
1009 line, run := "rejected "+branch+": deleted from origin", ""
1010 if r.c.id != "" {
1011 if err := setState(r.g, []string{r.c.id}, io.Discard, r.stderr, "withdraw", change.Withdrawn, r.c.head); err != nil {
1012 fmt.Fprintf(r.stderr, "valley: %s\n", err)
1013 line += " · withdrawing " + r.c.handle + " failed"
1014 run = " run: valley withdraw " + r.c.handle + "\n"
1015 } else {
1016 line += " · " + r.c.handle + " withdrawn"
1017 }
1018 }
1019 fmt.Fprint(r.stdout, line+"\n"+run)
1020 r.outcome(stepOutcome{kind: "rejected", branch: branch})
1021 })
1022}
1023
1024// recordedTip reports whether the branch's tip on origin is the head a
1025// change's record names, and refuses, naming both, when it is not:
1026// [r]eject acts on the branch itself, and deleting it while it is
1027// elsewhere would delete a commit no version records. undone is what the
1028// refusal leaves undone.
1029func (r *review) recordedTip(branch, undone string) bool {
1030 tip := r.ref("refs/remotes/origin/" + branch)
1031 switch {
1032 case tip == "":
1033 return r.refuse("no such branch on origin: " + branch + "; " + undone)
1034 case tip != r.c.head:
1035 return r.refuse(fmt.Sprintf("change %s v%s records the head %s, and origin/%s is at %s; %s. Ready the branch's head as a new version of %s to act on it",
1036 r.c.handle, r.c.version, r.c.head, branch, tip, undone, r.c.handle))
1037 }
1038 return true
1039}