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