gunk-dev/the-valley

valley

source5facbe322680main's published tip history
30.3 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# .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 —
17# graduation is now owed; recording the decision node is part of taking it.);
18# - its behavior gets subtle enough to need real tests
19# (CROSSED by checks: glob matching is pinned by the policy-deriver
20# flake check, not by reading the code.);
21# - it needs nontrivial parsing or concurrency
22# (CROSSED by checks: glob-to-regex translation and -z diff parsing.).
23# The size tripwire (~300 lines) is crossed too. Which way to take the
24# graduation is dcr-2aa1a12, still `proposed`.
25# Graduation is a deliberate act, recorded as a decision node.
26# Precedent: klaus — born in cosmo, graduated deliberately.
27
28set -euo pipefail
29
30die() {
31 printf 'valley: %s\n' "$*" >&2
32 exit 1
33}
34
35usage() {
36 cat <<'EOF'
37valley — S1 integrator verbs for a valley project (direct-push mode)
38
39usage: valley <verb> [args]
40
41 pending list branches on origin not merged into origin/main
42 review <branch> page through the branch's log and diff vs origin/main,
43 then choose:
44 [i]ntegrate ff-only merge onto main, push origin main,
45 delete the merged branch from origin
46 [r]eject delete the remote branch (confirmed first)
47 [s]kip do nothing
48 a stale branch (won't fast-forward from main) is first
49 offered:
50 [b]ase rebase it onto origin/main in a throwaway
51 worktree, push --force-with-lease, then
52 re-review the diff that would actually land
53 while paging, press v: less opens the diff in $EDITOR.
54 every line you insert there is a note. it is anchored to
55 the file and new-side line it sits on — to the file alone
56 when it sits above the first hunk — then appended to
57 $XDG_STATE_HOME/valley/notes/<branch>.md (default
58 ~/.local/state) and printed after the verdict. notes
59 survive [b]ase. lines you change or delete instead of
60 inserting are ignored, with a warning.
61 checks [<base> [<head>]]
62 print the check names the change between two commits owes
63 under the composed verification policy (dcr-f41f718), and
64 which class made each one required. It prints: no check is
65 run, nothing is gated, nothing is written.
66 base defaults to the merge base with main, head to HEAD.
67 the policy layers are not discovered — they are named:
68 --schema FILE default schema/verification.cue
69 --instance DIR default examples/policy/instance
70 --project DIR default examples/policy/project
71 all three relative to the repository root.
72 tail [subject] watch bus events scroll by (default subject: valley.>);
73 the server comes from the nats CLI's own config
74 (NATS_URL or a nats context; default localhost)
75 replay [dir] publish one ref-updated event per current ref of the
76 repo at dir (default: .) — rebuilds the stream's
77 projection, e.g. after nats stream purge valley
78 help show this help
79
80Runs from any checkout of the project; needs only git and coreutils,
81except tail and replay, which also need the nats CLI (natscli), checks,
82which also needs the cue CLI, and review's notes, which need less.
83No config, no batch mode, and no state but the notes file — the judgment
84stays with the human.
85EOF
86}
87
88fetch_origin() {
89 git fetch --prune --quiet origin
90}
91
92# Resolve the pager as git would for a diff: pager.diff first (per-command
93# pager configs — e.g. home-manager's delta module — set pager.diff and leave
94# core.pager alone), then git var GIT_PAGER (core.pager, GIT_PAGER, PAGER,
95# less). pager.<cmd> may legally be a boolean; treat true/false — and an
96# empty or missing value — as unset and fall back. The value is
97# shell-interpreted, hence sh -c.
98diff_pager() {
99 local pager
100 pager="$(git config --get pager.diff || true)"
101 case "$pager" in '' | true | false) pager="$(git var GIT_PAGER)" ;; esac
102 printf '%s' "$pager"
103}
104
105# Page a file rather than a pipe, so less's v key has something to hand
106# $EDITOR: with a real file open, v runs LESSEDIT, whose default
107# `%E ?lm+%lm. %g` is the editor, +<line>, and the file name. That file is
108# the review buffer, and editing it is how notes get written (see
109# collect_notes). A pipe has no name, so less refuses to edit one — which is
110# why review no longer pipes.
111#
112# Two ways to keep both the rendering and the editable file were open; this
113# takes the second. Paging the buffer directly is exact but throws away
114# delta's rendering, which is most of what makes a diff readable. So instead
115# the configured diff pager runs as less's input preprocessor: it still reads
116# the buffer on stdin exactly as it did when it was the pager, less displays
117# what it emits, and less still calls the raw buffer "the current file" — so
118# v edits the diff, not the rendering. The cost is the line number: a filter
119# that restructures the diff (delta's default does) makes %lm a line of the
120# rendered view, so the editor opens near the cursor rather than on it. A
121# structure-preserving filter (pager.diff = `delta --color-only`) makes it
122# exact. Anchoring never depends on it: a note is anchored by where it was
123# inserted, not by where the editor opened.
124page_file() {
125 local file="$1" pager
126 [ -t 1 ] || { cat -- "$file"; return; } # a non-tty just cats
127 pager="$(diff_pager)"
128 case "${pager%%[[:space:]]*}" in
129 less | */less)
130 # Already less: give it the file and there is no filter to run.
131 sh -c "$pager \"\$1\"" sh "$file"
132 return
133 ;;
134 esac
135 # Without less there is no editor key; fall back to filtering into a pipe.
136 command -v less > /dev/null 2>&1 || {
137 sh -c "$pager" < "$file"
138 return
139 }
140 # -R because the filter's color is the whole point of running it, and no
141 # LESSCLOSE because a stray one would run against a buffer we still read.
142 LESSOPEN="|$pager < %s" env -u LESSCLOSE less -R -- "$file"
143}
144
145pending_line() {
146 local ref="$1" age author ahead stat
147 age="$(git log -1 --format='%cr' "$ref")"
148 author="$(git log -1 --format='%an' "$ref")"
149 ahead="$(git rev-list --count "origin/main..$ref")"
150 stat="$(git diff --shortstat "origin/main...$ref")"
151 stat="${stat# }"
152 printf '%s | %s | %s | ahead %s | %s\n' \
153 "${ref#origin/}" "$age" "$author" "$ahead" "${stat:-no file changes}"
154}
155
156cmd_pending() {
157 [ $# -eq 0 ] || die "pending takes no arguments"
158 fetch_origin
159 local ref found=0
160 while IFS= read -r ref; do
161 case "$ref" in
162 origin/HEAD | origin/main) continue ;;
163 esac
164 found=1
165 pending_line "$ref"
166 done < <(git for-each-ref --format='%(refname:short)' \
167 --no-merged=origin/main refs/remotes/origin)
168 [ "$found" -eq 1 ] || echo "nothing pending"
169}
170
171integrate() {
172 local branch="$1" local_main origin_main
173 local_main="$(git rev-parse --verify --quiet refs/heads/main)" \
174 || die "no local main branch to fast-forward — nothing merged"
175 origin_main="$(git rev-parse refs/remotes/origin/main)"
176 [ "$local_main" = "$origin_main" ] \
177 || die "local main is not at origin/main — sync it first; nothing merged"
178 git merge-base --is-ancestor refs/heads/main "refs/remotes/origin/$branch" \
179 || die "$branch does not fast-forward from main — resolve by hand; nothing merged"
180 git checkout --quiet main
181 git merge --ff-only --quiet "refs/remotes/origin/$branch"
182 git push --quiet origin main
183 echo "integrated $branch: main is now $(git rev-parse --short main), pushed to origin"
184 # The branch tip is now an ancestor of the main just pushed, so deleting it
185 # loses nothing; without this every integration leaves a fully-merged ghost
186 # ref that later reads as a confusing "empty" branch. Best-effort: a failed
187 # delete must not report the integration as failed.
188 if git push --quiet origin --delete "$branch"; then
189 echo "deleted merged branch $branch from origin"
190 else
191 printf 'valley: warning: could not delete origin/%s — delete it by hand\n' \
192 "$branch" >&2
193 fi
194}
195
196reject() {
197 local branch="$1" answer
198 printf 'really delete origin/%s? [y/N] ' "$branch"
199 read -r answer || answer=""
200 case "$answer" in
201 y | Y | yes)
202 git push --quiet origin --delete "$branch"
203 echo "rejected $branch: deleted from origin"
204 ;;
205 *) echo "kept $branch" ;;
206 esac
207}
208
209# ----------------------------------------------------------------------
210# review notes — the lines the reviewer inserts into the paged diff.
211#
212# The buffer the reviewer pages is a file, so the pager's editor key can open
213# it (page_file). Whatever comes back with lines inserted is read as notes:
214# no marker, no syntax, no mode — an inserted line is a note because it was
215# not there before. What a note is *about* is where it sits, so each one is
216# anchored to the file and the new-side line number of the diff line above
217# it, which is the pair a reviewer would otherwise have to copy out by hand.
218
219# The scratch directory holding the buffer and its pristine copy, and the
220# notes taken so far in this review — a global because [b]ase pages a second
221# time and the notes from the first pass are not thereby withdrawn.
222REVIEW_TMP=""
223NOTES=()
224
225cleanup_review_tmp() {
226 [ -n "$REVIEW_TMP" ] || return 0
227 rm -rf "$REVIEW_TMP"
228 REVIEW_TMP=""
229}
230
231# Where a branch's notes live. XDG_STATE_HOME is the right home for them:
232# they are neither config nor cache, and losing them loses judgment.
233notes_file() {
234 printf '%s/valley/notes/%s.md\n' "${XDG_STATE_HOME:-$HOME/.local/state}" "$1"
235}
236
237# The anchor of every line of the buffer, by line: the file that line belongs
238# to, and the new-side line number it sits on. Built in one pass so that
239# anchoring a note is a lookup. An empty path means the line is above every
240# file (the log); line 0 means the line is a file header, above every hunk.
241ANCHOR_PATH=()
242ANCHOR_LINE=()
243
244anchor_buffer() {
245 local file="$1" line path="" at=0 next=0 inhunk=0 rest
246 ANCHOR_PATH=()
247 ANCHOR_LINE=()
248 while IFS= read -r line; do
249 # Header lines are only headers outside a hunk: inside one, every line
250 # carries a +/-/space prefix, so a diff of a diff cannot be misread.
251 if [ "$inhunk" -eq 1 ]; then
252 case "$line" in
253 ' '* | '+'* | '')
254 at="$next" # this line's own new-side number
255 next=$((next + 1))
256 ;;
257 '-'* | \\*) ;; # a removal or the no-newline marker: no new-side line
258 *) inhunk=0 ;;
259 esac
260 fi
261 if [ "$inhunk" -eq 0 ]; then
262 case "$line" in
263 'diff --git '*)
264 path=""
265 # The b/ side, so a rename anchors to the name it will have.
266 if [[ "$line" =~ ^diff\ --git\ a/(.*)\ b/(.*)$ ]]; then
267 path="${BASH_REMATCH[2]}"
268 fi
269 at=0
270 ;;
271 '@@ '*)
272 rest="${line#*+}" # -12,7 +34,9 @@ -> 34,9 @@
273 at="${rest%%[!0-9]*}"
274 [ -n "$at" ] || at=0
275 next="$at"
276 inhunk=1
277 ;;
278 esac
279 fi
280 ANCHOR_PATH+=("$path")
281 ANCHOR_LINE+=("$at")
282 done < "$file"
283}
284
285# The anchor for a note inserted after buffer line n, as it is written down.
286anchor_of() {
287 local n="$1" path line
288 [ "$n" -ge 1 ] || { printf '(unanchored)'; return; }
289 path="${ANCHOR_PATH[n - 1]:-}"
290 line="${ANCHOR_LINE[n - 1]:-0}"
291 if [ -z "$path" ]; then
292 printf '(unanchored)'
293 elif [ "$line" -eq 0 ]; then
294 printf '%s' "$path"
295 else
296 printf '%s:%s' "$path" "$line"
297 fi
298}
299
300# The notes in an edited buffer, one `anchor: text` line each. git says where
301# the reviewer's lines landed; a hunk that removes nothing is an insertion,
302# and the line it was inserted after is the anchor. A hunk that removes
303# something is an edit of the diff itself — it anchors to nothing, since the
304# line it would name is the line it changed — so it is dropped with a count.
305notes_in() {
306 local orig="$1" edited="$2" line rest at old insert=0 touched=0 text
307 anchor_buffer "$orig"
308 while IFS= read -r line; do
309 case "$line" in
310 '@@ '*)
311 rest="${line#@@ -}" # 12,0 +13,2 @@ -> 12,0 +13,2 @@
312 at="${rest%%[!0-9]*}"
313 rest="${rest#"$at"}"
314 old=1
315 case "$rest" in
316 ,*)
317 rest="${rest#,}"
318 old="${rest%%[!0-9]*}"
319 ;;
320 esac
321 if [ "$old" -eq 0 ]; then
322 insert=1
323 else
324 insert=0
325 touched=$((touched + old))
326 fi
327 ;;
328 '+'*)
329 # Only inside an insertion hunk: the +++ of git's own header is not
330 # a note, and neither is the new side of an edit.
331 [ "$insert" -eq 1 ] || continue
332 text="${line#+}"
333 text="${text#"${text%%[![:space:]]*}"}"
334 [ -n "$text" ] || continue # a blank line says nothing
335 printf '%s: %s\n' "$(anchor_of "$at")" "$text"
336 ;;
337 esac
338 done < <(git --no-pager diff --no-ext-diff --no-index -U0 -- "$orig" "$edited")
339 [ "$touched" -eq 0 ] || printf \
340 'valley: warning: %d changed or deleted diff line(s) ignored — a note is a line you insert\n' \
341 "$touched" >&2
342}
343
344# Read the notes out of the paged buffer and keep them: appended to the
345# branch's notes file under the commit they were taken against, and held for
346# the print that follows the verdict. A notes file that cannot be written is
347# a warning, never a failure — the notes are still printed, and a review is
348# not undone by a missing directory.
349collect_notes() {
350 local branch="$1" sha="$2" file dir
351 local -a found=()
352 mapfile -t found < <(notes_in "$REVIEW_TMP/review.orig" "$REVIEW_TMP/review.diff")
353 [ "${#found[@]}" -gt 0 ] || return 0
354 NOTES+=("${found[@]}")
355 file="$(notes_file "$branch")"
356 dir="${file%/*}"
357 mkdir -p "$dir" 2> /dev/null && {
358 printf '## %s at %s\n\n' "$branch" "$sha"
359 printf '%s\n' "${found[@]}"
360 printf '\n'
361 } >> "$file" 2> /dev/null && return 0
362 printf 'valley: warning: could not write %s — the notes are printed only\n' \
363 "$file" >&2
364}
365
366print_notes() {
367 local branch="$1"
368 [ "${#NOTES[@]}" -gt 0 ] || return 0
369 printf '\n%d note(s) on %s, appended to %s:\n' \
370 "${#NOTES[@]}" "$branch" "$(notes_file "$branch")"
371 printf ' %s\n' "${NOTES[@]}"
372}
373
374show_review() {
375 local branch="$1" sha
376 sha="$(git rev-parse --short "refs/remotes/origin/$branch")"
377 REVIEW_TMP="$(mktemp -d)"
378 {
379 printf 'branch %s, log against origin/main:\n\n' "$branch"
380 git --no-pager log --oneline "origin/main..origin/$branch"
381 printf '\n'
382 git --no-pager diff "origin/main...origin/$branch"
383 } > "$REVIEW_TMP/review.diff"
384 cp "$REVIEW_TMP/review.diff" "$REVIEW_TMP/review.orig"
385 page_file "$REVIEW_TMP/review.diff" || true # quitting the pager early is not an error
386 collect_notes "$branch" "$sha"
387 cleanup_review_tmp
388}
389
390# Throwaway worktree for review's [b]ase choice; a global so the traps can
391# always clean it up — success, conflict, or ctrl-C. Never a mid-rebase state.
392REBASE_WT=""
393cleanup_rebase_wt() {
394 [ -n "$REBASE_WT" ] || return 0
395 git -C "$REBASE_WT" rebase --abort >/dev/null 2>&1 || true
396 git worktree remove --force "$REBASE_WT" >/dev/null 2>&1 || true
397 rm -rf "$REBASE_WT"
398 REBASE_WT=""
399}
400
401# Everything review leaves outside the repository: the throwaway worktree and
402# the paged buffer. One handler, installed once by cmd_review, so that no
403# path through the verb — and no ctrl-C in the pager — leaves either behind.
404cleanup_review() {
405 cleanup_rebase_wt
406 cleanup_review_tmp
407}
408
409# Rebase origin/<branch> onto origin/main in an isolated worktree — the
410# user's checkout is never touched — and push with a lease so a concurrently
411# updated branch is never clobbered. Mechanics only; the judgment on the
412# rebased diff stays with the human, back at the review prompt.
413rebase_onto_main() {
414 local branch="$1"
415 REBASE_WT="$(mktemp -d)"
416 git worktree add --quiet --detach "$REBASE_WT" "refs/remotes/origin/$branch"
417 if ! git -C "$REBASE_WT" rebase --quiet refs/remotes/origin/main; then
418 cleanup_rebase_wt
419 die "$branch conflicts with main — resolve by hand; nothing changed"
420 fi
421 if ! git -C "$REBASE_WT" push --quiet --force-with-lease \
422 origin "HEAD:refs/heads/$branch"; then
423 cleanup_rebase_wt
424 die "lease on origin/$branch failed (it moved since the fetch); nothing pushed"
425 fi
426 cleanup_rebase_wt
427 echo "rebased $branch onto origin/main, pushed with --force-with-lease"
428}
429
430# Page the branch and take the verdict. Split out of cmd_review so that
431# every way out of it — integrate, reject, skip — is followed by the notes.
432read_and_decide() {
433 local branch="$1" choice
434 show_review "$branch"
435 # A stale branch can't integrate, and its pre-rebase diff is not what would
436 # land; offer to rebase it mechanically, then re-review what actually would.
437 while ! git merge-base --is-ancestor refs/remotes/origin/main \
438 "refs/remotes/origin/$branch"; do
439 printf '%s does not fast-forward from main: [b]ase onto main, [r]eject, [s]kip? ' \
440 "$branch"
441 read -r choice || die "stdin closed before an answer; nothing done"
442 case "$choice" in
443 b)
444 rebase_onto_main "$branch"
445 fetch_origin
446 show_review "$branch"
447 ;;
448 r) reject "$branch" && return ;;
449 s)
450 echo "skipped $branch; nothing done"
451 return
452 ;;
453 *) echo "answer b, r, or s" ;;
454 esac
455 done
456 while true; do
457 printf '%s: [i]ntegrate, [r]eject, [s]kip? ' "$branch"
458 read -r choice || die "stdin closed before an answer; nothing done"
459 case "$choice" in
460 i) integrate "$branch" && return ;;
461 r) reject "$branch" && return ;;
462 s)
463 echo "skipped $branch; nothing done"
464 return
465 ;;
466 *) echo "answer i, r, or s" ;;
467 esac
468 done
469}
470
471cmd_review() {
472 [ $# -eq 1 ] || die "usage: valley review <branch>"
473 local branch="${1#origin/}"
474 fetch_origin
475 git rev-parse --verify --quiet "refs/remotes/origin/$branch" >/dev/null \
476 || die "no such branch on origin: $branch"
477 trap cleanup_review EXIT
478 trap 'exit 130' INT TERM
479 read_and_decide "$branch"
480 # The verdict disposes of the branch; the notes are what the human made of
481 # it, so they are printed whatever the verdict was.
482 print_notes "$branch"
483}
484
485# tail and replay are thin wrappers over the nats CLI — anything they do,
486# plain nats and git can do. They are the only verbs needing more than git
487# and coreutils.
488need_nats() {
489 command -v nats >/dev/null 2>&1 \
490 || die "this verb needs the nats CLI (natscli); nix run .#valley bundles it"
491}
492
493cmd_tail() {
494 [ $# -le 1 ] || die "usage: valley tail [subject]"
495 need_nats
496 exec nats sub "${1:-valley.>}"
497}
498
499# One ref-updated event per existing ref, from git for-each-ref alone. A
500# ref's prior value is not derivable from the repository, so `old` is the
501# all-zero id — the same payload a push creating the ref would produce.
502# The payload construction mirrors the host module's publisher hook
503# (nix/valley-host.nix); change one only with the other.
504cmd_replay() {
505 [ $# -le 1 ] || die "usage: valley replay [repo-dir]"
506 need_nats
507 local dir="${1:-.}" repo sha ref event count=0
508 git -C "$dir" rev-parse --git-dir >/dev/null 2>&1 \
509 || die "not a git repository: $dir"
510 if [ "$(git -C "$dir" rev-parse --is-bare-repository)" = true ]; then
511 repo="$(basename "$(git -C "$dir" rev-parse --absolute-git-dir)" .git)"
512 else
513 repo="$(basename "$(git -C "$dir" rev-parse --show-toplevel)")"
514 fi
515 while read -r sha ref; do
516 # " is the only JSON-significant character a refname can contain (git
517 # forbids \ and control characters); names and object ids are safe.
518 event="$(printf '{"event":"ref-updated","repo":"%s","ref":"%s","old":"%s","new":"%s"}' \
519 "$repo" "${ref//\"/\\\"}" "${sha//?/0}" "$sha")"
520 nats pub "valley.git.$repo.ref-updated" "$event" >/dev/null
521 count=$((count + 1))
522 done < <(git -C "$dir" for-each-ref --format='%(objectname) %(refname)')
523 echo "replayed $count refs of $repo onto the bus"
524}
525
526# ----------------------------------------------------------------------
527# checks — the verification-policy deriver (dcr-f41f718). It composes the
528# instance layer with the project layer, matches every side of a diff
529# against the composed classes, and prints the check names the change owes
530# with the class or classes that made each one required. It reports: no
531# check is run, nothing is gated, nothing is written.
532#
533# Composition is CUE's, never this script's. The whole of the mandatory-
534# versus-overridable distinction is unification, so reimplementing it here
535# would be reimplementing the decision. What this script does that CUE
536# cannot is glob matching and reading a diff.
537
538need_cue() {
539 command -v cue >/dev/null 2>&1 \
540 || die "this verb needs the cue CLI; nix run .#valley bundles it"
541}
542
543# One glob segment as an ERE fragment: `*` and `?` are wildcards that never
544# cross a `/`, and every ERE metacharacter is escaped.
545segment_ere() {
546 local seg="$1" out="" i c
547 for ((i = 0; i < ${#seg}; i++)); do
548 c="${seg:i:1}"
549 case "$c" in
550 '*') out+='[^/]*' ;;
551 '?') out+='[^/]' ;;
552 '.' | '^' | '$' | '+' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | \\) out+="\\$c" ;;
553 *) out+="$c" ;;
554 esac
555 done
556 printf '%s' "$out"
557}
558
559# A path glob as an anchored ERE, segment by segment. A `**` segment matches
560# any number of segments including none, so it swallows the separator that
561# would otherwise follow it and `a/**/b` matches `a/b`; every other segment
562# matches exactly one.
563glob_ere() {
564 local ere='^' i last
565 local -a segs=()
566 IFS=/ read -r -a segs <<<"$1"
567 last=$((${#segs[@]} - 1))
568 for ((i = 0; i <= last; i++)); do
569 if [ "${segs[i]}" = '**' ]; then
570 if [ "$i" -eq "$last" ]; then ere+='.*'; else ere+='(.*/)?'; fi
571 else
572 ere+="$(segment_ere "${segs[i]}")"
573 [ "$i" -eq "$last" ] || ere+='/'
574 fi
575 done
576 printf '%s$' "$ere"
577}
578
579# The composed policy as one tab-separated line per covered pattern and per
580# required check, so the shell never parses CUE. The field is hidden because
581# the schema's sentinel rejects unknown top-level fields, and `unclassified`
582# is rendered as a class of that name — it is one more source a check can
583# come from.
584render_cue() {
585 cat <<'EOF'
586package verification
587
588import (
589 "list"
590 "strings"
591)
592
593_render: strings.Join(list.Concat([[
594 for cn, c in policy.classes
595 for p, on in c.paths if on {"path\t\(cn)\t\(p)"}
596], [
597 for cn, c in policy.classes
598 for k, on in c.requires if on {"requires\t\(cn)\t\(k)"}
599], [
600 for k, on in policy.unclassified if on {"requires\tunclassified\t\(k)"}
601]]), "\n")
602EOF
603}
604
605# The composed layer, and a scratch directory for the documents this verb
606# writes into the composition. Globals so the probe below can see them.
607POLICY_LAYER=()
608POLICY_TMP=""
609
610# Is this check mandatory in this class, or a default the project left
611# alone? The bit is the form of the composed value, so the test is CUE's
612# own: a project supplying `false` either conflicts or unifies cleanly.
613# Answering by unifying rather than by inspecting syntax means the script
614# cannot disagree with `cue vet`.
615check_is_mandatory() {
616 local class="$1" check="$2" field
617 if [ "$class" = unclassified ]; then
618 field="policy: unclassified: \"$check\": false"
619 else
620 field="policy: classes: \"$class\": requires: \"$check\": false"
621 fi
622 printf 'package verification\n%s\n' "$field" > "$POLICY_TMP/probe.cue"
623 ! cue vet "${POLICY_LAYER[@]}" "$POLICY_TMP/probe.cue" > /dev/null 2>&1
624}
625
626# Every side of the diff: an added, modified or deleted path, and both the
627# old and the new path of a rename or copy. -z because a path may contain
628# anything but NUL.
629diff_paths() {
630 local base="$1" head="$2" status path
631 while IFS= read -r -d '' status; do
632 IFS= read -r -d '' path || die "truncated diff output; nothing derived"
633 printf '%s\n' "$path"
634 case "$status" in
635 R* | C*)
636 IFS= read -r -d '' path || die "truncated diff output; nothing derived"
637 printf '%s\n' "$path"
638 ;;
639 esac
640 done < <(git diff --no-relative --name-status -M -z "$base" "$head")
641}
642
643# Lines in, one comma-separated line out.
644join_lines() {
645 local out="" line
646 while IFS= read -r line; do out="${out:+$out, }$line"; done
647 printf '%s' "$out"
648}
649
650# The ref a branch is derived against, preferring what origin last said.
651main_ref() {
652 git rev-parse --verify --quiet refs/remotes/origin/main > /dev/null \
653 && { echo refs/remotes/origin/main; return; }
654 git rev-parse --verify --quiet refs/heads/main > /dev/null \
655 && { echo refs/heads/main; return; }
656 return 1
657}
658
659cmd_checks() {
660 local root schema instance project base head
661 root="$(git rev-parse --show-toplevel 2> /dev/null)" \
662 || die "not a git repository"
663 schema="$root/schema/verification.cue"
664 instance="$root/examples/policy/instance"
665 project="$root/examples/policy/project"
666 while [ $# -gt 0 ]; do
667 case "$1" in
668 --schema) [ $# -ge 2 ] || die "--schema needs a file"; schema="$2"; shift 2 ;;
669 --instance) [ $# -ge 2 ] || die "--instance needs a directory"; instance="$2"; shift 2 ;;
670 --project) [ $# -ge 2 ] || die "--project needs a directory"; project="$2"; shift 2 ;;
671 --) shift; break ;;
672 -*) die "unknown option: $1" ;;
673 *) break ;;
674 esac
675 done
676 [ $# -le 2 ] || die "usage: valley checks [options] [<base> [<head>]]"
677
678 need_cue
679 [ -f "$schema" ] || die "no policy schema at $schema"
680 # An unmatched glob stays literal, so the first entry is a real file
681 # exactly when the directory holds a document.
682 local -a instance_docs=("$instance"/*.cue) project_docs=("$project"/*.cue)
683 [ -f "${instance_docs[0]}" ] || die "no instance policy layer at $instance"
684 [ -f "${project_docs[0]}" ] || die "no project policy layer at $project"
685
686 head="$(git rev-parse --verify --quiet "${2:-HEAD}^{commit}")" \
687 || die "no such commit: ${2:-HEAD}"
688 if [ $# -ge 1 ]; then
689 base="$(git rev-parse --verify --quiet "$1^{commit}")" \
690 || die "no such commit: $1"
691 else
692 local against
693 against="$(main_ref)" || die "no main branch to derive a base from — name one"
694 base="$(git merge-base "$against" "$head")" \
695 || die "$head and ${against#refs/} do not share history — name a base"
696 fi
697
698 local -a paths=()
699 mapfile -t paths < <(diff_paths "$base" "$head" | sort -u)
700
701 POLICY_LAYER=("$schema" "${instance_docs[@]}" "${project_docs[@]}")
702 POLICY_TMP="$(mktemp -d)"
703 # shellcheck disable=SC2064 # expand POLICY_TMP now, not at trap time
704 trap "rm -rf '$POLICY_TMP'" EXIT
705 render_cue > "$POLICY_TMP/render.cue"
706 cue vet -c "${POLICY_LAYER[@]}" \
707 || die "the policy layers do not compose; nothing derived"
708
709 # Sorted once here, so every list below comes out in a stable order.
710 local -a rendered=()
711 mapfile -t rendered < <(cue eval --out text -e _render \
712 "${POLICY_LAYER[@]}" "$POLICY_TMP/render.cue" | sort)
713
714 local -a pat_class=() pat_ere=() req_class=() req_check=()
715 local line kind class value
716 for line in "${rendered[@]}"; do
717 kind="${line%%$'\t'*}"
718 class="${line#*$'\t'}"
719 value="${class#*$'\t'}"
720 class="${class%%$'\t'*}"
721 case "$kind" in
722 path)
723 pat_class+=("$class")
724 pat_ere+=("$(glob_ere "$value")")
725 ;;
726 requires)
727 req_class+=("$class")
728 req_check+=("$value")
729 ;;
730 esac
731 done
732
733 local -A matched=()
734 local -a uncovered=()
735 local path i hit
736 for path in "${paths[@]}"; do
737 hit=0
738 for ((i = 0; i < ${#pat_ere[@]}; i++)); do
739 if [[ "$path" =~ ${pat_ere[i]} ]]; then
740 matched["${pat_class[i]}"]=1
741 hit=1
742 fi
743 done
744 [ "$hit" -eq 1 ] || uncovered+=("$path")
745 done
746 # A path no class covers is answered by the policy's `unclassified` set,
747 # which is why it is treated as one more matched class rather than as an
748 # absence.
749 [ "${#uncovered[@]}" -eq 0 ] || matched[unclassified]=1
750
751 local -A owed=() pinned=()
752 local check width=0 uncovered_owes=0
753 for ((i = 0; i < ${#req_check[@]}; i++)); do
754 class="${req_class[i]}"
755 check="${req_check[i]}"
756 [ -n "${matched[$class]:-}" ] || continue
757 [ "$class" != unclassified ] || uncovered_owes=1
758 owed["$check"]="${owed[$check]:+${owed[$check]}, }$class"
759 if check_is_mandatory "$class" "$check"; then
760 pinned["$check"]=mandatory
761 else
762 pinned["$check"]="${pinned[$check]:-default}"
763 fi
764 [ "${#check}" -le "$width" ] || width="${#check}"
765 done
766
767 printf '%s..%s: %d changed path(s)\n' \
768 "$(git rev-parse --short "$base")" "$(git rev-parse --short "$head")" \
769 "${#paths[@]}"
770 printf 'policy: %s + %s\n' "${instance#"$root"/}" "${project#"$root"/}"
771 if [ "${#matched[@]}" -eq 0 ]; then
772 printf 'classes matched: none\n\n'
773 else
774 printf 'classes matched: %s\n\n' \
775 "$(printf '%s\n' "${!matched[@]}" | sort | join_lines)"
776 fi
777
778 if [ "${#owed[@]}" -eq 0 ]; then
779 echo "required checks: none"
780 else
781 echo "required checks:"
782 while IFS= read -r check; do
783 printf ' %-*s %-9s %s\n' \
784 "$width" "$check" "${pinned[$check]}" "${owed[$check]}"
785 done < <(printf '%s\n' "${!owed[@]}" | sort)
786 fi
787
788 if [ "${#uncovered[@]}" -gt 0 ]; then
789 printf '\nunclassified: %d path(s) matched no class\n' "${#uncovered[@]}"
790 printf ' %s\n' "${uncovered[@]}"
791 # The failure the `unclassified` field exists to prevent: paths outside
792 # every class that the policy then asks nothing of.
793 [ "$uncovered_owes" -eq 1 ] \
794 || echo " the policy requires nothing of them — it is behind the tree"
795 fi
796}
797
798main() {
799 local verb="${1:-help}"
800 if [ $# -gt 0 ]; then shift; fi
801 # The verb set is mirrored in completions/ (valley.bash, _valley) —
802 # update both when it changes.
803 case "$verb" in
804 pending) cmd_pending "$@" ;;
805 review) cmd_review "$@" ;;
806 checks) cmd_checks "$@" ;;
807 tail) cmd_tail "$@" ;;
808 replay) cmd_replay "$@" ;;
809 help | -h | --help) usage ;;
810 *)
811 printf 'valley: unknown verb: %s\n\n' "$verb" >&2
812 usage >&2
813 exit 1
814 ;;
815 esac
816}
817
818main "$@"