Repository navigation
Expand file tree
/
Copy pathrelease.sh
More file actions
executable file
·2044 lines (1953 loc) · 105 KB
/
Copy pathrelease.sh
File metadata and controls
executable file
·2044 lines (1953 loc) · 105 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
#!/usr/bin/env bash
# release.sh — ONE command for a full HugMesh org release, beta or stable (docs/RELEASING.md).
#
# scripts/release.sh # = --channel beta --dry-run: read-only plan
# scripts/release-beta.sh ... # the same as scripts/release.sh --channel beta ...
# scripts/release.sh --channel beta --apply --studio 0.3.0-beta.2
# # run every phase in order, asking y/N before each write
# scripts/release.sh --apply --merge hugmesh-games#50 --studio next
# scripts/release.sh --apply --from java # resume at a phase (re-running skips DONE work anyway)
# scripts/release.sh --apply --only hugmesh-admin-ui # act on these repos only (repeatable);
# # stages with none of them are skipped, never a stop
# scripts/release.sh --apply --only hugmesh-generator@akkoma
# # an ARTIFACT row: a repository's second artifact
# # (repos.tsv; beta channel only)
# scripts/release.sh --urls # only list the packages that are not public yet
# scripts/release.sh --channel stable # dry run of a stable cut: release/X.Y per repo
# scripts/release.sh --channel stable --apply # cut, bump PRs, tag, next-beta PRs (asks first)
# scripts/release.sh --channel stable --version 0.3.1 --only hugmesh-admin-ui
# # a patch release on the existing release/0.3
#
# Options: --channel beta|stable (default beta) --dry-run (default) | --apply
# --yes (answer y to every y/N; each action is still printed)
# --merge <repo>#<n> (repeatable) --only <repo> (repeatable) --from <phase>
# --studio <version>|next | --no-studio --expect <repo>=<version> (repeatable pin)
# --version X.Y.Z (stable only, needs --only: a patch release on release/X.Y)
#
# Phases, beta: preflight merge maven apps rerun gateway gateway-access overlays java
# studio visibility site verify
# Phases, stable: preflight cut bump merge maven apps rerun gateway gateway-access overlays
# java studio visibility site next verify
#
# Versions are never typed here (except a stable patch's --version): each repo's version
# is read from its version file (scripts/release/repos.tsv says which file). BETA releases
# main, whose version must be MAJOR.MINOR.PATCH-beta.N. STABLE releases the repo's own
# release/X.Y branch as X.Y.Z, where X.Y.Z is main's beta with the -beta.N dropped (a cut)
# or --version (a patch). Every repo is reported as DONE (tag exists and its run is
# green), READY, REFUSE (with the reason and the next command), NEEDS-BUMP (beta: the
# published tag IS main's version but main has commits since it, or a stable X.Y.Z at or
# above main's beta line is already out), RUNNING (its tag run is
# in flight), and on the stable channel NEEDS-CUT (release/X.Y does not exist yet: the
# cut phase creates it) or NEEDS-PR (release/X.Y does not carry X.Y.Z yet: the bump phase
# opens the version-bump PR). The verify phase also flags each selected image package's
# floating tags (:latest, :beta, :X.Y, :main) that are unsigned, unreadable, or a :latest
# with no stable X.Y.Z, and prints the operator's delete command; it never deletes.
#
# Every gh call goes through GH() with GH_TOKEN/GITHUB_TOKEN unset (an exported read-only
# token shadows the keyring login on this fleet). No secret value is ever read or printed.
# Under --dry-run nothing writes: no POST/PATCH/PUT/DELETE, no run rerun, workflow run,
# pr create/merge/ready or release create (tests/scripts/test-release-beta.sh proves it).
set -euo pipefail
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
ROOT=$(cd "$HERE/.." && pwd)
ORG="${RELEASE_BETA_ORG:-hugmesh}"
TABLE="${RELEASE_BETA_TABLE:-$HERE/release/repos.tsv}"
STUDIO_SCRIPT="${RELEASE_BETA_STUDIO_SCRIPT:-$HERE/release-studio.sh}"
SITE_REPO="$ORG/hugmesh.github.io"
POLL="${RELEASE_BETA_POLL:-10}" # seconds between polls
TRIES="${RELEASE_BETA_TRIES:-30}" # polls before "no run appeared" (30 x 10 s = 5 min)
RERUN_MAX_DAYS=30 # GitHub refuses to re-run a run older than this
BETA_PHASES=(preflight merge maven apps rerun gateway gateway-access overlays java studio visibility site verify)
STABLE_PHASES=(preflight cut bump merge maven apps rerun gateway gateway-access overlays java studio visibility site next verify)
usage() { sed -n '2,/^set -euo pipefail$/p' "${BASH_SOURCE[0]}" | sed '$d' | sed 's/^# \{0,1\}//'; }
MODE=dry; YES=false; FROM=preflight; STUDIO=""; URLS_ONLY=false; CHANNEL=beta; PATCH_VERSION=""
ONLY=(); MERGES=(); declare -A EXPECT=()
ORIG_ARGS=()
while [ $# -gt 0 ]; do
case "$1" in
--channel) shift; CHANNEL="${1:?--channel needs beta or stable}" ;;
--channel=*) CHANNEL="${1#--channel=}" ;;
--version) shift; PATCH_VERSION="${1:?--version needs X.Y.Z}"; ORIG_ARGS+=(--version "$1") ;;
--dry-run|-n) MODE=dry ;;
--apply) MODE=apply ;;
--yes|-y) YES=true; ORIG_ARGS+=("$1") ;;
--urls) URLS_ONLY=true ;;
--only) shift; ONLY+=("${1:?--only needs a repo}"); ORIG_ARGS+=(--only "$1") ;;
--merge) shift; MERGES+=("${1:?--merge needs <repo>#<number>}"); ORIG_ARGS+=(--merge "$1") ;;
--from) shift; FROM="${1:?--from needs a phase}" ;;
--studio) shift; STUDIO="${1:?--studio needs a version, or next}"; ORIG_ARGS+=(--studio "$1") ;;
--no-studio) STUDIO=none; ORIG_ARGS+=("$1") ;;
--expect) shift; e="${1:?--expect needs <repo>=<version>}"; [[ "$e" == *=* ]] || { echo "release.sh: --expect needs <repo>=<version>, got '$e'" >&2; exit 2; }
EXPECT[${e%%=*}]="${e#*=}"; ORIG_ARGS+=(--expect "$e") ;;
-h|--help) usage; exit 0 ;;
*) echo "release.sh: unknown argument: $1 (see --help)" >&2; exit 2 ;;
esac
shift
done
case "$CHANNEL" in
beta) PHASES=("${BETA_PHASES[@]}") ;;
stable) PHASES=("${STABLE_PHASES[@]}") ;;
*) echo "release.sh: --channel must be beta or stable, got '$CHANNEL'" >&2; exit 2 ;;
esac
say() { printf '%s\n' "$*"; }
die() { say "release.sh: $*" >&2; exit 2; }
GH() { env -u GH_TOKEN -u GITHUB_TOKEN gh "$@" </dev/null; }
# ghq: like GH, but prints NOTHING and returns 1 on any error (gh prints the JSON error body
# to stdout on HTTP errors, which must never be mistaken for data). A 404 is an answer; any
# other error (a secondary rate limit, a dropped connection) is retried twice, because an
# empty answer here reads as "no run" / "no tag" and would misreport a repo's state.
RETRY_SLEEP="${RELEASE_BETA_RETRY_SLEEP:-5}"
# ghs: ghq with the 404 told apart: rc 0 data, rc 4 "not found" (HTTP 404, release not
# found), rc 1 anything else (after the retries). For checks that must fail closed.
ghs() {
local o e i
e=$(mktemp "${TMPDIR:-/tmp}/release-beta.XXXXXX")
for i in 1 2 3; do
if o=$(GH "$@" 2>"$e"); then rm -f "$e"; printf '%s' "$o"; return 0; fi
if grep -a 'HTTP 404' "$e" >/dev/null || grep -a 'release not found' "$e" >/dev/null; then rm -f "$e"; return 4; fi
[ "$i" = 3 ] || sleep "$RETRY_SLEEP"
done
rm -f "$e"; return 1
}
ghq() { ghs "$@" || return 1; }
# A path as it is safe to paste into a PR or a chat: relative to this checkout, or just
# its file name when it lies outside it (never a home directory).
shown() {
case "$1" in
"$ROOT"/*) printf '%s' "${1#"$ROOT"/}" ;;
*) printf '%s (outside the checkout)' "$(basename "$1")" ;;
esac
}
# The exact command that resumes this run at a phase.
resume_cmd() {
if [ "$CHANNEL" = beta ]; then printf 'scripts/release-beta.sh --apply'; else printf 'scripts/release.sh --channel %s --apply' "$CHANNEL"; fi
[ ${#ORIG_ARGS[@]} -eq 0 ] || printf ' %q' "${ORIG_ARGS[@]}"
printf ' --from %s\n' "$1"
}
next_phase() { local i; i=$(phase_index "$1"); echo "${PHASES[$((i+1))]:-verify}"; }
phase_index() { local i; for i in "${!PHASES[@]}"; do [ "${PHASES[$i]}" = "$1" ] && { echo "$i"; return 0; }; done; return 1; }
FROM_I=$(phase_index "$FROM") || die "--from: unknown phase '$FROM' (phases: ${PHASES[*]})"
# ── the table ────────────────────────────────────────────────────────────────
[ -r "$TABLE" ] || die "cannot read the repo table $TABLE"
ROWS=()
# A row's first column is its ID. Usually that is the repository; a repository that
# publishes a SECOND artifact with its own tag prefix and workflow (hugmesh-generator:
# the mesh-node image AND hugmesh-akkoma) gets one more row whose ID is
# <repository>@<artifact>. Every GitHub call takes the repository, ${id%@*}, which is
# the ID itself for every ordinary row; everything else (state, --only, --expect, the
# printed plan) is keyed by the ID. Artifact rows are BETA-ONLY: the stable channel
# cuts one release/X.Y and opens one bump PR per repository, and two rows of one
# repository would collide on both, so `--channel stable` skips them (and refuses one
# named with --only).
declare -A T_STAGE=() T_KIND=() T_VFILE=() T_PREFIX=() T_WF=() T_PKGS=() T_MIRRORS=()
ARTIFACT_SKIPPED=()
while IFS='|' read -r st repo kind vfile prefix wf pkgs mirrors; do
case "$st" in ''|'#'*) continue ;; esac
case "$st" in [1-9]) ;; *) die "$TABLE: bad stage '$st' for '$repo'" ;; esac
case "$kind" in mvn|img) ;; *) die "$TABLE: bad kind '$kind' for '$repo'" ;; esac
[ -n "$repo" ] && [ -n "$vfile" ] && [ -n "$prefix" ] && [ -n "$wf" ] && [ -n "$pkgs" ] || die "$TABLE: incomplete row for '$repo'"
case "$repo" in
*@*)
[[ "$repo" =~ ^[A-Za-z0-9._-]+@[a-z0-9-]+$ ]] || die "$TABLE: bad artifact row id '$repo' (expected <repository>@<artifact>, artifact in [a-z0-9-])"
[ "$kind" = img ] || die "$TABLE: artifact row '$repo' must be kind img"
if [ "$CHANNEL" = stable ]; then ARTIFACT_SKIPPED+=("$repo"); continue; fi
;;
esac
[ -z "${T_STAGE[$repo]:-}" ] || die "$TABLE: '$repo' is listed twice"
ROWS+=("$repo")
T_STAGE[$repo]=$st; T_KIND[$repo]=$kind; T_VFILE[$repo]=$vfile; T_PREFIX[$repo]=$prefix; T_WF[$repo]=$wf; T_PKGS[$repo]=$pkgs; T_MIRRORS[$repo]=${mirrors:-}
# A mirror is gateway-pin, a plain path, or <file>:<kind>. An unknown :kind would be read as
# a file name that never exists, and a missing mirror file moves nothing without a word.
for tok in ${T_MIRRORS[$repo]//,/ }; do
case "$tok" in
gateway-pin|*:Version|*:heading|*:currently|*:jar) ;;
*:*) die "$TABLE: unknown mirror kind '${tok##*:}' in '$tok' for '$repo' (kinds: Version, heading, currently, jar)" ;;
esac
done
done < "$TABLE"
[ ${#ROWS[@]} -gt 0 ] || die "$TABLE has no rows"
for o in "${ONLY[@]}"; do
for a in "${ARTIFACT_SKIPPED[@]}"; do
[ "$o" = "$a" ] && die "--only $o: an artifact row (<repository>@<artifact>) releases on the beta channel only; this script has no stable path for a second artifact of one repository"
done
[ -n "${T_STAGE[$o]:-}" ] || die "--only $o: not a repo in $TABLE"
done
for o in "${!EXPECT[@]}"; do [ -n "${T_STAGE[$o]:-}" ] || die "--expect $o: not a repo in $TABLE"; done
for m in "${MERGES[@]}"; do [[ "$m" =~ ^[A-Za-z0-9._-]+#[0-9]+$ ]] || die "--merge '$m': expected <repo>#<number>"; done
if [ -n "$STUDIO" ] && [ "$STUDIO" != none ] && [ "$STUDIO" != next ] && [ "$CHANNEL" = beta ]; then
[[ "$STUDIO" =~ ^[0-9]+\.[0-9]+\.[0-9]+-beta\.[0-9]+$ ]] || die "--studio '$STUDIO': expected MAJOR.MINOR.PATCH-beta.N, or next"
fi
if [ -n "$PATCH_VERSION" ]; then
[ "$CHANNEL" = stable ] || die "--version is for --channel stable (a beta's version is always main's version file)"
[[ "$PATCH_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "--version '$PATCH_VERSION': expected MAJOR.MINOR.PATCH"
[ ${#ONLY[@]} -gt 0 ] || die "--version $PATCH_VERSION needs --only <repo>: every repository has its own version line, so a patch names the repositories it is for"
fi
stage_title() {
case "$1" in
1) echo "Maven chain 1/4: build-config" ;;
2) echo "Maven chain 2/4: parent (needs 1)" ;;
3) echo "Maven chain 3/4: commons (needs 1-2)" ;;
4) echo "Maven chain 4/4: auth-core (needs 1-3)" ;;
5) echo "Gateway base image (needs 1-3)" ;;
6) echo "Gateway overlays be/fe/pki (FROM the gateway image; need 5)" ;;
7) echo "Java BFF/API images (need 1-4)" ;;
8) echo "Angular UI images (no Maven dependency)" ;;
9) echo "Games, forum-api (PHP), mesh-node, hugmesh-akkoma (no Maven dependency)" ;;
esac
}
stage_deps() {
case "$1" in
2) echo 1 ;; 3) echo "1 2" ;; 4) echo "1 2 3" ;; 5) echo "1 2 3" ;; 6) echo "1 2 3 5" ;; 7) echo "1 2 3 4" ;;
*) echo "" ;;
esac
}
rows_in_stage() { local r; for r in "${ROWS[@]}"; do [ "${T_STAGE[$r]}" = "$1" ] && echo "$r"; done; return 0; }
# --only selects what this run ACTS on. It never changes what a row IS: every row is
# classified, and a dependency stage counts as published when ALL its rows are DONE,
# whether or not they were selected. (release-all-20261022.sh marked every unselected row
# not-OK, so `--only <one downstream repo>` blocked its own stage.) A stage with no
# selected row is reported and skipped, never a stop; a stage with selected rows succeeds
# when its SELECTED rows are published. So `--only <a UI>` tags that UI whatever state the
# Maven chain is in, and `--only <a Java image>` still stops at its own stage when a Maven
# link it builds on is not published.
selected() {
[ ${#ONLY[@]} -eq 0 ] && return 0
local o; for o in "${ONLY[@]}"; do [ "$o" = "$1" ] && return 0; done; return 1
}
stage_has_selected() { local r; for r in $(rows_in_stage "$1"); do selected "$r" && return 0; done; return 1; }
# ── version helpers ──────────────────────────────────────────────────────────
is_beta() { [[ "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+-beta\.[0-9]+$ ]]; }
# vercmp A B -> lt|eq|gt (each MAJOR.MINOR.PATCH-beta.N or MAJOR.MINOR.PATCH; a final sorts
# after every beta of the same MAJOR.MINOR.PATCH)
vercmp() {
local a b i x y
IFS='.-' read -r -a a <<<"${1/-beta./.0.}"
IFS='.-' read -r -a b <<<"${2/-beta./.0.}"
[[ "$1" == *-beta.* ]] || a[4]=2147483647
[[ "$2" == *-beta.* ]] || b[4]=2147483647
for i in 0 1 2 4; do
x=${a[$i]:-0}; y=${b[$i]:-0}
if [ "$((10#$x))" -lt "$((10#$y))" ]; then echo lt; return; fi
if [ "$((10#$x))" -gt "$((10#$y))" ]; then echo gt; return; fi
done
echo eq
}
# next_beta X.Y.Z-beta.N [newest stable X.Y.Z] -> the version to advise. X.Y.Z-beta.(N+1), unless a
# stable at or above X.Y.Z is published: then a pre-release of a shipped version is never
# advised, and the next beta is the next minor after that stable (what the stable channel's
# `next` phase moves main to).
next_beta() {
local nb stable
nb="${1%.*}.$(( ${1##*.} + 1 ))"; stable=${2:-}
if [ -n "$stable" ] && [ "$(vercmp "$nb" "$stable")" != gt ]; then next_minor_beta "$stable"; return; fi
echo "$nb"
}
# newest_stable <tag refs, one per line> <prefix> -> the newest X.Y.Z among them, or nothing
newest_stable() {
local t v best=""
for t in $1; do
v=${t#refs/tags/$2}
is_stable "$v" || continue
if [ -z "$best" ] || [ "$(vercmp "$v" "$best")" = gt ]; then best=$v; fi
done
[ -n "$best" ] && echo "$best"
return 0
}
is_stable() { [[ "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; }
# b64-decoded file at a ref, via the contents API
file_at() { # repo ref path
local b
b=$(ghq api "repos/$ORG/${1%@*}/contents/$3?ref=$2" --jq .content) || return 1
printf '%s' "$b" | base64 -d 2>/dev/null
}
# parse_version <version file name> (file body on stdin) -> the version, or nothing
parse_version() {
case "$(basename "$1")" in
pom.xml)
python3 -I -c '
import sys, xml.etree.ElementTree as E
try:
r = E.fromstring(sys.stdin.read())
except Exception:
sys.exit(0)
v = r.find("{http://maven.apache.org/POM/4.0.0}version")
if v is None: v = r.find("version")
print(v.text.strip() if v is not None and v.text else "")' ;;
package.json|composer.json)
python3 -I -c '
import json, sys
try:
v = json.load(sys.stdin).get("version", "")
except Exception:
v = ""
print(v if isinstance(v, str) else "")' ;;
*) head -n 1 | tr -d '[:space:]'; echo ;;
esac
}
read_version() { # repo sha versionfile
local body
body=$(file_at "$1" "$2" "$3") || return 1
[ -n "$body" ] || return 1
printf '%s\n' "$body" | parse_version "$3"
}
# wf_facts (workflow YAML on stdin) -> "push_main=yes|no", then one on.push.paths glob per line.
# Stdlib only (no PyYAML): a line scanner over the `on:` block, which is all it needs.
# wf_branches (workflow YAML on stdin) -> one on.push.branches entry per line.
wf_facts() { python3 -I -c "$WF_PY" facts; }
wf_branches() { python3 -I -c "$WF_PY" branches; }
WF_PY='
import re, sys
ind = lambda l: len(l) - len(l.lstrip(" "))
def items(v): return [x.strip().strip("\x27\"") for x in v.strip()[1:-1].split(",") if x.strip()]
on_i = push_i = key_i = None; key = None; d = {}
for l in sys.stdin.read().splitlines():
if l.strip().startswith("#"): continue
s = re.sub(r"\s+#.*$", "", l).strip()
if not s: continue
i = ind(l)
if on_i is None:
if i == 0 and re.match(r"^[\"\x27]?on[\"\x27]?\s*:\s*$", s): on_i = 0
continue
if i <= on_i: break
if key is not None:
if s.startswith("- ") and i >= key_i:
d[key].append(s[2:].strip().strip("\x27\"")); continue
key = None
if push_i is not None and i <= push_i: push_i = None
if push_i is None:
if re.match(r"^push\s*:\s*$", s): push_i = i
continue
m = re.match(r"^([A-Za-z_-]+)\s*:\s*(.*)$", s)
if m:
k, v = m.group(1), m.group(2)
d.setdefault(k, [])
if v.startswith("["): d[k] += items(v)
elif v: d[k].append(v.strip("\x27\""))
else: key = k; key_i = i
if sys.argv[1:] == ["branches"]:
for b in d.get("branches", []): print(b)
sys.exit(0)
print("push_main=" + ("yes" if "main" in d.get("branches", []) else "no"))
for p in d.get("paths", []):
if not p.startswith("!"): print(p)'
# ── org-level facts ──────────────────────────────────────────────────────────
OPTIONAL_SECRETS=" SITE_DISPATCH_TOKEN PACKAGES_READ_ACTOR STUDIO_AUTHENTICODE_PFX_BASE64 STUDIO_AUTHENTICODE_PFX_PASSWORD ADMIN_BFF_READ_TOKEN RELEASE_CHAIN_TOKEN "
ORG_SECRETS_STATE=unknown; ORG_SECRETS=""
load_org_secrets() {
local out
if out=$(GH api "/orgs/$ORG/actions/secrets?per_page=100" --jq '.secrets[]|.name+"="+.visibility' 2>&1); then
ORG_SECRETS_STATE=ok; ORG_SECRETS="$out"
else
ORG_SECRETS_STATE="unreadable ($(printf '%s' "$out" | head -1 | cut -c1-80))"
fi
}
# secret_present repo NAME -> prints where; names only, never a value
secret_present() {
local repo_secrets line vis
if ! repo_secrets=$(ghq secret list -R "$ORG/${1%@*}" --json name -q '.[].name'); then echo "repo secret list unreadable"; return 1; fi
if printf '%s\n' "$repo_secrets" | grep -axF -- "$2" >/dev/null; then echo repo; return 0; fi
if [ "$ORG_SECRETS_STATE" = ok ]; then
line=$(printf '%s\n' "$ORG_SECRETS" | grep -a "^$2=" || true)
if [ -n "$line" ]; then
vis=${line#*=}
if [ "$vis" = all ] || [ "$vis" = public ]; then echo "org($vis)"; return 0; fi
if ghq api "/orgs/$ORG/actions/secrets/$2/repositories" --jq '.repositories[].name' | grep -axF -- "$1" >/dev/null; then
echo "org(selected)"; return 0
fi
fi
echo missing; return 1
fi
echo "missing-in-repo; org secrets $ORG_SECRETS_STATE"; return 1
}
# ── classification (read-only) ───────────────────────────────────────────────
# Per repo: S_STATE DONE|READY|REFUSE|NEEDS-BUMP|RUNNING, S_REASON, S_NOTE, S_SHA (main),
# S_VER, S_TAG, S_RERUN (id of a red main push run that a re-run can fix, when that is the
# ONLY reason), S_BUSY (id of a main push run still in flight), S_TAGRUN (the tag's run),
# S_TAGRERUN (id of a red TAG run that published nothing, so re-running it is the fix).
declare -A S_STATE=() S_REASON=() S_NOTE=() S_SHA=() S_VER=() S_TAG=() S_RERUN=() S_BUSY=() S_TAGRUN=() S_OLD=() S_TAGRERUN=()
# tag_commit repo tag -> prints the COMMIT sha; rc 0 found, 1 absent, 2 cannot tell
tag_commit() {
local out typ sha
if out=$(GH api "repos/$ORG/${1%@*}/git/ref/tags/$2" --jq '.object.type+" "+.object.sha' 2>&1); then
read -r typ sha <<<"$out"
if [ "$typ" = tag ]; then sha=$(ghq api "repos/$ORG/${1%@*}/git/tags/$sha" --jq .object.sha) || { echo "annotated tag $2 unreadable"; return 2; }; fi
printf '%s' "$sha"; return 0
fi
case "$out" in *'HTTP 404'*|*'"status":"404"'*|*'Not Found'*) return 1 ;; esac
printf '%s' "$out" | head -1 | cut -c1-120; return 2
}
# commits_since repo base paths... -> number of main commits since base (a tag or a commit
# sha) that the workflow would build (all of them when it has no paths filter)
commits_since() {
local repo=$1
local base=$2
shift 2
local cmp ahead shas p pfx rel n=0 s
cmp=$(ghq api "repos/$ORG/${repo%@*}/compare/$base...${CS_REF:-main}" --jq '(.ahead_by|tostring), .commits[].sha') || { echo "?"; return 1; }
ahead=$(printf '%s\n' "$cmp" | head -1)
if [ $# -eq 0 ]; then echo "$ahead"; return 0; fi
shas=$(printf '%s\n' "$cmp" | tail -n +2)
rel=""
for p in "$@"; do
pfx=${p%%\**}; pfx=${pfx%/}
rel="$rel"$'\n'"$(ghq api "repos/$ORG/${repo%@*}/commits?sha=${CS_REF:-main}&path=$pfx&per_page=100" --jq '.[].sha' || true)"
done
for s in $shas; do printf '%s\n' "$rel" | grep -axF -- "$s" >/dev/null && n=$((n+1)); done
echo "$n"
}
run_age_days() { # ISO-8601 -> whole days ago
local t now
t=$(date -u -d "$1" +%s 2>/dev/null) || { echo 0; return; }
now=$(date -u +%s)
echo $(( (now - t) / 86400 ))
}
# pkg_has_version kind package version -> rc 0 listed, 1 absent (no such version, or no such
# package), 2 cannot tell. kind is the repos.tsv kind (img = GHCR image, mvn = Maven).
pkg_has_version() {
local enc typ jq out rc=0
enc=$(printf '%s' "$2" | sed 's#/#%2F#g')
if [ "$1" = img ]; then typ=container; jq='.[].metadata.container.tags[]'; else typ=maven; jq='.[].name'; fi
out=$(ghs api "/orgs/$ORG/packages/$typ/$enc/versions?per_page=100" --paginate --jq "$jq") || rc=$?
case "$rc" in
0) printf '%s\n' "$out" | grep -axF -- "$3" >/dev/null && return 0; return 1 ;;
4) return 1 ;;
esac
return 2
}
# A step that publishes something: a registry push, a package deploy, an attestation or a
# GitHub Release. A tag run that got past one of these has burned its beta number.
PUBLISH_STEP_RE='publish|push|upload|deploy|attest|release'
# A step that checks the world around the commit, not the commit: the version job, the
# cross-repo package-read preflight, the base-image pull check, checkout and setup. Its
# failure is fixed by a re-run once the world is right (an upstream package published).
# A failed test or build step is the tagged commit's own fault, and a re-run repeats it.
PREFLIGHT_JOB_RE='^(version|preflight)'
PREFLIGHT_STEP_RE='preflight|version|cross-repo|package read|pull|set up job|check ?out|log ?in'
# tag_run_unpublished repo run-id created-at -> rc 0 when the tag's run failed in a preflight
# step BEFORE it published anything (no publish step succeeded or failed, no package carries
# the version, there is no GitHub Release for the tag, and it is the run's first attempt),
# so `gh run rerun --failed` is the fix and no bump is needed. Prints the evidence, or why
# not. Anything it cannot read means "no" (the bump advice stays).
tag_run_unpublished() {
local repo=$1 rid=$2 created=$3 facts att=1 failed="" fjob="" fstep="" pubstep="" con job step p rc age
local ver=${S_VER[$1]} tag=${S_TAG[$1]}
age=$(run_age_days "$created")
if [ "$age" -ge "$RERUN_MAX_DAYS" ]; then echo "it is $age days old, and GitHub cannot re-run it"; return 1; fi
facts=$(ghq run view "$rid" -R "$ORG/${repo%@*}" --json attempt,jobs \
-q '"attempt\t\(.attempt // 1)", (.jobs[] as $j | $j.steps[]? | "\(.conclusion // "")\t\($j.name)\t\(.name)")') \
|| { echo "its jobs are unreadable"; return 1; }
while IFS=$'\t' read -r con job step; do
if [ "$con" = attempt ]; then att=$job; continue; fi
case "$con" in
failure|timed_out|cancelled)
if [[ "${step,,}" =~ $PUBLISH_STEP_RE ]]; then echo "it failed in the publish step '$job / $step'"; return 1; fi
[ -n "$failed" ] || { failed="$job / $step"; fjob=$job; fstep=$step; } ;;
success)
[[ "${step,,}" =~ $PUBLISH_STEP_RE ]] && pubstep="$job / $step" ;;
esac
done <<<"$facts"
if [ -n "$pubstep" ]; then echo "its step '$pubstep' succeeded"; return 1; fi
if [ -z "$failed" ]; then echo "no failed step is recorded"; return 1; fi
if [ "${att:-1}" != 1 ]; then echo "it failed in '$failed' again on attempt $att, so a re-run does not fix it"; return 1; fi
for p in ${T_PKGS[$repo]}; do
rc=0; pkg_has_version "${T_KIND[$repo]}" "$p" "$ver" || rc=$?
case "$rc" in
0) echo "$p:$ver is published"; return 1 ;;
2) echo "cannot tell whether $p:$ver was published"; return 1 ;;
esac
done
rc=0; ghs release view "$tag" -R "$ORG/${repo%@*}" --json tagName >/dev/null || rc=$?
case "$rc" in
0) echo "GitHub Release $tag exists"; return 1 ;;
4) ;;
*) echo "cannot tell whether GitHub Release $tag exists"; return 1 ;;
esac
if ! [[ "${fjob,,}" =~ $PREFLIGHT_JOB_RE ]] && ! [[ "${fstep,,}" =~ $PREFLIGHT_STEP_RE ]]; then
echo "it published nothing, but it failed in '$failed', a test or build of the tagged commit itself, which a re-run repeats (if it was a flake: gh run rerun $rid --failed -R $ORG/${repo%@*})"
return 1
fi
echo "failed in '$failed' before it published anything (no ${T_PKGS[$repo]// /, } $ver, no GitHub Release $tag)"
}
classify() { if [ "$CHANNEL" = stable ]; then classify_stable "$1"; else classify_beta "$1"; fi; }
classify_beta() {
local repo=$1
local vfile=${T_VFILE[$repo]}
local prefix=${T_PREFIX[$repo]}
local wf=${T_WF[$repo]}
local ref=main
local sha ver tag tc rc wft facts pushref run rid rsha rst rcon rcreated reasons=() s where t pin age n why tags stable
local -a paths=()
S_REF[$repo]=main
S_STATE[$repo]=REFUSE; S_REASON[$repo]=""; S_NOTE[$repo]=""; S_SHA[$repo]=""; S_VER[$repo]=""; S_TAG[$repo]=""
S_RERUN[$repo]=""; S_BUSY[$repo]=""; S_TAGRUN[$repo]=""; S_OLD[$repo]=""; S_TAGRERUN[$repo]=""
sha=$(ghq api "repos/$ORG/${repo%@*}/git/ref/heads/main" --jq .object.sha || true)
if [ -z "$sha" ]; then S_REASON[$repo]="cannot read main: gh api repos/$ORG/${repo%@*}/git/ref/heads/main"; return; fi
S_SHA[$repo]=$sha
ver=$(read_version "$repo" "$sha" "$vfile" || true)
S_VER[$repo]=$ver
if [ -z "$ver" ]; then S_REASON[$repo]="cannot read a version from $vfile on main"; return; fi
if ! is_beta "$ver"; then S_REASON[$repo]="main's $vfile says '$ver', not MAJOR.MINOR.PATCH-beta.N: merge a version bump"; return; fi
pin=""; [ "$CHANNEL" = stable ] || pin=${EXPECT[$repo]:-}
if [ -n "$pin" ] && [ "$pin" != "$ver" ]; then S_REASON[$repo]="--expect $repo=$pin, but main's $vfile says $ver"; return; fi
tag="$prefix$ver"; S_TAG[$repo]=$tag
# Every tag under the prefix, once: the beta ordering check below reads the betas, and the
# newest stable X.Y.Z decides whether main's beta line has already shipped (#855). A failed
# read is REFUSE, never "no tags": an empty listing would skip both checks and read READY.
# (No tags under the prefix is an empty 200, which is a success here.)
tags=$(ghq api "repos/$ORG/${repo%@*}/git/matching-refs/tags/$prefix" --jq '.[].ref') || { S_REASON[$repo]="cannot read tags: gh api repos/$ORG/${repo%@*}/git/matching-refs/tags/$prefix"; return; }
stable=$(newest_stable "$tags" "$prefix")
wft=$(file_at "$repo" "$sha" ".github/workflows/$wf" || true)
facts=$(printf '%s\n' "$wft" | wf_facts)
pushref=no; [ "$(printf '%s\n' "$facts" | head -1)" = push_main=yes ] && pushref=yes
while IFS= read -r t; do [ -n "$t" ] && paths+=("$t"); done < <(printf '%s\n' "$facts" | tail -n +2)
rc=0; tc=$(tag_commit "$repo" "$tag") || rc=$?
if [ "$rc" = 2 ]; then S_REASON[$repo]="cannot tell whether tag $tag exists: $tc"; return; fi
if [ "$rc" = 0 ]; then
# Published (or being published). A published beta is never re-tagged.
run=$(ghq run list -R "$ORG/${repo%@*}" --workflow "$wf" --branch "$tag" --limit 1 \
--json databaseId,status,conclusion,createdAt -q '.[]|[(.databaseId|tostring),.status,(.conclusion//""),.createdAt]|join("|")' || true)
IFS='|' read -r rid rst rcon rcreated <<<"${run:-}"
if [ -z "${rid:-}" ]; then
S_REASON[$repo]="tag $tag exists (${tc:0:12}) but no $wf run for it was found: look at https://github.com/$ORG/${repo%@*}/actions"; return
fi
S_TAGRUN[$repo]=$rid
if [ "$rst" != completed ]; then
S_STATE[$repo]=RUNNING; S_NOTE[$repo]="tag $tag run $rid is $rst: gh run watch $rid -R $ORG/${repo%@*}"; return
fi
if [ "$rcon" != success ]; then
if why=$(tag_run_unpublished "$repo" "$rid" "${rcreated:-}"); then
# Nothing went out, so the beta number is not burned: re-run the run, do not bump.
S_TAGRERUN[$repo]=$rid
S_REASON[$repo]="tag $tag exists and its run $rid is '$rcon', but it $why. The beta number is not burned, so do NOT bump: gh run rerun $rid --failed -R $ORG/${repo%@*} (this stage offers it). That fixes a cause outside the tagged commit (a package that was not published yet, a flaky step); if the cause is in the commit itself, the re-run fails the same way: then fix it on main and bump $vfile to $(next_beta "$ver" "$stable")"
else
S_REASON[$repo]="tag $tag exists and its run $rid is '$rcon' (no re-run: $why). A published beta is never re-tagged: read gh run view $rid --log-failed -R $ORG/${repo%@*}, fix it on main, bump $vfile to $(next_beta "$ver" "$stable") and run this again"
fi
return
fi
if [ "$tc" = "$sha" ]; then
S_STATE[$repo]=DONE; S_NOTE[$repo]="tag $tag at main ${sha:0:12}, run $rid green"; return
fi
n=$(commits_since "$repo" "$tag" "${paths[@]}" || true)
if [ "$n" = 0 ]; then
S_STATE[$repo]=DONE; S_NOTE[$repo]="tag $tag (${tc:0:12}) run $rid green; main has no commit since it that $wf builds (paths: ${paths[*]})"
else
S_STATE[$repo]=NEEDS-BUMP
S_REASON[$repo]="$tag is published and main's $vfile still says $ver, but main has ${n} commit(s) since it$([ ${#paths[@]} -gt 0 ] && printf ' under %s' "${paths[*]}"): merge a PR that bumps $vfile to $(next_beta "$ver" "$stable"), then run this again"
fi
return
fi
# Not tagged yet. A stable X.Y.Z at or above the beta's X.Y.Z means that line has shipped:
# tagging X.Y.Z-beta.N now would publish a pre-release of a released version, so main must
# move past the newest stable first (#855).
if [ -n "$stable" ] && [ "$(vercmp "$ver" "$stable")" != gt ]; then
S_STATE[$repo]=NEEDS-BUMP
S_REASON[$repo]="stable tag $prefix$stable is published, so main's $vfile=$ver is a pre-release of a version that has already shipped and is never tagged: merge a PR that bumps $vfile to $(next_beta "$ver" "$stable"), then run this again"
return
fi
# Every check that decides whether tagging main now would publish cleanly.
local old
for t in $tags; do
old=${t#refs/tags/$prefix}
is_beta "$old" || continue
if [ "$(vercmp "$old" "$ver")" = gt ]; then reasons+=("tag $prefix$old already exists and is later than main's $ver: bump $vfile past it"); fi
done
check_unreleased "$ref"
if [ ${#reasons[@]} -gt 0 ]; then
S_REASON[$repo]=$(printf '%s; ' "${reasons[@]}"); S_REASON[$repo]=${S_REASON[$repo]%; }
[ ${#reasons[@]} -eq 1 ] || S_RERUN[$repo]="" # a re-run alone cannot fix several reasons
return
fi
S_STATE[$repo]=READY
S_NOTE[$repo]="main ${sha:0:12} $vfile=$ver, signing on main, tag $tag free${S_NOTE[$repo]:+; ${S_NOTE[$repo]}}"
}
# check_unreleased ref: the checks that decide whether tagging <ref>'s HEAD now would
# publish cleanly (signing, DOCKER_CONFIG, secrets, check 7: the latest push run of the
# workflow on <ref> is green at <ref>'s HEAD). Called from classify_beta (ref main) and
# classify_stable (ref release/X.Y); it reads and appends to the CALLER's locals (bash
# dynamic scope): repo wf wft sha ver paths pushref reasons.
check_unreleased() {
local ref=$1
local ncos natt s where run rid rsha rst rcon rcreated age n
if [ -z "$wft" ]; then
reasons+=(".github/workflows/$wf is missing on $ref")
else
ncos=$(printf '%s\n' "$wft" | grep -aEc 'cosign sign(-blob)? ' || true)
natt=$(printf '%s\n' "$wft" | grep -ac 'actions/attest-build-provenance@' || true)
if [ "${ncos:-0}" -lt 1 ] || [ "${natt:-0}" -lt 1 ]; then
reasons+=("signing absent in $wf on $ref (cosign sign: ${ncos:-0}, attest-build-provenance: ${natt:-0})")
fi
if printf '%s\n' "$wft" | grep -a 'DOCKER_CONFIG=' >/dev/null; then
reasons+=("$wf writes a private DOCKER_CONFIG: attest-build-provenance then fails 'No credentials found for registry ghcr.io' AFTER :$ver is pushed (burns the beta number)")
fi
for s in $(printf '%s\n' "$wft" | grep -aoE 'secrets\.[A-Z_][A-Z0-9_]*' | sed 's/^secrets\.//' | sort -u); do
[ "$s" = GITHUB_TOKEN ] && continue
case "$OPTIONAL_SECRETS" in *" $s "*) continue ;; esac
if [ "$s" = PACKAGES_READ_TOKEN ] && ! printf '%s\n' "$wft" | grep -a 'PACKAGES_READ_TOKEN is not set for this repository' >/dev/null; then
continue # this workflow falls back to GITHUB_TOKEN
fi
if ! where=$(secret_present "$repo" "$s"); then reasons+=("required secret $s: $where"); fi
done
fi
# The latest PUSH run of the workflow on the ref must be green (a workflow_dispatch run
# does not count): a red run means the tag run would push :<version> and then die, which
# burns that version number.
if [ "$pushref" = yes ]; then
run=$(ghq run list -R "$ORG/${repo%@*}" --workflow "$wf" --branch "$ref" --event push --limit 1 \
--json databaseId,headSha,status,conclusion,createdAt -q '.[]|[(.databaseId|tostring),.headSha,.status,(.conclusion//""),.createdAt]|join("|")' || true)
IFS='|' read -r rid rsha rst rcon rcreated <<<"${run:-}"
if [ -z "${rid:-}" ]; then
reasons+=("no push-to-$ref run of $wf found: push a commit to $ref (the next merge starts one)")
elif [ "$rst" != completed ]; then
S_BUSY[$repo]=$rid
reasons+=("$ref push run $rid (${rsha:0:8}) is still $rst: wait for it (gh run watch $rid -R $ORG/${repo%@*})")
elif [ "$rcon" != success ]; then
age=$(run_age_days "$rcreated")
if [ "$age" -ge "$RERUN_MAX_DAYS" ]; then
S_OLD[$repo]=$rid
reasons+=("last $ref push run $rid (${rsha:0:8}) is $rcon and $age days old: GitHub cannot re-run it. Push a commit to $ref (the next merge creates a new push run)")
else
S_RERUN[$repo]=$rid
reasons+=("last $ref push run $rid (${rsha:0:8}) is $rcon: fix the cause, then gh run rerun $rid --failed -R $ORG/${repo%@*} (the rerun phase does this)")
fi
elif [ "$rsha" != "$sha" ]; then
# main's HEAD has no push run of its own. Without a paths filter that run is still to
# come (just merged, Actions lagging, a [skip ci] commit): tagging now would publish a
# commit whose release workflow never ran on main. With a paths filter it is fine only
# when nothing since the green run touches those paths.
if [ ${#paths[@]} -eq 0 ]; then
reasons+=("$ref is ${sha:0:8} but the latest $ref push run of $wf ($rid, green) is at ${rsha:0:8}: $ref's HEAD has no push run yet (just merged, Actions lagging, or [skip ci]). Wait for it (https://github.com/$ORG/${repo%@*}/actions); if none ever comes, push a commit to $ref")
else
n=$(CS_REF=$ref commits_since "$repo" "$rsha" "${paths[@]}" || true)
if [ "$n" = 0 ]; then
S_NOTE[$repo]="last $ref push run $rid green at ${rsha:0:8} ($ref is ${sha:0:8}; no commit since it under ${paths[*]}, so no push run is due)"
else
reasons+=("$ref is ${sha:0:8} and has ${n} commit(s) under ${paths[*]} since ${rsha:0:8}, where the latest $ref push run $rid is green; their push run has not appeared yet: wait for it (https://github.com/$ORG/${repo%@*}/actions)")
fi
fi
else
S_NOTE[$repo]="last $ref push run $rid green at HEAD"
fi
fi
}
published() { case "${S_STATE[$1]:-}" in DONE|NEEDS-BUMP) return 0 ;; esac; return 1; }
# Stage state: "published" (every row DONE/NEEDS-BUMP), or "plan" (dry run: every row is
# published or will be by this run: selected and READY/RUNNING/re-runnable), else "no".
stage_published() { local r; for r in $(rows_in_stage "$1"); do published "$r" || return 1; done; return 0; }
stage_plan_ok() {
local r
for r in $(rows_in_stage "$1"); do
published "$r" && continue
selected "$r" || return 1
case "${S_STATE[$r]:-}" in READY|RUNNING) continue ;; esac
[ -n "${S_RERUN[$r]:-}" ] || [ -n "${S_BUSY[$r]:-}" ] || [ -n "${S_TAGRERUN[$r]:-}" ] || return 1
done
return 0
}
# The same two verdicts over the rows --only selected (all rows without --only): what a
# stage that ACTS has to achieve. A dependency stage is always judged on all its rows.
stage_sel_published() {
local r
for r in $(rows_in_stage "$1"); do
selected "$r" || continue
published "$r" || return 1
done
return 0
}
stage_sel_plan_ok() {
local r
for r in $(rows_in_stage "$1"); do
selected "$r" || continue
if published "$r"; then continue; fi
case "${S_STATE[$r]:-}" in READY|RUNNING) continue ;; esac
[ -n "${S_RERUN[$r]:-}" ] || [ -n "${S_BUSY[$r]:-}" ] || [ -n "${S_TAGRERUN[$r]:-}" ] || return 1
done
return 0
}
# blocked_by stage plan|real -> the dependency stages that are not (going to be) published.
# A stable PATCH has none: its release branch already pins published stables (a -beta pin
# is refused per repo), and the other repos are not part of the patch.
blocked_by() {
local d out=""
if [ -n "$PATCH_VERSION" ]; then echo ""; return 0; fi
for d in $(stage_deps "$1"); do
if [ "$2" = plan ]; then
stage_plan_ok "$d" && [ -z "$(blocked_by "$d" plan)" ] || out="$out $d"
else
stage_published "$d" || out="$out $d"
fi
done
echo "${out# }"
}
row_line() {
local r=$1 detail
case "${S_STATE[$r]}" in
DONE|READY|RUNNING|NEEDS-CUT|NEEDS-PR) detail=${S_NOTE[$r]} ;;
*) detail=${S_REASON[$r]} ;;
esac
printf ' %-10s %-38s %-22s %s%s\n' "${S_STATE[$r]}" "$r" "${S_TAG[$r]:-${S_VER[$r]:-?}}" "$detail" "$(selected "$r" || printf ' [not selected by --only]')"
}
# A dry run classifies each row once (in preflight); --apply re-reads before every action.
classify_stage() {
local r
for r in $(rows_in_stage "$1"); do
if [ "$MODE" = dry ] && [ -n "${S_STATE[$r]:-}" ]; then continue; fi
classify "$r"
done
}
# ── the stable channel ───────────────────────────────────────────────────────
# A stable release X.Y.Z of a repo is the tag <prefix>X.Y.Z on that repo's OWN branch
# release/X.Y, never on main: main carries the next beta. Each repo has its own X.Y (the
# Maven chain, the gateway and the UIs are versioned independently), so a cut is "every
# repo's main beta X.Y.Z-beta.N, released as X.Y.Z from release/X.Y", and a patch is one
# repo's --version X.Y.(Z+1) on its existing release/X.Y after the operator cherry-picked
# the fix there.
#
# The repo's release workflow has to know channels first (stable tag only from
# release/X.Y, :X.Y and :latest, the GitHub Release marked latest). Those per-repo PRs
# land separately; until the workflow AT THE REF THAT WOULD BE TAGGED carries both
# markers below, stable is REFUSED for that repo with the PR to merge.
# 1. its on.push.branches lists a release/ glob (release/** or release/*), so a
# release branch gets the same push run that check 7 reads on main;
# 2. the literal CHANNEL_MARKER, written by those PRs next to the channel logic.
CHANNEL_MARKER='hugmesh-release-channels: beta+stable'
CHANNEL_PR_TITLE='Release channels'
# The head branch of a stable version-bump PR. Deliberately NOT under release/: every
# channel-aware workflow runs on pushes to release/**, and a bump branch named
# release/stable-X.Y.Z would start a release-branch run on an unmerged bump.
BUMP_PREFIX=bump
declare -A S_MODE=() S_RB=() S_REF=() S_MSTATE=() S_MWHY=() S_MVER=() S_MSHA=() S_RBVER=() S_PRURL=()
MAIN_NEEDS_BUMP=()
stable_reset() {
S_MODE[$1]=""; S_RB[$1]=""; S_REF[$1]=main; S_MSTATE[$1]=""; S_MWHY[$1]=""; S_MVER[$1]=""; S_MSHA[$1]=""; S_RBVER[$1]=""; S_PRURL[$1]=""
}
# channel_pr repo -> the URL of the open per-repo "Release channels" PR, or a description
channel_pr() {
local u
u=$(ghq pr list -R "$ORG/${1%@*}" --state open --search "$CHANNEL_PR_TITLE in:title" --json url -q '.[0].url // empty' || true)
if [ -n "$u" ]; then printf '%s' "$u"; else printf 'the "%s: beta from main, stable from release/X.Y" PR for %s/%s (none is open yet)' "$CHANNEL_PR_TITLE" "$ORG" "$1"; fi
}
# channel_missing <workflow text> -> prints what is missing; rc 0 when both markers are there
channel_missing() {
local miss=()
if ! printf '%s\n' "$1" | wf_branches | grep -a '^release/' >/dev/null; then miss+=("a push trigger on release/**"); fi
if ! printf '%s\n' "$1" | grep -aF -- "$CHANNEL_MARKER" >/dev/null; then miss+=("the marker '$CHANNEL_MARKER'"); fi
[ ${#miss[@]} -eq 0 ] && return 0
printf '%s' "$(printf '%s; ' "${miss[@]}" | sed 's/; $//')"
return 1
}
# stable_tags repo prefix -> every plain X.Y.Z tag of the repo, one per line
stable_tags() {
local t v
for t in $(ghq api "repos/$ORG/${1%@*}/git/matching-refs/tags/$2" --jq '.[].ref' || true); do
v=${t#refs/tags/$2}
is_stable "$v" && echo "$v"
done
return 0
}
# ── bump content (stdlib Python; poms by element path, never by line number) ────
BUMP_PY=$(cat <<'PYEOF'
import json, os, re, sys
# argv: mode (stable|next|check) root spec.json ; prints a JSON result
mode, root, specf = sys.argv[1], sys.argv[2], sys.argv[3]
spec = json.load(open(specf))
own = spec.get("own") or ""
pins = spec.get("pins", {})
images = spec.get("images", {})
org = spec.get("org", "hugmesh")
vfile = spec["vfile"]
wf = spec.get("wf", "")
BETA = re.compile(r"-beta\.[0-9]+$")
res = {"changed": {}, "summary": [], "left": [], "notes": [], "missing": []}
def rd(p):
fp = os.path.join(root, p)
if not os.path.isfile(fp):
return None
with open(fp, encoding="utf-8", newline="") as f:
return f.read()
def line_of(text, pos):
return text.count("\n", 0, pos) + 1
TOKEN = re.compile(r"<!--.*?-->|<!\[CDATA\[.*?\]\]>|<\?.*?\?>|<![A-Za-z][^>]*>"
r"|<(/?)([A-Za-z_][\w.:-]*)((?:[^>\"']|\"[^\"]*\"|'[^']*')*?)(/?)>", re.S)
def pom(path, text, is_vfile):
edits = []
stack = []
def pin(where, art, v, s, e, gid_ok):
vs = v.strip()
if not gid_ok or not vs or vs.startswith("${"):
return
ln = line_of(text, s)
if mode == "check":
if BETA.search(vs):
res["left"].append("%s:%d %s is still %s" % (path, ln, where, vs))
return
if art in pins:
if vs != pins[art]:
edits.append((s, e, v.replace(vs, pins[art])))
res["summary"].append("%s:%d %s %s -> %s" % (path, ln, where, vs, pins[art]))
elif mode == "stable" and BETA.search(vs):
res["left"].append("%s:%d %s is %s, and no repository in the table publishes %s" % (path, ln, where, vs, art))
for m in TOKEN.finditer(text):
name = m.group(2)
if name is None:
continue
if m.group(4):
continue
if not m.group(1):
stack.append({"name": name, "start": m.end(), "kids": {}})
continue
if not stack or stack[-1]["name"] != name:
res["left"].append("%s: cannot parse (unbalanced <%s>); edit it by hand" % (path, name))
return None
fr = stack.pop()
if stack:
stack[-1]["kids"][name] = (text[fr["start"]:m.start()], fr["start"], m.start())
kids = fr["kids"]
if not stack and name == "project":
if is_vfile and "version" in kids:
v, s, e = kids["version"]
vs = v.strip()
if mode == "check":
pass
elif vs != own:
edits.append((s, e, v.replace(vs, own)))
res["summary"].append("%s:%d project version %s -> %s" % (path, line_of(text, s), vs, own))
continue
if name == "properties" and len(stack) == 1 and stack[0]["name"] == "project":
for k, (v, s, e) in kids.items():
if not k.endswith(".version"):
continue
art = k[: -len(".version")]
if art in pins or art.startswith("hugmesh"):
pin("property <%s>" % k, art, v, s, e, True)
continue
if "version" in kids and "artifactId" in kids:
gid = kids.get("groupId", ("", 0, 0))[0].strip()
art = kids["artifactId"][0].strip()
v, s, e = kids["version"]
pin("%s net.hugmesh:%s" % (name, art), art, v, s, e, gid == "net.hugmesh")
if stack:
res["left"].append("%s: cannot parse (unclosed <%s>); edit it by hand" % (path, stack[-1]["name"]))
return None
for s, e, new in sorted(edits, reverse=True):
text = text[:s] + new + text[e:]
return text
def detect_indent(text):
m = re.search(r"\n([ \t]+)\"", text)
return m.group(1) if m else " "
def jsonfile(path, text, lock):
try:
d = json.loads(text)
except Exception:
res["left"].append("%s: not valid JSON; edit it by hand" % path)
return None
if not isinstance(d, dict):
return None
ind = detect_indent(text)
nl = "\n" if text.endswith("\n") else ""
same_shape = json.dumps(d, indent=ind, ensure_ascii=False) + nl == text
old = d.get("version")
if mode == "check":
return text
changes = []
if old != own:
d["version"] = own
changes.append("version %s -> %s" % (old, own))
if lock:
pk = d.get("packages", {}).get("") if isinstance(d.get("packages"), dict) else None
if isinstance(pk, dict) and "version" in pk and pk["version"] != own:
changes.append('packages[""].version %s -> %s' % (pk["version"], own))
pk["version"] = own
if not changes:
return text
if same_shape:
out = json.dumps(d, indent=ind, ensure_ascii=False) + nl
else:
# not in canonical JSON.stringify shape: touch only the top-level "version" value
pat = re.compile(r'(\n%s"version"\s*:\s*")[^"]*(")' % re.escape(ind))
out, n = pat.subn(lambda m: m.group(1) + own + m.group(2), text, count=1)
if n != 1 or lock:
res["left"].append("%s: not in the JSON.stringify(…, 2) shape npm writes, so it is not rewritten; set its version to %s by hand" % (path, own))
return None
res["summary"].append("%s %s" % (path, "; ".join(changes)))
return out
def versionfile(path, text):
first, sep, rest = text.partition("\n")
if mode == "check" or first.strip() == own:
return text
res["summary"].append("%s %s -> %s" % (path, first.strip(), own))
return own + sep + rest if sep else own + "\n"
PIN_RE = re.compile(r"^(\s*(?:PINNED_GATEWAY_IMAGE|GATEWAY_IMAGE_PIN)\s*:\s*[\"']?ghcr\.io/%s/([A-Za-z0-9._/-]+):)([^\s\"'#]+)" % re.escape(org), re.M)
def gatewaypin(path, text):
out = []
pos = 0
for m in PIN_RE.finditer(text):
img, tag = m.group(2), m.group(3)
ln = line_of(text, m.start(3))
if mode == "check":
if BETA.search(tag):
res["left"].append("%s:%d FROM pin ghcr.io/%s/%s:%s is a beta" % (path, ln, org, img, tag))
continue
if img in images and images[img] != tag:
out.append((m.start(3), m.end(3), images[img]))
res["summary"].append("%s:%d FROM pin %s:%s -> %s" % (path, ln, img, tag, images[img]))
elif img not in images and mode == "stable" and BETA.search(tag):
res["left"].append("%s:%d FROM pin ghcr.io/%s/%s:%s is a beta and no repository in the table publishes it" % (path, ln, org, img, tag))
for s, e, new in sorted(out, reverse=True):
text = text[:s] + new + text[e:]
return text
def readme_version(path, text):
m = re.search(r"\*\*Version ([^*\s]+)\*\*", text)
if not m:
res["left"].append("%s: no **Version X.Y.Z** line to move; set it by hand" % path)
return None
if mode == "check" or m.group(1) == own:
return text
res["summary"].append("%s:%d **Version %s** -> %s" % (path, line_of(text, m.start()), m.group(1), own))
return text[:m.start(1)] + own + text[m.end(1):]
SEMVER = r"[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.]+)?"
def spelled(path, text, pattern, what):
# every occurrence of one version spelling in a doc; the version is group "v"
found = list(re.finditer(pattern, text))
if not found:
res["left"].append("%s: no %s spelling to move; set it by hand or drop the mirror" % (path, what))
return None
if mode == "check":
return text
for m in reversed(found):
if m.group("v") != own:
res["summary"].append("%s:%d %s %s -> %s" % (path, line_of(text, m.start()), what, m.group("v"), own))
text = text[:m.start("v")] + own + text[m.end("v"):]
return text
def changelog(path, text):
if mode != "stable":
return text
if re.search(r"^##\s*\[?%s\]?(\s|$)" % re.escape(own), text, re.M):
return text
m = re.search(r"^## ", text, re.M)
stub = ("## %s\n\nTODO: release notes for %s. scripts/release.sh added this heading; "
"write the prose before merging.\n\n" % (own, own))
at = m.start() if m else len(text)
res["summary"].append("%s: new heading ## %s (needs prose)" % (path, own))
res["notes"].append("%s needs release notes under the new ## %s heading before this PR merges" % (path, own))
return text[:at] + stub + text[at:]
def handle(path, how):
# a file named by several mirrors (README.md:currently,README.md:jar) is rewritten in turn,
# each from the previous rewrite: re-reading it would drop the earlier one
text = res["changed"].get(path)
if text is None:
text = rd(path)
if text is None:
res["missing"].append(path)
if how in ("vfile", "readme", "changelog", "gwpin", "currently", "jar"):
res["left"].append("%s is missing" % path)
return
base = os.path.basename(path)
if how == "gwpin":
new = gatewaypin(path, text)
elif how == "readme":
new = readme_version(path, text)
elif how == "currently":
new = spelled(path, text, r"currently `(?P<v>%s)`" % SEMVER, "'currently `X`'")