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