gunk-dev/the-valley

review.go

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