gunk-dev/the-valley

valley

source4f191e3f6ec1main's published tip history
94.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 owed; 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
44die() {
45 printf 'valley: %s\n' "$*" >&2
46 exit 1
47}
48
49usage() {
50 cat <<'EOF'
51valley — S1 integrator verbs for a valley project
52
53usage: valley <verb> [args]
54
55 pending list branches on origin not merged into origin/main,
56 one line each: branch | head subject | age | author |
57 ahead N | diffstat. then, under drafts, the changes
58 whose record says they are drafts, one line each, the
59 same way, for the head of the active version: handle
60 and version, and the branch the version names. a branch
61 at a draft's head is listed only there. drafts need the
62 valley-go helper.
63 review <change> page through the change's branch: its log and diff vs
64 origin/main. then choose:
65 [a]pprove file an integration request. runs the
66 checks the composed policy requires of
67 this change over a throwaway worktree of
68 the branch, signs each result as an
69 attestation, and publishes the evidence
70 and the request ref to origin in ONE
71 atomic push. this files the request;
72 it does not wait for integration or
73 update your local checkout. use status
74 to read the result. the policy comes
75 from the target's tip and the owning
76 valley's, as checks describes below,
77 so your checkout
78 can be on any branch. a change the policy
79 requires no check of is filed too, as a
80 request with no evidence, and says so.
81 approving a change already requested is
82 how it is filed again. at a head rebased
83 onto a moved main it replaces the request
84 ref under a lease and names the head it
85 replaced; at the same head it leaves the
86 ref alone and publishes only the new
87 evidence, which the create-only
88 attestation namespace refuses when this
89 signer has already attested that tree
90 (bd-7b7d58f). every write of the request
91 ref is leased, filing included, so an
92 approval that lost a race is refused
93 rather than clobbering the one that won.
94 needs the attest helper and
95 VALLEY_ATTEST_KEY, the ed25519 key this
96 host signs with, whenever a check is
97 owed; VALLEY_ATTEST_NAME is the name it
98 signs under, defaulting to this host's.
99 [r]eject delete the remote branch (confirmed first)
100 [s]kip do nothing
101 when [a]pprove's checks fail, the prompt says approving
102 needs a new head and stops offering [a]pprove until the
103 change has one. any other refusal keeps the prompt as
104 it was.
105 [a]pprove is the only way a change reaches main from
106 here, and approve below is the same act without the
107 pager.
108 Nothing in this script writes the protected ref: the
109 integrator does, having judged the request.
110 a stale branch (won't fast-forward from main) is first
111 offered:
112 [b]ase rebase it onto origin/main in a throwaway
113 worktree, push --force-with-lease, then
114 re-review the diff that would actually land
115 [a]pprove is offered there too: a stale branch is nothing
116 the integrator cannot apply, so it need not be rebased
117 first.
118 while paging, press v: less opens the diff in $EDITOR.
119 every line you insert there is a note. it is anchored to
120 the file and new-side line it sits on — to the file alone
121 when it sits above the first hunk — then appended to
122 $XDG_STATE_HOME/valley/notes/<branch>.md (default
123 ~/.local/state) and printed after the verdict. notes
124 survive [b]ase. lines you change or delete instead of
125 inserting are ignored, with a warning.
126 approve <change> do what review's [a]pprove does for the change, without
127 paging it: the same checks, the same refusals, the same
128 leased request write and the same output. exits non-zero
129 when it refuses.
130 rebase <change> do what review's [b]ase does for the change: rebase it
131 onto origin/main in a throwaway worktree and push it
132 with --force-with-lease, then print its new head. it
133 does not re-review the result. a change that already
134 fast-forwards from main is left as it is.
135 status [--json] <change>
136 read the request and the integrator's last decision from
137 origin. distinguish waiting, a decision that needs
138 attention, and a change integrated into origin/main.
139 after integration, show how to update the local checkout.
140 fetches objects without moving local branches or files;
141 no checks run and no request is filed.
142 --json print the status as one JSON object,
143 valley-status/v1, for front ends to read
144 (docs/architecture.md). an error prints
145 no object: it goes to stderr and the exit
146 status is non-zero.
147 needs the valley-go helper.
148 ready [--head <sha>] [--change <id>] [--stamp] [<branch>]
149 mark a head of the branch ready, as a new version of its
150 change, in the change's record on origin:
151 refs/the-valley/changes/main/<change id>. the branch
152 defaults to the current one. the head is --head, or else
153 origin/<branch>, and it must be on origin already. the
154 first ready of a change makes v1; each later one adds
155 the next version, at a head other than the active
156 version's. a draft or a withdrawn change comes back this
157 way: at the active version's head, it is ready again at
158 that version, and at another head it gains the next
159 version. prints the handle and version, e.g.
160 `cosmo nxvp v2 ready`.
161 the change id is --change, else the head commit's jj
162 change-id header, else a Change-Id: trailer in its
163 message, else a new one, which is printed. a header and
164 a trailer that disagree are refused. so is a change
165 whose commits from its merge base with origin/main hold
166 a merge, or that has more than one merge base.
167 --stamp amend the head of your local branch to
168 carry the id as a Change-Id: trailer and
169 push the branch, leased, before marking it
170 ready. it only starts a new change: it
171 is refused for a change that has a
172 record on origin already, and for a head
173 already on origin.
174 the record names the principal your key pushes as, read
175 from git config valley.principal; the host refuses one
176 naming anyone else. the record ref is pushed leased on
177 the value read. a new change is owned by the principal
178 that readies it, and a later version may come from its
179 owner or the operator, who holds the request grant.
180 records are observational: nothing reads them for
181 authority, and approve is still the only way to main.
182 needs the valley-go helper.
183 unready <change>
184 make a ready change a draft in its record on origin, as
185 its owner or the operator. a draft is a pause: it voids
186 nothing, and approvals of its active version stand when
187 it is readied again. ready brings it back. prints e.g.
188 `cosmo nxvp v2 draft`. needs the valley-go helper.
189 withdraw <change>
190 mark a ready change or a draft withdrawn in its record
191 on origin, as its owner or the operator. withdrawing
192 voids everything outstanding on the change: its
193 integration requests, and the approvals and reviews of
194 every version, so a change brought back needs fresh
195 approvals. ready brings it back, at the same version
196 or a new one. prints e.g. `cosmo nxvp v2 withdrawn`.
197 needs the valley-go helper.
198 the integrator does not read records yet, so neither
199 unready nor withdraw stops a pending integration
200 request from landing the change. each warns when origin
201 holds one, under the branch-derived name or c-<change
202 id>: only a holder of the request grant may touch a
203 request ref, so the operator must drop it.
204 checks [<base> [<head>]]
205 print the check names the change between two commits owes
206 under the composed verification policy (dcr-f41f718), and
207 which class made each one required. It prints: no check is
208 run, nothing is gated, nothing is written.
209 base defaults to the merge base with main, head to HEAD.
210 by default both layers come from the target's tip
211 (origin/main), never from your checkout: the project's
212 own layer is policy/project there, and the owning valley
213 is named one line at policy/valley there, fetched and
214 read at policy/instance in that repository's integrated
215 tip. a valley's own config repository carries
216 policy/instance and uses it. a target carrying no
217 policy/project is derived under the floor alone; a floor
218 that is not there is refused. this is what the
219 integrator reads, so the answer is the same from any
220 branch, however stale. an option overrides each layer,
221 which is the only way to derive against a layer that
222 does not govern — the worked example under
223 examples/policy/, say:
224 --schema FILE default $VALLEY_VERIFICATION_SCHEMA
225 --instance DIR default the owning valley's floor
226 --project DIR default policy/project at the target
227 naming a layer stops this reading the source it
228 replaced. the schema is the shape a policy is written
229 in rather than a layer, so it ships with this tool: the
230 package sets VALLEY_VERIFICATION_SCHEMA to its own copy.
231 with that unset, as when this script runs straight from
232 a the-valley checkout, it is schema/verification.cue in
233 the checkout.
234 after the report, two lines group the owed checks by
235 the cost the policy declares, `quick` or `slow`. a slow
236 check takes minutes or needs special hardware. the cost
237 changes nothing owed: approving runs every owed check
238 whatever its cost, and the integrator requires evidence
239 for every one.
240 --names print only the owed check names,
241 one per line
242 --cost COST with --names, only the quick or
243 the slow ones, e.g.
244 `valley checks --names --cost slow`
245 tail [subject] watch bus events scroll by (default subject: valley.>);
246 the server comes from the nats CLI's own config
247 (NATS_URL or a nats context; default localhost)
248 replay [dir] publish one ref-updated event per current ref of the
249 repo at dir (default: .) — rebuilds the stream's
250 projection, e.g. after nats stream purge valley
251 help show this help
252
253A change is named by its full change id, by its handle — the shortest
254prefix of the id, four letters at least, that no other change recorded on
255origin shares — or by its branch. A name written origin/<branch> is always
256a branch. A handle that is also a branch on origin is refused unless the
257change is on that branch. review, approve and rebase read a branch name,
258written either way, against every record on origin: when exactly one
259record's active version is on the branch, the name is that change, as if
260its id were given, and when more than one's is, the verb refuses and lists
261their ids. A branch no record's active version is on is acted on as a
262branch. A change with a record is reviewed, approved and rebased at the
263head its active version records, never at its branch's tip: review shows
264that head, and approve, rebase and review's [r]eject refuse, naming both,
265when the branch's tip on origin is another commit. [r]eject deletes the
266branch under a lease on the recorded head. approve, rebase, and review's
267[a]pprove and [b]ase refuse a change whose record is not ready, naming
268its state. Each reads the record again just before it acts, and again
269before approve files or rebase pushes, and refuses when the change is no
270longer ready or its active version has moved to another head since the
271verb began.
272
273Runs from any checkout of the project; needs only git and coreutils,
274except tail and replay, which also need the nats CLI (natscli), checks,
275which also needs the cue CLI, review's notes, which need less, approve
276and review's [a]pprove, which need both the cue CLI and the attest
277helper, and status, ready, unready, withdraw, review, approve and rebase,
278which need the valley-go helper, as pending does for drafts.
279nix run .#valley bundles all of them. Deriving a policy fetches the owning
280valley's repository, so checks and approving also need whatever reaching
281it takes.
282No config but valley.principal, which ready reads; no batch mode; and no
283state but the notes file — the judgment stays with the human.
284EOF
285}
286
287fetch_origin() {
288 git fetch --prune --quiet origin
289}
290
291# Resolve the pager as git would for a diff: pager.diff first (per-command
292# pager configs — e.g. home-manager's delta module — set pager.diff and leave
293# core.pager alone), then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER,
294# less). pager.<cmd> may legally be a boolean; treat true/false — and an
295# empty or missing value — as unset and fall back. The value is
296# shell-interpreted, hence sh -c.
297diff_pager() {
298 local pager
299 pager="$(git config --get pager.diff || true)"
300 case "$pager" in '' | true | false) pager="$(git var GIT_PAGER)" ;; esac
301 printf '%s' "$pager"
302}
303
304# Page a file rather than a pipe, so less's v key has something to hand
305# $EDITOR: with a real file open, v runs LESSEDIT, whose default
306# `%E ?lm+%lm. %g` is the editor, +<line>, and the file name. That file is
307# the review buffer, and editing it is how notes get written (see
308# collect_notes). A pipe has no name, so less refuses to edit one — which is
309# why review no longer pipes.
310#
311# The configured diff pager stays the renderer, but as less's input
312# preprocessor rather than as the pager. It still reads the buffer on stdin
313# exactly as it did when it was the pager, less displays what it emits, and
314# less still calls the raw buffer "the current file" — so v edits the diff
315# and not the rendering. The alternative was to page the buffer with no
316# filter at all: exact, and it throws delta's rendering away, which is the
317# worse trade for a verb whose whole job is reading a diff.
318#
319# What this costs is the line number. A filter that restructures the diff —
320# delta's default rendering does — makes %lm a line of the rendered view, so
321# the editor opens near the cursor rather than on it. A structure-preserving
322# filter (pager.diff = `delta --color-only`) makes it exact. No anchor
323# depends on it: a note is anchored by where it was inserted, not by where
324# the editor opened.
325page_file() {
326 local file="$1" pager
327 [ -t 1 ] || { cat -- "$file"; return; } # a non-tty just cats
328 pager="$(diff_pager)"
329 case "${pager%%[[:space:]]*}" in
330 less | */less)
331 # Already less: give it the file and there is no filter to run.
332 sh -c "$pager \"\$1\"" sh "$file"
333 return
334 ;;
335 esac
336 # Without less there is no editor key; fall back to filtering into a pipe.
337 command -v less > /dev/null 2>&1 || {
338 sh -c "$pager" < "$file"
339 return
340 }
341 # -R because the filter's color is the whole point of running it, and no
342 # LESSCLOSE because a stray one would run against a buffer we still read.
343 LESSOPEN="|$pager < %s" env -u LESSCLOSE less -R -- "$file"
344}
345
346# One line of pending: the label, then the subject, age, author, distance
347# from main and diffstat of the commit named.
348pending_line() {
349 local label="$1" ref="$2" subject age author ahead stat
350 subject="$(git log -1 --format='%s' "$ref")"
351 [ "${#subject}" -le 60 ] || subject="${subject:0:57}..."
352 age="$(git log -1 --format='%cr' "$ref")"
353 author="$(git log -1 --format='%an' "$ref")"
354 ahead="$(git rev-list --count "origin/main..$ref")"
355 stat="$(git diff --shortstat "origin/main...$ref")"
356 stat="${stat# }"
357 printf '%s | %s | %s | %s | ahead %s | %s\n' \
358 "$label" "$subject" "$age" "$author" "$ahead" "${stat:-no file changes}"
359}
360
361# pending lists the branches on origin not merged into main. With the
362# helper, it also lists the changes whose record says they are drafts, in
363# a section of their own, each at the head of its active version. A branch
364# whose tip is a draft's head is that draft, and is listed with it rather
365# than among the branches.
366cmd_pending() {
367 [ $# -eq 0 ] || die "pending takes no arguments"
368 fetch_origin
369 local ref line handle version head branch found=0
370 local -a drafts=()
371 local -A drafted=()
372 if command -v valley-go > /dev/null 2>&1; then
373 line="$(valley-go drafts)" || exit 1
374 [ -z "$line" ] || mapfile -t drafts <<< "$line"
375 fi
376 for line in ${drafts[@]+"${drafts[@]}"}; do
377 IFS=$'\t' read -r handle version head branch <<< "$line"
378 if [ -n "$branch" ] \
379 && [ "$(git rev-parse --verify --quiet "refs/remotes/origin/$branch")" = "$head" ]; then
380 drafted["origin/$branch"]=1
381 fi
382 done
383 while IFS= read -r ref; do
384 case "$ref" in
385 origin/HEAD | origin/main) continue ;;
386 esac
387 [ -z "${drafted[$ref]:-}" ] || continue
388 found=1
389 pending_line "${ref#origin/}" "$ref"
390 done < <(git for-each-ref --format='%(refname:short)' \
391 --no-merged=origin/main refs/remotes/origin)
392 [ "$found" -eq 1 ] || echo "nothing pending"
393 [ "${#drafts[@]}" -gt 0 ] || return 0
394 printf '\ndrafts\n'
395 for line in "${drafts[@]}"; do
396 IFS=$'\t' read -r handle version head branch <<< "$line"
397 pending_line "$handle v$version${branch:+ on $branch}" "$head"
398 done
399}
400
401# For a change with a record, what is rejected is the head its record
402# names. So the branch is deleted only while its tip is that head, and the
403# delete is leased on it. When the tip is another commit, reject refuses
404# and names both, and deletes nothing. A branch no record names is deleted
405# as before.
406#
407# reject runs inside a condition, where bash suspends `set -e`, so the push
408# is checked by hand.
409reject() {
410 local branch="$1" answer
411 local -a lease=()
412 if [ -n "$CHANGE_HEAD" ]; then
413 check_recorded_tip "$branch" "nothing deleted" || return 1
414 lease=("--force-with-lease=refs/heads/$branch:$CHANGE_HEAD")
415 fi
416 printf 'really delete origin/%s? [y/N] ' "$branch"
417 read -r answer || answer=""
418 case "$answer" in
419 y | Y | yes)
420 if ! git push --quiet "${lease[@]}" origin --delete "$branch"; then
421 refuse "origin did not delete $branch, which may have moved since the fetch; nothing deleted"
422 return 1
423 fi
424 echo "rejected $branch: deleted from origin"
425 ;;
426 *) echo "kept $branch" ;;
427 esac
428}
429
430# ----------------------------------------------------------------------
431# review notes — the lines the reviewer inserts into the paged diff.
432#
433# The buffer the reviewer pages is a file, so the pager's editor key can open
434# it (page_file). Whatever comes back with lines inserted is read as notes:
435# no marker, no syntax, no mode — an inserted line is a note because it was
436# not there before. What a note is *about* is where it sits, so each one is
437# anchored to the file and the new-side line number of the diff line above
438# it, which is the pair a reviewer would otherwise have to copy out by hand.
439
440# The scratch directory holding the buffer and its pristine copy, and the
441# notes taken so far in this review — a global because [b]ase pages a second
442# time and the notes from the first pass are not thereby withdrawn.
443REVIEW_TMP=""
444NOTES=()
445
446cleanup_review_tmp() {
447 [ -n "$REVIEW_TMP" ] || return 0
448 rm -rf "$REVIEW_TMP"
449 REVIEW_TMP=""
450}
451
452# Where a branch's notes live. XDG_STATE_HOME is the right home for them:
453# they are neither config nor cache, and losing them loses judgment.
454notes_file() {
455 printf '%s/valley/notes/%s.md\n' "${XDG_STATE_HOME:-$HOME/.local/state}" "$1"
456}
457
458# The anchor of every line of the buffer, by line: the file that line belongs
459# to, and the new-side line number it sits on. Built in one pass so that
460# anchoring a note is a lookup. An empty path means the line is above every
461# file (the log); line 0 means the line is a file header, above every hunk.
462ANCHOR_PATH=()
463ANCHOR_LINE=()
464
465anchor_buffer() {
466 local file="$1" line path="" at=0 next=0 inhunk=0 rest
467 ANCHOR_PATH=()
468 ANCHOR_LINE=()
469 while IFS= read -r line; do
470 # Header lines are only headers outside a hunk: inside one, every line
471 # carries a +/-/space prefix, so a diff of a diff cannot be misread.
472 if [ "$inhunk" -eq 1 ]; then
473 case "$line" in
474 ' '* | '+'* | '')
475 at="$next" # this line's own new-side number
476 next=$((next + 1))
477 ;;
478 '-'* | \\*) ;; # a removal or the no-newline marker: no new-side line
479 *) inhunk=0 ;;
480 esac
481 fi
482 if [ "$inhunk" -eq 0 ]; then
483 case "$line" in
484 'diff --git '*)
485 path=""
486 # The b/ side, so a rename anchors to the name it will have.
487 if [[ "$line" =~ ^diff\ --git\ a/(.*)\ b/(.*)$ ]]; then
488 path="${BASH_REMATCH[2]}"
489 fi
490 at=0
491 ;;
492 '@@ '*)
493 rest="${line#*+}" # -12,7 +34,9 @@ -> 34,9 @@
494 at="${rest%%[!0-9]*}"
495 [ -n "$at" ] || at=0
496 next="$at"
497 inhunk=1
498 ;;
499 esac
500 fi
501 ANCHOR_PATH+=("$path")
502 ANCHOR_LINE+=("$at")
503 done < "$file"
504}
505
506# The anchor for a note inserted after buffer line n, as it is written down.
507anchor_of() {
508 local n="$1" path line
509 [ "$n" -ge 1 ] || { printf '(unanchored)'; return; }
510 path="${ANCHOR_PATH[n - 1]:-}"
511 line="${ANCHOR_LINE[n - 1]:-0}"
512 if [ -z "$path" ]; then
513 printf '(unanchored)'
514 elif [ "$line" -eq 0 ]; then
515 printf '%s' "$path"
516 else
517 printf '%s:%s' "$path" "$line"
518 fi
519}
520
521# The notes in an edited buffer, one `anchor: text` line each. git says where
522# the reviewer's lines landed; a hunk that removes nothing is an insertion,
523# and the line it was inserted after is the anchor. A hunk that removes
524# something is an edit of the diff itself — it anchors to nothing, since the
525# line it would name is the line it changed — so it is dropped with a count.
526notes_in() {
527 local orig="$1" edited="$2" line rest at old insert=0 touched=0 text
528 anchor_buffer "$orig"
529 while IFS= read -r line; do
530 case "$line" in
531 '@@ '*)
532 rest="${line#@@ -}" # 12,0 +13,2 @@ -> 12,0 +13,2 @@
533 at="${rest%%[!0-9]*}"
534 rest="${rest#"$at"}"
535 old=1
536 case "$rest" in
537 ,*)
538 rest="${rest#,}"
539 old="${rest%%[!0-9]*}"
540 ;;
541 esac
542 if [ "$old" -eq 0 ]; then
543 insert=1
544 else
545 insert=0
546 touched=$((touched + old))
547 fi
548 ;;
549 '+'*)
550 # Only inside an insertion hunk: the +++ of git's own header is not
551 # a note, and neither is the new side of an edit.
552 [ "$insert" -eq 1 ] || continue
553 text="${line#+}"
554 text="${text#"${text%%[![:space:]]*}"}"
555 [ -n "$text" ] || continue # a blank line says nothing
556 printf '%s: %s\n' "$(anchor_of "$at")" "$text"
557 ;;
558 esac
559 done < <(git --no-pager diff --no-ext-diff --no-index -U0 -- "$orig" "$edited")
560 [ "$touched" -eq 0 ] || printf \
561 'valley: warning: %d changed or deleted diff line(s) ignored — a note is a line you insert\n' \
562 "$touched" >&2
563}
564
565# Read the notes out of the paged buffer and keep them: appended to the
566# branch's notes file under the commit they were taken against, and held for
567# the print that follows the verdict. A notes file that cannot be written is
568# a warning, never a failure — the notes are still printed, and a review is
569# not undone by a missing directory.
570collect_notes() {
571 local branch="$1" sha="$2" file dir
572 local -a found=()
573 mapfile -t found < <(notes_in "$REVIEW_TMP/review.orig" "$REVIEW_TMP/review.diff")
574 [ "${#found[@]}" -gt 0 ] || return 0
575 NOTES+=("${found[@]}")
576 file="$(notes_file "$branch")"
577 dir="${file%/*}"
578 mkdir -p "$dir" 2> /dev/null && {
579 printf '## %s at %s\n\n' "$branch" "$sha"
580 printf '%s\n' "${found[@]}"
581 printf '\n'
582 } >> "$file" 2> /dev/null && return 0
583 printf 'valley: warning: could not write %s — the notes are printed only\n' \
584 "$file" >&2
585}
586
587print_notes() {
588 local branch="$1"
589 [ "${#NOTES[@]}" -gt 0 ] || return 0
590 printf '\n%d note(s) on %s, appended to %s:\n' \
591 "${#NOTES[@]}" "$branch" "$(notes_file "$branch")"
592 printf ' %s\n' "${NOTES[@]}"
593}
594
595show_review() {
596 local branch="$1" head sha
597 head="$(change_head "$branch")"
598 sha="$(git rev-parse --short "$head")"
599 REVIEW_TMP="$(mktemp -d)"
600 {
601 if [ -n "$CHANGE_HEAD" ]; then
602 printf 'change %s v%s at %s, on branch %s, log against origin/main:\n\n' \
603 "$CHANGE_HANDLE" "$CHANGE_VERSION" "$sha" "$branch"
604 else
605 printf 'branch %s, log against origin/main:\n\n' "$branch"
606 fi
607 git --no-pager log --oneline "origin/main..$head"
608 printf '\n'
609 git --no-pager diff "origin/main...$head"
610 } > "$REVIEW_TMP/review.diff"
611 cp "$REVIEW_TMP/review.diff" "$REVIEW_TMP/review.orig"
612 page_file "$REVIEW_TMP/review.diff" || true # quitting the pager early is not an error
613 collect_notes "$branch" "$sha"
614 cleanup_review_tmp
615}
616
617# Throwaway worktree for review's [b]ase choice; a global so the traps can
618# always clean it up — success, conflict, or ctrl-C. Never a mid-rebase state.
619REBASE_WT=""
620cleanup_rebase_wt() {
621 [ -n "$REBASE_WT" ] || return 0
622 git -C "$REBASE_WT" rebase --abort >/dev/null 2>&1 || true
623 git worktree remove --force "$REBASE_WT" >/dev/null 2>&1 || true
624 rm -rf "$REBASE_WT"
625 REBASE_WT=""
626}
627
628# Everything review, approve and rebase leave outside the repository: the
629# two throwaway worktrees, the paged buffer, the two policy layers read out
630# of their tips, and the scratch the policy deriver writes into. One
631# handler, installed once by each of those verbs, so that no path through
632# them — and no ctrl-C in the pager — leaves any of them behind.
633cleanup_scratch() {
634 cleanup_rebase_wt
635 cleanup_approve_wt
636 cleanup_policy_tmp
637 cleanup_instance_tmp
638 cleanup_project_tmp
639 cleanup_review_tmp
640}
641
642# Rebase origin/<branch> onto origin/main in an isolated worktree — the
643# user's checkout is never touched — and push with a lease so a concurrently
644# updated branch is never clobbered. Mechanics only; the judgment on the
645# rebased diff stays with the human, back at the review prompt or in
646# whatever front end ran the rebase verb.
647#
648# Every step is checked by hand rather than left to `set -e`, because
649# rebase_change runs this inside a condition, where bash suspends `set -e`
650# for the whole call. An unchecked step that failed there would leave
651# REBASE_WT empty, and `git -C ""` would rebase and push the user's own
652# checkout.
653#
654# The commit rebased is the second argument when given, the head a change's
655# record names, and otherwise origin/<branch> as the fetch left it. It is
656# read once, and the push is leased on exactly that commit, so a fetch that
657# moves origin/<branch> meanwhile changes neither.
658rebase_onto_main() {
659 local branch="$1" from="${2:-}" rebased
660 if [ -z "$from" ]; then
661 from="$(git rev-parse --verify --quiet "refs/remotes/origin/$branch^{commit}")" \
662 || die "no such branch on origin: $branch; nothing changed"
663 fi
664 REBASE_WT="$(mktemp -d)" && [ -d "$REBASE_WT" ] || {
665 REBASE_WT=""
666 die "could not make a directory for the rebase; nothing changed"
667 }
668 git worktree add --quiet --detach "$REBASE_WT" "$from" || {
669 cleanup_rebase_wt
670 die "could not check out origin/$branch for the rebase; nothing changed"
671 }
672 if ! git -C "$REBASE_WT" rebase --quiet refs/remotes/origin/main; then
673 cleanup_rebase_wt
674 die "$branch conflicts with main — resolve by hand; nothing changed"
675 fi
676 rebased="$(git -C "$REBASE_WT" rev-parse HEAD)" || {
677 cleanup_rebase_wt
678 die "could not read the rebased head of $branch; nothing pushed"
679 }
680 # A change with a record is read once more, just before the push.
681 if ! check_record "nothing pushed"; then
682 cleanup_rebase_wt
683 exit 1
684 fi
685 if ! git -C "$REBASE_WT" push --quiet "--force-with-lease=refs/heads/$branch:$from" \
686 origin "HEAD:refs/heads/$branch"; then
687 cleanup_rebase_wt
688 die "lease on origin/$branch failed (it moved since the fetch); nothing pushed"
689 fi
690 cleanup_rebase_wt
691 echo "rebased $branch onto origin/main, pushed with --force-with-lease"
692 printf ' head %s\n' "$rebased"
693}
694
695# ----------------------------------------------------------------------
696# approve — file an integration request for the branch under review.
697#
698# This is the one way a change reaches main from here: the checks the
699# policy requires are run over the branch's tree and signed, the evidence
700# and one request ref are published, and the integrator judges the request
701# and lands it (archive/design/integration.md). main is never touched from here.
702#
703# Nothing in this script writes the protected ref. Whether a given pusher
704# may write it is a fact about origin's pre-receive hook, so origin is
705# where it is answered, and a verb that merged onto main locally would only
706# be asking the same question in a worse place.
707#
708# What this verb removes is a second push. `attest run --push` publishes
709# the branch and the attestation refs in one atomic push and knows nothing
710# about a request ref, so filing a request by hand is two beats: the
711# evidence, then the request after it. In between, evidence stands
712# published for a change nobody has approved. So this verb does not
713# use --push at all. `attest run` without it stores each note at its ref in
714# the repository and stops, and one `git push --atomic` then carries the
715# evidence and the request together — all of it or none of it. Nothing in
716# attest had to change for that; the sequencing was the whole of it.
717#
718# The branch itself is not in that push. What is under review is
719# origin/<branch>, so the commit the request names is already on origin and
720# the objects with it.
721
722# The tree the checks run over: a throwaway worktree of the branch, as
723# [b]ase uses, so that what is checked is the branch's tree and not the
724# operator's working copy. A global, so the traps clean it up whatever
725# happens.
726APPROVE_WT=""
727# The head approve last ran the checks over and saw them fail, for the
728# review prompt: see approve_failed_at.
729CHECKS_FAILED_AT=""
730cleanup_approve_wt() {
731 [ -n "$APPROVE_WT" ] || return 0
732 git worktree remove --force "$APPROVE_WT" > /dev/null 2>&1 || true
733 rm -rf "$APPROVE_WT"
734 APPROVE_WT=""
735}
736
737# Report and fail, without leaving the review. A refusal here is not a
738# reason to end the session: the branch is still under review and the
739# operator can still answer. die() is for the verbs that have nothing left
740# to offer. The approve verb has nothing left to offer either, and turns a
741# refusal into its exit status itself.
742refuse() {
743 printf 'valley: %s\n' "$*" >&2
744 return 1
745}
746
747# The change segment of a request ref. The integrator reads a request as
748# <prefix>/<target>/<change> and refuses a change segment holding a slash
749# (integrator/refs.go), so a branch name with one is written with dashes
750# instead. The ref that results is printed, never left to be assumed.
751#
752# The mapping is lossy: `topic/x` and `topic-x` are one change name and so
753# one request ref, and this verb cannot tell a sibling's request from its
754# own. That is bd-57f7f9f, and what is done about it here is to print the
755# subject of any request being replaced, so a collision is visible at the
756# moment it happens rather than after it.
757change_name() {
758 printf '%s' "${1//\//-}"
759}
760
761# One line of a commit, for saying which commit is meant. A request being
762# replaced is usually this operator's own pre-rebase head and so is in
763# this repository; one another operator filed may not be, and saying so is
764# better than printing an id alone.
765subject_of() {
766 local s
767 if s="$(git log -1 --format=%s "$1" 2>/dev/null)" && [ -n "$s" ]; then
768 printf '%s' "$s"
769 else
770 printf 'subject not in this repository'
771 fi
772}
773
774# The value of a ref on origin, as one id or the empty string. Failing to
775# read it is not the same as reading that it is absent, so the two are
776# separate answers: this returns 1 for a read that did not happen.
777remote_ref() {
778 local out
779 out="$(git ls-remote origin "$1" 2>/dev/null)" || return 1
780 printf '%s' "$out" | cut -f1
781 return 0
782}
783
784# Where the checks this run signed are stored, for every failure that
785# happens after they have run. One stanza, so no failure path invents its
786# own wording. Called with no refs it says nothing.
787report_local_evidence() {
788 [ "$#" -gt 0 ] || return 0
789 printf 'valley: the evidence is stored locally at:\n' >&2
790 printf ' %s\n' "$@" >&2
791}
792
793# Whether origin already holds one of these attestation refs at a value
794# other than the one being pushed. The namespace admits creations only, so
795# that is the one refusal approving again will never clear: it is what a
796# re-observation of a tree this signer has already attested runs into
797# (bd-7b7d58f).
798attestation_stands_elsewhere() {
799 local digest="$1" remote spec have want
800 shift
801 remote="$(git ls-remote origin "refs/the-valley/attestations/$digest/*" 2>/dev/null)" || return 1
802 for spec in "$@"; do
803 have="$(printf '%s\n' "$remote" | awk -v r="$spec" '$2 == r { print $1 }')"
804 [ -n "$have" ] || continue
805 want="$(git rev-parse "$spec" 2>/dev/null)" || continue
806 [ "$have" = "$want" ] || return 0
807 done
808 return 1
809}
810
811# Why a push carrying the request ref failed, said as precisely as the
812# state allows. Every such push is leased, and a lease refuses when the
813# ref it named is not where the read before it saw it — which covers three
814# different events. Reading the ref again is what tells them apart, and a
815# read that does not happen is its own answer rather than a guess.
816#
817# Anything the lease is not responsible for is origin's own refusal, and
818# git has already printed it.
819diagnose_request_push() {
820 local ref="$1" pending="$2" now
821 if ! now="$(remote_ref "$ref")"; then
822 refuse "origin refused the push, and $ref could not be read again to say why. Nothing was published there and main is untouched"
823 return 0
824 fi
825 if [ "$now" = "$pending" ]; then
826 refuse "origin refused the push; nothing was published there and main is untouched"
827 elif [ -z "$now" ]; then
828 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"
829 elif [ -z "$pending" ]; then
830 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"
831 else
832 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"
833 fi
834}
835
836# File the request. Called in a condition, from the review prompt and from
837# the approve verb alike, which suspends `set -e` for the whole call — so
838# every step below is checked by hand, and the failures say what was
839# published before they happened.
840approve() {
841 local branch="$1" target=main tip change head base digest root ref check spec
842 local key
843 local -a signer=() owed=() run=() evidence=()
844
845 root="$(git rev-parse --show-toplevel)" || {
846 refuse "not a git repository; nothing published"
847 return 1
848 }
849 tip=refs/remotes/origin/main
850 head="$(git rev-parse "refs/remotes/origin/$branch")" || {
851 refuse "no such branch on origin: $branch; nothing published"
852 return 1
853 }
854 # A change with a record is filed only while its record says it is
855 # ready, at the head its record names, and only while its branch is there
856 # too.
857 if [ -n "$CHANGE_HEAD" ]; then
858 check_record "nothing published" || return 1
859 check_recorded_tip "$branch" "nothing published" || return 1
860 head="$CHANGE_HEAD"
861 fi
862 base="$(git merge-base "$tip" "$head")" || {
863 refuse "$branch and main share no history; nothing published"
864 return 1
865 }
866 change="$(change_name "$branch")"
867 ref="refs/the-valley/integration-requests/$target/$change"
868
869 # What the change owes, read out of exactly the sources the integrator
870 # reads: both layers from the target's tip, which review has just
871 # fetched, and the floor from the owning valley's own tip. A change never
872 # supplies the policy that gates it, and neither does the checkout this
873 # runs from — so the answer here is the same answer the integrator will
874 # derive, from whatever branch the operator happens to be on. It is
875 # printed for exactly that reason.
876 policy_defaults "$root"
877 resolve_instance_layer "$root" "$tip" || return 1
878 resolve_project_layer "$root" "$tip" || return 1
879 derive_owed "$POLICY_SCHEMA" "$POLICY_INSTANCE" "$POLICY_PROJECT" \
880 "$base" "$head" || return 1
881 sort_into owed "${!DERIVED_OWED[@]}" || {
882 refuse "could not sort the owed checks; nothing published"
883 return 1
884 }
885
886 # A change the policy asks nothing of is still a change, and approving
887 # is how one reaches main. The integrator already lands a request owing no
888 # check and records the landing as one that required nothing
889 # (archive/design/integration.md), so refusing to file it here would strand
890 # exactly the changes the policy requires nothing of. Nothing is owed, so
891 # nothing is signed and no key is needed: what gets published is one
892 # request ref and no evidence at all.
893 if [ "${#owed[@]}" -gt 0 ]; then
894 key="${VALLEY_ATTEST_KEY:-}"
895 [ -n "$key" ] || {
896 refuse "no signing key: set VALLEY_ATTEST_KEY to the ed25519 key this host attests with. The host signs; nothing published"
897 return 1
898 }
899 [ -f "$key" ] || {
900 refuse "no signing key at $key; nothing published"
901 return 1
902 }
903 command -v attest > /dev/null 2>&1 || {
904 refuse "this choice needs the attest helper; nix run .#valley bundles it. Nothing published"
905 return 1
906 }
907 signer=(--key "$key")
908 [ -z "${VALLEY_ATTEST_NAME:-}" ] || signer+=(--name "$VALLEY_ATTEST_NAME")
909
910 for check in "${owed[@]}"; do
911 case "${CHECK_RUNNER[$check]:-}" in
912 nix) run+=(--check "$check=${CHECK_ATTRIBUTE[$check]}") ;;
913 command) run+=(--command "$check=${CHECK_COMMAND[$check]}") ;;
914 *)
915 refuse "the policy requires $check but does not say how to run it; nothing published"
916 return 1
917 ;;
918 esac
919 done
920
921 cleanup_approve_wt
922 APPROVE_WT="$(mktemp -d)" || {
923 refuse "no scratch directory to check $branch in; nothing published"
924 return 1
925 }
926 git worktree add --quiet --detach "$APPROVE_WT" "$head" || {
927 cleanup_approve_wt
928 refuse "could not check $branch out to run its checks; nothing published"
929 return 1
930 }
931
932 printf '\nchecking %s at %s: %s\n' "$branch" "$(git rev-parse --short "$head")" \
933 "$(printf '%s\n' "${owed[@]}" | join_lines)"
934 if ! attest run --repo "$APPROVE_WT" "${signer[@]}" "${run[@]}"; then
935 cleanup_approve_wt
936 CHECKS_FAILED_AT="$head"
937 refuse "the checks did not pass; nothing published, main untouched"
938 return 1
939 fi
940 digest="$(attest digest --repo "$APPROVE_WT")" || {
941 cleanup_approve_wt
942 refuse "could not digest the tree that was checked; nothing published"
943 return 1
944 }
945 cleanup_approve_wt
946 digest="${digest#*:}"
947
948 # Every attestation stored for this tree, whoever signed it: the
949 # evidence for this change is what the subject digest is keyed by, not
950 # what this run happened to add to it.
951 mapfile -t evidence < <(git for-each-ref --format='%(refname)' \
952 "refs/the-valley/attestations/$digest")
953 [ "${#evidence[@]}" -gt 0 ] || {
954 refuse "no attestation is stored for $digest; nothing published"
955 return 1
956 }
957 else
958 printf '\n%s owes no check under %s + %s; filing the request with no evidence\n' \
959 "$branch" "$POLICY_INSTANCE_LABEL" "$POLICY_PROJECT_LABEL"
960 fi
961
962 # What origin already holds for this request, read once and remembered.
963 # Approving the same change twice is ordinary: evidence expires, and a
964 # change whose input closure moved under it is told to re-attest. So the
965 # request ref may already exist, and what to do about it depends on
966 # where it points. A read that does not happen is not a read that found
967 # nothing, so it ends the verb here.
968 local pending
969 if ! pending="$(remote_ref "$ref")"; then
970 refuse "could not read $ref from origin; nothing published"
971 report_local_evidence ${evidence[@]+"${evidence[@]}"}
972 return 1
973 fi
974
975 # The one push: every evidence ref as it stands, and the request ref
976 # wherever it has to go. --atomic, so a hook that refuses any of them
977 # leaves origin exactly as it was.
978 #
979 # Every write of the request ref is leased against exactly what the read
980 # above saw, including when it saw nothing: git spells that expectation
981 # `--force-with-lease=<ref>:` with an empty value, and it refuses if the
982 # ref exists at all. So filing a change for the first time is a
983 # compare-and-swap too. Without it, two operators filing one change at
984 # once would have the second silently fast-forward the first away.
985 #
986 # A pending request at this same head is a re-attestation of the tree
987 # already approved. The evidence is new and the ref does not move, so
988 # the ref is left out of the refspec entirely — a push cannot carry a
989 # compare-and-swap on a ref it is not changing, because git leaves an
990 # up-to-date ref out of what it sends. Nothing this run does establishes
991 # where that ref stands afterwards, so it is read again below.
992 #
993 # A pending request at a different head is a replacement. This is the
994 # shape a change takes when main moved through its checks' input
995 # closures: no attestation over the old tree can transfer again, so the
996 # cure is a new head rebased onto the moved main — and that head is not
997 # a descendant of the old one, which makes replacing the ref a
998 # non-fast-forward update that git refuses unless told.
999 #
1000 # The lease is the whole of the force, and the refspec carries no `+`.
1001 # A leading `+` sets git's per-ref force flag, and that flag defeats
1002 # every rejection the push rules produce — the lease's stale-info among
1003 # them. The two together are a plain force wearing a lease's name.
1004 local -a push=() lease=()
1005 for spec in ${evidence[@]+"${evidence[@]}"}; do push+=("$spec:$spec"); done
1006 if [ "$pending" != "$head" ]; then
1007 lease+=("--force-with-lease=$ref:$pending")
1008 push+=("$head:$ref")
1009 fi
1010
1011 # The checks can take minutes, and the record may have moved meanwhile.
1012 # So it is read once more, just before anything is filed.
1013 if ! check_record "nothing published"; then
1014 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1015 return 1
1016 fi
1017
1018 # Nothing owed and the request already standing at this head leaves
1019 # nothing to push at all, and a push assembled with an empty refspec
1020 # would fall back to origin's default one. So none is made.
1021 local made_push=no
1022 if [ "${#push[@]}" -gt 0 ]; then
1023 made_push=yes
1024 if ! git push --atomic --quiet ${lease[@]+"${lease[@]}"} origin "${push[@]}"; then
1025 if [ "${#lease[@]}" -eq 0 ] \
1026 && attestation_stands_elsewhere "$digest" ${evidence[@]+"${evidence[@]}"}; then
1027 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"
1028 else
1029 diagnose_request_push "$ref" "$pending"
1030 fi
1031 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1032 return 1
1033 fi
1034 fi
1035
1036 # The lines under the request line, which differ by what was found and
1037 # what was done about it.
1038 local -a standing=()
1039
1040 if [ "$pending" = "$head" ]; then
1041 # The request ref was not in that push, so where it stands now is not
1042 # something this run established. Read it again rather than repeat
1043 # what was read before it: in between, the integrator may have landed
1044 # the change and consumed the ref, or another approval may have
1045 # replaced it.
1046 #
1047 # Nothing here writes it back. Re-creating a consumed request would
1048 # file a change already in the stream, which the commit rule calls out
1049 # as the state it consumes the ref to avoid; replacing a request
1050 # another approval has just filed would clobber the winner; and
1051 # either would be a second push behind the one this verb promises. So
1052 # what this does is say what is true and stop. Approving again is the
1053 # repair, and by then it takes the create or the replace path against
1054 # what is actually there.
1055 local after
1056 if ! after="$(remote_ref "$ref")"; then
1057 refuse "$ref could not be read again, so whether the request still stands at this head is not known here"
1058 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1059 return 1
1060 fi
1061 if [ -z "$after" ]; then
1062 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 $branch again, and approve it once more if it has not landed"
1063 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1064 return 1
1065 fi
1066 if [ "$after" != "$head" ]; then
1067 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"
1068 report_local_evidence ${evidence[@]+"${evidence[@]}"}
1069 return 1
1070 fi
1071 if [ "$made_push" = yes ]; then
1072 standing+=("the request already stood at this head; the evidence is what was published")
1073 else
1074 standing+=("the request already stood at this head and nothing was owed, so nothing needed publishing")
1075 fi
1076 elif [ -n "$pending" ]; then
1077 standing+=("replaced the pending request, which stood at $(git rev-parse --short "$pending") ($(subject_of "$pending"))")
1078 fi
1079
1080 printf '\nApproved %s (%s): its integration request for origin/%s is filed.\n' \
1081 "$branch" "$(git rev-parse --short "$head")" "$target"
1082 printf 'The integrator will decide whether this change can land.\n'
1083 printf 'Your local checkout has not changed.\n\n'
1084 printf 'Check the result: valley status %q\n\n' "$branch"
1085 printf ' request %s -> %s\n' "$ref" "$(git rev-parse --short "$head")"
1086 [ "${#standing[@]}" -eq 0 ] || printf ' %s\n' "${standing[@]}"
1087 if [ "${#evidence[@]}" -eq 0 ]; then
1088 printf ' evidence none — nothing was owed, so nothing was signed\n'
1089 printf ' checks none — the policy requires no check of this change\n'
1090 else
1091 printf ' evidence %s\n' "${evidence[@]}"
1092 printf ' checks %s\n' "$(printf '%s\n' "${owed[@]}" | join_lines)"
1093 fi
1094}
1095
1096# status, ready, unready and withdraw are a Go program, valley-go
1097# (status/). status reads a change's request and outcome from origin,
1098# because what front ends read from it is a JSON contract, and because the
1099# read is subtle enough to want a real parser: an outcome record it does
1100# not recognise must read as unknown, never as success. It writes nothing
1101# and moves no local branch. ready, unready and withdraw write a change's
1102# record, in the one format the push hook reads it in (change/).
1103cmd_go() {
1104 command -v valley-go > /dev/null 2>&1 \
1105 || die "$1 needs the valley-go helper; nix run .#valley bundles it"
1106 exec valley-go "$@"
1107}
1108
1109# A change is named by its full change ID, its handle, or its branch.
1110# resolve_change reads the name with the helper and sets CHANGE_BRANCH, the
1111# branch to act on. When the name is a change's, it also sets the change's
1112# ID, handle, active version and state, and CHANGE_HEAD, the head that
1113# version records. A branch name is a change's when exactly one record's
1114# active version is on that branch, and is refused when more than one's is.
1115# So whether a change's record is read never depends on how it is named,
1116# and review, approve and rebase cannot run without the helper.
1117#
1118# A change with a record is acted on at CHANGE_HEAD, and never at the
1119# branch's tip. The branch a record names is only where its head is
1120# expected to be, and anyone who can push the branch can move it, in the
1121# same push as the record if they like.
1122CHANGE_ID="" CHANGE_HANDLE="" CHANGE_VERSION="" CHANGE_HEAD="" CHANGE_BRANCH="" CHANGE_STATE=""
1123resolve_change() {
1124 local line kind
1125 command -v valley-go > /dev/null 2>&1 \
1126 || die "review, approve and rebase read the change's record with the valley-go helper; nix run .#valley bundles it"
1127 line="$(valley-go resolve "$1")" || return 1
1128 IFS=$'\t' read -r kind CHANGE_ID CHANGE_HANDLE CHANGE_VERSION CHANGE_HEAD CHANGE_BRANCH CHANGE_STATE <<< "$line"
1129 case "$kind" in
1130 branch)
1131 CHANGE_BRANCH="$CHANGE_ID"
1132 CHANGE_ID=""
1133 ;;
1134 change)
1135 [[ "$CHANGE_HEAD" =~ ^[0-9a-f]{40}$ ]] \
1136 || die "valley-go resolve named the head $CHANGE_HEAD, which is no object ID"
1137 case "$CHANGE_STATE" in
1138 ready | draft | withdrawn) ;;
1139 *) die "valley-go resolve named the state $CHANGE_STATE, which this script does not read" ;;
1140 esac
1141 ;;
1142 *) die "valley-go resolve answered $line, which this script does not read" ;;
1143 esac
1144}
1145
1146# The commit review, approve and rebase act on: the recorded head for a
1147# change with a record, and otherwise the branch's head on origin.
1148change_head() {
1149 if [ -n "$CHANGE_HEAD" ]; then
1150 printf '%s\n' "$CHANGE_HEAD"
1151 else
1152 git rev-parse "refs/remotes/origin/$1"
1153 fi
1154}
1155
1156# For a change with a record, refuse unless the branch's tip on origin is
1157# the recorded head, and name both. Acting on the branch would
1158# act on a commit no version records; acting on the recorded head while the
1159# branch is elsewhere would file or rebase something the branch no longer
1160# says. The second argument is what the refusal leaves undone.
1161check_recorded_tip() {
1162 local branch="$1" undone="$2" tip
1163 [ -n "$CHANGE_HEAD" ] || return 0
1164 tip="$(git rev-parse "refs/remotes/origin/$branch")" || {
1165 refuse "no such branch on origin: $branch; $undone"
1166 return 1
1167 }
1168 [ "$tip" = "$CHANGE_HEAD" ] && return 0
1169 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"
1170}
1171
1172# For a change with a record, read the record again from origin, and
1173# refuse unless the change is still ready at the head this run began with.
1174# A draft is paused and a withdrawn change given up, and neither is
1175# approved or rebased until it is readied again. The record was read when
1176# review, approve or rebase began, and another principal may unready,
1177# withdraw or ready a new version of the change while a review is open or
1178# the checks run. So approve reads it again before it runs the checks and
1179# before it files, and rebase before it starts and before it pushes. Until
1180# the integrator reads records, nothing on origin makes this check. The
1181# argument is what the refusal leaves undone.
1182check_record() {
1183 [ -n "$CHANGE_ID" ] || return 0
1184 local line kind id handle version head branch state
1185 if ! line="$(valley-go resolve "$CHANGE_ID")"; then
1186 refuse "could not read the record of change $CHANGE_HANDLE again; $1"
1187 return 1
1188 fi
1189 IFS=$'\t' read -r kind id handle version head branch state <<< "$line"
1190 if [ "$kind" != change ] || [ "$id" != "$CHANGE_ID" ]; then
1191 refuse "origin no longer holds a record of change $CHANGE_HANDLE; $1"
1192 return 1
1193 fi
1194 if [ "$state" != ready ]; then
1195 refuse "change $CHANGE_HANDLE v$version is $state, not ready; $1. Ready it first: valley ready --change $CHANGE_ID $(printf '%q' "$branch")"
1196 return 1
1197 fi
1198 if [ "$head" != "$CHANGE_HEAD" ]; then
1199 refuse "change $CHANGE_HANDLE is at v$version, $head, and this run began at v$CHANGE_VERSION, $CHANGE_HEAD; $1. Review it again at its new head"
1200 return 1
1201 fi
1202}
1203
1204# rebase for a change with a record rebases the recorded head alone, so
1205# the branch must still be at it. The rebased head is a commit no version
1206# records, so the change is readied again before its handle names it.
1207rebase_change() {
1208 local branch="$1"
1209 check_record "nothing rebased" || return 1
1210 check_recorded_tip "$branch" "nothing rebased" || return 1
1211 rebase_onto_main "$branch" "$CHANGE_HEAD"
1212 if [ -n "$CHANGE_HEAD" ]; then
1213 printf 'No version of %s records the rebased head yet. Record it: valley ready --change %s %q\n' \
1214 "$CHANGE_HANDLE" "$CHANGE_ID" "$branch"
1215 fi
1216}
1217
1218# The head the checks failed at in this review, short, while the change is
1219# still at it. Approving that head again would run the same checks over
1220# the same tree and fail the same way, so the prompt stops offering
1221# [a]pprove until the change has a new head. Fails when the checks have
1222# not failed at the head the change is at.
1223approve_failed_at() {
1224 if [ -z "$CHECKS_FAILED_AT" ] || [ "$CHECKS_FAILED_AT" != "$(change_head "$1")" ]; then
1225 return 1
1226 fi
1227 git rev-parse --short "$CHECKS_FAILED_AT"
1228}
1229
1230# Page the branch and take the verdict. Split out of cmd_review so that
1231# every way out of it — approve, reject, skip — is followed by the notes.
1232read_and_decide() {
1233 local branch="$1" choice failed answers
1234 show_review "$branch"
1235 # A stale branch's pre-rebase diff is not what would land; offer to rebase it
1236 # mechanically, then re-review what actually would. [a]pprove is offered
1237 # here as well, because the integrator applies a delta to the tip rather
1238 # than fast-forwarding: a stale branch is a request it can judge, and
1239 # rebasing first is a convenience rather than a precondition.
1240 while ! git merge-base --is-ancestor refs/remotes/origin/main \
1241 "$(change_head "$branch")"; do
1242 if failed="$(approve_failed_at "$branch")"; then
1243 printf '%s does not fast-forward from main. Its checks failed at %s, so approving needs a new head: [b]ase onto main, [r]eject, [s]kip? ' \
1244 "$branch" "$failed"
1245 answers="b, r, or s"
1246 else
1247 printf '%s does not fast-forward from main: [a]pprove, [b]ase onto main, [r]eject, [s]kip? ' \
1248 "$branch"
1249 answers="a, b, r, or s"
1250 fi
1251 read -r choice || die "stdin closed before an answer; nothing done"
1252 case "$choice" in
1253 a)
1254 if [ -n "$failed" ]; then
1255 echo "answer $answers"
1256 elif approve "$branch"; then
1257 return
1258 fi
1259 ;;
1260 b)
1261 # The rebased head of a change named by its handle is no version
1262 # of it yet, so there is nothing more to review by that handle.
1263 if [ -n "$CHANGE_HEAD" ]; then
1264 rebase_change "$branch" && return
1265 else
1266 rebase_onto_main "$branch"
1267 fetch_origin
1268 show_review "$branch"
1269 fi
1270 ;;
1271 r) reject "$branch" && return ;;
1272 s)
1273 echo "skipped $branch; nothing done"
1274 return
1275 ;;
1276 *) echo "answer $answers" ;;
1277 esac
1278 done
1279 while true; do
1280 if failed="$(approve_failed_at "$branch")"; then
1281 printf '%s: its checks failed at %s, so approving needs a new head: [r]eject, [s]kip? ' \
1282 "$branch" "$failed"
1283 answers="r or s"
1284 else
1285 printf '%s: [a]pprove, [r]eject, [s]kip? ' "$branch"
1286 answers="a, r, or s"
1287 fi
1288 read -r choice || die "stdin closed before an answer; nothing done"
1289 case "$choice" in
1290 # A refusal from approve is not a verdict: it says what it did not do
1291 # and the prompt comes back, so the branch can still be rejected or
1292 # skipped. When the checks failed, approving the same head again is
1293 # no longer offered.
1294 a)
1295 if [ -n "$failed" ]; then
1296 echo "answer $answers"
1297 elif approve "$branch"; then
1298 return
1299 fi
1300 ;;
1301 r) reject "$branch" && return ;;
1302 s)
1303 echo "skipped $branch; nothing done"
1304 return
1305 ;;
1306 *) echo "answer $answers" ;;
1307 esac
1308 done
1309}
1310
1311cmd_review() {
1312 [ $# -eq 1 ] || die "usage: valley review <change>"
1313 resolve_change "$1" || exit 1
1314 local branch="$CHANGE_BRANCH"
1315 fetch_origin
1316 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
1317 || die "no such branch on origin: $branch"
1318 trap cleanup_scratch EXIT
1319 trap 'exit 130' INT TERM
1320 read_and_decide "$branch"
1321 # The verdict disposes of the branch; the notes are what the human made of
1322 # it, so they are printed whatever the verdict was.
1323 print_notes "$branch"
1324}
1325
1326# approve and rebase are review's [a]pprove and [b]ase without the pager,
1327# for a front end that has shown the change its own way. Each runs the
1328# function its key runs, so the verb and the key cannot drift apart. A
1329# change is named as resolve_change reads it.
1330cmd_approve() {
1331 [ $# -eq 1 ] || die "usage: valley approve <change>"
1332 resolve_change "$1" || exit 1
1333 local branch="$CHANGE_BRANCH"
1334 fetch_origin
1335 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
1336 || die "no such branch on origin: $branch"
1337 trap cleanup_scratch EXIT
1338 trap 'exit 130' INT TERM
1339 # In a condition, as the review prompt calls it: approve checks each of
1340 # its own steps, and has already said why when it refuses.
1341 approve "$branch" || exit 1
1342}
1343
1344cmd_rebase() {
1345 [ $# -eq 1 ] || die "usage: valley rebase <change>"
1346 resolve_change "$1" || exit 1
1347 local branch="$CHANGE_BRANCH"
1348 fetch_origin
1349 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
1350 || die "no such branch on origin: $branch"
1351 check_record "nothing rebased" || exit 1
1352 check_recorded_tip "$branch" "nothing rebased" || exit 1
1353 # review offers [b]ase only to a stale branch. One that fast-forwards
1354 # already is left alone, rather than rewritten for nothing.
1355 if git merge-base --is-ancestor refs/remotes/origin/main \
1356 "refs/remotes/origin/$branch"; then
1357 echo "$branch already fast-forwards from origin/main; nothing rebased"
1358 printf ' head %s\n' "$(git rev-parse "refs/remotes/origin/$branch")"
1359 return
1360 fi
1361 trap cleanup_scratch EXIT
1362 trap 'exit 130' INT TERM
1363 rebase_change "$branch" || exit 1
1364}
1365
1366# tail and replay are thin wrappers over the nats CLI — anything they do,
1367# plain nats and git can do. They are the only verbs needing more than git
1368# and coreutils.
1369need_nats() {
1370 command -v nats >/dev/null 2>&1 \
1371 || die "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
1372}
1373
1374cmd_tail() {
1375 [ $# -le 1 ] || die "usage: valley tail [subject]"
1376 need_nats
1377 exec nats sub "${1:-valley.>}"
1378}
1379
1380# One ref-updated event per existing ref, from git for-each-ref alone. A
1381# ref's prior value is not derivable from the repository, so `old` is the
1382# all-zero id — the same payload a push creating the ref would produce.
1383# The payload construction mirrors the host module's publisher hook
1384# (nix/valley-host.nix); change one only with the other.
1385cmd_replay() {
1386 [ $# -le 1 ] || die "usage: valley replay [repo-dir]"
1387 need_nats
1388 local dir="${1:-.}" repo sha ref event count=0
1389 git -C "$dir" rev-parse --git-dir >/dev/null 2>&1 \
1390 || die "not a git repository: $dir"
1391 if [ "$(git -C "$dir" rev-parse --is-bare-repository)" = true ]; then
1392 repo="$(basename "$(git -C "$dir" rev-parse --absolute-git-dir)" .git)"
1393 else
1394 repo="$(basename "$(git -C "$dir" rev-parse --show-toplevel)")"
1395 fi
1396 while read -r sha ref; do
1397 # " is the only JSON-significant character a refname can contain (git
1398 # forbids \ and control characters); names and object ids are safe.
1399 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
1400 "$repo" "${ref//\"/\\\"}" "${sha//?/0}" "$sha")"
1401 nats pub "valley.git.$repo.ref-updated" "$event" >/dev/null
1402 count=$((count + 1))
1403 done < <(git -C "$dir" for-each-ref --format='%(objectname) %(refname)')
1404 echo "replayed $count refs of $repo onto the bus"
1405}
1406
1407# ----------------------------------------------------------------------
1408# checks — the verification-policy deriver (dcr-f41f718). It composes the
1409# instance layer with the project layer, matches every side of a diff
1410# against the composed classes, and prints the check names the change owes
1411# with the class or classes that made each one required. It reports: no
1412# check is run, nothing is gated, nothing is written.
1413#
1414# Composition is CUE's, never this script's. The whole of the mandatory-
1415# versus-overridable distinction is unification, so reimplementing it here
1416# would be reimplementing the decision. What this script does that CUE
1417# cannot is glob matching and reading a diff.
1418
1419need_cue() {
1420 command -v cue >/dev/null 2>&1 \
1421 || die "this verb needs the cue CLI; nix run .#valley bundles it"
1422}
1423
1424# One glob segment as an ERE fragment: `*` and `?` are wildcards that never
1425# cross a `/`, and every ERE metacharacter is escaped.
1426segment_ere() {
1427 local seg="$1" out="" i c
1428 for ((i = 0; i < ${#seg}; i++)); do
1429 c="${seg:i:1}"
1430 case "$c" in
1431 '*') out+='[^/]*' ;;
1432 '?') out+='[^/]' ;;
1433 '.' | '^' | '$' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | \\) out+="\\$c" ;;
1434 *) out+="$c" ;;
1435 esac
1436 done
1437 printf '%s' "$out"
1438}
1439
1440# A path glob as an anchored ERE, segment by segment. A `**` segment matches
1441# any number of segments including none, so it swallows the separator that
1442# would otherwise follow it and `a/**/b` matches `a/b`; every other segment
1443# matches exactly one.
1444glob_ere() {
1445 local ere='^' i last
1446 local -a segs=()
1447 IFS=/ read -r -a segs <<<"$1"
1448 last=$((${#segs[@]} - 1))
1449 for ((i = 0; i <= last; i++)); do
1450 if [ "${segs[i]}" = '**' ]; then
1451 if [ "$i" -eq "$last" ]; then ere+='.*'; else ere+='(.*/)?'; fi
1452 else
1453 ere+="$(segment_ere "${segs[i]}")"
1454 [ "$i" -eq "$last" ] || ere+='/'
1455 fi
1456 done
1457 printf '%s$' "$ere"
1458}
1459
1460# The composed policy as one tab-separated line per covered pattern, per
1461# required check, and per field of the check catalogue, so the shell never
1462# parses CUE. Every line is three fields — a kind, a name, and a value —
1463# whatever the kind, so one reader takes them all. The field is hidden
1464# because the schema's sentinel rejects unknown top-level fields, and
1465# `unclassified` is rendered as a class of that name: it is one more source
1466# a check can come from.
1467#
1468# The catalogue is rendered because a caller that runs a check needs what
1469# the policy says a check IS — its runner, and the attribute or command
1470# line that runner takes — and a tool that groups the owed checks needs
1471# their cost. `checks` reads only the cost, to group the owed checks by
1472# it; approve turns the rest into the arguments attest is given.
1473render_cue() {
1474 cat <<'EOF'
1475package verification
1476
1477import (
1478 "list"
1479 "strings"
1480)
1481
1482_render: strings.Join(list.Concat([[
1483 for cn, c in policy.classes
1484 for p, on in c.paths if on {"path\t\(cn)\t\(p)"}
1485], [
1486 for cn, c in policy.classes
1487 for k, on in c.requires if on {"requires\t\(cn)\t\(k)"}
1488], [
1489 for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)"}
1490], [
1491 for n, c in policy.checks {"runner\t\(n)\t\(c.runner)"}
1492], [
1493 for n, c in policy.checks if c.runner == "nix" {"attribute\t\(n)\t\(c.attribute)"}
1494], [
1495 for n, c in policy.checks if c.runner == "command" {"command\t\(n)\t\(c.command)"}
1496], [
1497 for n, c in policy.checks {"cost\t\(n)\t\(c.cost)"}
1498]]), "\n")
1499EOF
1500}
1501
1502# The composed layer, and a scratch directory for the documents the
1503# derivation writes into the composition. Globals so the probe below can
1504# see them.
1505POLICY_LAYER=()
1506POLICY_TMP=""
1507
1508cleanup_policy_tmp() {
1509 [ -n "$POLICY_TMP" ] || return 0
1510 rm -rf "$POLICY_TMP"
1511 POLICY_TMP=""
1512}
1513
1514# Where the schema and the two policy layers come from in a project
1515# following the convention (dcr-f41f718).
1516#
1517# The client derives from exactly the sources the integrator uses
1518# (integrator/policy.go), and the working tree is not among them. The
1519# project's own layer is read from the TARGET's tip, the pointer naming the
1520# owning valley is read from the target's tip, and the floor is read from
1521# that valley's integrated tip. A change never supplies the policy that
1522# gates it, and neither does whoever happens to be reviewing it: the
1523# reviewer's checkout may be any branch, however stale, and derivation
1524# gives the same answer from all of them.
1525#
1526# The schema is not a policy layer. It is the shape a policy is written in,
1527# and it ships with this tool: the package sets VALLEY_VERIFICATION_SCHEMA
1528# to the copy it was built with, as the integrator's package does. Only
1529# the-valley's own tree carries schema/, so this script reads the schema
1530# there only when it runs straight from such a checkout with the variable
1531# unset.
1532#
1533# Neither layer is ever the worked example under examples/policy/ — a gate
1534# derived from an example is a gate nobody wrote. `checks` takes an option
1535# for each, so a reader can point it at the example or anywhere else on
1536# purpose; approve takes no such option, because a request is filed
1537# against the policy that governs the project and nowhere else.
1538#
1539# Neither layer is a path in this tree, so policy_defaults leaves both
1540# empty and the two resolvers answer for them. That split is also what
1541# keeps `checks --instance DIR` from fetching a repository whose layer it
1542# was told to ignore, and `checks --project DIR` from reading a tip whose
1543# layer it was told to ignore.
1544POLICY_SCHEMA=""
1545POLICY_INSTANCE=""
1546POLICY_INSTANCE_LABEL=""
1547POLICY_PROJECT=""
1548POLICY_PROJECT_LABEL=""
1549policy_defaults() {
1550 POLICY_SCHEMA="${VALLEY_VERIFICATION_SCHEMA:-$1/schema/verification.cue}"
1551 POLICY_INSTANCE=""
1552 POLICY_INSTANCE_LABEL=""
1553 POLICY_PROJECT=""
1554 POLICY_PROJECT_LABEL=""
1555}
1556
1557# The floor, copied out of a fetch of the owning valley's repository, and
1558# the project's own layer, copied out of the target's tip. Globals, so the
1559# traps clean them up whatever happens.
1560INSTANCE_TMP=""
1561cleanup_instance_tmp() {
1562 [ -n "$INSTANCE_TMP" ] || return 0
1563 rm -rf "$INSTANCE_TMP"
1564 INSTANCE_TMP=""
1565}
1566
1567PROJECT_TMP=""
1568cleanup_project_tmp() {
1569 [ -n "$PROJECT_TMP" ] || return 0
1570 rm -rf "$PROJECT_TMP"
1571 PROJECT_TMP=""
1572}
1573
1574# The directory each layer lives in, the file naming this project's owning
1575# valley, and the ref of that valley whose tip carries the floor. The floor
1576# resolves at the integrated tip, because a floor a project could pin is
1577# not a floor (dcr-f41f718).
1578INSTANCE_DIR=policy/instance
1579PROJECT_DIR=policy/project
1580VALLEY_POINTER=policy/valley
1581VALLEY_POINTER_REF=refs/heads/main
1582
1583# The *.cue documents of one directory at one tree-ish, copied out of a
1584# repository into a directory on disk. Reading a tip with ls-tree and
1585# cat-file rather than checking it out is what lets the layers come from
1586# the target while the checkout stays on whatever branch the reviewer is
1587# on. 0 copied something, 1 the directory holds no *.cue, 2 the read
1588# failed.
1589#
1590# -z because a path may hold anything but NUL, and *.cue because the layer
1591# is the directory's documents — the same reading the composer takes.
1592#
1593# The listing is written out and its status checked before it is read. A
1594# listing read straight from a process substitution that failed reads as a
1595# directory holding nothing, and for the project layer that is the floor
1596# alone: fewer checks owed, from a read that never happened. The listing's
1597# name is not a *.cue name, so the composer never reads it.
1598copy_layer() {
1599 local gitdir="$1" treeish="$2" dir="$3" dest="$4" path name copied=0
1600 local listing="$dest/.listing"
1601 git -C "$gitdir" ls-tree --name-only -z "$treeish" "$dir/" > "$listing" \
1602 || return 2
1603 while IFS= read -r -d '' path; do
1604 case "$path" in *.cue) ;; *) continue ;; esac
1605 name="${path##*/}"
1606 git -C "$gitdir" cat-file blob "$treeish:$path" > "$dest/$name" || return 2
1607 copied=1
1608 done < "$listing"
1609 rm -f "$listing"
1610 [ "$copied" -eq 1 ]
1611}
1612
1613# The ref whose tip supplies the policy, printed the way a person names it,
1614# with the commit it stood at. Staleness in a remote-tracking ref is a real
1615# thing to see, so the report says which commit the layers came out of
1616# rather than only which ref. A ref that cannot be read fails, so that no
1617# report names a tip nobody read.
1618target_label() {
1619 local ref="$1" short
1620 short="$(git rev-parse --short "$ref")" || return 1
1621 ref="${ref#refs/remotes/}"
1622 ref="${ref#refs/heads/}"
1623 printf '%s %s' "$ref" "$short"
1624}
1625
1626# Resolve the project's own layer, out of the target's tip, into
1627# POLICY_PROJECT, and set POLICY_PROJECT_LABEL to where it came from.
1628#
1629# A target carrying no layer of its own is derived under the floor alone.
1630# The project layer only ever adds (dcr-f41f718), so the identity of "adds"
1631# is "adds nothing"; refusing instead would make a repository underivable
1632# until its first policy commit, and that commit could not derive either.
1633# This is the integrator's own reading (integrator/policy.go), and the two
1634# have to agree about an absent layer as much as about a present one.
1635#
1636# Absence is answered with a document that adds nothing rather than with an
1637# argument left off, because the composer is handed a directory of *.cue
1638# and has no spelling for "no layer".
1639#
1640# It reports and returns rather than dying, for the reason derive_owed
1641# does: a refusal inside the review loop is not the end of the session.
1642resolve_project_layer() {
1643 local root="$1" target="$2" rc at
1644
1645 at="$(target_label "$target")" || {
1646 refuse "could not read $target; nothing derived"
1647 return 1
1648 }
1649 cleanup_project_tmp
1650 PROJECT_TMP="$(mktemp -d)" || {
1651 refuse "no scratch directory to read the project layer into; nothing derived"
1652 return 1
1653 }
1654 copy_layer "$root" "$target" "$PROJECT_DIR" "$PROJECT_TMP" && rc=0 || rc=$?
1655 case "$rc" in
1656 0)
1657 POLICY_PROJECT="$PROJECT_TMP"
1658 POLICY_PROJECT_LABEL="$PROJECT_DIR@$at"
1659 ;;
1660 1)
1661 printf 'package verification\n' > "$PROJECT_TMP/adds-nothing.cue" || {
1662 cleanup_project_tmp
1663 refuse "could not compose an empty project layer; nothing derived"
1664 return 1
1665 }
1666 POLICY_PROJECT="$PROJECT_TMP"
1667 POLICY_PROJECT_LABEL="no $PROJECT_DIR@$at — the floor alone"
1668 ;;
1669 *)
1670 cleanup_project_tmp
1671 refuse "could not read $PROJECT_DIR/ at $at; nothing derived"
1672 return 1
1673 ;;
1674 esac
1675}
1676
1677# The first line of the pointer that is neither blank nor a comment. Read
1678# in the shell so that naming an owning valley needs nothing beyond what
1679# the rest of this script needs.
1680pointer_url() {
1681 local line url=""
1682 while IFS= read -r line || [ -n "$line" ]; do
1683 line="${line%%#*}"
1684 line="${line#"${line%%[![:space:]]*}"}"
1685 line="${line%"${line##*[![:space:]]}"}"
1686 [ -n "$line" ] || continue
1687 url="$line"
1688 break
1689 done < "$1"
1690 printf '%s' "$url"
1691}
1692
1693# Resolve the floor to a directory on disk, into POLICY_INSTANCE, and set
1694# POLICY_INSTANCE_LABEL to where it came from — a temporary directory is
1695# not an answer a reader can check.
1696#
1697# Every project has exactly one owning valley, and the floor is that
1698# valley's (dcr-9b5da04). It is read from the valley's own repository and
1699# never from the project's tree, which is the tree under judgment. Two
1700# shapes, and the first is a special case of the second:
1701#
1702# - a valley's config repository carries policy/instance itself, and is
1703# governed by that floor like every other project. It uses its own,
1704# and fetches nothing.
1705# - every other project names its owning valley at policy/valley. That
1706# repository is fetched into scratch and its policy/instance is read
1707# at the integrated tip. Fetching is all this needs, and anyone the
1708# valley governs necessarily holds fetch on it.
1709#
1710# Both the pointer and a valley's own floor are read from the TARGET's tip
1711# and never from the working tree. The pointer is a file a branch can edit,
1712# so reading it from the branch would let a change name the valley that
1713# gates it; reading it from the checkout would let whoever is reviewing
1714# decide the same thing by accident, which is the failure this fixes. An
1715# absent floor is refused — that is the direction absence defaults in for
1716# this layer, because the floor is the minimum (dcr-f41f718).
1717#
1718# It reports and returns rather than dying, for the reason derive_owed
1719# does: a refusal inside the review loop is not the end of the session.
1720resolve_instance_layer() {
1721 local root="$1" target="$2" url bare dest rc at
1722 at="$(target_label "$target")" || {
1723 refuse "could not read $target; nothing derived"
1724 return 1
1725 }
1726 cleanup_instance_tmp
1727 INSTANCE_TMP="$(mktemp -d)" || {
1728 refuse "no scratch directory to read the floor into; nothing derived"
1729 return 1
1730 }
1731 dest="$INSTANCE_TMP/instance"
1732 mkdir -p "$dest"
1733
1734 copy_layer "$root" "$target" "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
1735 case "$rc" in
1736 0)
1737 POLICY_INSTANCE="$dest"
1738 POLICY_INSTANCE_LABEL="$INSTANCE_DIR@$at (this repository is its own valley)"
1739 return 0
1740 ;;
1741 1) ;; # no floor of its own: the pointer names the valley that has one
1742 *)
1743 cleanup_instance_tmp
1744 refuse "could not read $INSTANCE_DIR/ at $at; nothing derived"
1745 return 1
1746 ;;
1747 esac
1748
1749 git -C "$root" cat-file blob "$target:$VALLEY_POINTER" > "$INSTANCE_TMP/pointer" 2> /dev/null || {
1750 cleanup_instance_tmp
1751 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"
1752 return 1
1753 }
1754 url="$(pointer_url "$INSTANCE_TMP/pointer")"
1755 [ -n "$url" ] || {
1756 cleanup_instance_tmp
1757 refuse "$VALLEY_POINTER at $at names no repository — it wants one line, the owning valley as git fetch takes it; nothing derived"
1758 return 1
1759 }
1760
1761 bare="$INSTANCE_TMP/valley.git"
1762 git init --quiet --bare "$bare" || {
1763 cleanup_instance_tmp
1764 refuse "no scratch repository to fetch the floor into; nothing derived"
1765 return 1
1766 }
1767 git -C "$bare" fetch --quiet --depth 1 "$url" "$VALLEY_POINTER_REF" || {
1768 cleanup_instance_tmp
1769 refuse "could not fetch the owning valley $url at $VALLEY_POINTER_REF (named by $VALLEY_POINTER at $at); nothing derived"
1770 return 1
1771 }
1772
1773 copy_layer "$bare" FETCH_HEAD "$INSTANCE_DIR" "$dest" && rc=0 || rc=$?
1774 case "$rc" in
1775 0) ;;
1776 1)
1777 cleanup_instance_tmp
1778 refuse "the owning valley $url holds no *.cue in $INSTANCE_DIR/ at $VALLEY_POINTER_REF; nothing derived"
1779 return 1
1780 ;;
1781 *)
1782 cleanup_instance_tmp
1783 refuse "could not read $INSTANCE_DIR/ from $url; nothing derived"
1784 return 1
1785 ;;
1786 esac
1787
1788 POLICY_INSTANCE="$dest"
1789 POLICY_INSTANCE_LABEL="$url $INSTANCE_DIR@$VALLEY_POINTER_REF"
1790}
1791
1792# Is this check mandatory in this class, or a default the project left
1793# alone? The bit is the form of the composed value, so the test is CUE's
1794# own: a project supplying `false` either conflicts or unifies cleanly.
1795# Answering by unifying rather than by inspecting syntax means the script
1796# cannot disagree with `cue vet`.
1797#
1798# This is the one producer whose failure does not end the derivation. A
1799# probe that fails for any other reason, or that cannot be written, reads as
1800# mandatory, which is the strict answer, and the bit never changes which
1801# checks are owed.
1802check_is_mandatory() {
1803 local class="$1" check="$2" field
1804 if [ "$class" = unclassified ]; then
1805 field="policy: unclassified: \"$check\": false"
1806 else
1807 field="policy: classes: \"$class\": requires: \"$check\": false"
1808 fi
1809 # A probe that could not be written may leave the last one in its place,
1810 # and that one answers for another check. Mandatory is the strict answer.
1811 printf 'package verification\n%s\n' "$field" > "$POLICY_TMP/probe.cue" \
1812 || return 0
1813 ! cue vet "${POLICY_LAYER[@]}" "$POLICY_TMP/probe.cue" > /dev/null 2>&1
1814}
1815
1816# Every side of the diff: an added, modified or deleted path, and both the
1817# old and the new path of a rename or copy. It reads `git diff -z
1818# --name-status` on stdin, because a path may contain anything but NUL, and
1819# fails on a record cut short — including one cut inside its status, which
1820# a plain `while read` would end on quietly, dropping the record. It also
1821# fails when a write fails: the caller runs without `errexit`, so a lost
1822# path would otherwise end in a normal EOF and a status of 0.
1823diff_paths() {
1824 local status path
1825 while IFS= read -r -d '' status || { [ -z "$status" ] || return 1; false; }; do
1826 IFS= read -r -d '' path || return 1
1827 printf '%s\n' "$path" || return 1
1828 case "$status" in
1829 R* | C*)
1830 IFS= read -r -d '' path || return 1
1831 printf '%s\n' "$path" || return 1
1832 ;;
1833 esac
1834 done
1835}
1836
1837# Lines in, one comma-separated line out.
1838join_lines() {
1839 local out="" line
1840 while IFS= read -r line; do out="${out:+$out, }$line"; done
1841 printf '%s' "$out"
1842}
1843
1844# Arguments in, one comma-separated line out, or `none` when there are none.
1845join_or_none() {
1846 if [ $# -eq 0 ]; then echo none; else printf '%s\n' "$@" | join_lines; fi
1847}
1848
1849# The remaining arguments, sorted, into the array the first one names. The
1850# sort is captured and its status returned: a sort read through a process
1851# substitution that fails reads as a sort of nothing, and for a list of
1852# owed checks that is a change owing none.
1853#
1854# The destination is a nameref, so what is assigned is the caller's array,
1855# and the linter cannot see that array being read.
1856# shellcheck disable=SC2034
1857sort_into() {
1858 local -n sort_into_dest="$1"
1859 local sorted
1860 shift
1861 sort_into_dest=()
1862 [ $# -gt 0 ] || return 0
1863 sorted="$(printf '%s\n' "$@" | sort)" || return 1
1864 mapfile -t sort_into_dest <<<"$sorted"
1865}
1866
1867# The target: the ref a change is derived against, and the tip both policy
1868# layers are read out of. origin's answer is preferred, because the target
1869# is the branch as the integrator holds it and not as this checkout last
1870# built it.
1871#
1872# Only a ref that is not there falls through to the next. show-ref says
1873# "not there" with 1 and fails any other way with another status, so a
1874# read of origin's ref that failed ends here: falling through would read
1875# the policy out of the local main, which may be older. 1 no main at all,
1876# 2 a read failed.
1877target_ref() {
1878 local ref rc
1879 for ref in refs/remotes/origin/main refs/heads/main; do
1880 git show-ref --verify --quiet "$ref" && rc=0 || rc=$?
1881 case "$rc" in
1882 0) echo "$ref"; return 0 ;;
1883 1) ;;
1884 *) return 2 ;;
1885 esac
1886 done
1887 return 1
1888}
1889
1890# ----------------------------------------------------------------------
1891# The derivation itself, and the globals it answers with. Everything a
1892# caller could want from the policy comes out of one pass, because every
1893# part of it is a function of the same composition: `checks` prints the
1894# answer, approve runs what it names.
1895#
1896# It reports and returns rather than dying, so that a caller inside the
1897# review loop is refused rather than ended. Its callers are all in a
1898# condition, which suspends `set -e` for the whole call, so every step is
1899# checked by hand.
1900#
1901# Every producer — git, cue, sort — writes a file or a variable, and its
1902# status is checked before anything reads what it wrote. A producer read
1903# through a process substitution loses its status, and a failed one then
1904# reads as an empty list: no changed paths, no catalogue, no classes. Each
1905# of those derives a change that owes nothing, which is the one answer a
1906# failure must never give.
1907DERIVED_PATHS=() # every side of the diff, sorted
1908DERIVED_MATCHED=() # the class names at least one path matched, sorted
1909DERIVED_UNCOVERED=() # the paths no class covered
1910DERIVED_OWES=0 # whether `unclassified` is what owes something
1911declare -A DERIVED_OWED=() # check -> the classes that required it
1912declare -A DERIVED_PINNED=() # check -> mandatory | default
1913declare -A CHECK_RUNNER=() # check -> nix | command
1914declare -A CHECK_ATTRIBUTE=() # check -> the flake check attribute
1915declare -A CHECK_COMMAND=() # check -> the command line
1916declare -A CHECK_COST=() # check -> quick | slow
1917
1918derive_owed() {
1919 local schema="$1" instance="$2" project="$3" base="$4" head="$5"
1920
1921 need_cue
1922 [ -f "$schema" ] || {
1923 refuse "no policy schema at $schema; nothing derived"
1924 return 1
1925 }
1926 # An unmatched glob stays literal, so the first entry is a real file
1927 # exactly when the directory holds a document.
1928 local -a instance_docs=("$instance"/*.cue) project_docs=("$project"/*.cue)
1929 [ -f "${instance_docs[0]}" ] || {
1930 refuse "no instance policy layer at $instance; nothing derived"
1931 return 1
1932 }
1933 [ -f "${project_docs[0]}" ] || {
1934 refuse "no project policy layer at $project: a project's own layer is the *.cue documents under $PROJECT_DIR/ (dcr-f41f718). Nothing derived"
1935 return 1
1936 }
1937
1938 cleanup_policy_tmp
1939 POLICY_LAYER=("$schema" "${instance_docs[@]}" "${project_docs[@]}")
1940 POLICY_TMP="$(mktemp -d)" || {
1941 refuse "no scratch directory to compose the policy in; nothing derived"
1942 return 1
1943 }
1944
1945 git diff --no-relative --name-status -M -z "$base" "$head" > "$POLICY_TMP/diff" || {
1946 refuse "could not diff $base..$head; nothing derived"
1947 return 1
1948 }
1949 diff_paths < "$POLICY_TMP/diff" > "$POLICY_TMP/paths" || {
1950 refuse "truncated diff output; nothing derived"
1951 return 1
1952 }
1953 sort -u "$POLICY_TMP/paths" > "$POLICY_TMP/paths.sorted" || {
1954 refuse "could not sort the changed paths; nothing derived"
1955 return 1
1956 }
1957 DERIVED_PATHS=()
1958 mapfile -t DERIVED_PATHS < "$POLICY_TMP/paths.sorted"
1959
1960 render_cue > "$POLICY_TMP/render.cue" || {
1961 refuse "could not write the policy render; nothing derived"
1962 return 1
1963 }
1964 cue vet -c "${POLICY_LAYER[@]}" || {
1965 refuse "the policy layers do not compose; nothing derived"
1966 return 1
1967 }
1968
1969 # The render is checked before it is read. A render that fails prints
1970 # nothing, and an empty render reads as a policy that owes nothing. A
1971 # schema older than this script fails it, by lacking a field it reads.
1972 cue eval --out text -e _render "${POLICY_LAYER[@]}" "$POLICY_TMP/render.cue" \
1973 > "$POLICY_TMP/rendered" || {
1974 refuse "the composed policy does not render (a schema older than this script is one cause); nothing derived"
1975 return 1
1976 }
1977 # Sorted once here, so every list below comes out in a stable order.
1978 sort "$POLICY_TMP/rendered" > "$POLICY_TMP/rendered.sorted" || {
1979 refuse "could not sort the composed policy; nothing derived"
1980 return 1
1981 }
1982 local -a rendered=()
1983 mapfile -t rendered < "$POLICY_TMP/rendered.sorted"
1984
1985 unset CHECK_RUNNER CHECK_ATTRIBUTE CHECK_COMMAND CHECK_COST DERIVED_OWED \
1986 DERIVED_PINNED
1987 declare -gA CHECK_RUNNER=() CHECK_ATTRIBUTE=() CHECK_COMMAND=() \
1988 CHECK_COST=() DERIVED_OWED=() DERIVED_PINNED=()
1989
1990 # The middle field is a class name for a coverage or requirement line and
1991 # a check name for a catalogue one; `key` is what both are.
1992 local -a pat_class=() pat_ere=() req_class=() req_check=()
1993 local line kind key value
1994 for line in "${rendered[@]}"; do
1995 kind="${line%%$'\t'*}"
1996 key="${line#*$'\t'}"
1997 value="${key#*$'\t'}"
1998 key="${key%%$'\t'*}"
1999 case "$kind" in
2000 path)
2001 pat_class+=("$key")
2002 pat_ere+=("$(glob_ere "$value")")
2003 ;;
2004 requires)
2005 req_class+=("$key")
2006 req_check+=("$value")
2007 ;;
2008 runner) CHECK_RUNNER["$key"]="$value" ;;
2009 attribute) CHECK_ATTRIBUTE["$key"]="$value" ;;
2010 command) CHECK_COMMAND["$key"]="$value" ;;
2011 cost) CHECK_COST["$key"]="$value" ;;
2012 esac
2013 done
2014
2015 # A pattern bash cannot compile answers 2, not 1. Read as "no match", it
2016 # would drop the pattern's class from every change it covers.
2017 local -A matched=()
2018 local path i hit rc
2019 DERIVED_UNCOVERED=()
2020 for path in "${DERIVED_PATHS[@]}"; do
2021 hit=0
2022 for ((i = 0; i < ${#pat_ere[@]}; i++)); do
2023 [[ "$path" =~ ${pat_ere[i]} ]] && rc=0 || rc=$?
2024 case "$rc" in
2025 0)
2026 matched["${pat_class[i]}"]=1
2027 hit=1
2028 ;;
2029 1) ;;
2030 *)
2031 refuse "class ${pat_class[i]} has a path pattern that does not compile (${pat_ere[i]}); nothing derived"
2032 return 1
2033 ;;
2034 esac
2035 done
2036 [ "$hit" -eq 1 ] || DERIVED_UNCOVERED+=("$path")
2037 done
2038 # A path no class covers is answered by the policy's `unclassified` set,
2039 # which is why it is treated as one more matched class rather than as an
2040 # absence.
2041 [ "${#DERIVED_UNCOVERED[@]}" -eq 0 ] || matched[unclassified]=1
2042
2043 local check
2044 DERIVED_OWES=0
2045 for ((i = 0; i < ${#req_check[@]}; i++)); do
2046 key="${req_class[i]}"
2047 check="${req_check[i]}"
2048 [ -n "${matched[$key]:-}" ] || continue
2049 [ "$key" != unclassified ] || DERIVED_OWES=1
2050 DERIVED_OWED["$check"]="${DERIVED_OWED[$check]:+${DERIVED_OWED[$check]}, }$key"
2051 if check_is_mandatory "$key" "$check"; then
2052 DERIVED_PINNED["$check"]=mandatory
2053 else
2054 DERIVED_PINNED["$check"]="${DERIVED_PINNED[$check]:-default}"
2055 fi
2056 done
2057
2058 sort_into DERIVED_MATCHED "${!matched[@]}" || {
2059 refuse "could not sort the matched classes; nothing derived"
2060 return 1
2061 }
2062}
2063
2064cmd_checks() {
2065 local root schema instance="" label project="" plabel base head target=""
2066 local names=0 cost="" costed=0 short_base short_head
2067 root="$(git rev-parse --show-toplevel 2> /dev/null)" \
2068 || die "not a git repository"
2069 policy_defaults "$root"
2070 schema="$POLICY_SCHEMA"
2071 while [ $# -gt 0 ]; do
2072 case "$1" in
2073 --schema) [ $# -ge 2 ] || die "--schema needs a file"; schema="$2"; shift 2 ;;
2074 --instance) [ $# -ge 2 ] || die "--instance needs a directory"; instance="$2"; shift 2 ;;
2075 --project) [ $# -ge 2 ] || die "--project needs a directory"; project="$2"; shift 2 ;;
2076 --names) names=1; shift ;;
2077 --cost) [ $# -ge 2 ] || die "--cost needs quick or slow"; cost="$2"; costed=1; shift 2 ;;
2078 --) shift; break ;;
2079 -*) die "unknown option: $1" ;;
2080 *) break ;;
2081 esac
2082 done
2083 [ $# -le 2 ] || die "usage: valley checks [options] [<base> [<head>]]"
2084 if [ "$costed" -eq 1 ]; then
2085 case "$cost" in
2086 quick | slow) ;;
2087 *) die "--cost takes quick or slow, not '$cost'" ;;
2088 esac
2089 [ "$names" -eq 1 ] || die "--cost filters the --names list; pass --names too"
2090 fi
2091
2092 head="$(git rev-parse --verify --quiet "${2:-HEAD}^{commit}")" \
2093 || die "no such commit: ${2:-HEAD}"
2094 # The target is what the layers are read out of, so it is needed whenever
2095 # either layer is left to its default — and it is what an unnamed base
2096 # is the merge base with.
2097 if [ -z "$instance" ] || [ -z "$project" ] || [ $# -lt 1 ]; then
2098 target="$(target_ref)" || {
2099 [ $? -eq 1 ] || die "could not read the main branch; nothing derived"
2100 die "no main branch: the target's tip is where the policy layers are read from, and there is none here"
2101 }
2102 fi
2103 if [ $# -ge 1 ]; then
2104 base="$(git rev-parse --verify --quiet "$1^{commit}")" \
2105 || die "no such commit: $1"
2106 else
2107 base="$(git merge-base "$target" "$head")" \
2108 || die "$head and ${target#refs/} do not share history — name a base"
2109 fi
2110
2111 trap 'cleanup_policy_tmp; cleanup_instance_tmp; cleanup_project_tmp' EXIT
2112 # Each layer is resolved only when nobody named one. --instance and
2113 # --project are a reader pointing this at a layer on purpose, and
2114 # honouring that means not fetching the repository, and not reading the
2115 # tip, that the named layer replaced.
2116 if [ -n "$instance" ]; then
2117 label="${instance#"$root"/}"
2118 else
2119 resolve_instance_layer "$root" "$target" || exit 1
2120 instance="$POLICY_INSTANCE"
2121 label="$POLICY_INSTANCE_LABEL"
2122 fi
2123 if [ -n "$project" ]; then
2124 plabel="${project#"$root"/}"
2125 else
2126 resolve_project_layer "$root" "$target" || exit 1
2127 project="$POLICY_PROJECT"
2128 plabel="$POLICY_PROJECT_LABEL"
2129 fi
2130 derive_owed "$schema" "$instance" "$project" "$base" "$head" || exit 1
2131
2132 # The owed checks, sorted, and grouped by the cost the policy declares.
2133 # The grouping changes nothing owed: approve runs every owed check, and
2134 # the integrator requires evidence for every one, whatever it costs.
2135 local check width=0
2136 local -a owed=() quick=() slow=() listed=()
2137 sort_into owed "${!DERIVED_OWED[@]}" \
2138 || die "could not sort the owed checks; nothing derived"
2139 for check in "${owed[@]}"; do
2140 [ "${#check}" -le "$width" ] || width="${#check}"
2141 if [ "${CHECK_COST[$check]}" = slow ]; then
2142 slow+=("$check")
2143 else
2144 quick+=("$check")
2145 fi
2146 done
2147
2148 # The form for agents and scripts: the names alone, one per line.
2149 if [ "$names" -eq 1 ]; then
2150 case "$cost" in
2151 quick) listed=("${quick[@]}") ;;
2152 slow) listed=("${slow[@]}") ;;
2153 *) listed=("${owed[@]}") ;;
2154 esac
2155 [ "${#listed[@]}" -eq 0 ] || printf '%s\n' "${listed[@]}"
2156 return
2157 fi
2158
2159 # Read before the first line is printed, so a read that fails leaves no
2160 # partial report behind.
2161 short_base="$(git rev-parse --short "$base")" \
2162 || die "could not read $base; nothing derived"
2163 short_head="$(git rev-parse --short "$head")" \
2164 || die "could not read $head; nothing derived"
2165
2166 printf '%s..%s: %d changed path(s)\n' "$short_base" "$short_head" \
2167 "${#DERIVED_PATHS[@]}"
2168 printf 'policy: %s + %s\n' "$label" "$plabel"
2169 if [ "${#DERIVED_MATCHED[@]}" -eq 0 ]; then
2170 printf 'classes matched: none\n\n'
2171 else
2172 printf 'classes matched: %s\n\n' \
2173 "$(printf '%s\n' "${DERIVED_MATCHED[@]}" | join_lines)"
2174 fi
2175
2176 if [ "${#DERIVED_OWED[@]}" -eq 0 ]; then
2177 echo "required checks: none"
2178 else
2179 echo "required checks:"
2180 for check in "${owed[@]}"; do
2181 printf ' %-*s %-9s %s\n' \
2182 "$width" "$check" "${DERIVED_PINNED[$check]}" "${DERIVED_OWED[$check]}"
2183 done
2184 fi
2185
2186 if [ "${#DERIVED_UNCOVERED[@]}" -gt 0 ]; then
2187 printf '\nunclassified: %d path(s) matched no class\n' "${#DERIVED_UNCOVERED[@]}"
2188 printf ' %s\n' "${DERIVED_UNCOVERED[@]}"
2189 # The failure the `unclassified` field exists to prevent: paths outside
2190 # every class that the policy then asks nothing of.
2191 [ "$DERIVED_OWES" -eq 1 ] \
2192 || echo " the policy requires nothing of them — it is behind the tree"
2193 fi
2194
2195 # Below every line the integrator reads (integrator/policy.go), and
2196 # unindented, so neither line can read as a required check.
2197 if [ "${#owed[@]}" -gt 0 ]; then
2198 printf '\nquick: %s\n' "$(join_or_none "${quick[@]}")"
2199 printf 'slow: %s\n' "$(join_or_none "${slow[@]}")"
2200 fi
2201}
2202
2203main() {
2204 local verb="${1:-help}"
2205 if [ $# -gt 0 ]; then shift; fi
2206 # The verb set is mirrored in completions/ (valley.bash, _valley) —
2207 # update both when it changes.
2208 case "$verb" in
2209 pending) cmd_pending "$@" ;;
2210 review) cmd_review "$@" ;;
2211 approve) cmd_approve "$@" ;;
2212 rebase) cmd_rebase "$@" ;;
2213 status | ready | unready | withdraw) cmd_go "$verb" "$@" ;;
2214 checks) cmd_checks "$@" ;;
2215 tail) cmd_tail "$@" ;;
2216 replay) cmd_replay "$@" ;;
2217 help | -h | --help) usage ;;
2218 *)
2219 printf 'valley: unknown verb: %s\n\n' "$verb" >&2
2220 usage >&2
2221 exit 1
2222 ;;
2223 esac
2224}
2225
2226main "$@"