gunk-dev/the-valley

valley

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