gunk-dev/the-valley

approve.go

sourcec4c1671e1d82main's published tip history
48.5 KiB
1package main
2
3// approve files a change's integration request: the whole of `valley
4// approve`, and review's [a]pprove (review.go). Both run one attempt (approval.attempt), so the verb and
5// the key cannot drift apart.
6//
7// An attempt binds the head it files, derives what the policy at main's
8// tip requires of it (../derive), reuses the evidence origin already
9// holds for the head's tree (coverage.go), runs the rest in a throwaway
10// worktree through attest run, and files the request and the evidence in
11// one atomic push. attest run stores each note in this repository and
12// pushes nothing, so no evidence stands published for a change nobody has
13// approved, and the request is never filed without its evidence. Nothing
14// here writes the protected ref: the integrator judges the request and
15// lands it. Every way it ends is said in one verdict line
16// (verdict.go). With valley.telemetry on, each attempt is a telemetry run
17// of its own, recording approve.start, approve.policy, approve.coverage,
18// approve.checks, approve.request and approve.end, and attest records the
19// checks it runs under the linked run <run>-checks. A record is never
20// evidence, nothing reads one to decide anything, and a record that cannot
21// be stored costs that record alone.
22//
23// Review's [a]pprove is told the change review bound (reviewApproval), and
24// runs on review's own terminal. It leaves how the attempt ended in its
25// result, as fields:
26//
27// approved <change ID> <handle> <version> <head>
28// checks-failed <head>
29// refused
30// unknown
31// interrupted
32//
33// The approved result names what was filed, after the attempt's own reads
34// of the record, with empty fields for a plain branch. unknown is a
35// request whose state the attempt could not establish after the push.
36
37import (
38 "context"
39 "errors"
40 "fmt"
41 "io"
42 "os"
43 "os/exec"
44 "os/signal"
45 "regexp"
46 "sort"
47 "strconv"
48 "strings"
49 "sync"
50 "syscall"
51 "time"
52
53 "the-valley/derive"
54 "the-valley/telemetry"
55)
56
57const approveUsage = "usage: valley approve [-v] [--head <sha>] [--build-here] <change>"
58
59// interruptedStatus is the exit status of an approval cut short by a
60// signal, as a shell reports a process SIGINT ended.
61const interruptedStatus = 130
62
63// headArgument is the shape a --head value must have before it is read
64// as a commit: an object ID, or an abbreviation of one.
65var headArgument = regexp.MustCompile(`^[0-9a-f]{4,64}$`)
66
67// changeRequest is the request name of a change with a record, which no
68// branch is filed under.
69var changeRequest = regexp.MustCompile(`^c-[k-z]{32}$`)
70
71// approval is one approval attempt and what it was told.
72type approval struct {
73 g git
74 stdin *os.File // the terminal: the confirmation, and the checks' stdin
75 stdout, stderr io.Writer
76 v verifier // what reading what the head would bring verifies a transfer statement with
77
78 // exit ends the process once a signal has interrupted the attempt: the
79 // approve verb's records the command, and review's ends the review
80 // first (review.go). It does not return.
81 exit func(int)
82
83 verbose, buildHere bool
84 reviewing bool
85 result []string // how the attempt ended, for review
86
87 // carriedVersion is the later version review's answer carried to, and
88 // carriedHead its head: the version that lands, which the verdict
89 // names (carriedVerdict).
90 carriedVersion, carriedHead string
91
92 // name is the change as it was named, read again before filing in case
93 // a plain branch has come to name a change. For a change, id, handle,
94 // version, head, branch, state and owner are what resolving that name
95 // read; head is the active version's head.
96 name string
97 id, handle, version, head, branch string
98 state, owner string
99 bound, boundVersion, title string // the head filed, its version and title
100 failedAt string // the head whose checks failed
101 filedID, filedHandle, filedVersion string // what the approved line names
102 tel *approveTelemetry
103 mu sync.Mutex
104 interrupted, finished bool
105 child *os.Process
106 childDone chan struct{}
107 worktree string
108 signals chan os.Signal
109 unwatched chan struct{}
110}
111
112// errRefused is an attempt that ended without filing, having said why.
113var errRefused = errors.New("refused")
114
115// errUnknown is a request whose state could not be established after the
116// push, having said so.
117var errUnknown = errors.New("unknown")
118
119func runApprove(g git, args []string, stdout, stderr io.Writer, end func(int)) int {
120 a := &approval{g: g, stdin: os.Stdin, stdout: stdout, stderr: stderr, v: newVerifier(),
121 exit: func(status int) {
122 verification.done()
123 end(status)
124 }}
125 want, err := a.verbFlags(args)
126 if err != nil {
127 fmt.Fprintf(stderr, "valley: %s\n", err)
128 return 1
129 }
130 if !g.succeeds(true, "rev-parse", "--git-dir") {
131 fmt.Fprintln(stderr, "valley: not a git repository")
132 return 1
133 }
134 // The name is read before the fetch, as review reads it.
135 r, err := resolveRecorded(g, a.name)
136 if err != nil {
137 fmt.Fprintf(stderr, "valley: %s\n", err)
138 return 1
139 }
140 a.id, a.handle, a.head, a.branch, a.state, a.owner = r.id, r.handle, r.head, r.branch, r.state, r.owner
141 if r.id != "" {
142 a.version = strconv.Itoa(r.version)
143 }
144 fetch := g.command("fetch", "--prune", "--quiet", "origin")
145 fetch.Stdout, fetch.Stderr = stderr, stderr
146 processStarted()
147 if err := fetch.Run(); err != nil {
148 return exitCode(err)
149 }
150 a.watch(os.Interrupt, syscall.SIGTERM)
151 if a.id != "" {
152 if a.bindHead(want) != nil {
153 return 1
154 }
155 } else {
156 tip, ok, err := g.ref("refs/remotes/origin/" + a.branch)
157 if err != nil || !ok {
158 fmt.Fprintf(stderr, "valley: no such branch on origin: %s\n", a.branch)
159 return 1
160 }
161 if want != "" {
162 at, _ := g.output(true, "rev-parse", "--verify", "--quiet", want+"^{commit}")
163 if at != tip {
164 a.declined(fmt.Sprintf("origin/%s is at %s, not %s", a.branch, a.short(tip), want),
165 act{run: "valley approve " + shellQuote(a.branch)})
166 return 1
167 }
168 }
169 }
170 return a.run()
171}
172
173// verbFlags reads the approve verb's arguments, and returns --head's value.
174func (a *approval) verbFlags(args []string) (want string, err error) {
175 for i := 0; i < len(args); i++ {
176 switch arg := args[i]; {
177 case arg == "--build-here":
178 a.buildHere = true
179 case arg == "-v" || arg == "--verbose":
180 a.verbose = true
181 case arg == "--head" && i+1 < len(args):
182 want = args[i+1]
183 i++
184 case strings.HasPrefix(arg, "--head="):
185 want = strings.TrimPrefix(arg, "--head=")
186 case strings.HasPrefix(arg, "-") || a.name != "":
187 return "", failure(approveUsage)
188 default:
189 a.name = arg
190 }
191 }
192 if a.name == "" {
193 return "", failure(approveUsage)
194 }
195 return want, nil
196}
197
198// reviewApproval is review r's [a]pprove of the change it shows, c, bound
199// to the head r bound and, for a change with a record, to its version.
200// c's name is the change as review was given it, read again before
201// filing. A plain branch's attempt is told the branch, and the head review
202// showed when it showed one. r's carried version and head are given when
203// review's answer carried to that later version, whose line ended the one
204// review's prompt left open. The attempt runs in r's repository, on its
205// terminal, and an interrupt ends it through r's exit.
206func reviewApproval(r *review, c shownChange) *approval {
207 head, version := r.approveHead, r.approveVersion
208 a := &approval{g: r.g, stdin: r.stdin, stdout: r.stdout, stderr: r.stderr, v: r.verifier(), exit: r.exit,
209 reviewing: true, carriedVersion: r.carriedVersion, carriedHead: r.carriedHead,
210 verbose: r.verbose, buildHere: r.buildHere, name: c.name, bound: head}
211 if c.id == "" {
212 a.branch = c.branch
213 return a
214 }
215 // Review shows a change at its active version's head, and binds
216 // [a]pprove to it.
217 a.id, a.handle, a.version, a.head, a.boundVersion = c.id, c.handle, version, head, version
218 return a
219}
220
221// run is one attempt, its telemetry run, and its outcome: 0 when it
222// filed, 1 when it did not.
223func (a *approval) run() int {
224 // Off a terminal, the answer to review's prompt ends no line, so the
225 // verdict starts its own, unless the carry line has ended it.
226 if a.reviewing && a.carriedHead == "" {
227 if _, tty := windowColumns(a.stdin); !tty {
228 fmt.Fprintln(a.stdout)
229 }
230 }
231 t := a.beginTelemetry()
232 a.mu.Lock()
233 a.tel = t
234 a.mu.Unlock()
235 return a.ended(a.attempt())
236}
237
238// ended records how the attempt ended, err being what it returned, and
239// keeps that result: 0 when it filed, 1 when it did not.
240func (a *approval) ended(err error) int {
241 if !a.finish() {
242 select {} // the signal handler ends the process
243 }
244 switch {
245 case err == nil:
246 a.tel.end("filed")
247 a.writeOutcome("approved", a.filedID, a.filedHandle, a.filedVersion, a.bound)
248 return 0
249 case a.failedAt != "":
250 a.tel.end("refused")
251 a.writeOutcome("checks-failed", a.failedAt)
252 case errors.Is(err, errUnknown):
253 a.tel.end("refused")
254 a.writeOutcome("unknown")
255 default:
256 a.tel.end("refused")
257 a.writeOutcome("refused")
258 }
259 return 1
260}
261
262// writeOutcome keeps how the attempt ended, for review.
263func (a *approval) writeOutcome(fields ...string) {
264 a.mu.Lock()
265 a.result = fields
266 a.mu.Unlock()
267}
268
269// watch takes over the signals given until unwatch: one interrupts the
270// attempt. The approve verb is interrupted by SIGINT and SIGTERM. Review's
271// [a]pprove is interrupted by SIGINT alone, which a terminal's Ctrl-C sends
272// to the checks as well, and review acts on a SIGTERM once the attempt has
273// ended (review.go).
274func (a *approval) watch(signals ...os.Signal) {
275 a.signals, a.unwatched = make(chan os.Signal, 2), make(chan struct{})
276 signal.Notify(a.signals, signals...)
277 go func() {
278 select {
279 case <-a.signals:
280 a.interrupt()
281 case <-a.unwatched:
282 }
283 }()
284}
285
286// unwatch gives the signals back once the attempt has ended. Review holds
287// every signal while the attempt runs, so one the attempt took and did not
288// act on is review's to act on.
289func (a *approval) unwatch() {
290 signal.Stop(a.signals)
291 close(a.unwatched)
292}
293
294// interrupt ends an attempt a signal cut short: it stops the checks
295// running, if any, waits for them to end, removes their worktree, records
296// the attempt's end as interrupted, keeps that result, and ends with 130
297// through exit. A second signal while the checks are ending kills them. A
298// signal that reaches the checks first ends them, and checking's caller
299// interrupts the attempt itself; whichever comes first ends it.
300func (a *approval) interrupt() {
301 a.mu.Lock()
302 if a.finished {
303 a.mu.Unlock()
304 a.exit(interruptedStatus)
305 }
306 if a.interrupted {
307 a.mu.Unlock()
308 select {} // the first interrupt ends the process
309 }
310 a.interrupted = true
311 child, done, t := a.child, a.childDone, a.tel
312 a.mu.Unlock()
313 if child != nil {
314 _ = child.Signal(os.Interrupt)
315 select {
316 case <-done:
317 case <-a.signals:
318 _ = child.Kill()
319 <-done
320 }
321 }
322 a.removeWorktree()
323 t.end("interrupted")
324 a.writeOutcome("interrupted")
325 a.exit(interruptedStatus)
326}
327
328// finish marks the attempt ended, unless a signal has interrupted it,
329// when it reports false and the signal handler ends the process.
330func (a *approval) finish() bool {
331 a.mu.Lock()
332 defer a.mu.Unlock()
333 a.finished = !a.interrupted
334 return a.finished
335}
336
337func (a *approval) stopped() bool {
338 a.mu.Lock()
339 defer a.mu.Unlock()
340 return a.interrupted
341}
342
343// act is what a refusal tells the person to do next: a command to run,
344// one to read, or what to do when it is no command.
345type act struct{ run, see, then string }
346
347// declined says what stops the approval, as a verdict on stderr, and
348// returns errRefused. A change is named by its handle and the version
349// being approved, a plain branch by its name.
350func (a *approval) declined(why string, next act) error {
351 return a.refused(verdict{why: why, run: next.run, see: next.see, then: next.then, required: -1, passed: -1})
352}
353
354func (a *approval) refused(v verdict) error {
355 if a.stopped() {
356 return errRefused
357 }
358 v.outcome, v.target, v.name = "refused", "main", a.label()
359 if a.id != "" {
360 v.version = a.boundVersion
361 if v.version == "" {
362 v.version = a.version
363 }
364 }
365 fmt.Fprint(a.stderr, v.lines(terminalOf(a.stderr)))
366 return errRefused
367}
368
369// label is the change as the verdict names it: its handle, or a plain
370// branch's name.
371func (a *approval) label() string {
372 if a.handle != "" {
373 return a.handle
374 }
375 return a.branch
376}
377
378// quoted is the change as a command offered names it.
379func (a *approval) quoted() string { return shellQuote(a.label()) }
380
381func (a *approval) short(oid string) string {
382 s, _ := a.g.output(true, "rev-parse", "--short", oid)
383 return s
384}
385
386// subject is one line of a commit, for saying which commit is meant. A
387// request being replaced is usually this operator's own pre-rebase head;
388// one another operator filed may not be in this repository.
389func (a *approval) subject(oid string) string {
390 if s, err := a.g.output(true, "log", "-1", "--format=%s", oid); err == nil && s != "" {
391 return s
392 }
393 return "subject not in this repository"
394}
395
396// notReady refuses a change that is not ready, offering its owner, as
397// git config valley.principal names them, the command that readies it
398// again. A review is the operator's and the change is usually someone
399// else's, so review is offered nothing.
400func (a *approval) notReady(state, id, branch, owner string) error {
401 why := "change is " + state
402 if state == "draft" {
403 why = "change is a draft"
404 }
405 return a.declined(why, a.readyHint(id, branch, owner))
406}
407
408func (a *approval) readyHint(id, branch, owner string) act {
409 if a.reviewing || owner == "" {
410 return act{}
411 }
412 if principal, _ := a.g.output(true, "config", "valley.principal"); principal != owner {
413 return act{}
414 }
415 run := "valley ready --change " + id
416 if branch != "" {
417 run += " " + shellQuote(branch)
418 }
419 return act{run: run}
420}
421
422// bindHead binds the head approve files for a change with a record. With
423// --head it is exactly that head, which must be one of the record's
424// version heads while the change is ready, the active one or not: a front
425// end that shows the change its own way passes the head it showed, so
426// what is approved is what was seen. Without --head the person is shown
427// the active version's head and title and asked to confirm them, which
428// needs a terminal.
429func (a *approval) bindHead(want string) error {
430 if a.state != "ready" {
431 return a.notReady(a.state, a.id, a.branch, a.owner)
432 }
433 if want != "" {
434 var sha string
435 var err error
436 if headArgument.MatchString(want) {
437 sha, err = a.g.output(true, "rev-parse", "--verify", "--quiet", want+"^{commit}")
438 }
439 if sha == "" || err != nil {
440 return a.declined("--head "+want+" names no commit here", act{see: "valley status " + a.handle})
441 }
442 if err := a.checkVersion(sha); err != nil {
443 return err
444 }
445 a.bound = sha
446 return nil
447 }
448 if err := a.checkVersion(a.head); err != nil {
449 return err
450 }
451 if _, tty := windowColumns(a.stdin); !tty {
452 return a.declined("no terminal to confirm the head, "+a.title,
453 act{run: "valley approve --head " + a.head + " " + a.handle})
454 }
455 fmt.Fprintf(a.stdout, "approve change %s v%s at %s, %s? [y/N] ", a.handle, a.boundVersion, a.head, a.title)
456 switch readLine(a.stdin) {
457 case "y", "Y", "yes":
458 a.bound = a.head
459 return nil
460 }
461 return a.declined("not confirmed", act{})
462}
463
464// readLine reads one line, a byte at a time so that nothing after it is
465// taken from whatever reads the input next.
466func readLine(r io.Reader) string {
467 var line []byte
468 b := make([]byte, 1)
469 for {
470 n, err := r.Read(b)
471 if n == 1 {
472 if b[0] == '\n' {
473 break
474 }
475 line = append(line, b[0])
476 }
477 if err != nil {
478 break
479 }
480 }
481 return strings.TrimSuffix(string(line), "\r")
482}
483
484// checkVersion reads the change's versions from origin again, and
485// refuses unless the change is ready and head is one of its versions'
486// heads, whichever version is active by then: a record that moves after
487// review cannot change what lands, since the request names the head
488// approved. It binds that version's number and title.
489func (a *approval) checkVersion(head string) error {
490 a.boundVersion, a.title = "", ""
491 r, err := versionsOf(a.g, a.id)
492 if err != nil {
493 fmt.Fprintf(a.stderr, "valley: %s\n", err)
494 return a.declined("could not read the change's versions", act{})
495 }
496 var known []string
497 for _, v := range r.Versions {
498 known = append(known, fmt.Sprintf("v%d at %s", v.N, headOf(v)))
499 if headOf(v) == head {
500 a.boundVersion, a.title = strconv.Itoa(v.N), v.Title
501 }
502 }
503 if r.State != "ready" {
504 return a.notReady(r.State, a.id, a.branch, a.owner)
505 }
506 if a.boundVersion == "" {
507 return a.declined(fmt.Sprintf("%s is none of its versions (%s)", a.short(head), strings.Join(known, ", ")),
508 act{see: "valley status " + a.handle})
509 }
510 return nil
511}
512
513// checkRecord reads the change's record again from origin, and refuses
514// unless the change is still ready with the bound head among its
515// versions. The record was read when review or approve began, and another
516// principal may unready, withdraw or ready a new version of the change
517// while a review is open or the checks run. These reads save a run that
518// would come to nothing: the integrator makes the same check on origin.
519//
520// A name that read as a plain branch can come to name a change
521// meanwhile, so the last read before filing, given the head about to be
522// filed as acting, reads the name again: when it names a change now, the
523// change must be ready, and its active head must be that head.
524func (a *approval) checkRecord(acting string) error {
525 if a.id == "" {
526 if acting == "" {
527 return nil
528 }
529 r, err := resolveRecorded(a.g, a.name)
530 if err != nil {
531 fmt.Fprintf(a.stderr, "valley: %s\n", err)
532 return a.declined("could not read origin's records again", act{})
533 }
534 if r.id == "" {
535 return nil
536 }
537 if r.state != "ready" {
538 return a.declined(fmt.Sprintf("now change %s v%d, which is %s", r.handle, r.version, r.state),
539 a.readyHint(r.id, r.branch, r.owner))
540 }
541 if r.head != acting {
542 return a.declined(fmt.Sprintf("now change %s v%d, at another head", r.handle, r.version),
543 act{run: "valley review " + r.handle})
544 }
545 return nil
546 }
547 r, err := resolveRecorded(a.g, a.id)
548 if err != nil {
549 fmt.Fprintf(a.stderr, "valley: %s\n", err)
550 return a.declined("could not read the change's record again", act{})
551 }
552 if r.id != a.id {
553 return a.declined("origin no longer holds the change's record", act{})
554 }
555 if r.state != "ready" {
556 return a.notReady(r.state, a.id, r.branch, r.owner)
557 }
558 return a.checkVersion(a.bound)
559}
560
561// branchAtShown refuses unless the plain branch on origin is still at the
562// head bound to this approval. The operator reviewed a branch, and a
563// branch that moved holds commits nobody has read. origin itself is read,
564// not the tracking ref: a push from another checkout moves the branch
565// without moving this clone's ref.
566func (a *approval) branchAtShown() error {
567 now, err := a.remoteRef("refs/heads/" + a.branch)
568 switch {
569 case err != nil:
570 return a.declined("could not read origin/"+a.branch+" again", act{})
571 case now == "":
572 return a.declined("origin/"+a.branch+" is gone", act{})
573 case now != a.bound:
574 return a.declined(fmt.Sprintf("origin/%s moved from %s, the head shown, to %s", a.branch, a.short(a.bound), a.short(now)),
575 act{run: "valley review " + shellQuote(a.branch)})
576 }
577 return nil
578}
579
580// lsRemote lists origin's refs matching the patterns. ls-remote matches a
581// pattern against the tail of a ref name, so a caller compares each ref
582// it lists whole. A listing that fails is an error, never an empty one.
583func (a *approval) lsRemote(patterns ...string) (map[string]string, error) {
584 out, err := a.g.output(true, append([]string{"ls-remote", "origin"}, patterns...)...)
585 if err != nil {
586 return nil, err
587 }
588 refs := map[string]string{}
589 for _, line := range strings.Split(out, "\n") {
590 if oid, ref, ok := strings.Cut(line, "\t"); ok {
591 refs[ref] = oid
592 }
593 }
594 return refs, nil
595}
596
597// remoteRef is the value of a ref on origin, or "" when origin has none.
598func (a *approval) remoteRef(ref string) (string, error) {
599 refs, err := a.lsRemote(ref)
600 return refs[ref], err
601}
602
603// pushLookalike is a ref origin holds whose name ends in one of these,
604// other than the ref itself, or "". git push matches a destination as
605// rev-parse matches a name: with the ref missing on origin, a push to it
606// writes refs/heads/<ref> instead, and with both there it is refused as
607// ambiguous. So nothing is pushed while origin holds such a ref.
608func (a *approval) pushLookalike(refs ...string) (string, error) {
609 var patterns []string
610 exact := map[string]bool{}
611 for _, ref := range refs {
612 patterns = append(patterns, ref, ref+"/HEAD")
613 exact[ref] = true
614 }
615 listed, err := a.lsRemote(patterns...)
616 if err != nil {
617 return "", err
618 }
619 var others []string
620 for ref := range listed {
621 if !exact[ref] {
622 others = append(others, ref)
623 }
624 }
625 sort.Strings(others)
626 if len(others) == 0 {
627 return "", nil
628 }
629 return others[0], nil
630}
631
632// reportEvidence says, with -v, where the checks this run signed are
633// stored, for every failure after they have run.
634func (a *approval) reportEvidence(refs []string) {
635 if len(refs) == 0 || !a.verbose || a.stopped() {
636 return
637 }
638 fmt.Fprintln(a.stderr, "valley: the evidence is stored locally at:")
639 for _, ref := range refs {
640 fmt.Fprintf(a.stderr, " %s\n", ref)
641 }
642}
643
644// attestationStandsElsewhere reports whether origin holds one of these
645// attestation refs at a value other than the one being pushed. approve
646// pushes a ref of its own notes alone, and origin takes an existing one
647// only with every note it holds kept, so that is the one refusal
648// approving again will never clear.
649func (a *approval) attestationStandsElsewhere(digest string, refs []string) bool {
650 remote, err := a.lsRemote(attestationRefs + digest + "/*")
651 if err != nil {
652 return false
653 }
654 for _, ref := range refs {
655 have := remote[ref]
656 if have == "" {
657 continue
658 }
659 if want, err := a.g.output(true, "rev-parse", ref); err == nil && have != want {
660 return true
661 }
662 }
663 return false
664}
665
666// diagnosePush says why a push carrying the request ref failed, as
667// precisely as the state allows. Every such push is leased, and a lease
668// refuses when the ref is not where the read before it saw it: the
669// request was consumed, or another approval filed or moved it. Reading
670// the ref again tells them apart. Anything else is origin's own refusal,
671// which git has already printed.
672func (a *approval) diagnosePush(ref, pending string) error {
673 now, err := a.remoteRef(ref)
674 switch {
675 case err != nil || now == pending:
676 return a.declined("origin refused the push", act{})
677 case now == "":
678 return a.declined("the pending request was consumed meanwhile", act{see: "valley status " + a.quoted()})
679 }
680 return a.declined(fmt.Sprintf("another approval filed %s (%s) meanwhile", a.short(now), a.subject(now)),
681 act{run: "valley approve " + a.quoted()})
682}
683
684// requestName is the change segment of a request ref for a plain branch.
685// The integrator refuses a segment holding a slash (integrator/refs.go),
686// so a slash is written as a dash. The mapping is lossy: topic/x and
687// topic-x are one request, and approve cannot tell a sibling's request
688// from its own, so it prints the subject of any request it replaces.
689func requestName(branch string) string { return strings.ReplaceAll(branch, "/", "-") }
690
691// attempt is one approval attempt, from main's tip to the verdict.
692func (a *approval) attempt() error {
693 g := a.g
694 root, err := g.output(true, "rev-parse", "--show-toplevel")
695 if err != nil {
696 return a.declined("not in a git repository", act{})
697 }
698 // main's tip as the fetch left it, read once by its exact name. The
699 // merge base, the fast-forward and both policy layers are read at
700 // that one commit.
701 tip, ok, err := g.ref("refs/remotes/origin/main")
702 switch {
703 case err != nil:
704 return a.declined("could not read origin/main", act{run: "git fetch origin"})
705 case !ok:
706 return a.declined("origin has no main to approve onto", act{})
707 }
708
709 // A change with a record is filed at exactly the bound head, under its
710 // own request name, c-<change ID>, and only while its record says it
711 // is ready and lists that head as a version's. Where its branch is
712 // does not matter: the request names the head. A plain branch is
713 // filed at the head review showed, or else at its tip on origin.
714 var head, request, what, named string
715 switch {
716 case a.id != "":
717 if a.bound == "" {
718 return a.declined("no head is bound to this approval", act{})
719 }
720 if err := a.checkRecord(""); err != nil {
721 return err
722 }
723 head, request, named = a.bound, "c-"+a.id, a.handle
724 what = a.handle + " v" + a.boundVersion
725 case a.bound != "":
726 head, request, what, named = a.bound, requestName(a.branch), a.branch, a.branch
727 default:
728 oid, ok, err := g.ref("refs/remotes/origin/" + a.branch)
729 if err != nil || !ok {
730 return a.declined("origin has no branch "+a.branch, act{})
731 }
732 head, request, what, named = oid, requestName(a.branch), a.branch, a.branch
733 }
734 if a.id == "" && changeRequest.MatchString(request) {
735 return a.declined("the branch's request name "+request+" is change "+strings.TrimPrefix(request, "c-")+"'s",
736 act{then: "rename the branch, or name the change by its ID"})
737 }
738 base, err := g.output(true, "merge-base", tip, head)
739 if err != nil || !isObjectID(base) {
740 return a.declined("shares no history with main", act{})
741 }
742 ref := "refs/the-valley/integration-requests/main/" + request
743 a.tel.context(a.id, a.boundVersion, head)
744 a.tel.emit("approve.start", map[string]any{"what": what, "request": ref})
745
746 // A head that does not fast-forward from main, and would bring a
747 // version of another change that has not landed, is a layer above the
748 // bottom of a stale stack. The integrator could land it all the same,
749 // as one commit recorded against this request alone, and the changes
750 // under it would have no landing record of their own. So the stack is
751 // rebased first. This is the project's choice, not a rule the
752 // integrator needs: a stale head with no change under it is approved
753 // as it is, and the integrator merges it onto main.
754 if !g.succeeds(true, "merge-base", "--is-ancestor", tip, head) {
755 under, err := bringsOf(g, a.v, a.id, head)
756 if err != nil {
757 fmt.Fprintf(a.stderr, "valley: %s\n", err)
758 return a.declined("could not read which changes it would bring to main", act{})
759 }
760 if len(under) > 0 {
761 return a.declined("stack is behind main (includes "+strings.Join(under, ", ")+")",
762 act{run: "valley rebase " + shellQuote(named)})
763 }
764 }
765
766 // What the policy requires of the change, read out of exactly the
767 // sources the integrator reads: both layers at the target's tip, and
768 // the floor from the owning valley's own tip when the tip names one. A
769 // change never supplies the policy that gates it, and neither does
770 // the checkout this runs from.
771 res, label, plabel, err := a.derive(root, tip, base, head)
772 if err != nil {
773 fmt.Fprintf(a.stderr, "valley: %s\n", err)
774 return a.declined("the policy did not derive", act{})
775 }
776 required := res.Required
777 names := make([]string, len(required))
778 for i, q := range required {
779 names[i] = q.Name
780 }
781 a.tel.emit("approve.policy", map[string]any{"required": names, "instance": label, "project": plabel})
782
783 // A change the policy asks nothing of is still a change, and the
784 // integrator lands a request that requires no check: nothing is
785 // signed, no key is needed, and one request ref is published.
786 //
787 // A required nix check whose evidence origin already holds is reused,
788 // not built again: a check worker, or an earlier approval, may have
789 // published it. A read of origin that fails ends the approval rather
790 // than reading as no evidence.
791 var reused, missing, unbuilt []string
792 var e evidence
793 if len(required) > 0 {
794 if _, err := exec.LookPath("attest"); err != nil {
795 return a.declined("the attest helper is not installed", act{then: "nix run .#valley bundles it"})
796 }
797 var asked []nixCheck
798 for _, q := range required {
799 if q.Runner == "nix" {
800 asked = append(asked, nixCheck{q.Name, q.Attribute})
801 }
802 }
803 // What coverage and the git it runs say is shown only with -v.
804 quiet := g
805 var said io.Writer = io.Discard
806 if a.verbose {
807 said = a.stderr
808 } else {
809 quiet.stderr = io.Discard
810 }
811 if e, err = coverageOf(quiet, head, asked, said); err != nil {
812 if a.verbose {
813 fmt.Fprintf(a.stderr, "valley: %s\n", err)
814 }
815 return a.declined("could not read the evidence origin holds", act{run: "valley approve -v " + a.quoted()})
816 }
817 // A check whose evidence on origin records a failure is judged by
818 // that evidence, so building it again changes nothing for this
819 // tree, and nothing is filed.
820 var failed []string
821 for _, c := range asked {
822 if _, ok := e.failed[c.name]; ok {
823 failed = append(failed, c.name)
824 }
825 }
826 if len(failed) > 0 {
827 a.failedAt = head
828 return a.refused(verdict{required: len(required), passed: -1, failed: failed})
829 }
830 var signedBy []string
831 for _, q := range required {
832 if by, ok := e.covered[q.Name]; ok {
833 reused = append(reused, q.Name)
834 signedBy = append(signedBy, q.Name+"="+signerOf(by))
835 } else {
836 missing = append(missing, q.Name)
837 }
838 }
839 a.tel.emit("approve.coverage", map[string]any{"tree": e.digest, "reused": list(reused),
840 "reused_by": list(signedBy), "missing": list(missing)})
841 if a.verbose && len(reused) > 0 {
842 fmt.Fprintf(a.stdout, "reusing the evidence origin holds for %s at %s, tree %s:\n", what, a.short(head), e.digest)
843 for _, check := range reused {
844 fmt.Fprintf(a.stdout, " %-24s signed by %s\n", check, signerOf(e.covered[check]))
845 }
846 }
847 }
848
849 // A required nix check with no evidence on origin is built here only
850 // with --build-here. The host's check worker builds the same checks
851 // for a ready change and publishes the evidence, so without the flag
852 // approve files the request at once without it, and the integrator
853 // holds the request until the evidence arrives. Whether the worker
854 // publishes at all is not assured. A command check is never reused and
855 // no worker runs one, so it runs here either way. From here on,
856 // missing is what runs here, and unbuilt what nothing here builds.
857 runner := map[string]derive.Required{}
858 for _, q := range required {
859 runner[q.Name] = q
860 }
861 if !a.buildHere {
862 var here []string
863 for _, check := range missing {
864 if runner[check].Runner == "nix" {
865 unbuilt = append(unbuilt, check)
866 } else {
867 here = append(here, check)
868 }
869 }
870 missing = here
871 }
872
873 var evidenceRefs []string
874 took := ""
875 if len(missing) > 0 {
876 if evidenceRefs, took, err = a.check(head, e, required, reused, missing, runner); err != nil {
877 return err
878 }
879 } else if len(required) == 0 && a.verbose {
880 fmt.Fprintf(a.stdout, "%s requires no check under %s + %s; filing the request with no evidence\n", what, label, plabel)
881 }
882
883 // What origin holds for this request, read once. Approving the same
884 // change twice is ordinary: evidence expires, and a change whose input
885 // closure moved under it is told to re-attest. So the request ref may
886 // already exist. A ref whose name ends in the request's, or in an
887 // evidence ref's, would take the push in its place.
888 pending, err := a.remoteRef(ref)
889 lookalike := ""
890 if err == nil {
891 lookalike, err = a.pushLookalike(append([]string{ref}, evidenceRefs...)...)
892 }
893 if err != nil {
894 a.declined("could not read the request ref on origin", act{})
895 a.reportEvidence(evidenceRefs)
896 return errRefused
897 }
898 if lookalike != "" {
899 a.declined("origin holds "+lookalike+", which git would push to in place of a ref approve pushes",
900 act{then: "delete " + lookalike + " on origin"})
901 a.reportEvidence(evidenceRefs)
902 return errRefused
903 }
904
905 // The one push: every evidence ref, and the request ref wherever it
906 // has to go, --atomic, so a hook that refuses any of them leaves
907 // origin as it was.
908 //
909 // Every write of the request ref is leased against what the read above
910 // saw, including nothing: --force-with-lease=<ref>: refuses if the ref
911 // exists at all, so filing for the first time is a compare-and-swap
912 // too, and two operators filing one change at once cannot have the
913 // second silently replace the first. The lease is the whole of the
914 // force and no refspec carries a +, which would defeat the lease.
915 //
916 // A request already at this head is a re-attestation: the ref does not
917 // move, so it is left out of the push, which carries no
918 // compare-and-swap on a ref it does not change. Where it stands
919 // afterwards is read again below. A request at another head is
920 // replaced: a rebased head is no descendant of the old one.
921 var push, lease []string
922 for _, spec := range evidenceRefs {
923 push = append(push, spec+":"+spec)
924 }
925 if pending != head {
926 lease = append(lease, "--force-with-lease="+ref+":"+pending)
927 push = append(push, head+":"+ref)
928 }
929
930 // The checks can take minutes, and the record may have moved
931 // meanwhile, so it is read once more just before anything is filed.
932 //
933 // A window remains between this read and the push. A change unreadied
934 // or withdrawn in it is filed all the same: git compares only the refs
935 // a push changes, and the record ref is not one of them, so no client
936 // can make the filing conditional on the record. The integrator
937 // narrows the window: it lands no request that would bring a version
938 // of a change that is not ready, and reads the records last just
939 // before it moves the target, so only a record written in that moment
940 // is missed.
941 if err := a.checkRecord(head); err != nil {
942 a.reportEvidence(evidenceRefs)
943 return err
944 }
945 if a.id == "" && a.bound != "" {
946 if err := a.branchAtShown(); err != nil {
947 a.reportEvidence(evidenceRefs)
948 return err
949 }
950 }
951
952 // With no new evidence and the request already at this head there is
953 // nothing to push, and a push with no refspec would fall back to
954 // origin's default one, so none is made.
955 pushed := false
956 if len(push) > 0 {
957 pushed = true
958 args := append(append([]string{"push", "--atomic", "--quiet"}, lease...), "origin")
959 cmd := g.command(append(args, push...)...)
960 cmd.Stdout, cmd.Stderr = a.stderr, a.stderr
961 processStarted()
962 if err := cmd.Run(); err != nil {
963 a.tel.emit("approve.request", map[string]any{"ref": ref, "result": "refused"})
964 if len(lease) == 0 && a.attestationStandsElsewhere(e.digest, evidenceRefs) {
965 a.declined("this key's evidence for the tree is on origin already",
966 act{then: "attest with another key: set VALLEY_ATTEST_KEY"})
967 } else {
968 a.diagnosePush(ref, pending)
969 }
970 a.reportEvidence(evidenceRefs)
971 return errRefused
972 }
973 a.tel.emit("approve.request", map[string]any{"ref": ref, "result": "pushed"})
974 }
975
976 // The lines -v adds under the request line.
977 var standing []string
978 if pending == head {
979 // The request ref was not in that push, so where it stands now is
980 // read again: the integrator may have landed the change and
981 // consumed it, or another approval replaced it. Nothing here
982 // writes it back. Re-creating a consumed request would file a
983 // change already in the stream, replacing another approval's
984 // would clobber the winner, and either would be a second push. The
985 // approval stood before this run, so a request that cannot be read
986 // leaves its state unknown rather than unapproved; approving again
987 // takes the create or replace path against what is there.
988 after, err := a.remoteRef(ref)
989 if err != nil || after == "" {
990 v := verdict{outcome: "unknown", name: a.label(), required: -1, passed: -1}
991 if a.id != "" {
992 v.version = a.boundVersion
993 }
994 if err == nil {
995 v.why = "request consumed meanwhile"
996 }
997 if !a.stopped() {
998 fmt.Fprint(a.stdout, v.lines(terminalOf(a.stdout)))
999 }
1000 a.reportEvidence(evidenceRefs)
1001 return errUnknown
1002 }
1003 if after != head {
1004 a.declined(fmt.Sprintf("another approval filed %s (%s) meanwhile", a.short(after), a.subject(after)),
1005 act{run: "valley approve " + a.quoted()})
1006 a.reportEvidence(evidenceRefs)
1007 return errRefused
1008 }
1009 switch {
1010 case pushed:
1011 standing = append(standing, "the request already stood at this head; the evidence is what was published")
1012 case len(unbuilt) > 0:
1013 standing = append(standing, "the request already stood at this head, and nothing was built or published")
1014 case len(required) > 0:
1015 standing = append(standing, "the request already stood at this head and origin already held the evidence, so nothing needed publishing")
1016 default:
1017 standing = append(standing, "the request already stood at this head and nothing was required, so nothing needed publishing")
1018 }
1019 } else if pending != "" {
1020 standing = append(standing, fmt.Sprintf("replaced the pending request, which stood at %s (%s)", a.short(pending), a.subject(pending)))
1021 }
1022
1023 if a.verbose {
1024 w := a.stdout
1025 fmt.Fprintf(w, " request %s -> %s\n", ref, a.short(head))
1026 for _, s := range standing {
1027 fmt.Fprintf(w, " %s\n", s)
1028 }
1029 if len(required) == 0 {
1030 fmt.Fprintln(w, " evidence none — nothing was required, so nothing was signed")
1031 fmt.Fprintln(w, " checks none — the policy requires no check of this change")
1032 } else {
1033 fmt.Fprintf(w, " tree %s\n", e.digest)
1034 for _, spec := range evidenceRefs {
1035 fmt.Fprintf(w, " evidence %s\n", spec)
1036 }
1037 // The refs on origin whose evidence was reused, each once.
1038 shown := map[string]bool{}
1039 for _, check := range reused {
1040 spec, _, _ := strings.Cut(e.covered[check], " ")
1041 if !shown[spec] {
1042 shown[spec] = true
1043 fmt.Fprintf(w, " reused %s\n", spec)
1044 }
1045 }
1046 if len(unbuilt) > 0 {
1047 fmt.Fprintf(w, " missing %s\n", strings.Join(unbuilt, ", "))
1048 }
1049 fmt.Fprintf(w, " checks %s\n", strings.Join(names, ", "))
1050 }
1051 }
1052
1053 // The verdict. Checks with no evidence yet are built by a check
1054 // worker only for a ready change's active version. Elsewhere approve
1055 // offers to build them here, unless a command check that ran here put
1056 // this signer's evidence for the tree on origin, which approve cannot
1057 // add to, so a plain branch is offered readying instead, which lets a
1058 // worker build it.
1059 v := verdict{outcome: "approved", name: a.label(), target: "main", required: len(required),
1060 passed: len(required) - len(unbuilt), took: took, waiting: unbuilt}
1061 if a.id != "" {
1062 v.version = a.boundVersion
1063 }
1064 if len(unbuilt) > 0 {
1065 switch {
1066 case a.id != "" && head == a.head:
1067 v.worker = true
1068 case len(missing) == 0:
1069 at := ""
1070 if a.id != "" {
1071 at = "--head " + a.short(head) + " "
1072 }
1073 v.run = "valley approve --build-here " + at + a.quoted()
1074 case a.id == "":
1075 v.run = "valley ready " + a.quoted()
1076 default:
1077 v.see = "valley status " + a.quoted()
1078 }
1079 }
1080 if a.carriedHead != "" && !a.stopped() {
1081 v = a.carriedVerdict()
1082 }
1083 if !a.stopped() {
1084 fmt.Fprint(a.stdout, v.lines(terminalOf(a.stdout)))
1085 }
1086 a.filedID, a.filedHandle, a.filedVersion = a.id, a.handle, a.boundVersion
1087 if a.id == "" {
1088 a.filedVersion = ""
1089 }
1090 return nil
1091}
1092
1093// carriedVerdict is the verdict on an approval whose answer carried to a
1094// later version. The request names the head shown, and the integrator
1095// lands its delta once there is evidence for the tree it lands: the later
1096// version's, the change's active one. So the verdict names that version,
1097// and tells its checks as review's checks line reads them for the active
1098// version (activeChecks, versionchecks.go). What that read says goes to
1099// stderr with -v alone.
1100func (a *approval) carriedVerdict() verdict {
1101 said := io.Discard
1102 if a.verbose {
1103 said = a.stderr
1104 }
1105 var checks *jsonVersionChecks
1106 changes, err := activeChecks(a.g, []string{a.id}, nil, said)
1107 if err != nil {
1108 fmt.Fprintf(said, "valley: %s\n", err)
1109 }
1110 for _, c := range changes {
1111 if v := c.Versions[c.Active-1]; c.ChangeID == a.id && v.Head == a.carriedHead {
1112 checks = v.Checks
1113 }
1114 }
1115 return carriedVerdictOf(a.label(), a.carriedVersion, checks)
1116}
1117
1118// carriedVerdictOf is the verdict that names version, the one that lands,
1119// from its check state, or nil when that was not read. The host's worker
1120// builds the version's nix checks, as the change's active version. It runs
1121// no check of another runner, which the checks line does not judge, so
1122// such a check waits with no worker building it, and approving the change
1123// runs it here.
1124func carriedVerdictOf(name, version string, checks *jsonVersionChecks) verdict {
1125 v := verdict{outcome: "approved", name: name, version: version, target: "main", carried: true, worker: true}
1126 if checks == nil {
1127 v.outcome, v.why, v.required, v.passed = "unknown", "checks unknown", -1, -1
1128 return v
1129 }
1130 for _, q := range checks.Required {
1131 switch q.State {
1132 case checkPassed:
1133 v.passed++
1134 case checkFailed:
1135 v.failed = append(v.failed, q.Name)
1136 case checkPending:
1137 v.waiting = append(v.waiting, q.Name)
1138 default:
1139 v.waiting, v.worker = append(v.waiting, q.Name), false
1140 v.run = "valley approve " + shellQuote(name)
1141 }
1142 v.required++
1143 }
1144 return v
1145}
1146
1147// derive is what the policy at main's tip requires of the change from
1148// base to head, and where each layer was read from.
1149func (a *approval) derive(root, tip, base, head string) (res *derive.Result, label, plabel string, err error) {
1150 g := a.g
1151 schema, err := schemaFile(g, "")
1152 if err != nil {
1153 return nil, "", "", err
1154 }
1155 src, done, err := resolveLayers(g, tip, "", "")
1156 defer done()
1157 if err != nil {
1158 return nil, "", "", fmt.Errorf("%v; nothing derived", err)
1159 }
1160 model, err := policyModel(schema, src.instance, src.project, false)
1161 if err != nil {
1162 return nil, "", "", err
1163 }
1164 paths, err := derive.Diff(context.Background(), g.dir, g.env, base, head)
1165 if err != nil {
1166 return nil, "", "", fmt.Errorf("%v; nothing derived", err)
1167 }
1168 if res, err = derive.Derive(model, paths); err != nil {
1169 return nil, "", "", fmt.Errorf("%v; nothing derived", err)
1170 }
1171 label, plabel = src.labels(root, "", "", "origin/main "+a.short(tip))
1172 return res, label, plabel, nil
1173}
1174
1175// check runs the missing checks over head in a throwaway worktree, signed
1176// with this host's key, and returns every attestation ref stored here for
1177// the head's tree and how long the checks took.
1178func (a *approval) check(head string, e evidence, required []derive.Required, reused, missing []string, runner map[string]derive.Required) (refs []string, took string, err error) {
1179 key := os.Getenv("VALLEY_ATTEST_KEY")
1180 if key == "" {
1181 return nil, "", a.declined("no signing key", act{then: "set VALLEY_ATTEST_KEY to the ed25519 key this host attests with"})
1182 }
1183 if st, err := os.Stat(key); err != nil || !st.Mode().IsRegular() {
1184 return nil, "", a.declined("no signing key at "+key, act{})
1185 }
1186 signer := []string{"--key", key}
1187 if name := os.Getenv("VALLEY_ATTEST_NAME"); name != "" {
1188 signer = append(signer, "--name", name)
1189 }
1190
1191 // The ref this run's evidence goes to is keyed by the tree and this
1192 // signer's key hash, and approve pushes it holding this run's notes
1193 // alone, which origin refuses once it holds the ref. So origin
1194 // holding it is refused before anything is built.
1195 keyCmd := a.g.program("attest", append([]string{"key"}, signer...)...)
1196 keyCmd.Stderr = a.stderr
1197 processStarted()
1198 verifier, err := keyCmd.Output()
1199 if err != nil {
1200 return nil, "", a.declined("could not read the signing key at "+key, act{})
1201 }
1202 _, keyhash, _ := strings.Cut(strings.TrimRight(string(verifier), "\n"), "+")
1203 keyhash, _, _ = strings.Cut(keyhash, "+")
1204 if e.listed[attestationRefs+e.digest+"/"+keyhash] != "" {
1205 return nil, "", a.declined("this key's evidence for the tree, on origin, lacks "+strings.Join(missing, ", "),
1206 act{then: "attest with another key: set VALLEY_ATTEST_KEY"})
1207 }
1208
1209 // attest logs how long each check took, on this machine and outside
1210 // the evidence. What it cannot know itself is passed in: the change,
1211 // and each check's declared cost.
1212 timing := []string{"--timings"}
1213 if a.id != "" {
1214 timing = append(timing, "--change", a.id)
1215 }
1216 if a.boundVersion != "" {
1217 timing = append(timing, "--change-version", a.boundVersion)
1218 }
1219 var run []string
1220 for _, check := range missing {
1221 q := runner[check]
1222 switch q.Runner {
1223 case "nix":
1224 run = append(run, "--check", check+"="+q.Attribute)
1225 case "command":
1226 run = append(run, "--command", check+"="+q.Command)
1227 default:
1228 return nil, "", a.declined("the policy requires "+check+" but says no way to run it", act{})
1229 }
1230 if q.Cost != "" {
1231 timing = append(timing, "--cost", check+"="+q.Cost)
1232 }
1233 }
1234
1235 wt, err := os.MkdirTemp("", "valley-approve-")
1236 if err != nil {
1237 return nil, "", a.declined("no scratch directory to check it in", act{})
1238 }
1239 a.mu.Lock()
1240 a.worktree = wt
1241 a.mu.Unlock()
1242 defer a.removeWorktree()
1243 add := a.g.command("worktree", "add", "--quiet", "--detach", wt, head)
1244 add.Stdout, add.Stderr = a.stderr, a.stderr
1245 processStarted()
1246 if add.Run() != nil {
1247 a.removeWorktree()
1248 return nil, "", a.declined("could not check the head out to run its checks", act{})
1249 }
1250
1251 if a.tel != nil {
1252 timing = append(timing, "--telemetry", a.tel.spool, "--telemetry-run", a.tel.run+"-checks", "--project", a.tel.project)
1253 a.tel.emit("approve.checks", map[string]any{"attest_run": a.tel.run + "-checks", "checks": list(missing)})
1254 }
1255 v := verdict{name: a.label(), required: len(required), passed: len(reused)}
1256 if a.id != "" {
1257 v.version = a.boundVersion
1258 }
1259 args := append(append(append([]string{"run", "--repo", wt}, signer...), timing...), run...)
1260 // attest runs the checks in the worktree --repo names; its directory
1261 // and environment are the repository's, as for every program here.
1262 cmd := a.g.program("attest", args...)
1263 cmd.Stdin = a.stdin
1264 began := time.Now()
1265 done := make(chan struct{})
1266 a.mu.Lock()
1267 a.childDone = done
1268 a.mu.Unlock()
1269 status := v.checking(missing, cmd, a.verbose, droppable(a.stdout), droppable(a.stderr), a.started, a.stopped)
1270 a.mu.Lock()
1271 a.child = nil
1272 close(done)
1273 a.mu.Unlock()
1274 if a.stopped() || status == 128+int(syscall.SIGINT) || status == 128+int(syscall.SIGTERM) {
1275 a.interrupt()
1276 }
1277 if status != 0 {
1278 a.failedAt = head
1279 return nil, "", errRefused
1280 }
1281 took = fmt.Sprintf("%ds", int(time.Since(began).Seconds()))
1282 a.removeWorktree()
1283
1284 // Every attestation stored here for the tree, whoever signed it: the
1285 // evidence for this change is what the tree's digest keys, not what
1286 // this run happened to add.
1287 out, err := a.g.output(true, "for-each-ref", "--format=%(refname)", attestationRefs+e.digest)
1288 if err == nil && out != "" {
1289 refs = strings.Split(out, "\n")
1290 }
1291 if len(refs) == 0 {
1292 return nil, "", a.declined("no attestation is stored for the tree", act{})
1293 }
1294 return refs, took, nil
1295}
1296
1297// started is told of the attest run checking starts, so a signal can stop
1298// it.
1299func (a *approval) started(p *os.Process) {
1300 a.mu.Lock()
1301 a.child = p
1302 a.mu.Unlock()
1303}
1304
1305// removeWorktree removes the checks' worktree, if there is one.
1306func (a *approval) removeWorktree() {
1307 a.mu.Lock()
1308 wt := a.worktree
1309 a.worktree = ""
1310 a.mu.Unlock()
1311 if wt == "" {
1312 return
1313 }
1314 remove := a.g.command("worktree", "remove", "--force", wt)
1315 _ = remove.Run()
1316 _ = os.RemoveAll(wt)
1317}
1318
1319// signerOf is the signer of a covered check, as coverage maps it to
1320// "<ref> <signer>".
1321func signerOf(by string) string {
1322 _, signer, _ := strings.Cut(by, " ")
1323 return signer
1324}
1325
1326// list is a list as a telemetry record holds one: empty rather than null.
1327func list(items []string) []string {
1328 if items == nil {
1329 return []string{}
1330 }
1331 return items
1332}
1333
1334// approveTelemetry is an approval attempt's telemetry run, when the
1335// checkout has valley.telemetry on.
1336type approveTelemetry struct {
1337 emitter *telemetry.Emitter
1338 run, spool, project string
1339 began time.Time
1340 mu sync.Mutex
1341 about telemetry.Record
1342 ended bool
1343}
1344
1345// beginTelemetry starts the attempt's run, bound to the spool of the
1346// destination the checkout's telemetry remote names, and a flusher that
1347// sends it. Telemetry off is nil.
1348func (a *approval) beginTelemetry() *approveTelemetry {
1349 if on, _ := a.g.output(true, "config", "--get", "--bool", "valley.telemetry"); on != "true" {
1350 return nil
1351 }
1352 dest, err := telemetryRemote(a.g, "")
1353 if err == nil {
1354 var dir string
1355 if dir, err = bindSpool(dest); err == nil {
1356 version := versionStamp
1357 if version == "" {
1358 version = "unstamped"
1359 }
1360 t := &approveTelemetry{run: telemetry.NewRunID(), spool: dir, project: dest.project(), began: time.Now()}
1361 t.emitter = telemetry.NewEmitter(dir, telemetry.Self("valley", version), t.run)
1362 t.about.Project = t.project
1363 startFlusher()
1364 return t
1365 }
1366 }
1367 fmt.Fprintf(a.stderr, "valley: telemetry: %s\n", err)
1368 return nil
1369}
1370
1371// context is what every record of the attempt from here on is about.
1372func (t *approveTelemetry) context(id, version, head string) {
1373 if t == nil {
1374 return
1375 }
1376 n, _ := strconv.Atoi(version)
1377 t.mu.Lock()
1378 t.about.Change, t.about.Version, t.about.Head = id, n, head
1379 t.mu.Unlock()
1380}
1381
1382// emit records one step of the attempt. elapsed_ms is this machine's wall
1383// clock since the attempt began.
1384func (t *approveTelemetry) emit(typ string, data map[string]any) {
1385 if t == nil {
1386 return
1387 }
1388 t.mu.Lock()
1389 defer t.mu.Unlock()
1390 if t.ended {
1391 return
1392 }
1393 data["elapsed_ms"] = time.Since(t.began).Milliseconds()
1394 t.emitter.Emit(typ, t.about, data)
1395}
1396
1397// end records how the attempt ended: filed, refused or interrupted. Only
1398// the first end is recorded.
1399func (t *approveTelemetry) end(result string) {
1400 if t == nil {
1401 return
1402 }
1403 t.emit("approve.end", map[string]any{"result": result})
1404 t.mu.Lock()
1405 t.ended = true
1406 t.mu.Unlock()
1407}