-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdev.sh
More file actions
executable file
·2327 lines (2128 loc) · 103 KB
/
dev.sh
File metadata and controls
executable file
·2327 lines (2128 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# dev.sh — Development-only commands for StatBus
#
# These commands are for local development and are NOT available in production.
# For production/ops commands, use ./sb (the Go CLI).
#
# Usage: ./dev.sh <command> [args...]
#
set -euo pipefail
if [ "${DEBUG:-}" = "true" ] || [ "${DEBUG:-}" = "1" ]; then
set -x
fi
# Ensure Homebrew tools (Go, etc.) are in PATH on servers
if [ -f /home/linuxbrew/.linuxbrew/bin/brew ]; then
eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"
fi
WORKSPACE="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$WORKSPACE"
# Activate repo git hooks. `.githooks/pre-push` blocks hand-rolled release
# tags and guards the postgres/Dockerfile pgrx-builder stages. A fresh
# clone has core.hooksPath unset (defaults to .git/hooks, which is empty
# here), so the guards silently wouldn't run until a developer manually
# ran the config. Setting it on every dev.sh invocation is idempotent and
# ensures the guards are live for anyone who uses dev.sh at all.
if [ "$(git config core.hooksPath 2>/dev/null || true)" != ".githooks" ]; then
git config core.hooksPath .githooks
fi
# Rebuild ./sb when EITHER drift axis fires — they need different evidence,
# and neither tool can see the other's axis:
# - the binary doesn't exist, OR
# - HOT-EDIT axis: any cli/**/*.go is newer than the binary (local WIP edit).
# Only a file mtime catches this — git can't tell whether the binary was
# built from the current *uncommitted* bytes. Self-clears on rebuild.
# - COMMITTED axis: the binary's build commit differs from HEAD with cli/
# changes between. `git commit`/`checkout`/`pull` move HEAD WITHOUT touching
# working-tree mtimes, so the mtime check above is blind to it. `./sb
# committed-drift` answers from the binary's baked-in build commit vs live
# HEAD (reliable even when the binary is stale) and exits non-zero on drift
# (or if it cannot confirm freshness). It is guard-exempt, so it never warns
# into this check.
sb_needs_rebuild=false
if ! test -x ./sb; then
sb_needs_rebuild=true
elif [ -n "$(find cli -name '*.go' -newer ./sb -print -quit 2>/dev/null)" ]; then
sb_needs_rebuild=true
elif ! ./sb committed-drift; then
sb_needs_rebuild=true
fi
if [ "$sb_needs_rebuild" = true ]; then
if command -v go >/dev/null 2>&1; then
echo "Building sb from source..."
# Inject version from git describe. Strip "v" prefix to match release.yaml
# convention — service.go adds "v" back, avoiding double-v.
# --match 'v[0-9]*' restricts git describe to release tags. The moving
# install-verified tag was deleted in rc.62; this filter remains as
# defense against any stray non-release tags landing in the refs/tags/ space.
_SB_VERSION=$(git describe --tags --always --match 'v[0-9]*' 2>/dev/null | sed 's/^v//' || echo "dev")
# Full 40-char commit_sha for cmd.commit ldflag — equality-compared
# against public.upgrade.commit_sha in the upgrade service's
# ground-truth check. Display-only trimming happens via
# upgrade.ShortForDisplay() / commitShort() in Go (rc.63 canonical).
_SB_COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
_SB_LDFLAGS="-X 'github.com/statisticsnorway/statbus/cli/cmd.version=${_SB_VERSION}' -X 'github.com/statisticsnorway/statbus/cli/cmd.commit=${_SB_COMMIT}'"
(cd cli && go build -ldflags "$_SB_LDFLAGS" -o ../sb .)
else
echo "Error: ./sb binary not found or out of date. Build it with: cd cli && go build -o ../sb ."
exit 1
fi
fi
# Auto-fetch DB seed if not cached locally.
# Intent: speeds up create-db from ~294 migrations to one pg_restore (~2 seconds).
# Uses ./sb db seed fetch — one implementation in Go, shared by dev.sh and ./sb install.
# Placed AFTER the rebuild block so the current binary is always used.
if [ ! -f "$WORKSPACE/.db-seed/seed.pg_dump" ] && [ -x ./sb ]; then
./sb db seed fetch
fi
# Set TTY_INPUT to /dev/tty if available (interactive), otherwise /dev/null
if [ -e /dev/tty ]; then
export TTY_INPUT=/dev/tty
else
export TTY_INPUT=/dev/null
fi
# ---- Tier-1 stamp guard ----
#
# Used by `./dev.sh test fast`, `./dev.sh generate-doc-db`, and
# (via a parallel Go implementation in cli/cmd/types.go) `./sb types generate`.
# Three outcomes, each printed verbatim to stdout with reason + evidence +
# override hint:
#
# REFUSED any file inside the caller's content scope has uncommitted
# changes. A stamp written now would not honestly reflect HEAD
# (dirty files aren't in the commit the stamp records), so refuse
# before doing any work.
# SKIPPED the stamp file exists, points to an ancestor of HEAD, and no
# file in the caller's content scope has changed between that
# ancestor and HEAD — re-running the command would produce an
# identical result.
# RUNNING normal execution. No stamp, or the stamp is orphaned (not an
# ancestor of HEAD — branch switch, rebase, unknown commit), or
# in-scope content drifted since the stamp.
#
# Escape hatches:
# FORCE=1 bypass all guards, always run + stamp.
# rm tmp/<stamp> force next invocation from SKIP to RUN.
#
# Arguments: <command_label> <stamp_basename> <scope_path...>
# REFUSE and SKIP share the same scope — the files the command actually
# consumes. Fast-test passes "migrations test"; types/db-docs pass just
# "migrations". Non-strict baseline paths (test/expected/explain,
# test/expected/performance) are always excluded from dirty-checks: they
# drift with environment and shouldn't block a release.
#
# Return codes: 0 = RUN (continue), 1 = SKIP (caller should exit 0),
# 2 = REFUSE (caller should exit 1).
check_stamp_guard() {
local label="$1"
local stamp_basename="$2"
shift 2
local scopes=("$@")
local stamp_path="$WORKSPACE/tmp/$stamp_basename"
# Non-strict baselines: routine environment drift, never block release.
local excludes=(':!test/expected/explain/' ':!test/expected/performance/')
if [ "${FORCE:-}" = "1" ] || [ "${FORCE:-}" = "true" ]; then
echo "RUNNING: $label"
echo "Reason: FORCE=1 — guard bypassed."
return 0
fi
# REFUSE: any file inside the scope (minus excludes) has uncommitted
# staged or unstaged changes. A stamp written on top of that would lie.
local dirty
dirty=$(git -C "$WORKSPACE" status --porcelain -- "${scopes[@]}" "${excludes[@]}" 2>/dev/null)
if [ -n "$dirty" ]; then
echo "REFUSED: $label"
echo "Reason: ${scopes[*]} has uncommitted changes — stamping would not"
echo " honestly reflect HEAD."
echo "Evidence:"
printf '%s\n' "$dirty" | sed 's/^/ /'
echo "Override: commit or stash the changes, or set FORCE=1 to bypass."
return 2
fi
if [ ! -f "$stamp_path" ]; then
echo "RUNNING: $label"
echo "Reason: no stamp at tmp/$stamp_basename — no prior successful run to skip."
return 0
fi
# Two-line stamp format: line 1 = HEAD SHA, line 2 = source DB
# migration_version. Extract line 1 for the freshness check below.
# Pre-upgrade legacy stamps have only line 1; the count check after
# this one catches and force-RUNs them so the generator upgrades the
# stamp format on next run. Without that short-circuit, an operator
# with a legacy stamp + no migrations-changed gets stuck in a SKIP
# loop: preflight refuses the stamp ("legacy single-line"), generator
# SKIPs because the stamp's SHA still matches HEAD's migrations.
local stamp_sha
stamp_sha=$(head -n 1 "$stamp_path" 2>/dev/null | tr -d '[:space:]')
if [ -z "$stamp_sha" ]; then
echo "RUNNING: $label"
echo "Reason: stamp tmp/$stamp_basename is empty."
return 0
fi
# Legacy single-line stamp detection. Two-line stamps have ≥2
# non-blank lines (SHA + migration_version); legacy stamps have 1.
# Force RUN so the generator writes the upgraded format. awk 'NF>0'
# filters non-blank lines, wc -l counts them.
local non_blank_lines
non_blank_lines=$(awk 'NF>0' "$stamp_path" 2>/dev/null | wc -l | tr -d ' ')
if [ "${non_blank_lines:-0}" -lt 2 ]; then
echo "RUNNING: $label"
echo "Reason: legacy single-line stamp at tmp/$stamp_basename — two-line format required by preflight."
return 0
fi
if ! git -C "$WORKSPACE" merge-base --is-ancestor "$stamp_sha" HEAD 2>/dev/null; then
echo "RUNNING: $label"
echo "Reason: stamp SHA $stamp_sha is not an ancestor of HEAD (branch switch, rebase, or unknown commit)."
return 0
fi
local head_sha
head_sha=$(git -C "$WORKSPACE" rev-parse HEAD 2>/dev/null)
local changed
changed=$(git -C "$WORKSPACE" diff --name-only "$stamp_sha" HEAD -- "${scopes[@]}" 2>/dev/null)
if [ -z "$changed" ]; then
# Version-coherence check: the SHA-diff axis says "no change" but the
# stamp's source-DB version (line 2) must ALSO match HEAD's on-disk max
# migration. If they diverge, release.go preflight would refuse this
# stamp — the "catch-22" scenario where a migration was applied to dev
# DB then later reverted (file deleted from tree). RUNNING so regen
# writes a fresh, coherent stamp and breaks the loop.
local stamp_version disk_max_version
stamp_version=$(sed -n '2p' "$stamp_path" 2>/dev/null | tr -d '[:space:]')
disk_max_version=$(find "$WORKSPACE/migrations" -maxdepth 1 \
\( -name '*.up.sql' -o -name '*.up.psql' \) 2>/dev/null \
| sed -E 's|.*/([0-9]{14})_.*|\1|' | sort -r | head -1)
if [ -n "$stamp_version" ] && [ -n "$disk_max_version" ] && \
[ "$stamp_version" != "$disk_max_version" ]; then
echo "RUNNING: $label"
echo "Reason: SHA-diff is empty but stamp's source-DB version ($stamp_version)"
echo " != HEAD's on-disk max migration ($disk_max_version)."
echo " release.go preflight would refuse this stamp; regen must run."
echo " (catch-22: migration applied to dev DB then reverted from tree)"
echo "Evidence:"
echo " stamp SHA: $stamp_sha"
echo " stamp source-DB version: $stamp_version"
echo " HEAD on-disk max migration: $disk_max_version"
return 0
fi
echo "SKIPPED: $label"
echo "Reason: stamp tmp/$stamp_basename points to a commit whose ${scopes[*]} content matches HEAD — re-running would produce an identical result."
echo "Evidence:"
echo " stamp SHA: $stamp_sha"
echo " HEAD SHA: $head_sha"
echo " files changed in scope (${scopes[*]}): 0"
echo "Override: rm tmp/$stamp_basename, or set FORCE=1."
return 1
fi
echo "RUNNING: $label"
echo "Reason: in-scope content has drifted since stamp."
echo "Evidence:"
echo " stamp SHA: $stamp_sha"
echo " HEAD SHA: $head_sha"
echo " files changed in scope (${scopes[*]}):"
printf '%s\n' "$changed" | sed 's/^/ /'
return 0
}
# the bash assert_db_at_head() helper has moved to Go.
# Single source of truth lives in cli/internal/migrate/at_head.go and is
# exposed at the CLI surface as `./sb assert-db-at-head <db_name> <caller>`.
# Reasons for the move:
# - The Go path can hold a PG advisory lock during the query window
# (shared variant of hashtext('statbus_seed_mutate')), serialising
# against `./sb db with-seed-lock --exclusive` so a parallel
# recreate-seed doesn't drop statbus_seed mid-query.
# - Two implementations of the same diagnostic-shape contract is one
# too many. Drift between the bash and Go copies has bitten us
# before (template-vs-seed targeting, preflight ordering); the
# bash copy is now retired.
action=${1:-}
shift || true
# ── Expected-output guardrail ─────────────────────────────────────────
#
# Used by `./dev.sh test ... --update-expected` and `make-all-failed-test-
# results-expected`. Detects NEW ERROR/FATAL/PANIC lines that the regen
# would introduce into a test/expected/*.out file. If any new error
# lacks a WANTED-context marker in the surrounding result (SAVEPOINT,
# \set ON_ERROR_STOP off, DO $$ EXCEPTION block, or "-- expected to
# fail" comment), BLOCK the regen with an educational message.
#
# Rationale: silently baselining a real error into expected hides bugs
# from CI. Future runs match the bug; everyone forgets it's there; it
# grows roots. This forces a deliberate decision at regen time.
#
# Cascade errors ("current transaction is aborted, commands ignored")
# are skipped — consequences of an earlier ERROR, not new failures.
#
# Override (rare, deliberate): ACCEPT_NEW_ERRORS=true
_unmarked_new_errors=""
_has_wanted_marker() {
local file="$1" center_line="$2"
local start=$((center_line - 10))
[ $start -lt 1 ] && start=1
local end=$((center_line + 5))
sed -n "${start},${end}p" "$file" | grep -qE '\\set ON_ERROR_STOP off|^SAVEPOINT[[:space:]]+[a-zA-Z_][a-zA-Z0-9_]*|^DO[[:space:]]+\$\$|--[[:space:]]*(expected|will|should)[[:space:]]+(to[[:space:]]+)?(fail|error)'
}
_check_new_errors() {
local expected="$1" result="$2"
_unmarked_new_errors=""
local error_linenums
if [ ! -f "$expected" ]; then
error_linenums=$(grep -nE '^(ERROR|FATAL|PANIC):' "$result" 2>/dev/null | cut -d: -f1 || true)
else
error_linenums=$(diff -u "$expected" "$result" 2>/dev/null | awk '
/^@@/ {
for (i = 1; i <= NF; i++) {
if ($i ~ /^\+/) {
sub(/^\+/, "", $i)
split($i, a, ",")
new_line = a[1] - 1
break
}
}
next
}
/^---/ || /^\+\+\+/ { next }
/^\+/ {
new_line++
if (/^\+(ERROR|FATAL|PANIC):/) print new_line
next
}
/^-/ { next }
{ new_line++ }
' || true)
fi
[ -z "$error_linenums" ] && return 0
local lineno line_text
while IFS= read -r lineno; do
[ -z "$lineno" ] && continue
line_text=$(sed -n "${lineno}p" "$result")
if echo "$line_text" | grep -q "current transaction is aborted"; then
continue
fi
if ! _has_wanted_marker "$result" "$lineno"; then
_unmarked_new_errors="${_unmarked_new_errors} ${expected#$WORKSPACE/}:${lineno}: ${line_text}"$'\n'
fi
done <<< "$error_linenums"
[ -z "$_unmarked_new_errors" ] && return 0
return 1
}
safe_update_expected() {
local result="$1" expected="$2"
if _check_new_errors "$expected" "$result"; then
cp "$result" "$expected"
return 0
fi
if [ "${ACCEPT_NEW_ERRORS:-false}" = "true" ]; then
echo " WARNING (ACCEPT_NEW_ERRORS=true override): baselining unmarked error(s):" >&2
printf '%s' "$_unmarked_new_errors" >&2
cp "$result" "$expected"
return 0
fi
cat >&2 <<EOF
═══════════════════════════════════════════════════════════════════════
BLOCKED: ${expected#$WORKSPACE/} would gain ERROR/FATAL/PANIC line(s) without WANTED-context markers.
Unmarked new error(s):
${_unmarked_new_errors}
WHY: silently baselining unexpected errors into expected files hides
bugs from CI. Future runs match the bug; everyone forgets it's there;
it grows roots.
FIX OPTIONS:
1. INTENTIONAL (bug-capture for TDD, or testing a failure path)
— add an explicit marker to the test SQL:
- Wrap in SAVEPOINT sp_<name> / ROLLBACK TO SAVEPOINT sp_<name>, OR
- Bracket with \\set ON_ERROR_STOP off ... \\set ON_ERROR_STOP on, OR
- Use DO \$\$ ... EXCEPTION WHEN ... END \$\$ for assertions, OR
- Add a comment immediately before the failing line:
-- expected to fail with <error class>
Then re-run regen. The marker travels into the expected output
and the guardrail recognises the intent.
2. ACCIDENTAL (a real bug surfacing) — FIX THE TEST SQL.
Don't baseline the bug. Investigate the failure first.
3. Deliberate override (rare; cite reason in commit message):
ACCEPT_NEW_ERRORS=true ./dev.sh ${action} ...
Hook source: dev.sh safe_update_expected
═══════════════════════════════════════════════════════════════════════
EOF
exit 1
}
case "$action" in
'postgres-variables' )
SITE_DOMAIN=$(./sb dotenv -f .env get SITE_DOMAIN || echo "local.statbus.org")
CADDY_DEPLOYMENT_MODE=$(./sb dotenv -f .env get CADDY_DEPLOYMENT_MODE || echo "development")
PGDATABASE=$(./sb dotenv -f .env get POSTGRES_APP_DB)
PGUSER=${PGUSER:-$(./sb dotenv -f .env get POSTGRES_ADMIN_USER)}
PGPASSWORD=$(./sb dotenv -f .env get POSTGRES_ADMIN_PASSWORD)
PGHOST=$SITE_DOMAIN
if [ "${TLS:-}" = "1" ] || [ "${TLS:-}" = "true" ]; then
PGPORT=$(./sb dotenv -f .env get CADDY_DB_TLS_PORT)
PGSSLNEGOTIATION=direct
PGSSLMODE=require
PGSSLSNI=1
POSTGRES_TEST_DB=$(./sb dotenv -f .env get POSTGRES_TEST_DB 2>/dev/null || echo "statbus_test_template")
cat <<EOS
export PGHOST=$PGHOST PGPORT=$PGPORT PGDATABASE=$PGDATABASE PGUSER=$PGUSER PGPASSWORD=$PGPASSWORD PGSSLMODE=$PGSSLMODE PGSSLNEGOTIATION=$PGSSLNEGOTIATION PGSSLSNI=$PGSSLSNI POSTGRES_TEST_DB=$POSTGRES_TEST_DB
EOS
else
PGPORT=$(./sb dotenv -f .env get CADDY_DB_PORT)
PGSSLMODE=disable
POSTGRES_TEST_DB=$(./sb dotenv -f .env get POSTGRES_TEST_DB 2>/dev/null || echo "statbus_test_template")
cat <<EOS
export PGHOST=$PGHOST PGPORT=$PGPORT PGDATABASE=$PGDATABASE PGUSER=$PGUSER PGPASSWORD=$PGPASSWORD PGSSLMODE=$PGSSLMODE POSTGRES_TEST_DB=$POSTGRES_TEST_DB
EOS
fi
;;
'is-db-running' )
docker compose exec -T db pg_isready -U postgres > /dev/null 2>&1
;;
'continous-integration-test' )
BRANCH=${BRANCH:-${1:-}}
COMMIT=${COMMIT:-${2:-}}
if [ -z "$BRANCH" ]; then
BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo "No branch argument provided, using the currently checked-out branch $BRANCH"
else
if ! git diff-index --quiet HEAD --; then
echo "Error: Repository has uncommitted changes. Please commit or stash changes before switching branches."
exit 1
fi
git fetch origin
if [ -z "$COMMIT" ]; then
echo "Error: Commit hash must be provided."
exit 1
fi
if ! git cat-file -e "$COMMIT" 2>/dev/null; then
echo "Error: Commit '$COMMIT' is invalid or not found."
exit 1
fi
echo "Checking out commit '$COMMIT' (from branch '$BRANCH')"
git checkout "$COMMIT"
fi
# Build sb from source if it doesn't exist or is outdated.
# The test server may not have a pre-built binary.
if [ ! -x ./sb ] || ! ./sb --version >/dev/null 2>&1; then
echo "Building sb from source..."
_SB_VERSION=$(git describe --tags --always --match 'v[0-9]*' 2>/dev/null | sed 's/^v//' || echo "dev")
# Full 40-char SHA — see note at line ~51 for rationale.
_SB_COMMIT=$(git rev-parse HEAD 2>/dev/null || echo "unknown")
_SB_LDFLAGS="-X 'github.com/statisticsnorway/statbus/cli/cmd.version=${_SB_VERSION}' -X 'github.com/statisticsnorway/statbus/cli/cmd.commit=${_SB_COMMIT}'"
(cd cli && go build -ldflags "$_SB_LDFLAGS" -o ../sb .)
fi
./sb config generate
# Pull pre-built Docker images from ghcr.io if available.
# CI Images workflow builds sha-tagged images for every master push.
if [ -n "$COMMIT" ]; then
echo "Pulling cached Docker images for sha-${COMMIT}..."
VERSION="sha-${COMMIT}" docker compose pull --quiet 2>/dev/null || echo "No cached images, will build locally"
fi
./dev.sh delete-db
./dev.sh create-db > /dev/null
trap './dev.sh delete-db > /dev/null' EXIT
TEST_OUTPUT=$(mktemp)
# Use the auto-fix composition for CI: bootstraps seed +
# test template if a fresh runner needs them. Human-facing
# `./dev.sh test fast` is check-don't-fix; this path is the
# CI-friendly equivalent. Plan section R commit 4.
./dev.sh migrate-and-test fast 2>&1 | tee "$TEST_OUTPUT" || true
if grep -q "not ok" "$TEST_OUTPUT" || grep -q "of .* tests failed" "$TEST_OUTPUT"; then
echo "One or more tests failed."
echo "Test summary:"
grep -A 20 "======================" "$TEST_OUTPUT"
if command -v delta >/dev/null 2>&1; then
echo "Showing the color-coded diff:"
docker compose exec --workdir /statbus db cat /statbus/test/regression.diffs | delta
else
echo "Error: 'delta' tool is not installed. Install with: brew install git-delta"
echo "Showing raw diff:"
docker compose exec --workdir /statbus db cat /statbus/test/regression.diffs
fi
exit 1
else
echo "All tests passed successfully."
fi
;;
'test' )
eval $(./dev.sh postgres-variables)
POSTGRESQL_MAJOR=$(grep -E "^ARG postgresql_major=" "$WORKSPACE/postgres/Dockerfile" | cut -d= -f2)
if [ -z "$POSTGRESQL_MAJOR" ]; then
echo "Error: Could not extract PostgreSQL major version from Dockerfile"
exit 1
fi
PG_REGRESS_DIR="$WORKSPACE/test"
PG_REGRESS="/usr/lib/postgresql/$POSTGRESQL_MAJOR/lib/pgxs/src/test/regress/pg_regress"
CONTAINER_REGRESS_DIR="/statbus/test"
for suffix in "sql" "expected" "results"; do
if ! test -d "$PG_REGRESS_DIR/$suffix"; then
mkdir -p "$PG_REGRESS_DIR/$suffix"
fi
done
ORIGINAL_ARGS=("$@")
update_expected=false
TEST_ARGS=()
if [ ${#ORIGINAL_ARGS[@]} -gt 0 ]; then
for arg in "${ORIGINAL_ARGS[@]}"; do
if [ "$arg" = "--update-expected" ]; then
update_expected=true
else
TEST_ARGS+=("$arg")
fi
done
fi
if [ ${#TEST_ARGS[@]} -eq 0 ]; then
echo "Available tests:"
echo "all"
echo "fast"
echo "benchmarks"
echo "failed"
basename -s .sql "$PG_REGRESS_DIR/sql"/*.sql
exit 0
fi
if [ "${TEST_ARGS[0]}" = "all" ]; then
ALL_TESTS=$(basename -s .sql "$PG_REGRESS_DIR/sql"/*.sql)
TEST_BASENAMES=""
for test in $ALL_TESTS; do
exclude=false
for arg in "${TEST_ARGS[@]:1}"; do
if [ "$arg" = "-$test" ]; then
exclude=true
break
fi
done
if [ "$exclude" = "false" ]; then
TEST_BASENAMES="$TEST_BASENAMES $test"
fi
done
elif [ "${TEST_ARGS[0]}" = "fast" ]; then
ALL_TESTS=$(basename -s .sql "$PG_REGRESS_DIR/sql"/*.sql)
TEST_BASENAMES=""
for test in $ALL_TESTS; do
exclude=false
if [[ "$test" == 4* ]] || [[ "$test" == 5* ]]; then
exclude=true
fi
if [ "$exclude" = "false" ]; then
for arg in "${TEST_ARGS[@]:1}"; do
if [ "$arg" = "-$test" ]; then
exclude=true
break
fi
done
fi
if [ "$exclude" = "false" ]; then
TEST_BASENAMES="$TEST_BASENAMES $test"
fi
done
elif [ "${TEST_ARGS[0]}" = "benchmarks" ]; then
ALL_TESTS=$(basename -s .sql "$PG_REGRESS_DIR/sql"/*.sql)
TEST_BASENAMES=""
for test in $ALL_TESTS; do
exclude=false
if [[ "$test" != 4* ]]; then
exclude=true
fi
if [ "$exclude" = "false" ]; then
for arg in "${TEST_ARGS[@]:1}"; do
if [ "$arg" = "-$test" ]; then
exclude=true
break
fi
done
fi
if [ "$exclude" = "false" ]; then
TEST_BASENAMES="$TEST_BASENAMES $test"
fi
done
elif [ "${TEST_ARGS[0]}" = "failed" ]; then
FAILED_TESTS=$(grep -E '^not ok' $WORKSPACE/test/regression.out | sed -E 's/not ok[[:space:]]+[0-9]+[[:space:]]+- ([^[:space:]]+).*/\1/')
TEST_BASENAMES=""
for test in $FAILED_TESTS; do
exclude=false
for arg in "${TEST_ARGS[@]:1}"; do
if [ "$arg" = "-$test" ]; then
exclude=true
break
fi
done
if [ "$exclude" = "false" ]; then
TEST_BASENAMES="$TEST_BASENAMES $test"
fi
done
else
TEST_BASENAMES=""
for arg in "${TEST_ARGS[@]}"; do
if [[ "$arg" != -* ]]; then
TEST_BASENAMES="$TEST_BASENAMES $arg"
fi
done
fi
INVALID_TESTS=""
for test_basename in $TEST_BASENAMES; do
if [ ! -f "$PG_REGRESS_DIR/sql/$test_basename.sql" ]; then
INVALID_TESTS="$INVALID_TESTS $test_basename"
fi
done
if [ -n "$INVALID_TESTS" ]; then
echo "Error: Test(s) not found:$INVALID_TESTS"
echo ""
echo "Available tests:"
echo " all - Run all tests"
echo " fast - Run all tests except 4xx/5xx (large imports)"
echo " benchmarks - Run only 4xx tests (performance benchmarks)"
echo " failed - Re-run previously failed tests"
echo ""
echo "Individual tests:"
basename -s .sql "$PG_REGRESS_DIR/sql"/*.sql | sed 's/^/ /'
exit 1
fi
# Tier-1 stamp guard — only on the `fast` selector, which writes
# tmp/fast-test-passed-sha on success. Refuse dirty migrations (stamp
# would lie), skip when the stamp still represents HEAD's migrations +
# test content.
if [ "${TEST_ARGS[0]}" = "fast" ]; then
set +e
check_stamp_guard "./dev.sh test fast" "fast-test-passed-sha" "migrations" "test"
guard_rc=$?
set -e
case $guard_rc in
0) : ;;
1) exit 0 ;;
2) exit 1 ;;
esac
fi
SHARED_TESTS=""
ISOLATED_TESTS=""
for test_basename in $TEST_BASENAMES; do
expected_file="$PG_REGRESS_DIR/expected/$test_basename.out"
if [ ! -f "$expected_file" ] && [ -f "$PG_REGRESS_DIR/sql/$test_basename.sql" ]; then
echo "Warning: Expected output file $expected_file not found. Creating an empty placeholder."
touch "$expected_file"
fi
if [[ "$test_basename" == 4* ]] || [[ "$test_basename" == 5* ]]; then
ISOLATED_TESTS="$ISOLATED_TESTS $test_basename"
else
SHARED_TESTS="$SHARED_TESTS $test_basename"
fi
done
debug_arg=""
if [ "${DEBUG:-}" = "true" ] || [ "${DEBUG:-}" = "1" ]; then
debug_arg="--debug"
fi
# Precondition (plan section R commit 4: check, don't fix —
# consolidated to use the unified ./sb assert-db-at-head primitive).
# `./dev.sh test ...` is human-facing — refuses to
# run with stale state and prints the exact remediation command.
# CI/automation that wants auto-rebuild should call
# `./dev.sh migrate-and-test ...` instead.
#
# Assert against the SEED (canonical source-of-truth), not the
# test_template. The seed/template chain
# is: template_statbus → statbus_seed → statbus_test_template.
# The test_template is intentionally non-connectable
# (ALLOW_CONNECTIONS=false) so per-test clones go fast; querying
# it directly silently returned 0 rows and produced a false
# "BEHIND HEAD" diagnostic in the original wiring. The seed
# IS the source of truth — when it's at HEAD, every clone
# downstream (test_template, transient test DBs) is too by
# construction. The test_template's freshness relative to the
# seed is policed separately by the tmp/test-template-migrations-sha
# stamp check that migrate-and-test fast enforces.
#
# SOURCE_VERSION captured for the H1 two-line stamp write below.
SEED_NAME_PRECHECK="${POSTGRES_SEED_DB:-statbus_seed}"
# migrated from the bash assert_db_at_head
# function to the Go subcommand `./sb assert-db-at-head`, which
# internally acquires a SHARED advisory lock on the
# statbus_seed mutation key. That serialises against
# `./sb db with-seed-lock --exclusive` so a parallel
# recreate-seed doesn't drop statbus_seed mid-query.
# A3: assert-db-at-head already prints a complete REFUSED / Reason / Fix
# block whose Fix line is the seed/template rebuild command — don't echo
# a second, near-identical remediation. With the binary-staleness noise
# gone (A1/A2), this legitimate seed-drift refuse stands alone as one
# actionable block.
if ! SOURCE_VERSION=$(./sb assert-db-at-head "$SEED_NAME_PRECHECK" "./dev.sh test fast"); then
exit 1
fi
OVERALL_EXIT_CODE=0
if [ -n "$SHARED_TESTS" ]; then
TEMPLATE_NAME="${POSTGRES_TEST_DB:-statbus_test_template}"
SHARED_TEST_DB="test_shared_$$"
TEMPLATE_EXISTS=$(./sb psql -d postgres -t -A -c \
"SELECT 1 FROM pg_database WHERE datname = '$TEMPLATE_NAME';" 2>/dev/null || echo "0")
if [ "$TEMPLATE_EXISTS" != "1" ]; then
echo "Error: Template database '$TEMPLATE_NAME' not found."
echo "Create it with: ./dev.sh create-test-template"
exit 1
fi
echo "=== Running shared tests (BEGIN/ROLLBACK isolation on cloned database) ==="
echo "Creating shared test database: $SHARED_TEST_DB from template $TEMPLATE_NAME"
if ! ./sb psql -d postgres -v ON_ERROR_STOP=1 <<EOF
SELECT pg_advisory_lock(59328);
ALTER DATABASE $TEMPLATE_NAME WITH ALLOW_CONNECTIONS = true;
CREATE DATABASE "$SHARED_TEST_DB" WITH TEMPLATE $TEMPLATE_NAME;
ALTER DATABASE $TEMPLATE_NAME WITH ALLOW_CONNECTIONS = false;
SELECT pg_advisory_unlock(59328);
EOF
then
echo "Error: Failed to create shared test database from template"
exit 1
fi
cleanup_shared_test_db() {
local exit_code=$?
if [ "${PERSIST:-false}" = "true" ]; then
echo "PERSIST=true: Keeping shared test database: $SHARED_TEST_DB"
return $exit_code
fi
if [ -n "$SHARED_TEST_DB" ]; then
echo "Cleaning up shared test database: $SHARED_TEST_DB"
./sb psql -d postgres -c "DROP DATABASE IF EXISTS \"$SHARED_TEST_DB\";" 2>/dev/null || true
fi
return $exit_code
}
trap cleanup_shared_test_db EXIT
docker compose exec --workdir "/statbus" db \
$PG_REGRESS $debug_arg \
--use-existing \
--bindir="/usr/lib/postgresql/$POSTGRESQL_MAJOR/bin" \
--inputdir=$CONTAINER_REGRESS_DIR \
--outputdir=$CONTAINER_REGRESS_DIR \
--dbname="$SHARED_TEST_DB" \
--user=$PGUSER \
$SHARED_TESTS || OVERALL_EXIT_CODE=$?
fi
if [ -n "$ISOLATED_TESTS" ]; then
echo ""
echo "=== Running isolated tests (database-per-test from template) ==="
for test_basename in $ISOLATED_TESTS; do
update_arg=""
if [ "$update_expected" = "true" ]; then
update_arg="--update-expected"
fi
./dev.sh test-isolated "$test_basename" $update_arg || OVERALL_EXIT_CODE=$?
done
fi
if [ "$update_expected" = "true" ] && [ -n "$SHARED_TESTS" ]; then
echo "Updating expected output for shared tests: $(echo $SHARED_TESTS)"
for test_basename in $SHARED_TESTS; do
result_file="$PG_REGRESS_DIR/results/$test_basename.out"
expected_file="$PG_REGRESS_DIR/expected/$test_basename.out"
if [ -f "$result_file" ]; then
echo " -> Copying results for $test_basename"
safe_update_expected "$result_file" "$expected_file"
else
echo "Warning: Result file not found for test: '$test_basename'. Cannot update expected output."
fi
done
fi
# Write the stamp unconditionally on success — the upfront REFUSE
# guard already verified migrations/ and test/ (minus non-strict
# baselines) were clean at RUN time, AND ./sb assert-db-at-head
# above confirmed the seed matches HEAD's on-disk migrations,
# so HEAD + SOURCE_VERSION is an honest pair. No silent skip:
# if we got here, we stamp.
#
# H1 two-line stamp:
# line 1: HEAD SHA at test-pass time
# line 2: source DB (test template) migration_version at test-pass time
if [ $OVERALL_EXIT_CODE -eq 0 ]; then
mkdir -p "$WORKSPACE/tmp"
{
git rev-parse HEAD
echo "$SOURCE_VERSION"
} > "$WORKSPACE/tmp/fast-test-passed-sha"
echo "Fast test stamp recorded: $(head -1 "$WORKSPACE/tmp/fast-test-passed-sha") (source version: $SOURCE_VERSION)"
fi
exit $OVERALL_EXIT_CODE
;;
'migrate-and-test' )
# CI-friendly composition (plan section R commit 4): bootstrap
# the seed + test template if needed, then run tests. Auto-fix
# complement to the human-facing `./dev.sh test ...` (which is
# check-don't-fix).
#
# Use case: CI workflow on a fresh runner with no DB state, OR
# a local cold workspace post-`git pull` with new migrations.
# Bootstraps from cold to running tests in one command.
eval $(./dev.sh postgres-variables)
SEED_NAME="${POSTGRES_SEED_DB:-statbus_seed}"
LATEST_MIGRATION=$(for f in "$WORKSPACE/migrations/"*.up.sql "$WORKSPACE/migrations/"*.up.psql; do
[ -e "$f" ] || continue
basename "$f" | cut -d_ -f1
done | sort | tail -1)
# Step 1: ensure seed exists and is at HEAD.
SEED_EXISTS=$(./sb psql -d postgres -t -A -c \
"SELECT 1 FROM pg_database WHERE datname = '$SEED_NAME';" 2>/dev/null || echo "0")
SEED_MAX_VERSION=""
if [ "$SEED_EXISTS" = "1" ]; then
SEED_MAX_VERSION=$(./sb psql -d "$SEED_NAME" -t -A -c \
"SELECT MAX(version) FROM db.migration" 2>/dev/null | tr -d ' ' || true)
fi
if [ "$SEED_EXISTS" != "1" ] || [ "$SEED_MAX_VERSION" != "$LATEST_MIGRATION" ]; then
echo "migrate-and-test: seed bootstrap (exists=$SEED_EXISTS, version='$SEED_MAX_VERSION', want '$LATEST_MIGRATION')..."
./dev.sh recreate-seed
else
echo "migrate-and-test: seed already at $SEED_MAX_VERSION (matches HEAD)."
fi
# Step 2: ensure test template fresh.
TEMPLATE_STAMP=""
if [ -f "$WORKSPACE/tmp/test-template-migrations-sha" ]; then
TEMPLATE_STAMP=$(cat "$WORKSPACE/tmp/test-template-migrations-sha")
fi
if [ "$TEMPLATE_STAMP" != "$LATEST_MIGRATION" ]; then
echo "migrate-and-test: test template stale (stamp='$TEMPLATE_STAMP', want '$LATEST_MIGRATION'). Rebuilding..."
./dev.sh create-test-template
else
echo "migrate-and-test: test template already at $TEMPLATE_STAMP."
fi
# Step 3: run tests with whatever args were passed.
./dev.sh test "$@"
;;
'diff-fail-first' )
if [ ! -f "$WORKSPACE/test/regression.out" ]; then
echo "Error: File $WORKSPACE/test/regression.out not found."
echo "Run tests first: ./dev.sh test fast"
exit 1
fi
if [ ! -r "$WORKSPACE/test/regression.out" ]; then
echo "Error: Cannot read $WORKSPACE/test/regression.out"
exit 1
fi
test_line=$(grep -a -E '^not ok' "$WORKSPACE/test/regression.out" | head -n 1)
if [[ "$test_line" =~ ^Binary\ file.*matches$ ]]; then
echo "Error: Cannot parse test results. The regression.out file may be corrupted."
echo "Try running tests again: ./dev.sh test fast"
exit 1
fi
if [ -n "$test_line" ]; then
test=$(echo "$test_line" | sed -E 's/not ok[[:space:]]+[0-9]+[[:space:]]+- ([^[:space:]]+).*/\1/')
ui_choice=${1:-pipe}
line_limit=${2:-}
case $ui_choice in
'gui')
echo "Running opendiff for test: $test"
opendiff $WORKSPACE/test/expected/$test.out $WORKSPACE/test/results/$test.out -merge $WORKSPACE/test/expected/$test.out
;;
'vim'|'tui')
echo "Running vim -d for test: $test"
vim -d $WORKSPACE/test/expected/$test.out $WORKSPACE/test/results/$test.out < "$TTY_INPUT"
;;
'vimo')
echo "Running vim -d -o for test: $test"
vim -d -o $WORKSPACE/test/expected/$test.out $WORKSPACE/test/results/$test.out < "$TTY_INPUT"
;;
'pipe')
echo "Running diff for test: $test"
if [[ "$line_limit" =~ ^[0-9]+$ ]]; then
diff $WORKSPACE/test/expected/$test.out $WORKSPACE/test/results/$test.out | head -n "$line_limit" || true
else
diff $WORKSPACE/test/expected/$test.out $WORKSPACE/test/results/$test.out || true
fi
;;
*)
echo "Error: Unknown UI option '$ui_choice'. Please use 'gui', 'vim', 'vimo', or 'pipe'."
exit 1
;;
esac
else
echo "No failing tests found."
fi
;;
'diff-fail-all' )
if [ ! -f "$WORKSPACE/test/regression.out" ]; then
echo "Error: File $WORKSPACE/test/regression.out not found."
echo "Run tests first: ./dev.sh test fast"
exit 1
fi
if [ ! -r "$WORKSPACE/test/regression.out" ]; then
echo "Error: Cannot read $WORKSPACE/test/regression.out"
exit 1
fi
ui_choice=${1:-pipe}
line_limit=${2:-}
first_line=$(grep -a -E '^not ok' "$WORKSPACE/test/regression.out" | head -n 1)
if [[ "$first_line" =~ ^Binary\ file.*matches$ ]]; then
echo "Error: Cannot parse test results. The regression.out file may be corrupted."
echo "Try running tests again: ./dev.sh test fast"
exit 1
fi
if [ -z "$first_line" ]; then
echo "No failing tests found in regression.out"
exit 0
fi
while read test_line; do
test=$(echo "$test_line" | sed -E 's/not ok[[:space:]]+[0-9]+[[:space:]]+- ([^[:space:]]+).*/\1/')
if [ "$ui_choice" != "pipe" ]; then
echo "Next test: $test"
echo "Press C to continue, s to skip, or b to break (default: C)"
read -n 1 -s input < "$TTY_INPUT"
if [ "$input" = "b" ]; then
break
elif [ "$input" = "s" ]; then
continue
fi
fi
case $ui_choice in
'gui')
echo "Running opendiff for test: $test"
opendiff $WORKSPACE/test/expected/$test.out $WORKSPACE/test/results/$test.out -merge $WORKSPACE/test/expected/$test.out
;;
'vim'|'tui')
echo "Running vim -d for test: $test"
vim -d $WORKSPACE/test/expected/$test.out $WORKSPACE/test/results/$test.out < "$TTY_INPUT"
;;
'vimo')
echo "Running vim -d -o for test: $test"
vim -d -o $WORKSPACE/test/expected/$test.out $WORKSPACE/test/results/$test.out < "$TTY_INPUT"
;;
'pipe')
echo "Running diff for test: $test"
if [[ "$line_limit" =~ ^[0-9]+$ ]]; then
diff $WORKSPACE/test/expected/$test.out $WORKSPACE/test/results/$test.out | head -n "$line_limit" || true
else
diff $WORKSPACE/test/expected/$test.out $WORKSPACE/test/results/$test.out || true
fi
;;
*)
echo "Error: Unknown UI option '$ui_choice'. Please use 'gui', 'vim', 'vimo', or 'pipe'."
exit 1
;;
esac
done < <(grep -a -E '^not ok' "$WORKSPACE/test/regression.out")
;;
'make-all-failed-test-results-expected' )
if [ ! -f "$WORKSPACE/test/regression.out" ]; then
echo "Error: No regression.out file found."
echo "Run tests first: ./dev.sh test fast"
exit 1
fi
if [ ! -r "$WORKSPACE/test/regression.out" ]; then
echo "Error: Cannot read $WORKSPACE/test/regression.out"
exit 1
fi
grep -a -E '^not ok' "$WORKSPACE/test/regression.out" | while read -r test_line; do
test=$(echo "$test_line" | sed -E 's/not ok[[:space:]]+[0-9]+[[:space:]]+- ([^[:space:]]+).*/\1/')
if [ -f "$WORKSPACE/test/results/$test.out" ]; then
echo "Copying results to expected for test: $test"
safe_update_expected "$WORKSPACE/test/results/$test.out" "$WORKSPACE/test/expected/$test.out"
else
echo "Warning: No results file found for test: $test"
fi
done
;;
'create-db-structure' )
eval $(./dev.sh postgres-variables)