gunk-dev/the-valley

valley

source2a81e33b614dmain's published tip history
153.0 KiB
1#!/usr/bin/env bash
2# valley — the S1 integrator's verbs, as a plain shell script.
3#
4# EVICTION CLAUSE (owner-ratified; the decision node is
5# archive/.the-valley/decisions/dcr-74c3158-valley-cli-lifecycle.md).
6# This tool is deliberately a shell script: it runs from any checkout with
7# nothing but git and coreutils — no machinery, the portability stance of
8# ida-b9f646c. It GRADUATES to its own repo and a real language the moment
9# ANY tripwire is crossed:
10# - it grows past ~300 lines;
11# - it needs persistent state, config, or a daemon
12# (CROSSED by review's notes, which outlive the session in
13# $XDG_STATE_HOME/valley/notes.);
14# - it needs dependencies beyond git + coreutils
15# (CROSSED by Phase 1's tail/replay, which need the nats CLI, and again
16# by checks, which needs the cue CLI, again by review's [a]pprove, which
17# needs the attest helper, and again by status, ready, unready and
18# withdraw, which are a Go program (status/) this script runs —
19# graduation is now due; recording the decision node is part of taking it.);
20# - its behavior gets subtle enough to need real tests
21# (CROSSED by checks: glob matching is pinned by the policy-deriver
22# flake check, not by reading the code.);
23# - it needs nontrivial parsing or concurrency
24# (CROSSED by checks: glob-to-regex translation and -z diff parsing.).
25# The size tripwire (~300 lines) is crossed too. Which way to take the
26# graduation is dcr-2aa1a12, still `proposed`.
27# Graduation is a deliberate act, recorded as a decision node.
28# Precedent: klaus — born in cosmo, graduated deliberately.
29
30set -euo pipefail
31
32# Every verb reads the repository's own objects. A replacement ref makes one
33# object stand in for another wherever git looks it up, so a fetched or
34# planted refs/replace/* could change the diff a reviewer reads, the policy
35# a derivation composes, and the tree a request is filed for. git is told
36# to ignore them, whatever configuration says, and the variables that point
37# it at other objects or at another replacement namespace are dropped. What
38# chooses the repository and the person's own configuration are kept: a
39# fetch of the owning valley needs that configuration, and neither changes
40# what an object id reads as once replacement refs are off.
41export GIT_NO_REPLACE_OBJECTS=1
42unset GIT_REPLACE_REF_BASE GIT_GRAFT_FILE GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES
43
44# The version the package stamped on this script when nix built it
45# (nix/packages.nix): the CLI's version and the commit it was built from.
46# A script run straight from a checkout has none. It is taken here and
47# unset, so no program this script runs inherits a stamp that is not its
48# own; self-update is handed it explicitly.
49VALLEY_STAMP="${VALLEY_VERSION:-}"
50unset VALLEY_VERSION
51
52die() {
53 printf 'valley: %s\n' "$*" >&2
54 exit 1
55}
56
57usage() {
58 cat <<'EOF'
59valley — S1 integrator verbs for a valley project
60
61usage: valley <verb> [args]
62
63 pending [--all] [--repo <name>] [--checks] [--json]
64 list what is waiting to land, in three sections: ready,
65 the ready changes whose active version has not landed;
66 branches, each branch on origin that main does not
67 reach and that is no change's active head; and drafts,
68 the changes whose record says they are drafts. each
69 entry is a block. its first line is its name, with its
70 head's age and author: handle and version for a change,
71 the branch for a branch, and handle and version on its
72 branch for a draft. under it come its title (the
73 record's for a change, the subject of its first own
74 commit for a branch), then the commits and the diff it
75 adds to its base: the nearest other entry its head
76 strictly contains, or main. a stack is its top entry,
77 then every entry the top contains, listed under it at
78 one indentation, each before the entries it contains
79 (ancestry alone: approving the top lands everything
80 listed under it, and the top says how many). each
81 listed entry is on the one listed after it, or says
82 `on <base>`, as at a fork. a listed entry is marked
83 when it is from another section. a
84 change also says `includes <handle>` for a change its
85 head contains that is no entry, such as a withdrawn
86 one, and `uncertain` when the version may have landed
87 without its evidence being stored. the stack with the
88 latest commit comes first. lines fit the terminal, or
89 80 columns off one; titles are cut short with …, names
90 never. names are bold on a terminal unless NO_COLOR is
91 set.
92 --all every project the serving host
93 publishes, each headed by its name (see
94 changes below)
95 --repo NAME that one project
96 --checks add a line to each change with the
97 checks the policy requires of it, by
98 cost, as checks derives them
99 --json print valley-pending/v1: the
100 valley-changes/v1 shape, with the
101 pending changes in changes and the
102 drafts in drafts
103 needs the valley-go helper.
104 changes --json [--all] [--repo <name>]
105 print every change origin holds a record of, in every
106 state, as one JSON object, valley-changes/v1, for front
107 ends to read (docs/architecture.md): each version's
108 head, title and branch, how far it has landed
109 (landed, landed-recorded, uncertain or not-landed),
110 its pending request and its last outcome, and the
111 branches no change is on. handles are unique across
112 everything listed: a change id recorded in more than
113 one repository listed has the handle <repo>:<prefix>
114 in each. without --all it covers this
115 repository. --all covers every project the serving
116 host lists at refs/the-valley/projects in its instance
117 repository, which policy/valley names at main's tip on
118 origin; each project's URL is the instance's with its
119 last path segment replaced, and is read through a clone
120 kept under $XDG_CACHE_HOME/valley/repos. a url that
121 opens with a dash, names a <transport>:: helper such
122 as ext::, or has a scheme other than ssh, git, https or
123 file is refused. a repository that cannot be read is
124 listed with its error. --repo limits it to one
125 project. landed means on main's first-parent history
126 with no merge above it. landed-recorded needs a landed
127 commit with one parent and the integrator's transfer
128 statement for the version's request name, verified;
129 the integrator's outcome record for that name saying
130 land at the version's head; and the integrator's merge
131 of the head onto the landed commit's parent giving the
132 landed tree. the statement is verified with these:
133 VALLEY_KNOWN_SIGNERS names the registry's known-signers
134 file and VALLEY_INTEGRATOR_SIGNER the integrator's
135 signing name, and attest checks the note.
136 needs the valley-go helper.
137 review <change> page through the change's branch: its log and diff vs
138 origin/main, or a stack layer by layer (below). then
139 choose:
140 [a]pprove file an integration request for the
141 head shown. runs the
142 checks the composed policy requires of
143 this change over a throwaway worktree of
144 that head, signs each result as an
145 attestation, and publishes the evidence
146 and the request ref to origin in ONE
147 atomic push. this files the request;
148 it does not wait for integration or
149 update your local checkout. use status
150 to read the result. the policy comes
151 from the target's tip and the owning
152 valley's, as checks describes below,
153 so your checkout
154 can be on any branch. a change the policy
155 requires no check of is filed too, as a
156 request with no evidence, and says so.
157 approving a change already requested is
158 how it is filed again. at a head rebased
159 onto a moved main it replaces the request
160 ref under a lease and names the head it
161 replaced; at the same head it leaves the
162 ref alone and publishes only the new
163 evidence, which the create-only
164 attestation namespace refuses when this
165 signer has already attested that tree
166 (bd-7b7d58f). every write of the request
167 ref is leased, filing included, so an
168 approval that lost a race is refused
169 rather than clobbering the one that won.
170 needs the attest helper and
171 VALLEY_ATTEST_KEY, the ed25519 key this
172 host signs with, whenever a check is
173 required; VALLEY_ATTEST_NAME is the name it
174 signs under, defaulting to this host's.
175 [v]iew full diff
176 page the change's whole diff, with
177 notes taken as below, and ask again
178 [r]eject delete the remote branch (confirmed first)
179 [s]kip do nothing
180 a change with a record is first set against its
181 approved version: the greatest version below the one
182 shown whose exact head an integration request or a
183 land, stale or reject outcome on origin names, under
184 c-<change id> or a branch name of the change that
185 nothing else maps to (valley-go compare). with none,
186 or an ambiguous one, review pages the whole diff. when
187 each version's diff from its merge base with main
188 changes the same files the same way (valley-delta-v1),
189 review prints `<change> v<n> at <head>: clean restack
190 of approved v<m> at <old head>.`, the two bases, and
191 the commits main landed between them, and pages
192 nothing. otherwise it pages `changed since approved
193 v<m>`, the files whose change differs, git
194 range-diff of the two versions, and the shown
195 version's diff of those files. a changed commit
196 message or author is shown either way. this is
197 information only: it files nothing and skips no check.
198 when [a]pprove's checks fail, the prompt says approving
199 needs a new head and stops offering [a]pprove until the
200 change has one. any other refusal keeps the prompt as
201 it was.
202 [a]pprove files the head shown, for a branch no record
203 is on too: it refuses, naming both heads, when the
204 branch on origin has moved off that head since.
205 [a]pprove is the only way a change reaches main from
206 here, and approve below is the same act without the
207 pager.
208 Nothing in this script writes the protected ref: the
209 integrator does, having judged the request.
210 a stale branch (won't fast-forward from main) is first
211 offered:
212 [b]ase rebase it onto origin/main, as rebase
213 does below, then re-review the diff that
214 would actually land
215 [a]pprove is offered there too: a stale branch is nothing
216 the integrator cannot apply, so it need not be rebased
217 first.
218 a change whose record is not ready says so above its
219 diff, and again in place of the prompt, which then
220 offers only [v]iew full diff and [s]kip:
221 `<change> v<n> is a draft: its owner (<owner>) hasn't
222 marked it ready, so it can't be approved yet.`
223 `<change> is withdrawn: there is nothing to approve.`
224 a draft is often a change an agent is still working on.
225 [a]pprove would be refused, and so would [b]ase, since
226 adding the rebased head as a version would ready the
227 change behind its owner's back. [r]eject records
228 nothing on the change: it would only delete a branch
229 its owner may still be working on. a change unreadied
230 or withdrawn while the review is open is still refused
231 by [a]pprove and [b]ase, which read the record again.
232 a branch no record is on has no state, and is offered
233 the usual prompt.
234 while paging, press v: less opens the diff in $EDITOR.
235 every line you insert there is a note. it is anchored to
236 the file and new-side line it sits on — to the file alone
237 when it sits above the first hunk. range-diff gives no
238 line numbers, so on a changed version a note keeps its
239 file and line only in the shown version's diff at the
240 end of the page. each note is then appended to
241 $XDG_STATE_HOME/valley/notes/<branch>.md (default
242 ~/.local/state) and printed after the verdict. notes
243 survive [b]ase. lines you change or delete instead of
244 inserting are ignored, with a warning.
245 a change whose active version names no branch is
246 refused, since notes and [r]eject act on a branch;
247 approve files its head without one.
248 a stack is reviewed one layer at a time, bottom first.
249 its layers are what pending lists under the change: the
250 changes not landed and the branches no record is on
251 that its head contains (valley-go stack). review first
252 lists them, warns of a lower layer that is a draft or
253 withdrawn, since the integrator lands nothing above it,
254 and says how the review goes: [n] through the layers,
255 and approving the top lands them all. a stack whose
256 bottom does not fast-forward from main is then asked,
257 before any layer is paged, as in `one, at the bottom,
258 does not fast-forward from main:`:
259 [b]ase all <n>
260 rebase the whole stack onto origin/main,
261 as rebase does below, then list it again
262 and page the rebased layers, so the
263 heads paged are the heads approved
264 [s]top end the review; nothing done
265 a rebase that is refused or left unfinished says what
266 happened, and then only [s]top is offered.
267 it then shows each layer, headed `change <k> of <n>:
268 <name> on <below>`, as a change alone is shown: set
269 against its own change's approved version, or its log
270 and diff against the layer below it paged, with notes
271 kept under that layer's branch.
272 after each lower layer it asks, naming the layer and
273 its place, as in `two, 2 of 3:`:
274 [n]ext layer go on to the layer above; the usual
275 answer
276 [a]pprove approve that layer at the head shown,
277 as review of it would. this lands it
278 and every layer under it, which the
279 prompt names (`one alone`, `one and
280 two`, `the <k> up to <name>`), and
281 ends the review
282 [v]iew full diff
283 page that layer's log and diff against
284 the layer below it, and ask again
285 [s]top end the review; nothing done
286 after the top it asks, as in `three, 3 of 3:`:
287 [a]pprove all <n>
288 approve the top at the head shown,
289 which lands every layer
290 [v]iew full diff
291 page the top's log and diff against
292 the layer below it, and ask again
293 [r]eject <name>
294 delete the top's branch (confirmed
295 first)
296 [s]top end the review; nothing done
297 only the top is offered [r]eject. when a layer's checks
298 fail, its prompt says approving needs a new head and
299 stops offering [a]pprove, as for any change. a layer
300 that is not ready says so as a change alone does, under
301 its heading and in its prompt. neither it nor any layer
302 above it is offered [a]pprove, since approving one would
303 land it: each prompt above it says `it would bring
304 <name>, change <k> of <n>, which is a draft` (or
305 withdrawn) in its place. a top that is not ready is not
306 offered [r]eject either. every layer's notes are printed
307 at the end.
308 approve [--head <sha>] <change>
309 do what review's [a]pprove does for the change, without
310 paging it: the same checks, the same refusals, the same
311 leased request write and the same output. exits non-zero
312 when it refuses. a change with a record is approved at
313 exactly one head, and its request is filed as
314 refs/the-valley/integration-requests/main/c-<change id>,
315 at that head:
316 --head SHA approve exactly this head, which must be
317 one of the record's version heads,
318 active or not. a front end passes the
319 head it showed, so a record that moves
320 after review cannot change what lands.
321 without --head, approve shows the active version's head
322 and title and asks to confirm them, on a terminal; off
323 one it refuses. a branch no record is on is approved at
324 its tip on origin, which --head must name if it is
325 given (review's [a]pprove files the head it showed, and
326 refuses once the branch on origin has moved off it), under
327 the branch's request name: the branch with
328 each / replaced by -. a branch whose request name would
329 be c-<change id> is refused, since that name is the
330 change's.
331 approve refuses, before any check runs, a head that does
332 not fast-forward from main and would bring a version of
333 another change that has not landed: a layer above the
334 bottom of a stale stack. the refusal names the command
335 that rebases the stack, valley rebase <change>. this is
336 the project's choice, not a rule the integrator needs:
337 approved as it is, the stack would land as one commit
338 recorded against this request alone, so the changes
339 under it would have no landing record of their own, and
340 the checks would run over a head that has to be rebased
341 anyway. a stale head with no change under it, such as
342 the bottom layer of a stack or a change alone, is
343 approved as it is, and the integrator merges it onto
344 main.
345 rebase <change> rebase the change's whole stack onto origin/main, as
346 review's [b]ase does: the layers valley-go stack lists
347 under the change, and the change itself. in a throwaway
348 worktree, bottom first, each layer's own commits go onto
349 the rebased layer below it, and the bottom's onto
350 origin/main, so each layer keeps its own diff. commits
351 under the bottom that a lower change landed through the
352 integrator drop out, since main holds them; that landing
353 is read as changes reads it, with VALLEY_KNOWN_SIGNERS
354 and VALLEY_INTEGRATOR_SIGNER. one atomic
355 push then moves every layer's branch, each leased on the
356 tip read: every branch moves, or none does. last, bottom
357 first, each change gains its rebased head as a new
358 version, as valley.principal names, the way ready
359 --if-active does: only while the change is still ready
360 at the head the rebase began with.
361 it refuses, with nothing changed, a stack holding a
362 change that is not ready, records no branch, or whose
363 branch is missing on origin or is not at its recorded
364 head; a plain branch that is the branch of a change not
365 in the stack; two layers on one branch; a merge among the
366 commits to be rebased, or a version head of a change
367 that is not ready or not in the stack, since a rebase
368 gives each commit a new id; and a stack holding a change
369 while git config valley.principal names no one. a
370 conflict in any layer pushes nothing, records nothing
371 and names the layer.
372 a change alone prints its new head. a
373 stack prints a manifest: one line for each layer, with
374 its old and new head, whether its branch was pushed, and
375 whether a version was added. then, for each change left
376 unfinished, the valley ready command that finishes it,
377 and the exit status is non-zero. rebasing again refuses
378 a change whose branch holds a head no version records,
379 and prints the same command. last, it names each ready
380 change or branch outside the stack that is left on an
381 old head of a layer, such as a second stack on a lower
382 layer, with the rebase that moves it; it does not move
383 it. rebase does not re-review the result. a stack that
384 already fast-forwards from main is left as it is.
385 status [--json] <change>
386 read the request and the integrator's last decision from
387 origin. distinguish waiting, a decision that needs
388 attention, and a change integrated into origin/main.
389 a change with a record is read at its active version's
390 head, under c-<change id>, and the status says the
391 version, its title, the owner, and how far the version
392 has landed, as changes reads it. a refusal for a record
393 that is not ready, or for a merge in the change's
394 commits, is a state of its own.
395 after integration, show how to update the local checkout.
396 fetches objects without moving local branches or files;
397 no checks run and no request is filed.
398 --json print the status as one JSON object,
399 valley-status/v1, for front ends to read
400 (docs/architecture.md). an error prints
401 no object: it goes to stderr and the exit
402 status is non-zero.
403 needs the valley-go helper.
404 ready [--head <sha>] [--change <id>] [--if-active <sha>] [--stamp] [<branch>]
405 mark a head of the branch ready, as a new version of its
406 change, in the change's record on origin:
407 refs/the-valley/changes/main/<change id>. the branch
408 defaults to the current one. the head is --head, or else
409 origin/<branch>, and it must be on origin already. the
410 first ready of a change makes v1; each later one adds
411 the next version, at a head other than the active
412 version's. a draft or a withdrawn change comes back this
413 way: at the active version's head, it is ready again at
414 that version, and at another head it gains the next
415 version. prints the handle and version, e.g.
416 `cosmo nxvp v2 ready`.
417 the change id is --change, else the head commit's jj
418 change-id header, else a Change-Id: trailer in its
419 message, else a new one, which is printed. a header and
420 a trailer that disagree are refused. so is a change
421 whose commits from its merge base with origin/main hold
422 a merge, or that has more than one merge base.
423 --if-active SHA
424 add the version only while the change
425 is ready at an active version whose head
426 is SHA. the record ref is leased on the
427 record read, so nothing comes between
428 that check and the write. rebase readies
429 the head it rebased this way.
430 --stamp amend the head of your local branch to
431 carry the id as a Change-Id: trailer and
432 push the branch, leased, before marking it
433 ready. it only starts a new change: it
434 is refused for a change that has a
435 record on origin already, and for a head
436 already on origin.
437 the record names the principal your key pushes as, read
438 from git config valley.principal; the host refuses one
439 naming anyone else. the record ref is pushed leased on
440 the value read. a new change is owned by the principal
441 that readies it, and a later version may come from its
442 owner, the operator, or a restack holder while the
443 change is ready.
444 a record never makes anything land, and approve is
445 still the only way to main. the integrator reads
446 records only to refuse: it lands no request that would
447 bring a version of a change that is not ready.
448 needs the valley-go helper.
449 unready <change>
450 make a ready change a draft in its record on origin, as
451 its owner or the operator. a draft is a pause: it voids
452 nothing, and approvals of its active version stand when
453 it is readied again. ready brings it back. prints e.g.
454 `cosmo nxvp v2 draft`. needs the valley-go helper.
455 withdraw <change>
456 mark a ready change or a draft withdrawn in its record
457 on origin, as its owner or the operator. withdrawing
458 voids everything outstanding on the change: its
459 integration requests, and the approvals and reviews of
460 every version, so a change brought back needs fresh
461 approvals. ready brings it back, at the same version
462 or a new one. prints e.g. `cosmo nxvp v2 withdrawn`.
463 needs the valley-go helper.
464 the integrator lands no request that would bring a
465 version of a change that is not ready, so unready and
466 withdraw both stop a
467 pending integration request, under c-<change id> or a
468 branch's request name. each says so when origin holds
469 one. a draft's request stands and lands once the change
470 is ready again. withdrawing voids the request: the
471 integrator deletes it on its next pass while the change
472 is still withdrawn. withdraw warns, since a ready before
473 then leaves the request standing: only a holder of the
474 request grant may touch a request ref, so the operator
475 must drop it then.
476 knot <verb> [args]
477 read and write the project's plan graph: knots, at
478 refs/the-valley/knots on origin. a knot is an outcome,
479 a bug, an idea or a question; `knot schema` prints the
480 types, their statuses, active and terminal, the fields
481 and the edges. a write is one commit on the ref, made
482 without a checkout and pushed with a lease on the tip
483 it was made on; no review is involved. a write that
484 loses the lease is made again on the new tip, up to 5
485 tries. every verb takes --project NAME, another
486 project on the same host, and --json. exit status 3
487 is a conflict. needs the valley-go helper, and
488 git config valley.principal for every write.
489 new <type> <title> [--parent ID] [--blocked-by ID]...
490 [--owner P] [--target PROJECT] [--body -]
491 make a knot. its id is the type's prefix
492 and 7 hex digits of the sha-256 of the
493 title's slug.
494 show <id> [--json]
495 its fields, body and comments, and the
496 edges both ways
497 list [--type T] [--status S] [--owner P] [--ready]
498 every knot. --status takes a status,
499 active or terminal. --ready lists the
500 active, unclaimed knots whose blockers
501 are all terminal.
502 set <id> <field>=<value>... [--if <field>=<value>]...
503 [--force]
504 change status, title, source, owner,
505 target or graduated_into. a field that
506 another write changed meanwhile is a
507 conflict unless --force. --if requires
508 a field to hold a value first.
509 link <id> (--blocked-by ID | --parent ID | --change X)...
510 unlink <id> (--blocked-by ID | --parent ID | --change X)...
511 add or drop an edge. a change is
512 valley:<project>/<change id> or a github
513 pull request url. outcomes and bugs link
514 the changes that do the work, and a
515 question links the change that records
516 its answer in the source.
517 edit <id> --body -
518 replace the body with stdin
519 comment <id> (-m TEXT | --body -)
520 add a comment. comments are never
521 changed or deleted.
522 claim <id> --run RUN
523 claim an active outcome or bug for a
524 run; an open outcome becomes
525 in-progress. a knot claimed already is
526 a conflict.
527 unclaim <id>
528 release the claim. a claim that
529 changes before the release lands is
530 a conflict.
531 schema [--json]
532 print the model
533 plan [--project NAME | --all] [--owner P] [--json]
534 show the project's plan graph as a tree, to see where
535 things stand. the roots are the outcomes with no
536 parent, the milestones, each with its progress: its
537 descendants that are terminal and not abandoned, out
538 of those not abandoned, as a count and a bar. under
539 each come its children, indented, in the order they
540 were created, then by title. each knot has a glyph for
541 its state (○ ready, ◐ in progress, ⊘ blocked, ◇
542 active, ✓ done, ✗ abandoned), its id and title, and,
543 while active, its claim and the claim's age (marked
544 stale past a day), its owner, and what blocks it. a
545 blocker that ended abandoned, discarded, superseded or
546 dropped clears the knot, and is marked with how it
547 ended. a reference to another project's knot,
548 <project>:<id>, is marked dangling when that
549 project's graph cannot be read or holds no such knot.
550 a root whose descendants are all terminal is one
551 line. three sections follow. waiting on you: the
552 active outcomes and bugs and the open questions the
553 operator owns, then the changes ready for
554 approval, as pending lists them. in flight: the
555 claimed knots, oldest claim first. open residuals:
556 the open bugs, under their parent. the operator is
557 git config valley.principal, or --owner. lines fit
558 the terminal as pending's do; glyphs are coloured on
559 a terminal unless NO_COLOR is set.
560 --project NAME another project on the same host
561 --all every project the serving host
562 publishes, each under its name, as
563 pending --all reads them. a project
564 that cannot be read is reported in
565 its own section
566 --owner P read P as the operator
567 --json print valley-plan/v1: every knot with
568 what the graph derives of it, and the
569 three sections (docs/architecture.md)
570 needs the valley-go helper.
571 checks [<base> [<head>]]
572 print the check names the composed verification policy
573 (dcr-f41f718) requires of the change between two
574 commits, which class made each one required, and the
575 change's carry mode: how far an approval of it carries
576 across a rebase, the strictest of exact, same-class and
577 same-paths among the classes it matched. It prints: no
578 check is run, nothing is gated, nothing is written.
579 base defaults to the merge base with main, head to HEAD.
580 by default both layers come from the target's tip
581 (origin/main), never from your checkout: the project's
582 own layer is policy/project there, and the owning valley
583 is named one line at policy/valley there, fetched and
584 read at policy/instance in that repository's integrated
585 tip. a valley's own config repository carries
586 policy/instance and uses it. a target carrying no
587 policy/project is derived under the floor alone; a floor
588 that is not there is refused. this is what the
589 integrator reads, so the answer is the same from any
590 branch, however stale. an option overrides each layer,
591 which is the only way to derive against a layer that
592 does not govern — the worked example under
593 examples/policy/, say:
594 --schema FILE default $VALLEY_VERIFICATION_SCHEMA
595 --instance DIR default the owning valley's floor
596 --project DIR default policy/project at the target
597 naming a layer stops this reading the source it
598 replaced. the schema is the shape a policy is written
599 in rather than a layer, so it ships with this tool: the
600 package sets VALLEY_VERIFICATION_SCHEMA to its own copy.
601 with that unset, as when this script runs straight from
602 a the-valley checkout, it is schema/verification.cue in
603 the checkout.
604 after the report, two lines group the required checks
605 by the cost the policy declares, `quick` or `slow`. a
606 slow check takes minutes or needs special hardware. the
607 cost changes nothing required: approving runs every
608 required check whatever its cost, and the integrator
609 requires evidence for every one.
610 --names print only the required check names,
611 one per line
612 --cost COST with --names, only the quick or
613 the slow ones, e.g.
614 `valley checks --names --cost slow`
615 tail [subject] watch bus events scroll by (default subject: valley.>);
616 the server comes from the nats CLI's own config
617 (NATS_URL or a nats context; default localhost)
618 replay [dir] publish one ref-updated event per current ref of the
619 repo at dir (default: .) — rebuilds the stream's
620 projection, e.g. after nats stream purge valley
621 self-update [-v] [--retry | --rollback | --pin | --unpin]
622 [--repo <url>] [--branch <name>]
623 install the tip of a branch of the-valley into your
624 default nix profile, in place of its valley element,
625 once that exact commit builds and passes a smoke test.
626 a commit that fails is skipped until the branch moves,
627 or until --retry. it is off until --repo or
628 git config valley.selfUpdate.repo names the
629 repository; the branch is valley.selfUpdate.branch,
630 or main. --rollback reinstalls the previous build, and
631 --pin and --unpin freeze and release the install.
632 `valley help self-update` gives every step. needs the
633 valley-go helper and nix.
634 --version print this valley's version: the package's version and
635 the commit it was built from, e.g. 0.1.0-97db597, with
636 -dirty after it for a tree with uncommitted changes and
637 -unknown in its place when nix knew no commit. run
638 straight from a checkout, it says it is unstamped.
639 help [self-update]
640 show this help, or self-update's
641
642A change is named by its full change id, by its handle — the shortest
643prefix of the id, four letters at least, that no other change recorded on
644origin shares, written <repo>:<handle> too, with this repository's name —
645or by its branch. A name written origin/<branch> is always
646a branch. A handle that is also a branch on origin is refused unless the
647change is on that branch. review, approve and rebase read a branch name,
648written either way, against every record on origin: when exactly one
649record's active version is on the branch, the name is that change, as if
650its id were given, and when more than one's is, the verb refuses and lists
651their ids. A change whose active version has landed — its head is on
652main's first-parent history with no merge above it, or the integrator's
653outcome record and verified transfer statement record that exact head
654landing — is skipped, so a branch can be used again once its change has
655landed. unready, withdraw and status read a branch the same way. A
656branch no record's active version is on is acted on as a branch. A
657change with a record is reviewed, approved and rebased at the
658head its active version records, never at its branch's tip: review shows
659that head and its [a]pprove approves it, and rebase and review's
660[r]eject refuse, naming both, when the branch's tip on origin is another
661commit. approve approves the head bound to it, wherever the branch is.
662[r]eject deletes the branch under a lease on the recorded head. approve,
663rebase, and review's [a]pprove and [b]ase refuse a change whose record is
664not ready, naming its state, and review offers none of them for a change
665that is not ready when it shows it. Each reads the record again just before it
666acts, and again before approve files or rebase pushes, and refuses when
667the change is not ready. rebase also refuses when the change's
668record has changed at all since it began, and approve when the head it
669approves is not a version's. A name that read as a plain branch is
670read again before approve files or rebase pushes. If it names a change by
671then, rebase refuses, and approve files only while the change is ready at
672the head it began with. An approval already past that last check can
673still file if the change is unreadied or withdrawn in the moment before
674its push; the integrator refuses to land it, since it lands no request
675that would bring a version of a change that is not ready, whatever the
676request is named.
677The integrator reads the records last just before it moves main, so a
678change paused in that moment can still land at the head the operator
679approved, and never at any other.
680
681Runs from any checkout of the project; needs only git and coreutils,
682except tail and replay, which also need the nats CLI (natscli), checks,
683which also needs the cue CLI, review's notes, which need less, approve
684and review's [a]pprove, which need both the cue CLI and the attest
685helper, and status, ready, unready, withdraw, review, approve and rebase,
686which need the valley-go helper, as pending, changes, knot, plan and
687self-update do. nix run .#valley bundles all of them. self-update also
688needs nix. Deriving a policy fetches the owning valley's repository, so
689checks and approving also need whatever reaching it takes.
690No config but valley.principal, which ready, rebase, knot and plan read,
691and valley.selfUpdate.repo and .branch, which self-update reads; no batch
692mode; and no state but the notes file, the handle cache pending and
693changes write for completion, and self-update's record of what it
694installed — the judgment stays with the human.
695EOF
696}
697
698fetch_origin() {
699 git fetch --prune --quiet origin
700}
701
702# Resolve the pager as git would for a diff: pager.diff first (per-command
703# pager configs — e.g. home-manager's delta module — set pager.diff and leave
704# core.pager alone), then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER,
705# less). pager.<cmd> may legally be a boolean; treat true/false — and an
706# empty or missing value — as unset and fall back. The value is
707# shell-interpreted, hence sh -c.
708diff_pager() {
709 local pager
710 pager="$(git config --get pager.diff || true)"
711 case "$pager" in '' | true | false) pager="$(git var GIT_PAGER)" ;; esac
712 printf '%s' "$pager"
713}
714
715# Page a file rather than a pipe, so less's v key has something to hand
716# $EDITOR: with a real file open, v runs LESSEDIT, whose default
717# `%E ?lm+%lm. %g` is the editor, +<line>, and the file name. That file is
718# the review buffer, and editing it is how notes get written (see
719# collect_notes). A pipe has no name, so less refuses to edit one — which is
720# why review no longer pipes.
721#
722# The configured diff pager stays the renderer, but as less's input
723# preprocessor rather than as the pager. It still reads the buffer on stdin
724# exactly as it did when it was the pager, less displays what it emits, and
725# less still calls the raw buffer "the current file" — so v edits the diff
726# and not the rendering. The alternative was to page the buffer with no
727# filter at all: exact, and it throws delta's rendering away, which is the
728# worse trade for a verb whose whole job is reading a diff.
729#
730# What this costs is the line number. A filter that restructures the diff —
731# delta's default rendering does — makes %lm a line of the rendered view, so
732# the editor opens near the cursor rather than on it. A structure-preserving
733# filter (pager.diff = `delta --color-only`) makes it exact. No anchor
734# depends on it: a note is anchored by where it was inserted, not by where
735# the editor opened.
736page_file() {
737 local file="$1" pager
738 [ -t 1 ] || { cat -- "$file"; return; } # a non-tty just cats
739 pager="$(diff_pager)"
740 case "${pager%%[[:space:]]*}" in
741 less | */less)
742 # Already less: give it the file and there is no filter to run.
743 sh -c "$pager \"\$1\"" sh "$file"
744 return
745 ;;
746 esac
747 # Without less there is no editor key; fall back to filtering into a pipe.
748 command -v less > /dev/null 2>&1 || {
749 sh -c "$pager" < "$file"
750 return
751 }
752 # -R because the filter's color is the whole point of running it, and no
753 # LESSCLOSE because a stray one would run against a buffer we still read.
754 LESSOPEN="|$pager < %s" env -u LESSCLOSE less -R -- "$file"
755}
756
757# pending is valley-go's (status/pending.go). The fetch first keeps this
758# checkout's remote-tracking branches current, as pending always has. The
759# helper runs valley checks for --checks, so it is told how this script was
760# run.
761cmd_pending() {
762 command -v valley-go > /dev/null 2>&1 \
763 || die "pending needs the valley-go helper; nix run .#valley bundles it"
764 fetch_origin
765 VALLEY_COMMAND="$0" exec valley-go pending "$@"
766}
767
768# For a change with a record, what is rejected is the head its record
769# names. So the branch is deleted only while its tip is that head, and the
770# delete is leased on it. When the tip is another commit, reject refuses
771# and names both, and deletes nothing. A branch no record names is deleted
772# as before.
773#
774# reject runs inside a condition, where bash suspends `set -e`, so the push
775# is checked by hand.
776reject() {
777 local branch="$1" answer
778 local -a lease=()
779 if [ -n "$CHANGE_HEAD" ]; then
780 check_recorded_tip "$branch" "nothing deleted" || return 1
781 lease=("--force-with-lease=refs/heads/$branch:$CHANGE_HEAD")
782 fi
783 printf 'really delete origin/%s? [y/N] ' "$branch"
784 read -r answer || answer=""
785 case "$answer" in
786 y | Y | yes)
787 if ! git push --quiet "${lease[@]}" origin --delete "$branch"; then
788 refuse "origin did not delete $branch, which may have moved since the fetch; nothing deleted"
789 return 1
790 fi
791 echo "rejected $branch: deleted from origin"
792 ;;
793 *) echo "kept $branch" ;;
794 esac
795}
796
797# ----------------------------------------------------------------------
798# review notes — the lines the reviewer inserts into the paged diff.
799#
800# The buffer the reviewer pages is a file, so the pager's editor key can open
801# it (page_file). Whatever comes back with lines inserted is read as notes:
802# no marker, no syntax, no mode — an inserted line is a note because it was
803# not there before. What a note is *about* is where it sits, so each one is
804# anchored to the file and the new-side line number of the diff line above
805# it, which is the pair a reviewer would otherwise have to copy out by hand.
806
807# The scratch directory holding the buffer and its pristine copy, and the
808# notes taken so far in this review — a global because [b]ase pages a second
809# time and the notes from the first pass are not thereby withdrawn.
810REVIEW_TMP=""
811NOTES=()
812
813cleanup_review_tmp() {
814 [ -n "$REVIEW_TMP" ] || return 0
815 rm -rf "$REVIEW_TMP"
816 REVIEW_TMP=""
817}
818
819# Where a branch's notes live. XDG_STATE_HOME is the right home for them:
820# they are neither config nor cache, and losing them loses judgment.
821notes_file() {
822 printf '%s/valley/notes/%s.md\n' "${XDG_STATE_HOME:-$HOME/.local/state}" "$1"
823}
824
825# The anchor of every line of the buffer, by line: the file that line belongs
826# to, and the new-side line number it sits on. Built in one pass so that
827# anchoring a note is a lookup. An empty path means the line is above every
828# file (the log); line 0 means the line is a file header, above every hunk.
829ANCHOR_PATH=()
830ANCHOR_LINE=()
831
832anchor_buffer() {
833 local file="$1" line path="" at=0 next=0 inhunk=0 rest
834 ANCHOR_PATH=()
835 ANCHOR_LINE=()
836 while IFS= read -r line; do
837 # Header lines are only headers outside a hunk: inside one, every line
838 # carries a +/-/space prefix, so a diff of a diff cannot be misread.
839 if [ "$inhunk" -eq 1 ]; then
840 case "$line" in
841 ' '* | '+'* | '')
842 at="$next" # this line's own new-side number
843 next=$((next + 1))
844 ;;
845 '-'* | \\*) ;; # a removal or the no-newline marker: no new-side line
846 *) inhunk=0 ;;
847 esac
848 fi
849 if [ "$inhunk" -eq 0 ]; then
850 case "$line" in
851 'diff --git '*)
852 path=""
853 # The b/ side, so a rename anchors to the name it will have.
854 if [[ "$line" =~ ^diff\ --git\ a/(.*)\ b/(.*)$ ]]; then
855 path="${BASH_REMATCH[2]}"
856 fi
857 at=0
858 ;;
859 '@@ '*)
860 rest="${line#*+}" # -12,7 +34,9 @@ -> 34,9 @@
861 at="${rest%%[!0-9]*}"
862 [ -n "$at" ] || at=0
863 next="$at"
864 inhunk=1
865 ;;
866 esac
867 fi
868 ANCHOR_PATH+=("$path")
869 ANCHOR_LINE+=("$at")
870 done < "$file"
871}
872
873# The anchor for a note inserted after buffer line n, as it is written down.
874anchor_of() {
875 local n="$1" path line
876 [ "$n" -ge 1 ] || { printf '(unanchored)'; return; }
877 path="${ANCHOR_PATH[n - 1]:-}"
878 line="${ANCHOR_LINE[n - 1]:-0}"
879 if [ -z "$path" ]; then
880 printf '(unanchored)'
881 elif [ "$line" -eq 0 ]; then
882 printf '%s' "$path"
883 else
884 printf '%s:%s' "$path" "$line"
885 fi
886}
887
888# The notes in an edited buffer, one `anchor: text` line each. git says where
889# the reviewer's lines landed; a hunk that removes nothing is an insertion,
890# and the line it was inserted after is the anchor. A hunk that removes
891# something is an edit of the diff itself — it anchors to nothing, since the
892# line it would name is the line it changed — so it is dropped with a count.
893notes_in() {
894 local orig="$1" edited="$2" line rest at old insert=0 touched=0 text
895 anchor_buffer "$orig"
896 while IFS= read -r line; do
897 case "$line" in
898 '@@ '*)
899 rest="${line#@@ -}" # 12,0 +13,2 @@ -> 12,0 +13,2 @@
900 at="${rest%%[!0-9]*}"
901 rest="${rest#"$at"}"
902 old=1
903 case "$rest" in
904 ,*)
905 rest="${rest#,}"
906 old="${rest%%[!0-9]*}"
907 ;;
908 esac
909 if [ "$old" -eq 0 ]; then
910 insert=1
911 else
912 insert=0
913 touched=$((touched + old))
914 fi
915 ;;
916 '+'*)
917 # Only inside an insertion hunk: the +++ of git's own header is not
918 # a note, and neither is the new side of an edit.
919 [ "$insert" -eq 1 ] || continue
920 text="${line#+}"
921 text="${text#"${text%%[![:space:]]*}"}"
922 [ -n "$text" ] || continue # a blank line says nothing
923 printf '%s: %s\n' "$(anchor_of "$at")" "$text"
924 ;;
925 esac
926 done < <(git --no-pager diff --no-ext-diff --no-index -U0 -- "$orig" "$edited")
927 [ "$touched" -eq 0 ] || printf \
928 'valley: warning: %d changed or deleted diff line(s) ignored — a note is a line you insert\n' \
929 "$touched" >&2
930}
931
932# Read the notes out of the paged buffer and keep them: appended to the
933# branch's notes file under the commit they were taken against, and held for
934# the print that follows the verdict. A notes file that cannot be written is
935# a warning, never a failure — the notes are still printed, and a review is
936# not undone by a missing directory.
937collect_notes() {
938 local branch="$1" sha="$2" file dir
939 local -a found=()
940 mapfile -t found < <(notes_in "$REVIEW_TMP/review.orig" "$REVIEW_TMP/review.diff")
941 [ "${#found[@]}" -gt 0 ] || return 0
942 NOTES+=("${found[@]}")
943 file="$(notes_file "$branch")"
944 dir="${file%/*}"
945 mkdir -p "$dir" 2> /dev/null && {
946 printf '## %s at %s\n\n' "$branch" "$sha"
947 printf '%s\n' "${found[@]}"
948 printf '\n'
949 } >> "$file" 2> /dev/null && return 0
950 printf 'valley: warning: could not write %s — the notes are printed only\n' \
951 "$file" >&2
952}
953
954print_notes() {
955 local branch="$1"
956 [ "${#NOTES[@]}" -gt 0 ] || return 0
957 printf '\n%d note(s) on %s, appended to %s:\n' \
958 "${#NOTES[@]}" "$branch" "$(notes_file "$branch")"
959 printf ' %s\n' "${NOTES[@]}"
960}
961
962# ----------------------------------------------------------------------
963# review sets the version it shows of a change against the change's
964# approved version: the greatest version below it whose head a request or
965# an outcome on origin names (valley-go compare, status/compare.go). The
966# logic is valley-go's, and this script prints what it says:
967#
968# - none: there is no approved version to compare with, so review pages
969# the whole diff, as for any change. Any note valley-go gives, such as
970# an approved version it could not compare, heads the page.
971# - clean: the file delta is the approved version's. review prints that
972# in a few lines, with the landings between the two bases, and pages
973# nothing.
974# - changed: review pages the files whose change differs, the
975# range-diff between the two versions, and the shown version's diff
976# of those files. range-diff's hunks carry no line numbers, so a note
977# taken beside them is unanchored. That last diff is in git's ordinary
978# form, so a note taken there keeps its file and line (anchor_buffer).
979#
980# A changed commit message or author is in valley-go's text either way.
981# [v]iew full diff pages the whole diff at every prompt. The comparison
982# files no request and skips no check: [a]pprove is the same act whatever
983# it says.
984#
985# compare_shown <change ID> <version> <head>: compare the version shown,
986# against main's tip as the fetch left it. Leaves none, clean or changed
987# in COMPARE_KIND, and the text to show in $REVIEW_TMP/compare. A plain
988# branch is none, and so is a comparison valley-go could not make, with a
989# warning.
990COMPARE_KIND=none
991compare_shown() {
992 local out="$REVIEW_TMP/compare.out" tip
993 COMPARE_KIND=none
994 : > "$REVIEW_TMP/compare"
995 [ -n "$1" ] || return 0
996 if ! tip="$(git rev-parse --verify --quiet refs/remotes/origin/main)" \
997 || ! valley-go compare --tip "$tip" "$1" "$2" "$3" > "$out"; then
998 printf 'valley: warning: could not compare v%s of change %s with its approved version; reviewing it in full\n' \
999 "$2" "$1" >&2
1000 return 0
1001 fi
1002 IFS= read -r COMPARE_KIND < "$out" || COMPARE_KIND=""
1003 case "$COMPARE_KIND" in
1004 none | clean | changed) tail -n +2 "$out" > "$REVIEW_TMP/compare" ;;
1005 *)
1006 printf 'valley: warning: valley-go compare answered %s, which this script does not read; reviewing it in full\n' \
1007 "$COMPARE_KIND" >&2
1008 COMPARE_KIND=none
1009 ;;
1010 esac
1011}
1012
1013# show_compared <notes key> <head> <heading> <writer> [<arg>…]: show what
1014# compare_shown found, under the heading when there is one. A clean
1015# restack is printed, and nothing is paged. A changed version pages the
1016# comparison. Otherwise the writer writes the whole diff, and it is paged.
1017# Notes taken in a page are kept under the notes key, against the head.
1018show_compared() {
1019 local key="$1" sha heading="$3"
1020 sha="$(git rev-parse --short "$2")"
1021 shift 3
1022 {
1023 [ -z "$heading" ] || printf '%s\n' "$heading"
1024 cat "$REVIEW_TMP/compare"
1025 [ "$COMPARE_KIND" != none ] || "$@"
1026 } > "$REVIEW_TMP/review.diff"
1027 if [ "$COMPARE_KIND" = clean ]; then
1028 cat "$REVIEW_TMP/review.diff"
1029 cleanup_review_tmp
1030 else
1031 page_buffer "$key" "$sha"
1032 fi
1033}
1034
1035# full_diff <branch> <head>: the whole diff of a change alone: its log
1036# and its diff against origin/main.
1037full_diff() {
1038 local sha
1039 sha="$(git rev-parse --short "$2")"
1040 if [ -n "$CHANGE_HEAD" ]; then
1041 printf 'change %s v%s at %s, on branch %s, log against origin/main:\n\n' \
1042 "$CHANGE_HANDLE" "$CHANGE_VERSION" "$sha" "$1"
1043 else
1044 printf 'branch %s, log against origin/main:\n\n' "$1"
1045 fi
1046 git --no-pager log --oneline "origin/main..$2"
1047 printf '\n'
1048 git --no-pager diff "origin/main...$2"
1049}
1050
1051# show_review <branch>: show a change alone. A change that is not ready
1052# says so first, before anything else shown of it (shown_not_ready).
1053show_review() {
1054 local branch="$1" head held
1055 head="$(change_head "$branch")"
1056 # [a]pprove approves exactly the head shown here (bind_review).
1057 [ -n "$CHANGE_ID" ] || APPROVE_HEAD="$head"
1058 held="$(shown_not_ready)" || held=""
1059 REVIEW_TMP="$(mktemp -d)"
1060 compare_shown "$CHANGE_ID" "$CHANGE_VERSION" "$head"
1061 show_compared "$branch" "$head" "$held" full_diff "$branch" "$head"
1062}
1063
1064# view_full <branch>: [v]iew full diff for a change alone. It pages the
1065# change's whole diff, and keeps the notes taken in it.
1066view_full() {
1067 local head
1068 head="$(change_head "$1")"
1069 REVIEW_TMP="$(mktemp -d)"
1070 full_diff "$1" "$head" > "$REVIEW_TMP/review.diff"
1071 page_buffer "$1" "$(git rev-parse --short "$head")"
1072}
1073
1074# page_buffer <branch> <sha>: page the buffer written to REVIEW_TMP, and
1075# keep the notes taken in it under the branch, against the commit shown.
1076page_buffer() {
1077 cp "$REVIEW_TMP/review.diff" "$REVIEW_TMP/review.orig"
1078 page_file "$REVIEW_TMP/review.diff" || true # quitting the pager early is not an error
1079 collect_notes "$1" "$2"
1080 cleanup_review_tmp
1081}
1082
1083# Everything review and approve leave outside the repository: approve's
1084# throwaway worktree, the paged buffer, the two policy layers read out of
1085# their tips, and the scratch the policy deriver writes into. One handler,
1086# installed once by each of those verbs, so that no path through them —
1087# and no ctrl-C in the pager — leaves any of them behind. The rebase's
1088# worktree is valley-go's, which removes it itself.
1089cleanup_scratch() {
1090 cleanup_approve_wt
1091 cleanup_policy_tmp
1092 cleanup_instance_tmp
1093 cleanup_project_tmp
1094 cleanup_review_tmp
1095}
1096
1097# [b]ase and the rebase verb are one piece of code, valley-go rebase
1098# (status/rebase.go). It rebases the change's whole stack in a throwaway
1099# worktree of its own — the user's checkout is never touched — pushes
1100# every layer's branch in one atomic push, leased on the tips it read, and
1101# adds each change's rebased head to its record as a new version. A
1102# change alone prints what rebase always has; a stack prints a manifest
1103# of what became of each layer. The judgment on the rebased diff stays
1104# with the human, back at the review prompt or in whatever front end ran
1105# the rebase verb.
1106#
1107# rebase_shown <head>: [b]ase for the change under review, while it is
1108# still at <head>, the head review showed of it.
1109rebase_shown() {
1110 valley-go rebase --head "$1" "${CHANGE_ID:-$CHANGE_NAME}"
1111}
1112
1113# ----------------------------------------------------------------------
1114# approve — file an integration request for the branch under review.
1115#
1116# This is the one way a change reaches main from here: the checks the
1117# policy requires are run over the branch's tree and signed, the evidence
1118# and one request ref are published, and the integrator judges the request
1119# and lands it (archive/design/integration.md). main is never touched from here.
1120#
1121# Nothing in this script writes the protected ref. Whether a given pusher
1122# may write it is a fact about origin's pre-receive hook, so origin is
1123# where it is answered, and a verb that merged onto main locally would only
1124# be asking the same question in a worse place.
1125#
1126# What this verb removes is a second push. `attest run --push` publishes
1127# the branch and the attestation refs in one atomic push and knows nothing
1128# about a request ref, so filing a request by hand is two beats: the
1129# evidence, then the request after it. In between, evidence stands
1130# published for a change nobody has approved. So this verb does not
1131# use --push at all. `attest run` without it stores each note at its ref in
1132# the repository and stops, and one `git push --atomic` then carries the
1133# evidence and the request together — all of it or none of it. Nothing in
1134# attest had to change for that; the sequencing was the whole of it.
1135#
1136# The branch itself is not in that push. What is under review is
1137# origin/<branch>, so the commit the request names is already on origin and
1138# the objects with it.
1139
1140# The tree the checks run over: a throwaway worktree of the branch, as
1141# [b]ase uses, so that what is checked is the branch's tree and not the
1142# operator's working copy. A global, so the traps clean it up whatever
1143# happens.
1144APPROVE_WT=""
1145# The head approve last ran the checks over and saw them fail, for the
1146# review prompt: see approve_failed_at.
1147CHECKS_FAILED_AT=""
1148cleanup_approve_wt() {
1149 [ -n "$APPROVE_WT" ] || return 0
1150 git worktree remove --force "$APPROVE_WT" > /dev/null 2>&1 || true
1151 rm -rf "$APPROVE_WT"
1152 APPROVE_WT=""
1153}
1154
1155# Report and fail, without leaving the review. A refusal here is not a
1156# reason to end the session: the branch is still under review and the
1157# operator can still answer. die() is for the verbs that have nothing left
1158# to offer. The approve verb has nothing left to offer either, and turns a
1159# refusal into its exit status itself.
1160refuse() {
1161 printf 'valley: %s\n' "$*" >&2
1162 return 1
1163}
1164
1165# The change segment of a request ref. The integrator reads a request as
1166# <prefix>/<target>/<change> and refuses a change segment holding a slash
1167# (integrator/refs.go), so a branch name with one is written with dashes
1168# instead. The ref that results is printed, never left to be assumed.
1169#
1170# The mapping is lossy: `topic/x` and `topic-x` are one change name and so
1171# one request ref, and this verb cannot tell a sibling's request from its
1172# own. That is bd-57f7f9f, and what is done about it here is to print the
1173# subject of any request being replaced, so a collision is visible at the
1174# moment it happens rather than after it.
1175change_name() {
1176 printf '%s' "${1//\//-}"
1177}
1178
1179# One line of a commit, for saying which commit is meant. A request being
1180# replaced is usually this operator's own pre-rebase head and so is in
1181# this repository; one another operator filed may not be, and saying so is
1182# better than printing an id alone.
1183subject_of() {
1184 local s
1185 if s="$(git log -1 --format=%s "$1" 2>/dev/null)" && [ -n "$s" ]; then
1186 printf '%s' "$s"
1187 else
1188 printf 'subject not in this repository'
1189 fi
1190}
1191
1192# The value of a ref on origin, as one id or the empty string. Failing to
1193# read it is not the same as reading that it is absent, so the two are
1194# separate answers: this returns 1 for a read that did not happen.
1195remote_ref() {
1196 local out
1197 out="$(git ls-remote origin "$1" 2>/dev/null)" || return 1
1198 printf '%s' "$out" | cut -f1
1199 return 0
1200}
1201
1202# Where the checks this run signed are stored, for every failure that
1203# happens after they have run. One stanza, so no failure path invents its
1204# own wording. Called with no refs it says nothing.
1205report_local_evidence() {
1206 [ "$#" -gt 0 ] || return 0
1207 printf 'valley: the evidence is stored locally at:\n' >&2
1208 printf ' %s\n' "$@" >&2
1209}
1210
1211# Whether origin already holds one of these attestation refs at a value
1212# other than the one being pushed. The namespace admits creations only, so
1213# that is the one refusal approving again will never clear: it is what a
1214# re-observation of a tree this signer has already attested runs into
1215# (bd-7b7d58f).
1216attestation_stands_elsewhere() {
1217 local digest="$1" remote spec have want
1218 shift
1219 remote="$(git ls-remote origin "refs/the-valley/attestations/$digest/*" 2>/dev/null)" || return 1
1220 for spec in "$@"; do
1221 have="$(printf '%s\n' "$remote" | awk -v r="$spec" '$2 == r { print $1 }')"
1222 [ -n "$have" ] || continue
1223 want="$(git rev-parse "$spec" 2>/dev/null)" || continue
1224 [ "$have" = "$want" ] || return 0
1225 done
1226 return 1
1227}
1228
1229# Why a push carrying the request ref failed, said as precisely as the
1230# state allows. Every such push is leased, and a lease refuses when the
1231# ref it named is not where the read before it saw it — which covers three
1232# different events. Reading the ref again is what tells them apart, and a
1233# read that does not happen is its own answer rather than a guess.
1234#
1235# Anything the lease is not responsible for is origin's own refusal, and
1236# git has already printed it.
1237diagnose_request_push() {
1238 local ref="$1" pending="$2" now
1239 if ! now="$(remote_ref "$ref")"; then
1240 refuse "origin refused the push, and $ref could not be read again to say why. Nothing was published there and main is untouched"
1241 return 0
1242 fi
1243 if [ "$now" = "$pending" ]; then
1244 refuse "origin refused the push; nothing was published there and main is untouched"
1245 elif [ -z "$now" ]; then
1246 refuse "the pending request was consumed while this one was being prepared, which is what the integrator does when a change lands. The lease on $ref refused and nothing was published; fetch and review the branch again before approving it a second time"
1247 elif [ -z "$pending" ]; then
1248 refuse "a request for this change appeared while this one was being prepared, at $(git rev-parse --short "$now") ($(subject_of "$now")); the lease on $ref refused and nothing was published"
1249 else
1250 refuse "the pending request moved from $(git rev-parse --short "$pending") to $(git rev-parse --short "$now") while this one was being prepared; the lease on $ref refused, nothing was published, and the request stands where the other approval put it"
1251 fi
1252}
1253
1254# File the request. Called in a condition, from the review prompt and from
1255# the approve verb alike, which suspends `set -e` for the whole call — so
1256# every step below is checked by hand, and the failures say what was
1257# published before they happened.
1258approve() {
1259 local branch="$1" target=main tip change head base digest root ref check spec what
1260 local key
1261 local -a signer=() required=() run=() evidence=()
1262
1263 root="$(git rev-parse --show-toplevel)" || {
1264 refuse "not a git repository; nothing published"
1265 return 1
1266 }
1267 tip=refs/remotes/origin/main
1268 # A change with a record is filed at exactly the head bound to this
1269 # approval, under its own request name, c-<change ID>, and only while its
1270 # record says it is ready and lists that head as a version's. Where its
1271 # branch is does not matter: the request names the head.
1272 if [ -n "$CHANGE_ID" ]; then
1273 head="$APPROVE_HEAD"
1274 [ -n "$head" ] || {
1275 refuse "no head of change $CHANGE_HANDLE is bound to this approval; nothing published"
1276 return 1
1277 }
1278 check_record "nothing published" "" "$head" || return 1
1279 change="c-$CHANGE_ID"
1280 what="$CHANGE_HANDLE v$APPROVE_VERSION"
1281 elif [ -n "$APPROVE_HEAD" ]; then
1282 # A plain branch that review showed is filed at the head shown. The
1283 # last check before the push refuses if the branch on origin has moved
1284 # off it since.
1285 head="$APPROVE_HEAD"
1286 change="$(change_name "$branch")"
1287 what="$branch"
1288 else
1289 head="$(git rev-parse "refs/remotes/origin/$branch")" || {
1290 refuse "no such branch on origin: $branch; nothing published"
1291 return 1
1292 }
1293 change="$(change_name "$branch")"
1294 what="$branch"
1295 fi
1296 # c-<change ID> is the request name of the change with that ID, so a
1297 # branch is never filed under one.
1298 if [ -z "$CHANGE_ID" ] && [[ "$change" =~ ^c-[k-z]{32}$ ]]; then
1299 refuse "the branch $branch would be requested as $change, and that name is reserved for the change with the ID ${change#c-}; rename the branch, or name the change by its ID. Nothing published"
1300 return 1
1301 fi
1302 base="$(git merge-base "$tip" "$head")" || {
1303 refuse "$what and main share no history; nothing published"
1304 return 1
1305 }
1306 ref="refs/the-valley/integration-requests/$target/$change"
1307 local named="$branch" under of
1308 [ -z "$CHANGE_ID" ] || named="$CHANGE_HANDLE"
1309
1310 # A head that does not fast-forward from main, and would bring a version
1311 # of another change that has not landed, is a layer above the bottom of
1312 # a stale stack. The integrator could land it all the same, as one
1313 # commit recorded against this request alone, and the changes under it
1314 # would have no landing record of their own. So it is refused before
1315 # any check runs over a head that has to be rebased anyway, and the
1316 # stack is rebased first. This is the project's choice, not a rule the
1317 # integrator needs. A stale head with no change under it, such as the
1318 # bottom layer of a stack or a change alone, is approved as it is, and
1319 # the integrator merges it onto main.
1320 if ! git merge-base --is-ancestor "$tip" "$head"; then
1321 if ! under="$(valley-go brings ${CHANGE_ID:+--change "$CHANGE_ID"} "$head")"; then
1322 refuse "could not read which changes $what would bring to main; nothing published"
1323 return 1
1324 fi
1325 if [ -n "$under" ]; then
1326 of="a version of $under"
1327 [ "$(printf '%s\n' "$under" | wc -l)" -eq 1 ] || of="versions of $(printf '%s\n' "$under" | join_lines)"
1328 refuse "$what does not fast-forward from main, and the commits it would bring hold $of, not landed. Approved as it is, it would land them with no landing record of their own; nothing published. Rebase the stack first: valley rebase $(printf '%q' "$named")"
1329 return 1
1330 fi
1331 fi
1332
1333 # What the policy requires of the change, read out of exactly the
1334 # sources the integrator reads: both layers from the target's tip, which
1335 # review has just fetched, and the floor from the owning valley's own
1336 # tip. A change never supplies the policy that gates it, and neither does
1337 # the checkout this runs from — so the answer here is the same answer the
1338 # integrator will derive, from whatever branch the operator happens to be
1339 # on. It is printed for exactly that reason.
1340 policy_defaults "$root"
1341 resolve_instance_layer "$root" "$tip" || return 1
1342 resolve_project_layer "$root" "$tip" || return 1
1343 derive_required "$POLICY_SCHEMA" "$POLICY_INSTANCE" "$POLICY_PROJECT" \
1344 "$base" "$head" || return 1
1345 sort_into required "${!DERIVED_REQUIRED[@]}" || {
1346 refuse "could not sort the required checks; nothing published"
1347 return 1
1348 }
1349
1350 # A change the policy asks nothing of is still a change, and approving
1351 # is how one reaches main. The integrator already lands a request that
1352 # requires no check and records the landing as one that required nothing
1353 # (archive/design/integration.md), so refusing to file it here would strand
1354 # exactly the changes the policy requires nothing of. Nothing is required,
1355 # so nothing is signed and no key is needed: what gets published is one
1356 # request ref and no evidence at all.
1357 if [ "${#required[@]}" -gt 0 ]; then
1358 key="${VALLEY_ATTEST_KEY:-}"
1359 [ -n "$key" ] || {
1360 refuse "no signing key: set VALLEY_ATTEST_KEY to the ed25519 key this host attests with. The host signs; nothing published"
1361 return 1
1362 }
1363 [ -f "$key" ] || {
1364 refuse "no signing key at $key; nothing published"
1365 return 1
1366 }
1367 command -v attest > /dev/null 2>&1 || {
1368 refuse "this choice needs the attest helper; nix run .#valley bundles it. Nothing published"
1369 return 1
1370 }
1371 signer=(--key "$key")
1372 [ -z "${VALLEY_ATTEST_NAME:-}" ] || signer+=(--name "$VALLEY_ATTEST_NAME")
1373
1374 for check in "${required[@]}"; do
1375 case "${CHECK_RUNNER[$check]:-}" in
1376 nix) run+=(--check "$check=${CHECK_ATTRIBUTE[$check]}") ;;
1377 command) run+=(--command "$check=${CHECK_COMMAND[$check]}") ;;
1378 *)
1379 refuse "the policy requires $check but does not say how to run it; nothing published"
1380 return 1
1381 ;;
1382 esac
1383 done
1384
1385 cleanup_approve_wt
1386 APPROVE_WT="$(mktemp -d)" || {
1387 refuse "no scratch directory to check $what in; nothing published"
1388 return 1
1389 }
1390 git worktree add --quiet --detach "$APPROVE_WT" "$head" || {
1391 cleanup_approve_wt
1392 refuse "could not check $what out to run its checks; nothing published"
1393 return 1
1394 }
1395
1396 printf '\nchecking %s at %s: %s\n' "$what" "$(git rev-parse --short "$head")" \
1397 "$(printf '%s\n' "${required[@]}" | join_lines)"
1398 if ! attest run --repo "$APPROVE_WT" "${signer[@]}" "${run[@]}"; then
1399 cleanup_approve_wt
1400 CHECKS_FAILED_AT="$head"
1401 refuse "the checks did not pass; nothing published, main untouched"
1402 return 1
1403 fi
1404 digest="$(attest digest --repo "$APPROVE_WT")" || {
1405 cleanup_approve_wt
1406 refuse "could not digest the tree that was checked; nothing published"
1407 return 1
1408 }
1409 cleanup_approve_wt
1410 digest="${digest#*:}"
1411
1412 # Every attestation stored for this tree, whoever signed it: the
1413 # evidence for this change is what the subject digest is keyed by, not
1414 # what this run happened to add to it.
1415 mapfile -t evidence < <(git for-each-ref --format='%(refname)' \
1416 "refs/the-valley/attestations/$digest")
1417 [ "${#evidence[@]}" -gt 0 ] || {
1418 refuse "no attestation is stored for $digest; nothing published"
1419 return 1
1420 }
1421 else
1422 printf '\n%s requires no check under %s + %s; filing the request with no evidence\n' \
1423 "$what" "$POLICY_INSTANCE_LABEL" "$POLICY_PROJECT_LABEL"
1424 fi
1425
1426 # What origin already holds for this request, read once and remembered.
1427 # Approving the same change twice is ordinary: evidence expires, and a
1428 # change whose input closure moved under it is told to re-attest. So the
1429 # request ref may already exist, and what to do about it depends on
1430 # where it points. A read that does not happen is not a read that found
1431 # nothing, so it ends the verb here.
1432 local pending
1433 if ! pending="$(remote_ref "$ref")"; then
1434 refuse "could not read $ref from origin; nothing published"
1435 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1436 return 1
1437 fi
1438
1439 # The one push: every evidence ref as it stands, and the request ref
1440 # wherever it has to go. --atomic, so a hook that refuses any of them
1441 # leaves origin exactly as it was.
1442 #
1443 # Every write of the request ref is leased against exactly what the read
1444 # above saw, including when it saw nothing: git spells that expectation
1445 # `--force-with-lease=<ref>:` with an empty value, and it refuses if the
1446 # ref exists at all. So filing a change for the first time is a
1447 # compare-and-swap too. Without it, two operators filing one change at
1448 # once would have the second silently fast-forward the first away.
1449 #
1450 # A pending request at this same head is a re-attestation of the tree
1451 # already approved. The evidence is new and the ref does not move, so
1452 # the ref is left out of the refspec entirely — a push cannot carry a
1453 # compare-and-swap on a ref it is not changing, because git leaves an
1454 # up-to-date ref out of what it sends. Nothing this run does establishes
1455 # where that ref stands afterwards, so it is read again below.
1456 #
1457 # A pending request at a different head is a replacement. This is the
1458 # shape a change takes when main moved through its checks' input
1459 # closures: no attestation over the old tree can transfer again, so the
1460 # cure is a new head rebased onto the moved main — and that head is not
1461 # a descendant of the old one, which makes replacing the ref a
1462 # non-fast-forward update that git refuses unless told.
1463 #
1464 # The lease is the whole of the force, and the refspec carries no `+`.
1465 # A leading `+` sets git's per-ref force flag, and that flag defeats
1466 # every rejection the push rules produce — the lease's stale-info among
1467 # them. The two together are a plain force wearing a lease's name.
1468 local -a push=() lease=()
1469 for spec in ${evidence[@]+"${evidence[@]}"}; do push+=("$spec:$spec"); done
1470 if [ "$pending" != "$head" ]; then
1471 lease+=("--force-with-lease=$ref:$pending")
1472 push+=("$head:$ref")
1473 fi
1474
1475 # The checks can take minutes, and the record may have moved meanwhile.
1476 # So it is read once more, just before anything is filed, and a name that
1477 # read as a plain branch is read again in case it names a change now.
1478 #
1479 # This is the last check, and a window remains between it and the push
1480 # below. A change unreadied or withdrawn in that window is filed all the
1481 # same. git compares only the refs a push changes, and the record ref is
1482 # not one of them, so no client can make the filing conditional on the
1483 # record. The integrator narrows the window: it lands no request that
1484 # would bring a version of a change that is not ready, whatever the
1485 # request is named, so a request filed in the window stays until the
1486 # change is ready again. It reads the records last just before it moves
1487 # the target, so only a record written in that moment is missed.
1488 if ! check_record "nothing published" "$head" "$APPROVE_HEAD"; then
1489 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1490 return 1
1491 fi
1492 # A plain branch is filed at the head review showed only while the
1493 # branch on origin is still there. The operator reviewed a branch, and a
1494 # branch that moved holds commits nobody has read. A change with a
1495 # record is filed at its head wherever its branch is.
1496 if [ -z "$CHANGE_ID" ] && [ -n "$APPROVE_HEAD" ] && ! branch_at_shown "$branch"; then
1497 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1498 return 1
1499 fi
1500
1501 # Nothing required and the request already standing at this head leaves
1502 # nothing to push at all, and a push assembled with an empty refspec
1503 # would fall back to origin's default one. So none is made.
1504 local made_push=no
1505 if [ "${#push[@]}" -gt 0 ]; then
1506 made_push=yes
1507 if ! git push --atomic --quiet ${lease[@]+"${lease[@]}"} origin "${push[@]}"; then
1508 if [ "${#lease[@]}" -eq 0 ] \
1509 && attestation_stands_elsewhere "$digest" ${evidence[@]+"${evidence[@]}"}; then
1510 refuse "origin already holds an attestation for this tree from this signer, and that namespace admits creations only, so a second observation of the same tree has nowhere to go. That is bd-7b7d58f rather than anything approving again will clear. Nothing was published and main is untouched"
1511 else
1512 diagnose_request_push "$ref" "$pending"
1513 fi
1514 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1515 return 1
1516 fi
1517 fi
1518
1519 # The lines under the request line, which differ by what was found and
1520 # what was done about it.
1521 local -a standing=()
1522
1523 if [ "$pending" = "$head" ]; then
1524 # The request ref was not in that push, so where it stands now is not
1525 # something this run established. Read it again rather than repeat
1526 # what was read before it: in between, the integrator may have landed
1527 # the change and consumed the ref, or another approval may have
1528 # replaced it.
1529 #
1530 # Nothing here writes it back. Re-creating a consumed request would
1531 # file a change already in the stream, which the commit rule calls out
1532 # as the state it consumes the ref to avoid; replacing a request
1533 # another approval has just filed would clobber the winner; and
1534 # either would be a second push behind the one this verb promises. So
1535 # what this does is say what is true and stop. Approving again is the
1536 # repair, and by then it takes the create or the replace path against
1537 # what is actually there.
1538 local after
1539 if ! after="$(remote_ref "$ref")"; then
1540 refuse "$ref could not be read again, so whether the request still stands at this head is not known here"
1541 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1542 return 1
1543 fi
1544 if [ -z "$after" ]; then
1545 refuse "the request was consumed while this run was working, which is what the integrator does when a change lands. Nothing here re-filed it: a request for a change already in the stream is judged against an empty delta on every pass. Fetch and review $what again, and approve it once more if it has not landed"
1546 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1547 return 1
1548 fi
1549 if [ "$after" != "$head" ]; then
1550 refuse "the request moved to $(git rev-parse --short "$after") ($(subject_of "$after")) while this run was working, so another approval filed it. Nothing here replaced it; approve again to replace it deliberately"
1551 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1552 return 1
1553 fi
1554 if [ "$made_push" = yes ]; then
1555 standing+=("the request already stood at this head; the evidence is what was published")
1556 else
1557 standing+=("the request already stood at this head and nothing was required, so nothing needed publishing")
1558 fi
1559 elif [ -n "$pending" ]; then
1560 standing+=("replaced the pending request, which stood at $(git rev-parse --short "$pending") ($(subject_of "$pending"))")
1561 fi
1562
1563 printf '\nApproved %s (%s): its integration request for origin/%s is filed.\n' \
1564 "$what" "$(git rev-parse --short "$head")" "$target"
1565 printf 'The integrator will decide whether this change can land.\n'
1566 printf 'Your local checkout has not changed.\n\n'
1567 printf 'Check the result: valley status %q\n\n' "$named"
1568 printf ' request %s -> %s\n' "$ref" "$(git rev-parse --short "$head")"
1569 [ "${#standing[@]}" -eq 0 ] || printf ' %s\n' "${standing[@]}"
1570 if [ "${#evidence[@]}" -eq 0 ]; then
1571 printf ' evidence none — nothing was required, so nothing was signed\n'
1572 printf ' checks none — the policy requires no check of this change\n'
1573 else
1574 printf ' evidence %s\n' "${evidence[@]}"
1575 printf ' checks %s\n' "$(printf '%s\n' "${required[@]}" | join_lines)"
1576 fi
1577}
1578
1579# status, ready, unready and withdraw are a Go program, valley-go
1580# (status/). status reads a change's request and outcome from origin,
1581# because what front ends read from it is a JSON contract, and because the
1582# read is subtle enough to want a real parser: an outcome record it does
1583# not recognise must read as unknown, never as success. It writes nothing
1584# and moves no local branch. ready, unready and withdraw write a change's
1585# record, in the one format the push hook reads it in (change/). knot
1586# reads and writes the plan graph at refs/the-valley/knots, in the one
1587# form the push hook validates (knot/), and plan shows that graph as a
1588# view.
1589cmd_go() {
1590 command -v valley-go > /dev/null 2>&1 \
1591 || die "$1 needs the valley-go helper; nix run .#valley bundles it"
1592 exec valley-go "$@"
1593}
1594
1595# A change is named by its full change ID, its handle, or its branch.
1596# resolve_change reads the name with the helper and sets CHANGE_BRANCH, the
1597# branch to act on. When the name is a change's, it also sets the change's
1598# ID, handle, active version, state and owner, and CHANGE_HEAD, the head
1599# that version records. A branch name is a change's when exactly one record's
1600# active version is on that branch, and is refused when more than one's is.
1601# So whether a change's record is read never depends on how it is named,
1602# and review, approve and rebase cannot run without the helper.
1603#
1604# A change with a record is acted on at a head its record names, and never
1605# at the branch's tip: review at CHANGE_HEAD, and approve at the head bound
1606# to it (bind_head). rebase reads the record itself (status/rebase.go).
1607# The branch a record names is only where its head is expected to be, and
1608# anyone who can push the branch can move it, in the same push as the
1609# record if they like.
1610CHANGE_NAME="" CHANGE_ID="" CHANGE_HANDLE="" CHANGE_VERSION="" CHANGE_HEAD="" CHANGE_BRANCH="" CHANGE_STATE=""
1611CHANGE_OWNER=""
1612
1613# read_resolved <line> <name…>: read a line of valley-go resolve into the
1614# variables named, one field each. A version's branch may be empty, and
1615# read runs consecutive tabs together, since a tab is whitespace to it: an
1616# empty branch would shift the state into the branch. So each tab is made
1617# a unit separator first, which read keeps apart.
1618read_resolved() {
1619 local resolved="$1"
1620 shift
1621 IFS=$'\x1f' read -r "$@" <<< "${resolved//$'\t'/$'\x1f'}"
1622}
1623
1624# ready_hint <change ID> <branch>: the valley ready line that readies the
1625# change again, naming the branch unless its version records none.
1626ready_hint() {
1627 printf 'valley ready --change %s' "$1"
1628 [ -z "$2" ] || printf ' %q' "$2"
1629}
1630
1631resolve_change() {
1632 local line kind
1633 CHANGE_NAME="$1"
1634 command -v valley-go > /dev/null 2>&1 \
1635 || die "review, approve and rebase read the change's record with the valley-go helper; nix run .#valley bundles it"
1636 line="$(valley-go resolve "$1")" || return 1
1637 read_resolved "$line" kind CHANGE_ID CHANGE_HANDLE CHANGE_VERSION CHANGE_HEAD CHANGE_BRANCH CHANGE_STATE CHANGE_OWNER
1638 case "$kind" in
1639 branch)
1640 CHANGE_BRANCH="$CHANGE_ID"
1641 CHANGE_ID=""
1642 ;;
1643 change)
1644 [[ "$CHANGE_HEAD" =~ ^[0-9a-f]{40}$ ]] \
1645 || die "valley-go resolve named the head $CHANGE_HEAD, which is no object ID"
1646 case "$CHANGE_STATE" in
1647 ready | draft | withdrawn) ;;
1648 *) die "valley-go resolve named the state $CHANGE_STATE, which this script does not read" ;;
1649 esac
1650 ;;
1651 *) die "valley-go resolve answered $line, which this script does not read" ;;
1652 esac
1653}
1654
1655# need_branch <verb>: refuse a change whose active version records no
1656# branch. review acts on the change's branch: it files its notes under it
1657# and its [r]eject deletes it. rebase, which pushes it, refuses such a
1658# change in valley-go. approve files the head alone, so it approves such a
1659# change.
1660need_branch() {
1661 if [ -n "$CHANGE_ID" ] && [ -z "$CHANGE_BRANCH" ]; then
1662 die "change $CHANGE_HANDLE v$CHANGE_VERSION records no branch, and $1 acts on a change's branch. Approve its head alone: valley approve --head $CHANGE_HEAD $CHANGE_HANDLE"
1663 fi
1664}
1665
1666# The commit review and approve act on: the recorded head for a change
1667# with a record, and otherwise the branch's head on origin.
1668change_head() {
1669 if [ -n "$CHANGE_HEAD" ]; then
1670 printf '%s\n' "$CHANGE_HEAD"
1671 else
1672 git rev-parse "refs/remotes/origin/$1"
1673 fi
1674}
1675
1676# For a change with a record, refuse unless the branch's tip on origin is
1677# the recorded head, and name both. review's [r]eject acts on the branch
1678# itself: deleting it while it is elsewhere would delete a commit no
1679# version records. rebase asks the same in valley-go. approve does not ask
1680# this, since the request it files names the head it approves and not the
1681# branch. The second argument is what the refusal leaves undone.
1682check_recorded_tip() {
1683 local branch="$1" undone="$2" tip
1684 [ -n "$CHANGE_HEAD" ] || return 0
1685 tip="$(git rev-parse "refs/remotes/origin/$branch")" || {
1686 refuse "no such branch on origin: $branch; $undone"
1687 return 1
1688 }
1689 [ "$tip" = "$CHANGE_HEAD" ] && return 0
1690 refuse "change $CHANGE_HANDLE v$CHANGE_VERSION records the head $CHANGE_HEAD, and origin/$branch is at $tip; $undone. Ready the branch's head as a new version of $CHANGE_HANDLE to act on it"
1691}
1692
1693# For a change with a record, read the record again from origin, and
1694# refuse unless the change is still ready at the head this run began with.
1695# A draft is paused and a withdrawn change given up, and neither is
1696# approved until it is readied again. The record was read when review or
1697# approve began, and another principal may unready, withdraw or ready a
1698# new version of the change while a review is open or the checks run. So
1699# approve reads it again before it runs the checks and before it files.
1700# These checks save a run that would come to nothing: the integrator makes
1701# the same one on origin, and lands no request for a change that is not
1702# ready. rebase makes its own checks in valley-go (status/rebase.go).
1703#
1704# A name that read as a plain branch can come to name a change meanwhile:
1705# someone readies the branch, and perhaps unreadies it, while the review
1706# is open. So the last check before approve files reads the original name
1707# again too. approve passes the head it is about to file as the second
1708# argument. When the name now names a change, the same rules hold: the
1709# change must be ready, and its recorded head must be that head. The first
1710# argument is what the refusal leaves undone.
1711#
1712# approve binds the head it approves (APPROVE_HEAD), and passes it as the
1713# third argument. For approve the change must be ready, and that head must
1714# be one of its version heads, whichever version is active by then: a
1715# record that moves after review cannot change what lands, since the
1716# request names the head approved.
1717check_record() {
1718 local undone="$1" acting="${2:-}" bound="${3:-}" line kind id handle version head branch state owner
1719 if [ -z "$CHANGE_ID" ]; then
1720 [ -n "$acting" ] || return 0
1721 if ! line="$(valley-go resolve "$CHANGE_NAME")"; then
1722 refuse "could not read $CHANGE_NAME again against origin's records; $undone"
1723 return 1
1724 fi
1725 read_resolved "$line" kind id handle version head branch state owner
1726 [ "$kind" = change ] || return 0
1727 if [ "$state" != ready ]; then
1728 refuse "$CHANGE_NAME is now change $handle v$version, which is $state, not ready; $undone. Ready it first: $(ready_hint "$id" "$branch")"
1729 return 1
1730 fi
1731 if [ "$head" != "$acting" ]; then
1732 refuse "$CHANGE_NAME is now change $handle v$version, which records the head $head, and this run began at $acting; $undone. Review it again by its handle"
1733 return 1
1734 fi
1735 return 0
1736 fi
1737 if ! line="$(valley-go resolve "$CHANGE_ID")"; then
1738 refuse "could not read the record of change $CHANGE_HANDLE again; $undone"
1739 return 1
1740 fi
1741 read_resolved "$line" kind id handle version head branch state owner
1742 if [ "$kind" != change ] || [ "$id" != "$CHANGE_ID" ]; then
1743 refuse "origin no longer holds a record of change $CHANGE_HANDLE; $undone"
1744 return 1
1745 fi
1746 if [ "$state" != ready ]; then
1747 refuse "change $CHANGE_HANDLE v$version is $state, not ready; $undone. Ready it first: $(ready_hint "$CHANGE_ID" "$branch")"
1748 return 1
1749 fi
1750 if [ -n "$bound" ]; then
1751 check_version "$undone" "$bound"
1752 return
1753 fi
1754 if [ "$head" != "$CHANGE_HEAD" ]; then
1755 refuse "change $CHANGE_HANDLE is at v$version, $head, and this run began at v$CHANGE_VERSION, $CHANGE_HEAD; $undone. Review it again at its new head"
1756 return 1
1757 fi
1758}
1759
1760# For a change with a record, read its versions from origin again, and
1761# refuse unless the change is ready and the head given is one of its
1762# versions' heads. Sets APPROVE_VERSION and APPROVE_TITLE to that
1763# version's number and title. The first argument is what the refusal
1764# leaves undone.
1765APPROVE_VERSION="" APPROVE_TITLE=""
1766check_version() {
1767 local undone="$1" head="$2" out n vhead vstate title state=""
1768 local -a known=()
1769 APPROVE_VERSION="" APPROVE_TITLE=""
1770 if ! out="$(valley-go versions "$CHANGE_ID")"; then
1771 refuse "could not read the versions of change $CHANGE_HANDLE; $undone"
1772 return 1
1773 fi
1774 # read empties its variables at the end of its input, so the state is
1775 # kept apart from them.
1776 while IFS=$'\t' read -r n vhead vstate title; do
1777 state="$vstate"
1778 known+=("v$n at $vhead")
1779 if [ "$vhead" = "$head" ]; then
1780 APPROVE_VERSION="$n"
1781 APPROVE_TITLE="$title"
1782 fi
1783 done <<< "$out"
1784 if [ "$state" != ready ]; then
1785 refuse "change $CHANGE_HANDLE is $state, not ready; $undone. Ready it first: $(ready_hint "$CHANGE_ID" "$CHANGE_BRANCH")"
1786 return 1
1787 fi
1788 if [ -z "$APPROVE_VERSION" ]; then
1789 refuse "$head is no version of change $CHANGE_HANDLE, whose versions are $(printf '%s\n' "${known[@]}" | join_lines); $undone"
1790 return 1
1791 fi
1792}
1793
1794# The head approve approves for a change with a record, in APPROVE_HEAD.
1795# With --head, it is exactly that head, which must be one of the record's
1796# version heads. A front end that shows the change its own way passes the
1797# head it showed, so what is approved is what was seen, whichever version
1798# the record makes active by then. Without --head, the operator is shown
1799# the active version's head and title and asked to confirm them, which
1800# needs a terminal; off one, approve refuses. The first argument is
1801# --head's value, or empty.
1802APPROVE_HEAD=""
1803bind_head() {
1804 local want="$1" sha answer
1805 APPROVE_HEAD=""
1806 if [ "$CHANGE_STATE" != ready ]; then
1807 refuse "change $CHANGE_HANDLE v$CHANGE_VERSION is $CHANGE_STATE, not ready; nothing published. Ready it first: $(ready_hint "$CHANGE_ID" "$CHANGE_BRANCH")"
1808 return 1
1809 fi
1810 if [ -n "$want" ]; then
1811 if ! [[ "$want" =~ ^[0-9a-f]{4,64}$ ]] \
1812 || ! sha="$(git rev-parse --verify --quiet "$want^{commit}")"; then
1813 refuse "--head takes the object ID of one of change $CHANGE_HANDLE's version heads, and $want is none here; nothing published"
1814 return 1
1815 fi
1816 check_version "nothing published" "$sha" || return 1
1817 APPROVE_HEAD="$sha"
1818 return 0
1819 fi
1820 check_version "nothing published" "$CHANGE_HEAD" || return 1
1821 if [ ! -t 0 ]; then
1822 refuse "approving change $CHANGE_HANDLE names the head it approves: off a terminal, pass it with --head. Its active version is v$APPROVE_VERSION at $CHANGE_HEAD, $APPROVE_TITLE: valley approve --head $CHANGE_HEAD $CHANGE_HANDLE. Nothing published"
1823 return 1
1824 fi
1825 printf 'approve change %s v%s at %s, %s? [y/N] ' \
1826 "$CHANGE_HANDLE" "$APPROVE_VERSION" "$CHANGE_HEAD" "$APPROVE_TITLE"
1827 read -r answer || answer=""
1828 case "$answer" in
1829 y | Y | yes) APPROVE_HEAD="$CHANGE_HEAD" ;;
1830 *)
1831 refuse "not approved; nothing published"
1832 return 1
1833 ;;
1834 esac
1835}
1836
1837# review shows a change with a record at its active version's head, and
1838# its [a]pprove approves exactly that head. A plain branch is bound to the
1839# head review pages, when it pages it (show_review, use_layer), and approve
1840# files that head. approve with no review binds nothing, and files the
1841# branch's tip on origin as the fetch left it.
1842bind_review() {
1843 APPROVE_HEAD="" APPROVE_VERSION=""
1844 if [ -n "$CHANGE_ID" ]; then
1845 APPROVE_HEAD="$CHANGE_HEAD"
1846 APPROVE_VERSION="$CHANGE_VERSION"
1847 fi
1848}
1849
1850# branch_at_shown <branch>: refuse unless the branch on origin is still at
1851# the head bound to this approval, and name both. origin itself is read,
1852# not the tracking ref: a push from another checkout moves the branch
1853# without moving this clone's ref. ls-remote matches a pattern against the
1854# tail of a ref name, so each ref it lists is compared whole.
1855branch_at_shown() {
1856 local out now
1857 out="$(git ls-remote origin "refs/heads/$1")" || {
1858 refuse "could not read $1 on origin to check that it is still at $APPROVE_HEAD, the head shown; nothing published"
1859 return 1
1860 }
1861 now="$(printf '%s\n' "$out" | awk -v r="refs/heads/$1" '$2 == r { print $1 }')"
1862 if [ -z "$now" ]; then
1863 refuse "origin/$1 is gone, and is no longer at $APPROVE_HEAD, the head shown; nothing published"
1864 return 1
1865 fi
1866 [ "$now" = "$APPROVE_HEAD" ] && return 0
1867 refuse "origin/$1 is at $now, and is no longer at $APPROVE_HEAD, the head shown; nothing published"
1868}
1869
1870# The head the checks failed at in this review, short, while the change is
1871# still at it. Approving that head again would run the same checks over
1872# the same tree and fail the same way, so the prompt stops offering
1873# [a]pprove until the change has a new head. Fails when the checks have
1874# not failed at the head the change is at.
1875approve_failed_at() {
1876 if [ -z "$CHECKS_FAILED_AT" ] || [ "$CHECKS_FAILED_AT" != "$(change_head "$1")" ]; then
1877 return 1
1878 fi
1879 git rev-parse --short "$CHECKS_FAILED_AT"
1880}
1881
1882# not_ready <handle> <version> <state> <owner>: the line review shows for a
1883# change whose record is not ready, above its diff and in its prompt.
1884# Prints nothing, and fails, for a ready change, and for a plain branch,
1885# which has no record. A draft is often a change an agent is still working
1886# on, so the prompt then offers only [v]iew full diff and [s]kip.
1887# [a]pprove would be refused. [b]ase is not offered either: rebase refuses
1888# such a change, since adding its rebased head as a version would ready it
1889# behind its owner's back. Nor is [r]eject, which records nothing on the
1890# change: it deletes the branch its owner may still be working on, and the
1891# record says what it said before. approve still reads the record again
1892# when it acts, since the state can change while the review is open.
1893not_ready() {
1894 case "$3" in
1895 draft) printf "%s v%s is a draft: its owner (%s) hasn't marked it ready, so it can't be approved yet." "$1" "$2" "$4" ;;
1896 withdrawn) printf '%s is withdrawn: there is nothing to approve.' "$1" ;;
1897 *) return 1 ;;
1898 esac
1899}
1900
1901# shown_not_ready: not_ready for the change review is showing.
1902shown_not_ready() {
1903 not_ready "$CHANGE_HANDLE" "$CHANGE_VERSION" "$CHANGE_STATE" "$CHANGE_OWNER"
1904}
1905
1906# Show the branch and take the verdict. Split out of cmd_review so that
1907# every way out of it — approve, reject, skip — is followed by the notes.
1908# A change that is not ready is asked as decide asks it: it can be neither
1909# approved nor rebased, so whether it fast-forwards from main changes
1910# nothing.
1911read_and_decide() {
1912 local branch="$1" choice failed answers
1913 show_review "$branch"
1914 # A stale branch's pre-rebase diff is not what would land; offer to rebase it
1915 # mechanically, then re-review what actually would. [a]pprove is offered
1916 # here as well, because the integrator applies a delta to the tip rather
1917 # than fast-forwarding: a stale branch is a request it can judge, and
1918 # rebasing first is a convenience rather than a precondition.
1919 while ! shown_not_ready > /dev/null \
1920 && ! git merge-base --is-ancestor refs/remotes/origin/main "$(change_head "$branch")"; do
1921 if failed="$(approve_failed_at "$branch")"; then
1922 printf '%s does not fast-forward from main. Its checks failed at %s, so approving needs a new head: [v]iew full diff, [b]ase onto main, [r]eject, [s]kip? ' \
1923 "$branch" "$failed"
1924 answers="v, b, r, or s"
1925 else
1926 printf '%s does not fast-forward from main: [a]pprove, [v]iew full diff, [b]ase onto main, [r]eject, [s]kip? ' \
1927 "$branch"
1928 answers="a, v, b, r, or s"
1929 fi
1930 read -r choice || die "stdin closed before an answer; nothing done"
1931 case "$choice" in
1932 a)
1933 if [ -n "$failed" ]; then
1934 echo "answer $answers"
1935 elif approve "$branch"; then
1936 return
1937 fi
1938 ;;
1939 v) view_full "$branch" ;;
1940 b)
1941 # A change with a record gains the rebased head as a new version,
1942 # so the review goes on at that version, as it does at the rebased
1943 # tip of a plain branch. A refused rebase has said why, and the
1944 # prompt comes back.
1945 if rebase_shown "$(change_head "$branch")"; then
1946 if [ -n "$CHANGE_ID" ]; then
1947 resolve_change "$CHANGE_ID" || die "could not read change $CHANGE_HANDLE again after the rebase"
1948 bind_review
1949 fi
1950 fetch_origin
1951 show_review "$branch"
1952 fi
1953 ;;
1954 r) reject "$branch" && return ;;
1955 s)
1956 echo "skipped $branch; nothing done"
1957 return
1958 ;;
1959 *) echo "answer $answers" ;;
1960 esac
1961 done
1962 decide "$branch"
1963}
1964
1965# decide <branch> [<name> <n>]: the verdict on a change that fast-forwards
1966# from main, and on the top of a stack, which is never offered [b]ase. A
1967# change alone is asked about by its branch. The top of a stack of <n> is
1968# asked about by its <name>, as the stack lists it, and its prompt says
1969# that approving it lands all <n> layers. [v]iew full diff pages the
1970# change's whole diff, or the top layer's.
1971#
1972# A change that is not ready is asked about by the line not_ready gives,
1973# in place of the label, and is offered only [v]iew full diff and
1974# [s]kip, or [s]top. The top of a stack with a layer under it that is not
1975# ready says why it can't be approved (layer_held), and is offered the
1976# rest.
1977decide() {
1978 local branch="$1" name="${2:-}" n="${3:-}" choice failed answers own held=""
1979 local label="$1" approve="[a]pprove" reject="[r]eject" stop="[s]kip"
1980 local stopped="skipped $1; nothing done"
1981 own="$(shown_not_ready)" || own=""
1982 if [ -n "$n" ]; then
1983 label="$name, $n of $n" approve="[a]pprove all $n" reject="[r]eject $name" stop="[s]top"
1984 stopped="stopped reviewing $name at change $n of $n; nothing done"
1985 held="$(layer_held $((n - 1)))" || held=""
1986 fi
1987 while true; do
1988 failed=""
1989 if [ -n "$own" ]; then
1990 if [ -n "$n" ]; then
1991 printf '%s: %s [v]iew full diff, %s? ' "$label" "$own" "$stop"
1992 else
1993 printf '%s [v]iew full diff, %s? ' "$own" "$stop"
1994 fi
1995 answers="v or s"
1996 elif [ -n "$held" ]; then
1997 printf '%s: %s [v]iew full diff, %s, %s? ' "$label" "$held" "$reject" "$stop"
1998 answers="v, r, or s"
1999 elif failed="$(approve_failed_at "$branch")"; then
2000 printf '%s: its checks failed at %s, so approving needs a new head: [v]iew full diff, %s, %s? ' \
2001 "$label" "$failed" "$reject" "$stop"
2002 answers="v, r, or s"
2003 else
2004 printf '%s: %s, [v]iew full diff, %s, %s? ' "$label" "$approve" "$reject" "$stop"
2005 answers="a, v, r, or s"
2006 fi
2007 read -r choice || die "stdin closed before an answer; nothing done"
2008 case "$choice" in
2009 # A refusal from approve is not a verdict: it says what it did not do
2010 # and the prompt comes back, so the branch can still be rejected or
2011 # skipped. When the checks failed, approving the same head again is
2012 # no longer offered, nor is approving a change that is not ready.
2013 a)
2014 if [ -n "$failed" ] || [ -n "$own" ] || [ -n "$held" ]; then
2015 echo "answer $answers"
2016 elif approve "$branch"; then
2017 return
2018 fi
2019 ;;
2020 v)
2021 if [ -n "$n" ]; then
2022 view_layer $((n - 1))
2023 else
2024 view_full "$branch"
2025 fi
2026 ;;
2027 r)
2028 if [ -n "$own" ]; then
2029 echo "answer $answers"
2030 else
2031 reject "$branch" && return
2032 fi
2033 ;;
2034 s)
2035 echo "$stopped"
2036 return
2037 ;;
2038 *) echo "answer $answers" ;;
2039 esac
2040 done
2041}
2042
2043# ----------------------------------------------------------------------
2044# A stack — a change with layers under it that have not landed — is
2045# reviewed one layer at a time, bottom first, each against the layer below
2046# it, the way it was built. Approving the top lands every layer under it,
2047# so reading the top against main alone would ask the operator to judge
2048# the whole stack as one diff.
2049#
2050# The layers are valley-go stack's (status/stack.go): one line each, bottom
2051# first, the change itself last, read here into one array per field.
2052# L_BRANCH is the branch a layer's notes are kept under: a branch's own
2053# name, or the branch a change's active version names. L_OWNER is a
2054# change's owner, as its record names it. L_NOTES holds the notes taken on
2055# each layer, for the print after the verdict.
2056L_KIND=() L_NAME=() L_BASE=() L_HEAD=() L_STATE=() L_TITLE=()
2057L_ID=() L_VERSION=() L_BRANCH=() L_OWNER=() L_NOTES=()
2058# The name review was given, which the top is read again by.
2059TOP_NAME=""
2060
2061# read_stack: read the stack under the change review resolved. Each change
2062# under the top is read again with resolve, for its ID, version, branch
2063# and owner, and must still be at the head the stack names. The top must be
2064# what review resolved. Fails, having said why, when either does not hold
2065# or the helper cannot read the stack. Called in a condition, so each step
2066# is checked by hand.
2067read_stack() {
2068 local out line kind name base head state title k last
2069 local rkind id handle version rhead branch rstate owner
2070 L_KIND=() L_NAME=() L_BASE=() L_HEAD=() L_STATE=() L_TITLE=()
2071 L_ID=() L_VERSION=() L_BRANCH=() L_OWNER=() L_NOTES=()
2072 out="$(valley-go stack "${CHANGE_ID:-origin/$CHANGE_BRANCH}")" || return 1
2073 while IFS= read -r line; do
2074 read_resolved "$line" kind name base head state title
2075 if ! [[ "$kind" =~ ^(change|branch)$ && "$base" =~ ^[0-9a-f]{40}$ && "$head" =~ ^[0-9a-f]{40}$ ]]; then
2076 refuse "valley-go stack answered $line, which this script does not read"
2077 return 1
2078 fi
2079 L_KIND+=("$kind") L_NAME+=("$name") L_BASE+=("$base") L_HEAD+=("$head")
2080 L_STATE+=("$state") L_TITLE+=("$title") L_NOTES+=("")
2081 L_ID+=("") L_VERSION+=("") L_BRANCH+=("$name") L_OWNER+=("")
2082 done <<< "$out"
2083 last=$((${#L_NAME[@]} - 1))
2084 if [ "${L_HEAD[last]}" != "$(change_head "$CHANGE_BRANCH")" ] \
2085 || [ "${L_KIND[last]}" != "$([ -n "$CHANGE_ID" ] && echo change || echo branch)" ]; then
2086 refuse "$TOP_NAME moved while its stack was read"
2087 return 1
2088 fi
2089 L_ID[last]="$CHANGE_ID" L_VERSION[last]="$CHANGE_VERSION" L_BRANCH[last]="$CHANGE_BRANCH"
2090 L_OWNER[last]="$CHANGE_OWNER"
2091 for ((k = 0; k < last; k++)); do
2092 [ "${L_KIND[k]}" = change ] || continue
2093 line="$(valley-go resolve "${L_NAME[k]}")" || return 1
2094 read_resolved "$line" rkind id handle version rhead branch rstate owner
2095 if [ "$rkind" != change ] || [ "$rhead" != "${L_HEAD[k]}" ]; then
2096 refuse "change ${L_NAME[k]}, under $TOP_NAME, moved while the stack was read"
2097 return 1
2098 fi
2099 L_ID[k]="$id" L_VERSION[k]="$version" L_BRANCH[k]="$branch" L_STATE[k]="$rstate"
2100 L_OWNER[k]="$owner"
2101 done
2102}
2103
2104# use_layer <k>: act on layer k as review acts on a change it was given,
2105# binding [a]pprove to the head the stack shows. A branch under the top is
2106# read again as origin/<branch>, which no handle can shadow.
2107use_layer() {
2108 local k="$1"
2109 CHANGE_ID="${L_ID[k]}" CHANGE_VERSION="${L_VERSION[k]}" CHANGE_BRANCH="${L_BRANCH[k]}"
2110 CHANGE_STATE="${L_STATE[k]}" CHANGE_OWNER="${L_OWNER[k]}" CHANGE_HANDLE="" CHANGE_HEAD=""
2111 CHANGE_NAME="origin/${L_NAME[k]}"
2112 [ "$k" -lt $((${#L_NAME[@]} - 1)) ] || CHANGE_NAME="$TOP_NAME"
2113 if [ -n "$CHANGE_ID" ]; then
2114 CHANGE_NAME="${L_NAME[k]}" CHANGE_HANDLE="${L_NAME[k]}" CHANGE_HEAD="${L_HEAD[k]}"
2115 fi
2116 bind_review
2117 [ -n "$CHANGE_ID" ] || APPROVE_HEAD="${L_HEAD[k]}"
2118}
2119
2120# notes_key <k>: the branch layer k's notes are kept under. A change whose
2121# active version names no branch keeps them under its handle.
2122notes_key() {
2123 printf '%s' "${L_BRANCH[$1]:-${L_NAME[$1]}}"
2124}
2125
2126# layer_label <k>: how a layer is named in the list: its name, then
2127# branch, or the change's state.
2128layer_label() {
2129 local k="$1"
2130 if [ "${L_KIND[k]}" = branch ]; then
2131 printf '%s (branch)' "${L_NAME[k]}"
2132 else
2133 printf '%s (%s)' "${L_NAME[k]}" "${L_STATE[k]}"
2134 fi
2135}
2136
2137# What is coming: the layers bottom first, the lower layers the integrator
2138# would refuse, and what each answer lands.
2139summarize_stack() {
2140 local n="${#L_NAME[@]}" k
2141 printf '%s is a stack of %d changes; reviewing from the bottom, each against the one below it:\n' \
2142 "${L_NAME[n - 1]}" "$n"
2143 for ((k = 0; k < n; k++)); do
2144 printf ' %d. %s: %s\n' "$((k + 1))" "$(layer_label "$k")" "${L_TITLE[k]}"
2145 done
2146 for ((k = 0; k < n - 1; k++)); do
2147 case "${L_STATE[k]}" in
2148 draft | withdrawn)
2149 printf 'warning: %s, change %d of %d, is %s. The integrator refuses to land it or anything above it (refused-not-ready).\n' \
2150 "${L_NAME[k]}" "$((k + 1))" "$n" "$([ "${L_STATE[k]}" = draft ] && echo 'a draft' || echo withdrawn)"
2151 ;;
2152 esac
2153 done
2154 printf 'read each layer and go on with [n]; approving %s at the top lands all %d. [a] on a lower layer lands it and the layers under it, and ends the review.\n' \
2155 "${L_NAME[n - 1]}" "$n"
2156}
2157
2158# base_stack: before any layer is paged, a stack whose bottom does not
2159# fast-forward from main is offered [b]ase, which rebases every layer as
2160# the rebase verb does (status/rebase.go), or [s]top. After a rebase the
2161# stack is read again and listed again, so the heads paged are the heads
2162# approved. A rebase refused or left unfinished has said what happened,
2163# and only [s]top is offered then. Fails when the review stops here.
2164base_stack() {
2165 local n choice offered="[b]ase" stopped="; nothing done"
2166 while ! git merge-base --is-ancestor refs/remotes/origin/main "${L_HEAD[0]}"; do
2167 n="${#L_NAME[@]}"
2168 if [ -n "$offered" ]; then
2169 printf '%s, at the bottom, does not fast-forward from main: [b]ase all %d onto main, [s]top? ' \
2170 "${L_NAME[0]}" "$n"
2171 else
2172 printf 'the stack under %s is not rebased: [s]top? ' "${L_NAME[n - 1]}"
2173 fi
2174 read -r choice || die "stdin closed before an answer; nothing done"
2175 case "$choice" in
2176 b)
2177 if [ -z "$offered" ]; then
2178 echo "answer s"
2179 elif rebase_shown "${L_HEAD[n - 1]}"; then
2180 fetch_origin
2181 if [ -n "$CHANGE_ID" ]; then
2182 resolve_change "$CHANGE_ID" || die "could not read change $CHANGE_HANDLE again after the rebase"
2183 fi
2184 bind_review
2185 read_stack || die "could not read the stack under $TOP_NAME again after the rebase"
2186 summarize_stack
2187 else
2188 offered="" stopped=""
2189 fi
2190 ;;
2191 s)
2192 echo "stopped reviewing ${L_NAME[n - 1]} before its first layer$stopped"
2193 return 1
2194 ;;
2195 *) echo "answer ${offered:+b or }s" ;;
2196 esac
2197 done
2198}
2199
2200# layer_heading <k>: the line that heads layer k wherever it is shown.
2201layer_heading() {
2202 local k="$1" below=main
2203 [ "$k" -eq 0 ] || below="${L_NAME[k - 1]}"
2204 printf 'change %d of %d: %s on %s' "$((k + 1))" "${#L_NAME[@]}" "${L_NAME[k]}" "$below"
2205}
2206
2207# layer_held <k>: why layer k can't be approved, when it or a layer under
2208# it is not ready. A layer that is not ready says so as a change alone
2209# does (not_ready). A layer above one says which: approving it would land
2210# that layer too, and the integrator lands nothing that would bring a
2211# version of a change that is not ready. Prints nothing, and fails, when
2212# every layer up to k is ready or a plain branch.
2213layer_held() {
2214 local k="$1" j
2215 not_ready "${L_NAME[k]}" "${L_VERSION[k]}" "${L_STATE[k]}" "${L_OWNER[k]}" && return
2216 for ((j = k - 1; j >= 0; j--)); do
2217 case "${L_STATE[j]}" in
2218 draft | withdrawn)
2219 printf "it would bring %s, change %d of %d, which is %s, so it can't be approved yet." \
2220 "${L_NAME[j]}" "$((j + 1))" "${#L_NAME[@]}" "$([ "${L_STATE[j]}" = draft ] && echo 'a draft' || echo withdrawn)"
2221 return
2222 ;;
2223 esac
2224 done
2225 return 1
2226}
2227
2228# page_layer <k>: show layer k, as show_review shows a change alone. The
2229# layer shown is compared with its own change's approved version, so a
2230# lower layer is set against its own approval, not the top's. Its whole
2231# diff is against the layer below it. The notes taken in it are kept
2232# under its own branch. When it can't be approved, layer_held's line
2233# follows its heading.
2234page_layer() {
2235 local k="$1" heading held
2236 NOTES=()
2237 heading="$(layer_heading "$k")"
2238 if held="$(layer_held "$k")"; then heading+=$'\n'"$held"; fi
2239 REVIEW_TMP="$(mktemp -d)"
2240 compare_shown "${L_ID[k]}" "${L_VERSION[k]}" "${L_HEAD[k]}"
2241 show_compared "$(notes_key "$k")" "${L_HEAD[k]}" "$heading" layer_diff "$k"
2242 keep_layer_notes "$k"
2243}
2244
2245# view_layer <k>: [v]iew full diff for layer k: its whole diff against
2246# the layer below it.
2247view_layer() {
2248 local k="$1"
2249 NOTES=()
2250 REVIEW_TMP="$(mktemp -d)"
2251 {
2252 layer_heading "$k"
2253 printf '\n'
2254 layer_diff "$k"
2255 } > "$REVIEW_TMP/review.diff"
2256 page_buffer "$(notes_key "$k")" "$(git rev-parse --short "${L_HEAD[k]}")"
2257 keep_layer_notes "$k"
2258}
2259
2260# keep_layer_notes <k>: add the notes just taken to layer k's.
2261keep_layer_notes() {
2262 [ "${#NOTES[@]}" -gt 0 ] || return 0
2263 L_NOTES[$1]="${L_NOTES[$1]:+${L_NOTES[$1]}$'\n'}$(printf '%s\n' "${NOTES[@]}")"
2264}
2265
2266# layer_diff <k>: layer k's whole diff: its log and its diff against the
2267# layer below it.
2268layer_diff() {
2269 local k="$1" below=main head base sha on
2270 [ "$k" -eq 0 ] || below="${L_NAME[k - 1]}"
2271 head="${L_HEAD[k]}" base="${L_BASE[k]}"
2272 sha="$(git rev-parse --short "$head")"
2273 on="$below at $(git rev-parse --short "$base")"
2274 if [ "${L_KIND[k]}" = branch ]; then
2275 printf 'branch %s, log against %s:\n\n' "${L_NAME[k]}" "$on"
2276 elif [ -n "${L_BRANCH[k]}" ]; then
2277 printf 'change %s v%s at %s, on branch %s, log against %s:\n\n' \
2278 "${L_NAME[k]}" "${L_VERSION[k]}" "$sha" "${L_BRANCH[k]}" "$on"
2279 else
2280 printf 'change %s v%s at %s, log against %s:\n\n' "${L_NAME[k]}" "${L_VERSION[k]}" "$sha" "$on"
2281 fi
2282 git --no-pager log --oneline "$base..$head"
2283 printf '\n'
2284 git --no-pager diff "$base...$head"
2285}
2286
2287# Show each layer under the top and ask after each, naming the layer and
2288# its place: [n]ext layer goes on to the layer above, [a]pprove approves
2289# that layer at the head shown, which lands it and every layer under it,
2290# as the prompt names them, [v]iew full diff pages the layer's whole diff,
2291# and [s]top ends the review. [r]eject is not offered under the top:
2292# deleting a lower layer's branch would leave the layers above still
2293# holding it. [a]pprove is not offered at or above a layer that is not
2294# ready, and the prompt says why in its place (layer_held). After the
2295# top, its verdict is taken as for any change, with a prompt that names
2296# the top and says approving it lands all n.
2297review_stack() {
2298 local n top k choice answers failed lands held
2299 summarize_stack
2300 base_stack || return 0
2301 printf '\n'
2302 n="${#L_NAME[@]}" top=$((${#L_NAME[@]} - 1))
2303 for ((k = 0; k < top; k++)); do
2304 page_layer "$k"
2305 case "$k" in
2306 0) lands="${L_NAME[0]} alone" ;;
2307 1) lands="${L_NAME[0]} and ${L_NAME[1]}" ;;
2308 *) lands="the $((k + 1)) up to ${L_NAME[k]}" ;;
2309 esac
2310 held="$(layer_held "$k")" || held=""
2311 while true; do
2312 failed=""
2313 [ "$CHECKS_FAILED_AT" != "${L_HEAD[k]}" ] || failed="$(git rev-parse --short "${L_HEAD[k]}")"
2314 if [ -n "$held" ]; then
2315 printf '%s, %d of %d: %s [n]ext layer, [v]iew full diff, [s]top? ' \
2316 "${L_NAME[k]}" "$((k + 1))" "$n" "$held"
2317 answers="n, v, or s"
2318 elif [ -n "$failed" ]; then
2319 printf '%s, %d of %d: its checks failed at %s, so approving needs a new head: [n]ext layer, [v]iew full diff, [s]top? ' \
2320 "${L_NAME[k]}" "$((k + 1))" "$n" "$failed"
2321 answers="n, v, or s"
2322 else
2323 printf '%s, %d of %d: [n]ext layer, [a]pprove %s, [v]iew full diff, [s]top? ' \
2324 "${L_NAME[k]}" "$((k + 1))" "$n" "$lands"
2325 answers="n, a, v, or s"
2326 fi
2327 read -r choice || die "stdin closed before an answer; nothing done"
2328 case "$choice" in
2329 n) break ;;
2330 a)
2331 if [ -n "$failed" ] || [ -n "$held" ]; then
2332 echo "answer $answers"
2333 continue
2334 fi
2335 use_layer "$k"
2336 if approve "$CHANGE_BRANCH"; then
2337 return
2338 fi
2339 use_layer "$top"
2340 ;;
2341 v) view_layer "$k" ;;
2342 s)
2343 echo "stopped reviewing ${L_NAME[top]} at change $((k + 1)) of $n, ${L_NAME[k]}; nothing done"
2344 return
2345 ;;
2346 *) echo "answer $answers" ;;
2347 esac
2348 done
2349 done
2350 page_layer "$top"
2351 use_layer "$top"
2352 decide "${L_BRANCH[top]}" "${L_NAME[top]}" "$n"
2353}
2354
2355# The notes taken on every layer, each under its own branch.
2356print_stack_notes() {
2357 local k
2358 for ((k = 0; k < ${#L_NAME[@]}; k++)); do
2359 [ -n "${L_NOTES[k]}" ] || continue
2360 mapfile -t NOTES <<< "${L_NOTES[k]}"
2361 print_notes "$(notes_key "$k")"
2362 done
2363}
2364
2365cmd_review() {
2366 [ $# -eq 1 ] || die "usage: valley review <change>"
2367 resolve_change "$1" || exit 1
2368 need_branch review
2369 local branch="$CHANGE_BRANCH"
2370 TOP_NAME="$1"
2371 fetch_origin
2372 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
2373 || die "no such branch on origin: $branch"
2374 bind_review
2375 trap cleanup_scratch EXIT
2376 trap 'exit 130' INT TERM
2377 # The verdict disposes of the change; the notes are what the human made
2378 # of it, so they are printed whatever the verdict was. A stack that
2379 # cannot be read is reviewed whole against main, as a change with
2380 # nothing under it is.
2381 if ! read_stack; then
2382 printf 'valley: warning: the stack under %s could not be read; reviewing it whole, against main\n' "$1" >&2
2383 L_NAME=()
2384 fi
2385 if [ "${#L_NAME[@]}" -gt 1 ]; then
2386 review_stack
2387 print_stack_notes
2388 else
2389 read_and_decide "$branch"
2390 print_notes "$branch"
2391 fi
2392}
2393
2394# approve and rebase are review's [a]pprove and [b]ase without the pager,
2395# for a front end that has shown the change its own way. Each runs the
2396# code its key runs, approve and valley-go rebase, so the verb and the key
2397# cannot drift apart. A change is named as resolve_change reads it, and
2398# rebase reads its name the same way, in valley-go.
2399#
2400# approve of a change with a record approves exactly one head (bind_head):
2401# --head's, or the active version's once the operator confirms it on a
2402# terminal. A plain branch is approved at its tip on origin, as the fetch
2403# left it, and --head, when given, must be that tip.
2404cmd_approve() {
2405 local name="" want=""
2406 local usage="usage: valley approve [--head <sha>] <change>"
2407 while [ $# -gt 0 ]; do
2408 case "$1" in
2409 --head)
2410 [ $# -ge 2 ] || die "$usage"
2411 want="$2"
2412 shift 2
2413 ;;
2414 --head=*)
2415 want="${1#--head=}"
2416 shift
2417 ;;
2418 -*) die "$usage" ;;
2419 *)
2420 [ -z "$name" ] || die "$usage"
2421 name="$1"
2422 shift
2423 ;;
2424 esac
2425 done
2426 [ -n "$name" ] || die "$usage"
2427 resolve_change "$name" || exit 1
2428 local branch="$CHANGE_BRANCH" tip
2429 fetch_origin
2430 trap cleanup_scratch EXIT
2431 trap 'exit 130' INT TERM
2432 if [ -n "$CHANGE_ID" ]; then
2433 bind_head "$want" || exit 1
2434 else
2435 tip="$(git rev-parse --verify --quiet "refs/remotes/origin/$branch")" \
2436 || die "no such branch on origin: $branch"
2437 if [ -n "$want" ] && [ "$(git rev-parse --verify --quiet "$want^{commit}" || true)" != "$tip" ]; then
2438 die "origin/$branch is at $tip, not $want; nothing published"
2439 fi
2440 fi
2441 # In a condition, as the review prompt calls it: approve checks each of
2442 # its own steps, and has already said why when it refuses.
2443 approve "$branch" || exit 1
2444}
2445
2446cmd_rebase() {
2447 case "${1:-}" in -*) die "usage: valley rebase <change>" ;; esac
2448 [ $# -eq 1 ] || die "usage: valley rebase <change>"
2449 command -v valley-go > /dev/null 2>&1 \
2450 || die "review, approve and rebase read the change's record with the valley-go helper; nix run .#valley bundles it"
2451 fetch_origin
2452 exec valley-go rebase "$1"
2453}
2454
2455# tail and replay are thin wrappers over the nats CLI — anything they do,
2456# plain nats and git can do. They are the only verbs needing more than git
2457# and coreutils.
2458need_nats() {
2459 command -v nats >/dev/null 2>&1 \
2460 || die "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
2461}
2462
2463cmd_tail() {
2464 [ $# -le 1 ] || die "usage: valley tail [subject]"
2465 need_nats
2466 exec nats sub "${1:-valley.>}"
2467}
2468
2469# One ref-updated event per existing ref, from git for-each-ref alone. A
2470# ref's prior value is not derivable from the repository, so `old` is the
2471# all-zero id — the same payload a push creating the ref would produce.
2472# The payload construction mirrors the host module's publisher hook
2473# (nix/valley-host.nix); change one only with the other.
2474cmd_replay() {
2475 [ $# -le 1 ] || die "usage: valley replay [repo-dir]"
2476 need_nats
2477 local dir="${1:-.}" repo sha ref event count=0
2478 git -C "$dir" rev-parse --git-dir >/dev/null 2>&1 \
2479 || die "not a git repository: $dir"
2480 if [ "$(git -C "$dir" rev-parse --is-bare-repository)" = true ]; then
2481 repo="$(basename "$(git -C "$dir" rev-parse --absolute-git-dir)" .git)"
2482 else
2483 repo="$(basename "$(git -C "$dir" rev-parse --show-toplevel)")"
2484 fi
2485 while read -r sha ref; do
2486 # " is the only JSON-significant character a refname can contain (git
2487 # forbids \ and control characters); names and object ids are safe.
2488 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
2489 "$repo" "${ref//\"/\\\"}" "${sha//?/0}" "$sha")"
2490 nats pub "valley.git.$repo.ref-updated" "$event" >/dev/null
2491 count=$((count + 1))
2492 done < <(git -C "$dir" for-each-ref --format='%(objectname) %(refname)')
2493 echo "replayed $count refs of $repo onto the bus"
2494}
2495
2496# ----------------------------------------------------------------------
2497# checks — the verification-policy deriver (dcr-f41f718). It composes the
2498# instance layer with the project layer, matches every side of a diff
2499# against the composed classes, and prints the check names the policy
2500# requires of the change, with the class or classes that made each one
2501# required. It reports: no check is run, nothing is gated, nothing is
2502# written.
2503#
2504# Composition is CUE's, never this script's. The whole of the mandatory-
2505# versus-overridable distinction is unification, so reimplementing it here
2506# would be reimplementing the decision. What this script does that CUE
2507# cannot is glob matching and reading a diff.
2508
2509need_cue() {
2510 command -v cue >/dev/null 2>&1 \
2511 || die "this verb needs the cue CLI; nix run .#valley bundles it"
2512}
2513
2514# One glob segment as an ERE fragment: `*` and `?` are wildcards that never
2515# cross a `/`, and every ERE metacharacter is escaped.
2516segment_ere() {
2517 local seg="$1" out="" i c
2518 for ((i = 0; i < ${#seg}; i++)); do
2519 c="${seg:i:1}"
2520 case "$c" in
2521 '*') out+='[^/]*' ;;
2522 '?') out+='[^/]' ;;
2523 '.' | '^' | '$' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | \\) out+="\\$c" ;;
2524 *) out+="$c" ;;
2525 esac
2526 done
2527 printf '%s' "$out"
2528}
2529
2530# A path glob as an anchored ERE, segment by segment. A `**` segment matches
2531# any number of segments including none, so it swallows the separator that
2532# would otherwise follow it and `a/**/b` matches `a/b`; every other segment
2533# matches exactly one.
2534glob_ere() {
2535 local ere='^' i last
2536 local -a segs=()
2537 IFS=/ read -r -a segs <<<"$1"
2538 last=$((${#segs[@]} - 1))
2539 for ((i = 0; i <= last; i++)); do
2540 if [ "${segs[i]}" = '**' ]; then
2541 if [ "$i" -eq "$last" ]; then ere+='.*'; else ere+='(.*/)?'; fi
2542 else
2543 ere+="$(segment_ere "${segs[i]}")"
2544 [ "$i" -eq "$last" ] || ere+='/'
2545 fi
2546 done
2547 printf '%s$' "$ere"
2548}
2549
2550# The composed policy as one tab-separated line per covered pattern, per
2551# required check, per class's carry mode, and per field of the check
2552# catalogue, so the shell never parses CUE. Every line is three fields — a
2553# kind, a name, and a value — whatever the kind, so one reader takes them
2554# all. The field is hidden because the schema's sentinel rejects unknown
2555# top-level fields, and `unclassified` is rendered as a class of that name:
2556# it is one more source a check can come from. A class's carry mode is the
2557# one the schema resolves (`_mode`), so the shell only picks the strictest.
2558#
2559# Each line is held to its shape (`line`): three fields, two tabs, and no
2560# other control character. A newline in a field would end its line and
2561# start one of the policy's choosing, and a tab would add a field. The
2562# schema already refuses control characters in every string rendered here,
2563# so this is a second wall: a line out of shape fails the render, and the
2564# deriver refuses a render that fails. The whole line is checked because a
2565# bound on a value inside an interpolation does not fail the string.
2566#
2567# The catalogue is rendered because a caller that runs a check needs what
2568# the policy says a check IS — its runner, and the attribute or command
2569# line that runner takes — and a tool that groups the required checks
2570# needs their cost. `checks` reads only the cost, to group the required
2571# checks by it; approve turns the rest into the arguments attest is given.
2572render_cue() {
2573 cat <<'EOF'
2574package verification
2575
2576import (
2577 "list"
2578 "strings"
2579)
2580
2581let line = =~"^[^\\x00-\\x1f\\x7f]+\t[^\\x00-\\x1f\\x7f]+\t[^\\x00-\\x1f\\x7f]+$"
2582
2583_render: strings.Join(list.Concat([[
2584 for cn, c in policy.classes
2585 for p, on in c.paths if on {"path\t\(cn)\t\(p)" & line}
2586], [
2587 for cn, c in policy.classes
2588 for k, on in c.requires if on {"requires\t\(cn)\t\(k)" & line}
2589], [
2590 for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)" & line}
2591], [
2592 for cn, m in _mode {"carry\t\(cn)\t\(m)" & line}
2593], [
2594 for n, c in policy.checks {"runner\t\(n)\t\(c.runner)" & line}
2595], [
2596 for n, c in policy.checks if c.runner == "nix" {"attribute\t\(n)\t\(c.attribute)" & line}
2597], [
2598 for n, c in policy.checks if c.runner == "command" {"command\t\(n)\t\(c.command)" & line}
2599], [
2600 for n, c in policy.checks {"cost\t\(n)\t\(c.cost)" & line}
2601]]), "\n")
2602EOF
2603}
2604
2605# The composed layer, and a scratch directory for the documents the
2606# derivation writes into the composition. Globals so the probe below can
2607# see them.
2608POLICY_LAYER=()
2609POLICY_TMP=""
2610
2611cleanup_policy_tmp() {
2612 [ -n "$POLICY_TMP" ] || return 0
2613 rm -rf "$POLICY_TMP"
2614 POLICY_TMP=""
2615}
2616
2617# Where the schema and the two policy layers come from in a project
2618# following the convention (dcr-f41f718).
2619#
2620# The client derives from exactly the sources the integrator uses
2621# (integrator/policy.go), and the working tree is not among them. The
2622# project's own layer is read from the TARGET's tip, the pointer naming the
2623# owning valley is read from the target's tip, and the floor is read from
2624# that valley's integrated tip. A change never supplies the policy that
2625# gates it, and neither does whoever happens to be reviewing it: the
2626# reviewer's checkout may be any branch, however stale, and derivation
2627# gives the same answer from all of them.
2628#
2629# The schema is not a policy layer. It is the shape a policy is written in,
2630# and it ships with this tool: the package sets VALLEY_VERIFICATION_SCHEMA
2631# to the copy it was built with, as the integrator's package does. Only
2632# the-valley's own tree carries schema/, so this script reads the schema
2633# there only when it runs straight from such a checkout with the variable
2634# unset.
2635#
2636# Neither layer is ever the worked example under examples/policy/ — a gate
2637# derived from an example is a gate nobody wrote. `checks` takes an option
2638# for each, so a reader can point it at the example or anywhere else on
2639# purpose; approve takes no such option, because a request is filed
2640# against the policy that governs the project and nowhere else.
2641#
2642# Neither layer is a path in this tree, so policy_defaults leaves both
2643# empty and the two resolvers answer for them. That split is also what
2644# keeps `checks --instance DIR` from fetching a repository whose layer it
2645# was told to ignore, and `checks --project DIR` from reading a tip whose
2646# layer it was told to ignore.
2647POLICY_SCHEMA=""
2648POLICY_INSTANCE=""
2649POLICY_INSTANCE_LABEL=""
2650POLICY_PROJECT=""
2651POLICY_PROJECT_LABEL=""
2652policy_defaults() {
2653 POLICY_SCHEMA="${VALLEY_VERIFICATION_SCHEMA:-$1/schema/verification.cue}"
2654 POLICY_INSTANCE=""
2655 POLICY_INSTANCE_LABEL=""
2656 POLICY_PROJECT=""
2657 POLICY_PROJECT_LABEL=""
2658}
2659
2660# The floor, copied out of a fetch of the owning valley's repository, and
2661# the project's own layer, copied out of the target's tip. Globals, so the
2662# traps clean them up whatever happens.
2663INSTANCE_TMP=""
2664cleanup_instance_tmp() {
2665 [ -n "$INSTANCE_TMP" ] || return 0
2666 rm -rf "$INSTANCE_TMP"
2667 INSTANCE_TMP=""
2668}
2669
2670PROJECT_TMP=""
2671cleanup_project_tmp() {
2672 [ -n "$PROJECT_TMP" ] || return 0
2673 rm -rf "$PROJECT_TMP"
2674 PROJECT_TMP=""
2675}
2676
2677# The directory each layer lives in, the file naming this project's owning
2678# valley, and the ref of that valley whose tip carries the floor. The floor
2679# resolves at the integrated tip, because a floor a project could pin is
2680# not a floor (dcr-f41f718).
2681INSTANCE_DIR=policy/instance
2682PROJECT_DIR=policy/project
2683VALLEY_POINTER=policy/valley
2684VALLEY_POINTER_REF=refs/heads/main
2685
2686# The *.cue documents of one directory at one tree-ish, copied out of a
2687# repository into a directory on disk. Reading a tip with ls-tree and
2688# cat-file rather than checking it out is what lets the layers come from
2689# the target while the checkout stays on whatever branch the reviewer is
2690# on. 0 copied something, 1 the directory holds no *.cue, 2 the read
2691# failed.
2692#
2693# -z because a path may hold anything but NUL, and *.cue because the layer
2694# is the directory's documents — the same reading the composer takes.
2695#
2696# The listing is written out and its status checked before it is read. A
2697# listing read straight from a process substitution that failed reads as a
2698# directory holding nothing, and for the project layer that is the floor
2699# alone: fewer checks required, from a read that never happened. The listing's
2700# name is not a *.cue name, so the composer never reads it.
2701copy_layer() {
2702 local gitdir="$1" treeish="$2" dir="$3" dest="$4" path name copied=0
2703 local listing="$dest/.listing"
2704 git -C "$gitdir" ls-tree --name-only -z "$treeish" "$dir/" > "$listing" \
2705 || return 2
2706 while IFS= read -r -d '' path; do
2707 case "$path" in *.cue) ;; *) continue ;; esac
2708 name="${path##*/}"
2709 git -C "$gitdir" cat-file blob "$treeish:$path" > "$dest/$name" || return 2
2710 copied=1
2711 done < "$listing"
2712 rm -f "$listing"
2713 [ "$copied" -eq 1 ]
2714}
2715
2716# The ref whose tip supplies the policy, printed the way a person names it,
2717# with the commit it stood at. Staleness in a remote-tracking ref is a real
2718# thing to see, so the report says which commit the layers came out of
2719# rather than only which ref. A ref that cannot be read fails, so that no
2720# report names a tip nobody read.
2721target_label() {
2722 local ref="$1" short
2723 short="$(git rev-parse --short "$ref")" || return 1
2724 ref="${ref#refs/remotes/}"
2725 ref="${ref#refs/heads/}"
2726 printf '%s %s' "$ref" "$short"
2727}
2728
2729# Resolve the project's own layer, out of the target's tip, into
2730# POLICY_PROJECT, and set POLICY_PROJECT_LABEL to where it came from.
2731#
2732# A target carrying no layer of its own is derived under the floor alone.
2733# The project layer only ever adds (dcr-f41f718), so the identity of "adds"
2734# is "adds nothing"; refusing instead would make a repository underivable
2735# until its first policy commit, and that commit could not derive either.
2736# This is the integrator's own reading (integrator/policy.go), and the two
2737# have to agree about an absent layer as much as about a present one.
2738#
2739# Absence is answered with a document that adds nothing rather than with an
2740# argument left off, because the composer is handed a directory of *.cue
2741# and has no spelling for "no layer".
2742#
2743# It reports and returns rather than dying, for the reason derive_required
2744# does: a refusal inside the review loop is not the end of the session.
2745resolve_project_layer() {
2746 local root="$1" target="$2" rc at
2747
2748 at="$(target_label "$target")" || {
2749 refuse "could not read $target; nothing derived"
2750 return 1
2751 }
2752 cleanup_project_tmp
2753 PROJECT_TMP="$(mktemp -d)" || {
2754 refuse "no scratch directory to read the project layer into; nothing derived"
2755 return 1
2756 }
2757 copy_layer "$root" "$target" "$PROJECT_DIR" "$PROJECT_TMP" && rc=0 || rc=$?
2758 case "$rc" in
2759 0)
2760 POLICY_PROJECT="$PROJECT_TMP"
2761 POLICY_PROJECT_LABEL="$PROJECT_DIR@$at"
2762 ;;
2763 1)
2764 printf 'package verification\n' > "$PROJECT_TMP/adds-nothing.cue" || {
2765 cleanup_project_tmp
2766 refuse "could not compose an empty project layer; nothing derived"
2767 return 1
2768 }
2769 POLICY_PROJECT="$PROJECT_TMP"
2770 POLICY_PROJECT_LABEL="no $PROJECT_DIR@$at — the floor alone"
2771 ;;
2772 *)
2773 cleanup_project_tmp
2774 refuse "could not read $PROJECT_DIR/ at $at; nothing derived"
2775 return 1
2776 ;;
2777 esac
2778}
2779
2780# The first line of the pointer that is neither blank nor a comment. Read
2781# in the shell so that naming an owning valley needs nothing beyond what
2782# the rest of this script needs.
2783pointer_url() {
2784 local line url=""
2785 while IFS= read -r line || [ -n "$line" ]; do
2786 line="${line%%#*}"
2787 line="${line#"${line%%[![:space:]]*}"}"
2788 line="${line%"${line##*[![:space:]]}"}"
2789 [ -n "$line" ] || continue
2790 url="$line"
2791 break
2792 done < "$1"
2793 printf '%s' "$url"
2794}
2795
2796# Resolve the floor to a directory on disk, into POLICY_INSTANCE, and set
2797# POLICY_INSTANCE_LABEL to where it came from — a temporary directory is
2798# not an answer a reader can check.
2799#
2800# Every project has exactly one owning valley, and the floor is that
2801# valley's (dcr-9b5da04). It is read from the valley's own repository and
2802# never from the project's tree, which is the tree under judgment. Two
2803# shapes, and the first is a special case of the second:
2804#
2805# - a valley's config repository carries policy/instance itself, and is
2806# governed by that floor like every other project. It uses its own,
2807# and fetches nothing.
2808# - every other project names its owning valley at policy/valley. That
2809# repository is fetched into scratch and its policy/instance is read
2810# at the integrated tip. Fetching is all this needs, and anyone the
2811# valley governs necessarily holds fetch on it.
2812#
2813# Both the pointer and a valley's own floor are read from the TARGET's tip
2814# and never from the working tree. The pointer is a file a branch can edit,
2815# so reading it from the branch would let a change name the valley that
2816# gates it; reading it from the checkout would let whoever is reviewing
2817# decide the same thing by accident, which is the failure this fixes. An
2818# absent floor is refused — that is the direction absence defaults in for
2819# this layer, because the floor is the minimum (dcr-f41f718).
2820#
2821# It reports and returns rather than dying, for the reason derive_required
2822# does: a refusal inside the review loop is not the end of the session.
2823resolve_instance_layer() {
2824 local root="$1" target="$2" url bare dest rc at
2825 at="$(target_label "$target")" || {
2826 refuse "could not read $target; nothing derived"
2827 return 1
2828 }
2829 cleanup_instance_tmp
2830 INSTANCE_TMP="$(mktemp -d)" || {
2831 refuse "no scratch directory to read the floor into; nothing derived"
2832 return 1
2833 }
2834 dest="$INSTANCE_TMP/instance"
2835 mkdir -p "$dest"
2836
2837 copy_layer "$root" "$target" "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
2838 case "$rc" in
2839 0)
2840 POLICY_INSTANCE="$dest"
2841 POLICY_INSTANCE_LABEL="$INSTANCE_DIR@$at (this repository is its own valley)"
2842 return 0
2843 ;;
2844 1) ;; # no floor of its own: the pointer names the valley that has one
2845 *)
2846 cleanup_instance_tmp
2847 refuse "could not read $INSTANCE_DIR/ at $at; nothing derived"
2848 return 1
2849 ;;
2850 esac
2851
2852 git -C "$root" cat-file blob "$target:$VALLEY_POINTER" > "$INSTANCE_TMP/pointer" 2> /dev/null || {
2853 cleanup_instance_tmp
2854 refuse "no owning valley: $VALLEY_POINTER names the repository whose $INSTANCE_DIR is this project's floor, and $at carries no such file. A valley's own config repository carries $INSTANCE_DIR instead. Nothing derived"
2855 return 1
2856 }
2857 url="$(pointer_url "$INSTANCE_TMP/pointer")"
2858 [ -n "$url" ] || {
2859 cleanup_instance_tmp
2860 refuse "$VALLEY_POINTER at $at names no repository — it wants one line, the owning valley as git fetch takes it; nothing derived"
2861 return 1
2862 }
2863
2864 bare="$INSTANCE_TMP/valley.git"
2865 git init --quiet --bare "$bare" || {
2866 cleanup_instance_tmp
2867 refuse "no scratch repository to fetch the floor into; nothing derived"
2868 return 1
2869 }
2870 git -C "$bare" fetch --quiet --depth 1 "$url" "$VALLEY_POINTER_REF" || {
2871 cleanup_instance_tmp
2872 refuse "could not fetch the owning valley $url at $VALLEY_POINTER_REF (named by $VALLEY_POINTER at $at); nothing derived"
2873 return 1
2874 }
2875
2876 copy_layer "$bare" FETCH_HEAD "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
2877 case "$rc" in
2878 0) ;;
2879 1)
2880 cleanup_instance_tmp
2881 refuse "the owning valley $url holds no *.cue in $INSTANCE_DIR/ at $VALLEY_POINTER_REF; nothing derived"
2882 return 1
2883 ;;
2884 *)
2885 cleanup_instance_tmp
2886 refuse "could not read $INSTANCE_DIR/ from $url; nothing derived"
2887 return 1
2888 ;;
2889 esac
2890
2891 POLICY_INSTANCE="$dest"
2892 POLICY_INSTANCE_LABEL="$url $INSTANCE_DIR@$VALLEY_POINTER_REF"
2893}
2894
2895# Is this check mandatory in this class, or a default the project left
2896# alone? The bit is the form of the composed value, so the test is CUE's
2897# own: a project supplying `false` either conflicts or unifies cleanly.
2898# Answering by unifying rather than by inspecting syntax means the script
2899# cannot disagree with `cue vet`.
2900#
2901# This is the one producer whose failure does not end the derivation. A
2902# probe that fails for any other reason, or that cannot be written, reads as
2903# mandatory, which is the strict answer, and the bit never changes which
2904# checks are required.
2905check_is_mandatory() {
2906 local class="$1" check="$2" field
2907 if [ "$class" = unclassified ]; then
2908 field="policy: unclassified: \"$check\": false"
2909 else
2910 field="policy: classes: \"$class\": requires: \"$check\": false"
2911 fi
2912 # A probe that could not be written may leave the last one in its place,
2913 # and that one answers for another check. Mandatory is the strict answer.
2914 printf 'package verification\n%s\n' "$field" > "$POLICY_TMP/probe.cue" \
2915 || return 0
2916 ! cue vet "${POLICY_LAYER[@]}" "$POLICY_TMP/probe.cue" > /dev/null 2>&1
2917}
2918
2919# Every side of the diff: an added, modified or deleted path, and both the
2920# old and the new path of a rename or copy. It reads `git diff -z
2921# --name-status` on stdin, because a path may contain anything but NUL, and
2922# fails on a record cut short — including one cut inside its status, which
2923# a plain `while read` would end on quietly, dropping the record. It also
2924# fails when a write fails: the caller runs without `errexit`, so a lost
2925# path would otherwise end in a normal EOF and a status of 0.
2926diff_paths() {
2927 local status path
2928 while IFS= read -r -d '' status || { [ -z "$status" ] || return 1; false; }; do
2929 IFS= read -r -d '' path || return 1
2930 printf '%s\n' "$path" || return 1
2931 case "$status" in
2932 R* | C*)
2933 IFS= read -r -d '' path || return 1
2934 printf '%s\n' "$path" || return 1
2935 ;;
2936 esac
2937 done
2938}
2939
2940# Lines in, one comma-separated line out.
2941join_lines() {
2942 local out="" line
2943 while IFS= read -r line; do out="${out:+$out, }$line"; done
2944 printf '%s' "$out"
2945}
2946
2947# Arguments in, one comma-separated line out, or `none` when there are none.
2948join_or_none() {
2949 if [ $# -eq 0 ]; then echo none; else printf '%s\n' "$@" | join_lines; fi
2950}
2951
2952# The remaining arguments, sorted, into the array the first one names. The
2953# sort is captured and its status returned: a sort read through a process
2954# substitution that fails reads as a sort of nothing, and for a list of
2955# required checks that is a change that requires none.
2956#
2957# The destination is a nameref, so what is assigned is the caller's array,
2958# and the linter cannot see that array being read.
2959# shellcheck disable=SC2034
2960sort_into() {
2961 local -n sort_into_dest="$1"
2962 local sorted
2963 shift
2964 sort_into_dest=()
2965 [ $# -gt 0 ] || return 0
2966 sorted="$(printf '%s\n' "$@" | sort)" || return 1
2967 mapfile -t sort_into_dest <<<"$sorted"
2968}
2969
2970# The target: the ref a change is derived against, and the tip both policy
2971# layers are read out of. origin's answer is preferred, because the target
2972# is the branch as the integrator holds it and not as this checkout last
2973# built it.
2974#
2975# Only a ref that is not there falls through to the next. show-ref says
2976# "not there" with 1 and fails any other way with another status, so a
2977# read of origin's ref that failed ends here: falling through would read
2978# the policy out of the local main, which may be older. 1 no main at all,
2979# 2 a read failed.
2980target_ref() {
2981 local ref rc
2982 for ref in refs/remotes/origin/main refs/heads/main; do
2983 git show-ref --verify --quiet "$ref" && rc=0 || rc=$?
2984 case "$rc" in
2985 0) echo "$ref"; return 0 ;;
2986 1) ;;
2987 *) return 2 ;;
2988 esac
2989 done
2990 return 1
2991}
2992
2993# ----------------------------------------------------------------------
2994# The derivation itself, and the globals it answers with. Everything a
2995# caller could want from the policy comes out of one pass, because every
2996# part of it is a function of the same composition: `checks` prints the
2997# answer, approve runs what it names.
2998#
2999# It reports and returns rather than dying, so that a caller inside the
3000# review loop is refused rather than ended. Its callers are all in a
3001# condition, which suspends `set -e` for the whole call, so every step is
3002# checked by hand.
3003#
3004# Every producer — git, cue, sort — writes a file or a variable, and its
3005# status is checked before anything reads what it wrote. A producer read
3006# through a process substitution loses its status, and a failed one then
3007# reads as an empty list: no changed paths, no catalogue, no classes. Each
3008# of those derives a change that requires nothing, which is the one answer a
3009# failure must never give.
3010DERIVED_PATHS=() # every side of the diff, sorted
3011DERIVED_MATCHED=() # the class names at least one path matched, sorted
3012DERIVED_UNCOVERED=() # the paths no class covered
3013DERIVED_UNCLASSIFIED=0 # whether `unclassified` requires something
3014DERIVED_CARRY="" # the strictest carry mode among the matched classes
3015declare -A DERIVED_REQUIRED=() # check -> the classes that required it
3016declare -A DERIVED_PINNED=() # check -> mandatory | default
3017declare -A CHECK_RUNNER=() # check -> nix | command
3018declare -A CHECK_ATTRIBUTE=() # check -> the flake check attribute
3019declare -A CHECK_COMMAND=() # check -> the command line
3020declare -A CHECK_COST=() # check -> quick | slow
3021
3022derive_required() {
3023 local schema="$1" instance="$2" project="$3" base="$4" head="$5"
3024
3025 need_cue
3026 [ -f "$schema" ] || {
3027 refuse "no policy schema at $schema; nothing derived"
3028 return 1
3029 }
3030 # An unmatched glob stays literal, so the first entry is a real file
3031 # exactly when the directory holds a document.
3032 local -a instance_docs=("$instance"/*.cue) project_docs=("$project"/*.cue)
3033 [ -f "${instance_docs[0]}" ] || {
3034 refuse "no instance policy layer at $instance; nothing derived"
3035 return 1
3036 }
3037 [ -f "${project_docs[0]}" ] || {
3038 refuse "no project policy layer at $project: a project's own layer is the *.cue documents under $PROJECT_DIR/ (dcr-f41f718). Nothing derived"
3039 return 1
3040 }
3041
3042 cleanup_policy_tmp
3043 POLICY_LAYER=("$schema" "${instance_docs[@]}" "${project_docs[@]}")
3044 POLICY_TMP="$(mktemp -d)" || {
3045 refuse "no scratch directory to compose the policy in; nothing derived"
3046 return 1
3047 }
3048
3049 git diff --no-relative --name-status -M -z "$base" "$head" > "$POLICY_TMP/diff" || {
3050 refuse "could not diff $base..$head; nothing derived"
3051 return 1
3052 }
3053 diff_paths < "$POLICY_TMP/diff" > "$POLICY_TMP/paths" || {
3054 refuse "truncated diff output; nothing derived"
3055 return 1
3056 }
3057 sort -u "$POLICY_TMP/paths" > "$POLICY_TMP/paths.sorted" || {
3058 refuse "could not sort the changed paths; nothing derived"
3059 return 1
3060 }
3061 DERIVED_PATHS=()
3062 mapfile -t DERIVED_PATHS < "$POLICY_TMP/paths.sorted"
3063
3064 render_cue > "$POLICY_TMP/render.cue" || {
3065 refuse "could not write the policy render; nothing derived"
3066 return 1
3067 }
3068 cue vet -c "${POLICY_LAYER[@]}" || {
3069 refuse "the policy layers do not compose; nothing derived"
3070 return 1
3071 }
3072
3073 # The render is checked before it is read. A render that fails prints
3074 # nothing, and an empty render reads as a policy that requires nothing. A
3075 # schema older than this script fails it, by lacking a field it reads. So
3076 # does a policy string holding a control character, which a schema that
3077 # admits one lets through.
3078 cue eval --out text -e _render "${POLICY_LAYER[@]}" "$POLICY_TMP/render.cue" \
3079 > "$POLICY_TMP/rendered" || {
3080 refuse "the composed policy does not render (a schema older than this script, and a policy string holding a control character, are two causes); nothing derived"
3081 return 1
3082 }
3083 # Sorted once here, so every list below comes out in a stable order.
3084 sort "$POLICY_TMP/rendered" > "$POLICY_TMP/rendered.sorted" || {
3085 refuse "could not sort the composed policy; nothing derived"
3086 return 1
3087 }
3088 local -a rendered=()
3089 mapfile -t rendered < "$POLICY_TMP/rendered.sorted"
3090
3091 unset CHECK_RUNNER CHECK_ATTRIBUTE CHECK_COMMAND CHECK_COST DERIVED_REQUIRED \
3092 DERIVED_PINNED
3093 declare -gA CHECK_RUNNER=() CHECK_ATTRIBUTE=() CHECK_COMMAND=() \
3094 CHECK_COST=() DERIVED_REQUIRED=() DERIVED_PINNED=()
3095
3096 # The middle field is a class name for a coverage or requirement line and
3097 # a check name for a catalogue one; `key` is what both are.
3098 #
3099 # The render states each thing once: a class has one carry mode, a check
3100 # one runner, and a class requires a check once. A second line for the
3101 # same thing is forged, and a reader that took the last one would let the
3102 # forgery win, so it is refused. A coverage or requirement line is one
3103 # member of a set, so it is identified by its value too.
3104 local -a pat_class=() pat_ere=() req_class=() req_check=()
3105 local -A class_carry=() seen=()
3106 local line kind key value id
3107 for line in "${rendered[@]}"; do
3108 kind="${line%%$'\t'*}"
3109 key="${line#*$'\t'}"
3110 value="${key#*$'\t'}"
3111 key="${key%%$'\t'*}"
3112 case "$kind" in
3113 path | requires) id="$kind $key $value" ;;
3114 *) id="$kind $key" ;;
3115 esac
3116 [ -z "${seen[$id]:-}" ] || {
3117 refuse "the composed policy rendered '$id' twice, and states each thing once; nothing derived"
3118 return 1
3119 }
3120 seen["$id"]=1
3121 case "$kind" in
3122 path)
3123 pat_class+=("$key")
3124 pat_ere+=("$(glob_ere "$value")")
3125 ;;
3126 requires)
3127 req_class+=("$key")
3128 req_check+=("$value")
3129 ;;
3130 carry) class_carry["$key"]="$value" ;;
3131 runner) CHECK_RUNNER["$key"]="$value" ;;
3132 attribute) CHECK_ATTRIBUTE["$key"]="$value" ;;
3133 command) CHECK_COMMAND["$key"]="$value" ;;
3134 cost) CHECK_COST["$key"]="$value" ;;
3135 esac
3136 done
3137
3138 # A pattern bash cannot compile answers 2, not 1. Read as "no match", it
3139 # would drop the pattern's class from every change it covers.
3140 local -A matched=()
3141 local path i hit rc
3142 DERIVED_UNCOVERED=()
3143 for path in "${DERIVED_PATHS[@]}"; do
3144 hit=0
3145 for ((i = 0; i < ${#pat_ere[@]}; i++)); do
3146 [[ "$path" =~ ${pat_ere[i]} ]] && rc=0 || rc=$?
3147 case "$rc" in
3148 0)
3149 matched["${pat_class[i]}"]=1
3150 hit=1
3151 ;;
3152 1) ;;
3153 *)
3154 refuse "class ${pat_class[i]} has a path pattern that does not compile (${pat_ere[i]}); nothing derived"
3155 return 1
3156 ;;
3157 esac
3158 done
3159 [ "$hit" -eq 1 ] || DERIVED_UNCOVERED+=("$path")
3160 done
3161
3162 # The change's carry mode: the strictest among the classes its paths
3163 # matched, each as the schema resolved it. It is taken before
3164 # `unclassified` joins the matched classes, because an unclassified path
3165 # is same-paths and can make no change stricter. A matched class with no
3166 # mode this script knows is refused rather than read as the loosest.
3167 local class
3168 DERIVED_CARRY=same-paths
3169 for class in "${!matched[@]}"; do
3170 case "${class_carry[$class]:-}" in
3171 exact) DERIVED_CARRY=exact ;;
3172 same-class) [ "$DERIVED_CARRY" = exact ] || DERIVED_CARRY=same-class ;;
3173 same-paths) ;;
3174 *)
3175 refuse "class $class has no carry mode this script knows ('${class_carry[$class]:-}'); nothing derived"
3176 return 1
3177 ;;
3178 esac
3179 done
3180
3181 # A path no class covers is answered by the policy's `unclassified` set,
3182 # which is why it is treated as one more matched class rather than as an
3183 # absence.
3184 [ "${#DERIVED_UNCOVERED[@]}" -eq 0 ] || matched[unclassified]=1
3185
3186 local check
3187 DERIVED_UNCLASSIFIED=0
3188 for ((i = 0; i < ${#req_check[@]}; i++)); do
3189 key="${req_class[i]}"
3190 check="${req_check[i]}"
3191 [ -n "${matched[$key]:-}" ] || continue
3192 [ "$key" != unclassified ] || DERIVED_UNCLASSIFIED=1
3193 DERIVED_REQUIRED["$check"]="${DERIVED_REQUIRED[$check]:+${DERIVED_REQUIRED[$check]}, }$key"
3194 if check_is_mandatory "$key" "$check"; then
3195 DERIVED_PINNED["$check"]=mandatory
3196 else
3197 DERIVED_PINNED["$check"]="${DERIVED_PINNED[$check]:-default}"
3198 fi
3199 done
3200
3201 sort_into DERIVED_MATCHED "${!matched[@]}" || {
3202 refuse "could not sort the matched classes; nothing derived"
3203 return 1
3204 }
3205}
3206
3207cmd_checks() {
3208 local root schema instance="" label project="" plabel base head target=""
3209 local names=0 cost="" costed=0 short_base short_head
3210 root="$(git rev-parse --show-toplevel 2> /dev/null)" \
3211 || die "not a git repository"
3212 policy_defaults "$root"
3213 schema="$POLICY_SCHEMA"
3214 while [ $# -gt 0 ]; do
3215 case "$1" in
3216 --schema) [ $# -ge 2 ] || die "--schema needs a file"; schema="$2"; shift 2 ;;
3217 --instance) [ $# -ge 2 ] || die "--instance needs a directory"; instance="$2"; shift 2 ;;
3218 --project) [ $# -ge 2 ] || die "--project needs a directory"; project="$2"; shift 2 ;;
3219 --names) names=1; shift ;;
3220 --cost) [ $# -ge 2 ] || die "--cost needs quick or slow"; cost="$2"; costed=1; shift 2 ;;
3221 --) shift; break ;;
3222 -*) die "unknown option: $1" ;;
3223 *) break ;;
3224 esac
3225 done
3226 [ $# -le 2 ] || die "usage: valley checks [options] [<base> [<head>]]"
3227 if [ "$costed" -eq 1 ]; then
3228 case "$cost" in
3229 quick | slow) ;;
3230 *) die "--cost takes quick or slow, not '$cost'" ;;
3231 esac
3232 [ "$names" -eq 1 ] || die "--cost filters the --names list; pass --names too"
3233 fi
3234
3235 head="$(git rev-parse --verify --quiet "${2:-HEAD}^{commit}")" \
3236 || die "no such commit: ${2:-HEAD}"
3237 # The target is what the layers are read out of, so it is needed whenever
3238 # either layer is left to its default — and it is what an unnamed base
3239 # is the merge base with.
3240 if [ -z "$instance" ] || [ -z "$project" ] || [ $# -lt 1 ]; then
3241 target="$(target_ref)" || {
3242 [ $? -eq 1 ] || die "could not read the main branch; nothing derived"
3243 die "no main branch: the target's tip is where the policy layers are read from, and there is none here"
3244 }
3245 fi
3246 if [ $# -ge 1 ]; then
3247 base="$(git rev-parse --verify --quiet "$1^{commit}")" \
3248 || die "no such commit: $1"
3249 else
3250 base="$(git merge-base "$target" "$head")" \
3251 || die "$head and ${target#refs/} do not share history — name a base"
3252 fi
3253
3254 trap 'cleanup_policy_tmp; cleanup_instance_tmp; cleanup_project_tmp' EXIT
3255 # Each layer is resolved only when nobody named one. --instance and
3256 # --project are a reader pointing this at a layer on purpose, and
3257 # honouring that means not fetching the repository, and not reading the
3258 # tip, that the named layer replaced.
3259 if [ -n "$instance" ]; then
3260 label="${instance#"$root"/}"
3261 else
3262 resolve_instance_layer "$root" "$target" || exit 1
3263 instance="$POLICY_INSTANCE"
3264 label="$POLICY_INSTANCE_LABEL"
3265 fi
3266 if [ -n "$project" ]; then
3267 plabel="${project#"$root"/}"
3268 else
3269 resolve_project_layer "$root" "$target" || exit 1
3270 project="$POLICY_PROJECT"
3271 plabel="$POLICY_PROJECT_LABEL"
3272 fi
3273 derive_required "$schema" "$instance" "$project" "$base" "$head" || exit 1
3274
3275 # The required checks, sorted, and grouped by the cost the policy
3276 # declares. The grouping changes nothing required: approve runs every
3277 # required check, and the integrator requires evidence for every one,
3278 # whatever it costs.
3279 local check width=0
3280 local -a required=() quick=() slow=() listed=()
3281 sort_into required "${!DERIVED_REQUIRED[@]}" \
3282 || die "could not sort the required checks; nothing derived"
3283 for check in "${required[@]}"; do
3284 [ "${#check}" -le "$width" ] || width="${#check}"
3285 if [ "${CHECK_COST[$check]}" = slow ]; then
3286 slow+=("$check")
3287 else
3288 quick+=("$check")
3289 fi
3290 done
3291
3292 # The form for agents and scripts: the names alone, one per line.
3293 if [ "$names" -eq 1 ]; then
3294 case "$cost" in
3295 quick) listed=("${quick[@]}") ;;
3296 slow) listed=("${slow[@]}") ;;
3297 *) listed=("${required[@]}") ;;
3298 esac
3299 [ "${#listed[@]}" -eq 0 ] || printf '%s\n' "${listed[@]}"
3300 return
3301 fi
3302
3303 # Read before the first line is printed, so a read that fails leaves no
3304 # partial report behind.
3305 short_base="$(git rev-parse --short "$base")" \
3306 || die "could not read $base; nothing derived"
3307 short_head="$(git rev-parse --short "$head")" \
3308 || die "could not read $head; nothing derived"
3309
3310 printf '%s..%s: %d changed path(s)\n' "$short_base" "$short_head" \
3311 "${#DERIVED_PATHS[@]}"
3312 printf 'policy: %s + %s\n' "$label" "$plabel"
3313 if [ "${#DERIVED_MATCHED[@]}" -eq 0 ]; then
3314 printf 'classes matched: none\n'
3315 else
3316 printf 'classes matched: %s\n' \
3317 "$(printf '%s\n' "${DERIVED_MATCHED[@]}" | join_lines)"
3318 fi
3319 # How far an approval of this change carries across a rebase. Nothing
3320 # here acts on it.
3321 printf 'carry mode: %s\n\n' "$DERIVED_CARRY"
3322
3323 if [ "${#DERIVED_REQUIRED[@]}" -eq 0 ]; then
3324 echo "required checks: none"
3325 else
3326 echo "required checks:"
3327 for check in "${required[@]}"; do
3328 printf ' %-*s %-9s %s\n' \
3329 "$width" "$check" "${DERIVED_PINNED[$check]}" "${DERIVED_REQUIRED[$check]}"
3330 done
3331 fi
3332
3333 if [ "${#DERIVED_UNCOVERED[@]}" -gt 0 ]; then
3334 printf '\nunclassified: %d path(s) matched no class\n' "${#DERIVED_UNCOVERED[@]}"
3335 printf ' %s\n' "${DERIVED_UNCOVERED[@]}"
3336 # The failure the `unclassified` field exists to prevent: paths outside
3337 # every class that the policy then asks nothing of.
3338 [ "$DERIVED_UNCLASSIFIED" -eq 1 ] \
3339 || echo " the policy requires nothing of them — it is behind the tree"
3340 fi
3341
3342 # Below every line the integrator reads (integrator/policy.go), and
3343 # unindented, so neither line can read as a required check.
3344 if [ "${#required[@]}" -gt 0 ]; then
3345 printf '\nquick: %s\n' "$(join_or_none "${quick[@]}")"
3346 printf 'slow: %s\n' "$(join_or_none "${slow[@]}")"
3347 fi
3348}
3349
3350# self-update installs the tip of a branch of the-valley into the user's
3351# nix profile (status/selfupdate.go). It is told this valley's stamp, which
3352# says what is installed until it has installed something itself.
3353cmd_self_update() {
3354 export VALLEY_VERSION="$VALLEY_STAMP"
3355 cmd_go self-update "$@"
3356}
3357
3358cmd_version() {
3359 printf 'valley %s\n' "${VALLEY_STAMP:-unstamped (run from a checkout, not built by nix)}"
3360}
3361
3362cmd_help() {
3363 case "${1:-}" in
3364 self-update) cmd_go self-update --help ;;
3365 *) usage ;;
3366 esac
3367}
3368
3369main() {
3370 local verb="${1:-help}"
3371 if [ $# -gt 0 ]; then shift; fi
3372 # The verb set is mirrored in completions/ (valley.bash, _valley) —
3373 # update both when it changes.
3374 case "$verb" in
3375 pending) cmd_pending "$@" ;;
3376 review) cmd_review "$@" ;;
3377 approve) cmd_approve "$@" ;;
3378 rebase) cmd_rebase "$@" ;;
3379 status | ready | unready | withdraw | changes | knot | plan) cmd_go "$verb" "$@" ;;
3380 checks) cmd_checks "$@" ;;
3381 tail) cmd_tail "$@" ;;
3382 replay) cmd_replay "$@" ;;
3383 self-update) cmd_self_update "$@" ;;
3384 --version) cmd_version ;;
3385 help | -h | --help) cmd_help "$@" ;;
3386 *)
3387 printf 'valley: unknown verb: %s\n\n' "$verb" >&2
3388 usage >&2
3389 exit 1
3390 ;;
3391 esac
3392}
3393
3394main "$@"