forked from NOAA-OWP/nextgen-support-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateRelease.sh
More file actions
executable file
·1691 lines (1484 loc) · 61.8 KB
/
Copy pathcreateRelease.sh
File metadata and controls
executable file
·1691 lines (1484 loc) · 61.8 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
# Define color codes
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
NC='\033[0m' # No Color
declare -a TEMP_BRANCHES
# Release branch names are selected in main(). The default environment uses
# development/ngwpc-candidate/ngwpc-release. Passing PW selects the -pw variants.
DEVELOPMENT_BRANCH="development"
RELEASE_CANDIDATE_BRANCH="ngwpc-candidate"
RELEASE_BRANCH="ngwpc-release"
BRANCH_ENVIRONMENT="STANDARD"
# Toggle for printing the exact 'gh' commands being executed.
# Printed commands go to STDERR so that JSON captures using $(...) are not polluted.
DEBUG_GH=false
#-----------------------------------------
# Function: usage
# Displays usage information and exits.
#-----------------------------------------
usage() {
cat <<EOF
Usage: $(basename "$0") --release-type <RC|OFFICIAL|OWP> [OPTIONS]
This script automates the release process for GitHub repositories repositories listed in a JSON
configuration file, handling merges, submodules, and versioning.
Release Type Workflows:
RC — Release Candidate Mode
- First RC (-rc1) for a release: merges development → ngwpc-candidate (creating ngwpc-candidate
from development if it doesn't exist yet), updates ngwpc-candidate's submodule pointers if
applicable, then tags and creates a pre-release on ngwpc-candidate.
- Subsequent RCs (-rc2, -rc3, ...): skips the merge (assumes ngwpc-candidate already has what it
needs), updates ngwpc-candidate's submodule pointers if applicable, tags and creates the next
pre-release, then merges ngwpc-candidate back into development and updates development's
submodule pointers if applicable. A conflict updating development's submodule pointers fails
that step only — the RC pre-release already created is not rolled back.
- The next RC number is determined automatically from existing git tags matching <release>-rcN[-pw].
- In the PW environment, the tag gets a -pw suffix (e.g. 10.2-rcN-pw).
OFFICIAL — Official Release Mode
- Merges ngwpc-candidate → ngwpc-release (creating ngwpc-release if needed), updates submodule
pointers if applicable, generates a changelog (commit log since the last official tag, written
to changelogs/<repo>_<release>_changelog.txt), tags and creates the official release on
ngwpc-release, then merges ngwpc-release back into development. A conflict updating development's
submodule pointers fails that step only — the Official release already created is not rolled back.
- In the PW environment, the tag gets a -pw suffix (e.g. 10.2-pw).
OWP — Branch-Only Mode
- Creates ngwpc-<release> (or ngwpc-<release>-pw under PW) branch directly from ngwpc-release and
pushes it. No merge request, no tagging, no GitHub release — the repo is done as soon as the
branch is pushed.
- This branch is what gets submitted as a pull request to the upstream NOAA OWP parent repository;
the script only prepares and pushes it, it does not open that PR for you.
- In the PW environment, the tag gets a -pw suffix (e.g. 10.2-pw).
OPTIONS
Required option:
-r, --release-type TYPE Release workflow: RC, OFFICIAL, or OWP.
Optional options:
-c, --config FILE Configuration JSON file.
Default: createReleaseConfig.json
-v, --verbose Print the exact 'gh' commands being executed
Default: false
-w, --wait-time SECONDS Maximum wait before prompting while a PR is blocked.
Default: 60
-e, --environment ENV Branch/release environment: STANDARD or PW.
Default: STANDARD
-a, --automatic-submodules For repos with has_submodules=true, update
submodule pointers automatically. Without this
flag (the default), the script pauses instead
so you can update and push them by hand on
each relevant branch, then continue.
Default: false (manual)
-h, --help Display this help and exit.
Environment branches:
STANDARD:
development
ngwpc-candidate
ngwpc-release
PW:
development-pw
ngwpc-candidate-pw
ngwpc-release-pw
Release tags:
STANDARD RC: 10.2-rc1
STANDARD official: 10.2
PW RC: 10.2-rc1-pw
PW official: 10.2-pw
Examples:
$(basename "$0") --release-type RC
$(basename "$0") --release-type OFFICIAL --config release_config.json
$(basename "$0") --release-type RC --config release_config.json --wait-time 120 --environment PW
$(basename "$0") --release-type OWP --environment PW
$(basename "$0") --release-type RC --automatic-submodules
Per-repo config field "env" (optional; PW, AWS, or ALL; defaults to ALL):
Controls which -e environment(s) a repo entry is processed under, independent
of the "skip" flag:
-e PW -> repo runs only if env is PW or ALL
-e STANDARD (default) -> repo runs only if env is AWS or ALL
A repo entry with "skip": true is always skipped regardless of "env".
EOF
exit "${1:-0}"
}
#-----------------------------------------
# Function: git_push
# Quiet wrapper around `git push` that suppresses routine output
# (e.g., GitHub's "Create a pull request" hint) but still surfaces
# real errors. It:
# - runs `git push -q` with all arguments passed through
# - captures stderr/stdout on failure and prints them
#
# Arguments:
# $@ - Arguments passed directly to `git push`
#
# Returns:
# 0 on success; 1 on failure (after printing the captured error output)
#-----------------------------------------
git_push() {
if ! out=$(git push -q "$@" 2>&1); then
echo -e "${RED}git push failed: git push $*${NC}"
echo "$out" >&2
return 1
fi
return 0
}
#-----------------------------------------
# Function: run_gh
# Prints and executes a `gh` command.
#
# WHY:
# We want to see the exact `gh` command lines that run (for debugging).
#
# BEHAVIOR:
# - If DEBUG_GH=true, prints: Executing: gh <args...>
# - The print goes to STDERR so that callers that capture STDOUT via $(...) do not
# get the "Executing:" line mixed into JSON or other command output.
# - Returns `gh`'s exit status and streams `gh`'s STDOUT/STDERR unchanged.
#
# USAGE:
# run_gh release create ...
# json=$(run_gh pr create --json number)
#-----------------------------------------
run_gh() {
local args=("$@")
if [ "$DEBUG_GH" = true ]; then
printf 'Executing: ' >&2; printf '%q ' gh "${args[@]}" >&2; echo >&2
fi
gh "${args[@]}"
}
#-----------------------------------------
# Function: clean_and_encode_project
# Normalizes a GitHub remote URL to the canonical "owner/repo" form.
# Works for HTTPS and SSH remotes, and strips embedded credentials and .git suffix.
#-----------------------------------------
clean_and_encode_project() {
local project_url="$1"
project_url=$(echo "$project_url" | sed -e 's#^https\?://[^/]*@#https://#')
project_url=$(echo "$project_url" | sed -e 's#^https://github\.com/##')
project_url=$(echo "$project_url" | sed -e 's#^git@github\.com:##')
project_url=$(echo "$project_url" | sed -e 's#\.git$##')
echo "$project_url"
}
#-----------------------------------------
# Function: repo_env_applies
# Decides whether a repo config entry should be processed under the current
# BRANCH_ENVIRONMENT (STANDARD or PW), based on the config's optional "env"
# field (PW, AWS, or ALL; defaults to ALL when absent).
#
# Rules:
# -e PW -> repo processed only if env is PW or ALL
# -e STANDARD -> repo processed only if env is AWS or ALL
#
# Arguments:
# $1 - The repo's env value (already uppercased; "ALL" if unset)
#
# Returns:
# 0 if the repo should be processed under the current environment, 1 otherwise.
#-----------------------------------------
repo_env_applies() {
local repo_env="$1"
case "$BRANCH_ENVIRONMENT" in
PW)
[[ "$repo_env" == "PW" || "$repo_env" == "ALL" ]]
;;
STANDARD)
[[ "$repo_env" == "AWS" || "$repo_env" == "ALL" ]]
;;
*)
return 1
;;
esac
}
#-----------------------------------------
# Function: create_merge_request
# Creates a pull request using the GitHub CLI (`gh`).
#
# Arguments:
# $1 - Source branch (head)
# $2 - Target branch (base)
# $3 - Title for the pull request
#
# Behavior:
# - Uses `gh api` to POST the PR and echoes the PR number on success.
# - If a matching open PR already exists (HTTP 422 case), queries for it and echoes its number.
#
# Requires:
# REPO_PROJECT to be set to "owner/repo".
#
# Returns:
# 0 if a PR was created or an existing one was found; 1 otherwise.
#-----------------------------------------
create_merge_request() {
local source_branch="$1"
local target_branch="$2"
local title="$3"
local pr_num
echo
echo -e "Creating pull request from ${GREEN}$source_branch${NC} to ${GREEN}$target_branch${NC}" >&2
# Try to create PR via REST API and capture its number
if pr_num=$(run_gh api \
-X POST "repos/$REPO_PROJECT/pulls" \
-f title="$title" \
-f head="$source_branch" \
-f base="$target_branch" \
--jq '.number'); then
if [[ -n "$pr_num" && "$pr_num" != "null" ]]; then
echo "$pr_num"
return 0
fi
fi
# If it already exists (typical 422 case), look up the open PR matching head/base
local owner="${REPO_PROJECT%%/*}"
if pr_num=$(run_gh api \
-X GET "repos/$REPO_PROJECT/pulls?state=open&head=${owner}:${source_branch}&base=${target_branch}" \
--jq '.[0].number' 2>/dev/null); then
if [[ -n "$pr_num" && "$pr_num" != "null" ]]; then
echo "$pr_num"
return 0
fi
fi
echo -e "${RED}Error creating Pull Request from $source_branch to $target_branch${NC}" >&2
return 1
}
#-----------------------------------------
# Function: trigger_merge
# Triggers merging a pull request using the GitHub CLI (`gh`).
#
# Arguments:
# $1 - Pull request number
# $2 - (Optional) delete branch flag:
# "true" -> delete source branch after merge (default)
# "false" -> preserve source branch
#
# Behavior:
# - If delete flag is true, passes --delete-branch to gh.
# - Attempts immediate merge first; if not allowed, falls back to auto-merge.
# - Logs clearly whether the branch will be deleted or preserved.
#
# Returns:
# 0 on success, 1 on failure.
#-----------------------------------------
trigger_merge() {
local pr_number="$1"
local delete_branch="${2:-true}" # default: true
local delete_flag=()
if [[ "$delete_branch" == "true" ]]; then
delete_flag=(--delete-branch)
echo "Triggering merge for PR #$pr_number (source branch WILL be deleted)..."
else
echo "Triggering merge for PR #$pr_number (source branch will be PRESERVED)..."
fi
# 1) Try to merge immediately (non-auto). Deletes source branch on success.
local merge_output auto_output
if merge_output=$(run_gh pr merge "$pr_number" --merge "${delete_flag[@]}" 2>&1); then
echo "Merge triggered successfully."
echo
return 0
fi
# 2) Fall back to auto-merge (queues merge once requirements are met).
if auto_output=$(run_gh pr merge "$pr_number" --merge --auto "${delete_flag[@]}" 2>&1); then
echo "Auto-merge enabled (will merge when requirements are met)."
echo
return 0
fi
echo -e "${RED}Error triggering merge for PR $pr_number.${NC}"
echo -e "${YELLOW} Direct merge attempt said:${NC} $merge_output"
echo -e "${YELLOW} Auto-merge attempt said:${NC} $auto_output"
return 1
}
#-----------------------------------------
# Function: poll_merge_status
# Polls the pull request via `gh` until its status is either "MERGED" or "CLOSED".
#
# Arguments:
# $1 - Pull request number
# $2 - Maximum wait time in seconds
#
# Behavior:
# Continuously queries the pull request state and displays progress until the state
# is either "MERGED" or "CLOSED", or until max_wait is exceeded — at which point
# this gives up and returns failure rather than waiting indefinitely (e.g. a PR
# queued via auto-merge whose required check never reports).
#-----------------------------------------
poll_merge_status() {
local pr_number="$1"
local max_wait="${2:-300}"
local elapsed=0
echo "Waiting up to $max_wait seconds for pull request $pr_number to complete..."
while true; do
local state
# We suppress gh's own stderr here to keep logs tidy; the wrapper's
# "Executing:" line is printed to STDERR and will also be suppressed.
state=$(run_gh pr view "$pr_number" --json state -q '.state' 2>/dev/null || echo "")
if [[ "$state" == "MERGED" ]]; then
echo "Merge is complete."
return 0
elif [[ "$state" == "CLOSED" ]]; then
echo -e "${RED}Pull request closed without merging.${NC}"
return 1
fi
if (( elapsed >= max_wait )); then
echo -e "${RED}Gave up waiting for pull request $pr_number to complete after ${max_wait}s (last state: ${state:-unknown}).${NC}"
return 1
fi
echo "Current pull request state: ${state:-unknown}. Waiting 10 seconds..."
sleep 10
elapsed=$((elapsed + 10))
done
}
#-----------------------------------------
# Function: wait_until_mergeable
#
# Waits until a PR is "merge-button eligible":
# - NOT a draft, and
# - NOT in conflict (mergeStateStatus != DIRTY), and
# - NOT explicitly blocked (mergeStateStatus != BLOCKED).
#
# We DO allow: CLEAN, UNSTABLE, BEHIND, HAS_HOOKS, UNKNOWN
# Rationale: The UI shows the "Merge" button for those states when branch
# protection doesn’t require passing checks. The merge API will
# still 405 if rules block you, so don’t pre-block here.
#
# Arguments:
# $1 - Pull Request number
# $2 - Maximum wait time in seconds
#
# gh pr view output:
# Command: gh pr view <PR#> --json isDraft,mergeStateStatus
# Example return:
# {
# "isDraft": false,
# "mergeStateStatus": "CLEAN"
# }
#
# Common values for mergeStateStatus:
# CLEAN -> mergeable right now (no conflicts, requirements met)
# DIRTY -> conflicts must be resolved
# BLOCKED -> explicitly blocked (e.g. required reviews not approved)
# DRAFT -> draft PR, cannot merge
# UNSTABLE -> checks pending/failing, but merge button may still be available
# BEHIND -> branch behind base, may need update (only blocks if required)
# HAS_HOOKS -> waiting on external hooks
# UNKNOWN -> status not yet computed
#
# Behavior:
# - Polls the PR and returns success once the PR is not draft/dirty/blocked.
# - If the timeout is reached, prompts the user to Continue waiting or Skip.
#
# Returns:
# 0 if the PR becomes mergeable within the timeout,
# 1 on timeout (if user chooses Skip).
#-----------------------------------------
wait_until_mergeable() {
local pr_number="$1"
local max_wait="$2"
local elapsed=0
echo "Waiting up to $max_wait seconds for PR $pr_number to be mergeable..."
while true; do
# Query both draft state and merge state from GitHub
local checks_state
checks_state=$(run_gh pr view "$pr_number" --json isDraft,mergeStateStatus \
-q '[.isDraft, .mergeStateStatus]' 2>/dev/null || echo '["",""]')
local is_draft state
is_draft=$(echo "$checks_state" | jq -r '.[0]')
state=$(echo "$checks_state" | jq -r '.[1] // "UNKNOWN"')
echo "PR $pr_number status: isDraft=$is_draft, mergeStateStatus=$state"
# Proceed if not a draft, not in conflict, not explicitly blocked
if [[ "$is_draft" != "true" && "$state" != "DIRTY" && "$state" != "BLOCKED" ]]; then
echo "Pull request $pr_number appears mergeable (state: $state)"
return 0
fi
if (( elapsed >= max_wait )); then
if [ ! -t 0 ]; then
echo -e "${RED}PR $pr_number still not mergeable after ${max_wait}s (state: ${state:-unknown}); stdin isn't a terminal, so skipping instead of prompting.${NC}"
return 1
fi
while true; do
read -n 1 -s -r -p "Pull Request $pr_number not ready (state: ${state:-unknown}). (C)ontinue waiting, (S)kip: " choice
echo
choice=$(echo "$choice" | tr '[:lower:]' '[:upper:]')
case "$choice" in
C) echo "Continuing to wait..."; elapsed=0; break;;
S) echo "Skipping repository due to timeout."; return 1;;
*) echo "Invalid option. Please enter C to continue waiting or S to skip.";;
esac
done
fi
echo "Waiting for PR $pr_number to be mergeable (state: ${state:-unknown})..."
sleep 2
elapsed=$((elapsed + 2))
done
}
#-----------------------------------------
# Function: create_release
# Creates a GitHub release using the GitHub CLI (`gh release create`).
#
# Arguments:
# $1 - Release tag (e.g., "v1.1")
# $2 - Release name (e.g., "Release 1.1")
# $3 - Release notes (description)
# $4 - Ref branch (the branch to base the release on)
#
# Behavior:
# - Invokes `gh release create` and captures its stdout (the release URL).
# - Prints the URL with a clear label: "New release: <url>".
#
# Returns:
# 0 on success, 1 on failure.
#-----------------------------------------
create_release() {
local release_tag="$1"
local release_name="$2"
local release_notes="$3"
local ref_branch="$4"
local prerelease_flag=()
[[ "$RELEASE_TYPE" == "RC" ]] && prerelease_flag=(--prerelease)
# Capture stdout from gh (which is the release URL on success). Our run_gh
# prints the "Executing:" line to STDERR, so it won't pollute this capture.
local release_url
if release_url=$(run_gh release create "$release_tag" \
--title "$release_name" \
--notes "$release_notes" \
--target "$ref_branch" \
"${prerelease_flag[@]}"); then
# Print with context so the URL isn't a naked line in logs
echo -e "Release ${GREEN}$release_url${NC} created successfully."
return 0
fi
echo -e "${RED}Error creating release.${NC}"
return 1
}
#-----------------------------------------
# Function: execute_merge_request
# Combines creating a pull request, waiting until it becomes mergeable, and triggering the merge.
# We validate it locally before creating the PR to better ensure that it will succeed.
#
# Arguments:
# $1 - Source branch
# $2 - Target branch
# $3 - Title for the pull request
# $4 - Wait time (seconds)
# $5 - (Optional) delete source branch after merge: true or false (default: false)
#
# Behavior:
# - Checks if the source branch has changes compared to the target.
# - Attempts a local merge to detect conflicts before creating a pull request.
# - Only proceeds to create the PR (via `gh`) if the merge is clean or only submodule-pointer conflicts exist.
#
# Returns:
# 0 on success; 1 on failure.
#-----------------------------------------
execute_merge_request() {
local source_branch="$1"
local target_branch="$2"
local title="$3"
local wait_time="$4"
local delete_source_branch="${5:-false}"
local branch_created=0 # Flag to track if the target branch was just created
local previous_branch
previous_branch=$(git rev-parse --abbrev-ref HEAD) # Save current branch
# Check if the target branch exists in the remote repository
# echo Checking if $target_branch exists...
if ! git ls-remote --exit-code --heads origin "$target_branch" > /dev/null 2>&1; then
### for debugging
git ls-remote --exit-code --heads origin "$target_branch" || true
###
echo -e "${YELLOW}Target branch $target_branch does not exist. Creating it from $source_branch...${NC}"
# Create the target branch directly from the current remote source branch.
if ! git fetch --quiet origin "$source_branch"; then
echo -e "${RED}Unable to fetch source branch $source_branch.${NC}"
return 1
fi
git branch --quiet -D "$target_branch" >/dev/null 2>&1 || true
if ! git checkout --quiet -b "$target_branch" "origin/$source_branch"; then
echo -e "${RED}Unable to create local branch $target_branch from origin/$source_branch.${NC}"
return 1
fi
git_push --set-upstream origin "$target_branch" || return 1
echo -e "${GREEN}Successfully created and pushed branch $target_branch from $source_branch.${NC}"
branch_created=1 # Mark that we just created the branch
fi
# If the target branch was just created, skip the pull request
if [ "$branch_created" -eq 1 ]; then
echo -e "${YELLOW}Skipping pull request since $target_branch was just created from $source_branch.${NC}"
git checkout --quiet "$previous_branch" # Restore original branch
return 0
fi
echo
echo -e "${YELLOW}Checking merge viability between $source_branch and $target_branch...${NC}"
# Ensure we have the latest updates for source and target branches
if ! git fetch --quiet origin "$source_branch" "$target_branch"; then
echo -e "${RED}Unable to fetch $source_branch and $target_branch from origin.${NC}"
return 1
fi
# Definitive check: is source actually ahead of target?
# Format: "behind ahead" (target behind source, source ahead of target)
local behind ahead
read behind ahead < <(git rev-list --left-right --count "origin/$target_branch...origin/$source_branch")
if [[ "${ahead:-0}" -eq 0 ]]; then
echo -e "${YELLOW}No changes detected in $source_branch relative to $target_branch (ahead=$ahead). Skipping pull request.${NC}"
git checkout --quiet "$previous_branch"
return 0
fi
# Create a temporary test merge branch (delete if it already exists)
local temp_merge_branch="merge_test_${source_branch}_to_${target_branch}"
git branch --quiet -D "$temp_merge_branch" >/dev/null 2>&1 || true
git checkout --quiet -b "$temp_merge_branch" "origin/$target_branch"
TEMP_BRANCHES+=("$temp_merge_branch")
# Attempt to merge the source branch into the target branch quietly
if ! git merge --no-commit --no-ff "origin/$source_branch" ; then
echo -e "${YELLOW}Merge conflicts detected between $source_branch and $target_branch.. Checking if they are only submodule pointers...${NC}"
# Get list of conflicting files
local conflict_files non_submodule_conflicts
conflict_files=$(git diff --name-only --diff-filter=U)
non_submodule_conflicts=$(echo "$conflict_files" | grep -vE '^extern/[^/]+(/[^/]+)?$' || true)
if [[ -n "$non_submodule_conflicts" ]]; then
echo -e "${RED}Merge has conflicts outside submodules. Pull request will not be created.${NC}"
echo
echo -e "${YELLOW}Conflicting files:${NC}"
echo "$conflict_files"
git merge --abort
git checkout --quiet "$previous_branch"
git branch --quiet -D "$temp_merge_branch"
return 1
else
echo -e "${GREEN}Only submodule pointer conflicts detected. The pull request will be allowed to resolve them according to repository rules.${NC}"
fi
fi
# A --no-commit test merge leaves MERGE_HEAD in place even when it succeeds.
# Always abort the test merge before restoring the user's original branch.
git merge --abort >/dev/null 2>&1 || true
echo -e "${GREEN}Local merge test completed. Proceeding with pull request creation...${NC}"
echo
if ! git checkout --quiet "$previous_branch"; then
echo -e "${RED}Unable to restore branch $previous_branch after the merge test.${NC}"
return 1
fi
git branch --quiet -D "$temp_merge_branch" >/dev/null 2>&1 || true
# Now, create the pull request
local pr_number
if ! pr_number=$(create_merge_request "$source_branch" "$target_branch" "$title" | tr -d '\n'); then
echo -e "${RED}Error: Pull Request creation failed for merging $source_branch into $target_branch.${NC}"
return 1
fi
if [[ -z "$pr_number" ]]; then
echo -e "${RED}Error: Pull Request creation failed for merging $source_branch into $target_branch.${NC}"
return 1
fi
echo "Waiting up to $wait_time seconds for pull request $pr_number to become mergeable..."
wait_until_mergeable "$pr_number" "$wait_time"
local ret=$?
# Leave these as if statements. It is clearer that way
if [ $ret -ne 0 ]; then
echo -e "${RED}Timeout or error waiting for pull request $pr_number to become mergeable.${NC}"
return 1
fi
# Long-lived release branches are preserved. Temporary automation branches may be deleted.
trigger_merge "$pr_number" "$delete_source_branch"
if [ $? -ne 0 ]; then
echo -e "${RED}Merge trigger failed for PR $pr_number.${NC}"
return 1
fi
if ! poll_merge_status "$pr_number" "$wait_time"; then
return 1
fi
return 0
}
#-----------------------------------------
# Function: get_next_rc_number
# Determines the next available release-candidate (rcX) number.
#
# Arguments:
# $1 - Release number (e.g., "10.2")
#
# Behavior:
# - Lists existing Git tags matching the pattern "<release_number>-rcX".
# - Extracts the numeric portion (X) from those tags.
# - Finds the highest existing rc number and increments it.
# - If no matching tags exist, starts at "rc1".
#
# Returns:
# The next available release candidate tag (e.g., "10.2-rc1", "10.2-rc2").
#-----------------------------------------
get_next_rc_number() {
local release_number="$1" # e.g., "10.2"
local tag_suffix=""
local tag_regex
local sed_expression
if [[ "$BRANCH_ENVIRONMENT" == "PW" ]]; then
tag_suffix="-pw"
tag_regex="^${release_number}-rc[0-9]+-pw$"
sed_expression="s/^${release_number}-rc([0-9]+)-pw$/\1/"
else
tag_regex="^${release_number}-rc[0-9]+$"
sed_expression="s/^${release_number}-rc([0-9]+)$/\1/"
fi
git fetch --tags --prune --prune-tags || return 1
local highest_rc
highest_rc=$(git tag | grep -E "$tag_regex" | sed -E "$sed_expression" | sort -nr | head -n1)
if [[ -z "$highest_rc" ]]; then
echo "${release_number}-rc1${tag_suffix}"
else
echo "${release_number}-rc$((highest_rc + 1))${tag_suffix}"
fi
}
#-----------------------------------------
# Function: generate_changelog
# Generates a changelog for the upcoming release by listing commit
# messages between the most recent official (previous) tag and HEAD.
#
# Behavior:
# - Finds the most recent tag that follows the format "X.Y" (e.g., "10.2"),
# excluding pre-release tags like "10.2-rc1".
# - If a previous tag is found, sets the commit range as "previous_tag..HEAD".
# Otherwise, uses HEAD as the range.
# - Retrieves commit messages (excluding merge commits) in reverse chronological order.
# - Ensures that the 'changelogs' directory exists in the script's original execution location.
# - Extracts the last segment of <REPO_PROJECT> (after the last '/') for the filename.
# - Outputs the changelog to "changelogs/<last_part_of_repo_project>_<RELEASE_NUMBER>_changelog.txt".
#
# Returns:
# 0 on success. Also sets the global variable GENERATED_CHANGELOG_COMMITS
# to the commit list (the same content written to the changelog file,
# minus the header) so callers can fold it into other output (e.g. GitHub
# release notes) without it ever going to stdout/terminal/log.
#-----------------------------------------
generate_changelog() {
# Find the most recent official tag for the selected environment.
local previous_tag
if [[ "$BRANCH_ENVIRONMENT" == "PW" ]]; then
previous_tag=$(git tag | grep -E '^[0-9]+(\.[0-9]+)+-pw$' | sort -V | tail -n1)
else
previous_tag=$(git tag | grep -E '^[0-9]+(\.[0-9]+)+$' | sort -V | tail -n1)
fi
local commit_range
if [ -n "$previous_tag" ]; then
commit_range="${previous_tag}..HEAD"
else
commit_range="HEAD"
fi
# Get the date and time of the HEAD commit
local head_date
head_date=$(git log -1 --pretty=format:'%ad' --date='format:%Y-%m-%d %H:%M:%S' HEAD)
# Extract the last part of REPO_PROJECT (everything after the last '/')
local repo_name
repo_name=$(basename "$REPO_PROJECT")
# Ensure the changelogs directory exists in the script's original execution location
local changelog_dir="${SCRIPT_DIR}/changelogs"
mkdir -p "$changelog_dir"
# Define the output file path
local changelog_file="${changelog_dir}/${repo_name}_${RELEASE_NUMBER}_changelog.txt"
# Print header for the upcoming release into the changelog file (single line)
printf "## Changelog for %s %s (%s)\n\n" "$REPO_PROJECT" "$RELEASE_NUMBER" "$head_date" > "$changelog_file"
# Capture the commit messages (excluding merge commits) once, so the same
# list can be written to the changelog file and also handed to the caller
# via a global variable — not stdout, so it never prints to the terminal
# or the log unless something explicitly echoes it.
local commit_log
commit_log=$(git log "$commit_range" --oneline --reverse --no-merges)
echo "$commit_log" >> "$changelog_file"
GENERATED_CHANGELOG_COMMITS="$commit_log"
echo -e "${GREEN}Changelog saved to $changelog_file${NC}"
return 0
}
#-----------------------------------------
# Function: process_submodules
# Updates the parent repository's submodule pointers to the latest commits on
# the branch that matches the parent target branch.
#
# Arguments:
# $1 - Parent target branch (for example: ngwpc-candidate, ngwpc-release,
# or the selected development branch)
#
# Behavior:
# - Creates a temporary parent branch from origin/<target_branch>.
# - Initializes and synchronizes all configured submodules.
# - Fetches origin/<target_branch> in each top-level submodule.
# - Checks out the exact commit at origin/<target_branch> in detached-HEAD mode.
# - Commits changed gitlink pointers in the parent repository.
# - Pushes the temporary branch and merges it into <target_branch> through a PR.
# - Leaves the parent checked out on the updated target branch with submodules
# synchronized to the committed pointers.
#
# Safety:
# - Fails without committing if any submodule does not have the requested branch.
# - Does not create commits inside submodule repositories.
# - Nested submodules are initialized recursively, but only top-level gitlink
# pointers recorded directly by this parent repository are changed.
#-----------------------------------------
process_submodules() {
local target_branch="$1"
local previous_branch temp_branch
local -a submodule_paths=()
echo -e "${GREEN}Updating submodule pointers for parent branch: $target_branch${NC}"
if [[ ! -f .gitmodules ]]; then
echo -e "${YELLOW}has_submodules=true, but this repository has no .gitmodules file. Nothing to update.${NC}"
return 0
fi
mapfile -t submodule_paths < <(
git config --file .gitmodules --get-regexp '^submodule\..*\.path$' 2>/dev/null | awk '{print $2}'
)
if (( ${#submodule_paths[@]} == 0 )); then
echo -e "${YELLOW}No submodule paths were found in .gitmodules. Nothing to update.${NC}"
return 0
fi
previous_branch=$(git rev-parse --abbrev-ref HEAD)
temp_branch="update_submodules_${target_branch//\//_}_${RELEASE_NUMBER//\//_}"
if ! git fetch --quiet origin "$target_branch"; then
echo -e "${RED}Unable to fetch parent target branch origin/$target_branch.${NC}"
return 1
fi
# Always recreate the temporary branch from the current remote target branch.
git merge --abort >/dev/null 2>&1 || true
git branch --quiet -D "$temp_branch" >/dev/null 2>&1 || true
if ! git checkout --quiet -b "$temp_branch" "origin/$target_branch"; then
echo -e "${RED}Unable to create temporary branch $temp_branch from origin/$target_branch.${NC}"
return 1
fi
TEMP_BRANCHES+=("$temp_branch")
if ! git submodule sync --recursive; then
echo -e "${RED}Unable to synchronize submodule URLs.${NC}"
git checkout --quiet "$previous_branch" || true
return 1
fi
if ! git submodule update --init --recursive; then
echo -e "${RED}Unable to initialize the repository submodules.${NC}"
git checkout --quiet "$previous_branch" || true
return 1
fi
local path
for path in "${submodule_paths[@]}"; do
echo -e "Updating ${GREEN}$path${NC} to origin/${GREEN}$target_branch${NC}..."
if [[ ! -d "$path" ]]; then
echo -e "${RED}Submodule directory does not exist after initialization: $path${NC}"
git checkout --quiet "$previous_branch" || true
return 1
fi
if ! git -C "$path" fetch --quiet origin "$target_branch"; then
echo -e "${RED}Unable to fetch origin/$target_branch for submodule $path.${NC}"
git checkout --quiet "$previous_branch" || true
return 1
fi
if ! git -C "$path" rev-parse --verify --quiet "refs/remotes/origin/$target_branch^{commit}" >/dev/null; then
echo -e "${RED}Submodule $path does not have an origin/$target_branch branch.${NC}"
git checkout --quiet "$previous_branch" || true
return 1
fi
if ! git -C "$path" checkout --quiet --detach "origin/$target_branch"; then
echo -e "${RED}Unable to check out origin/$target_branch in submodule $path.${NC}"
git checkout --quiet "$previous_branch" || true
return 1
fi
echo " $path -> $(git -C "$path" rev-parse --short HEAD)"
done
# Stage only the top-level submodule gitlinks listed in .gitmodules.
if ! git add -- "${submodule_paths[@]}"; then
echo -e "${RED}Unable to stage updated submodule pointers.${NC}"
git checkout --quiet "$previous_branch" || true
return 1
fi
if git diff --cached --quiet; then
echo -e "${YELLOW}All submodule pointers already match origin/$target_branch. No parent commit is required.${NC}"
if ! git checkout --quiet "$target_branch"; then
git checkout --quiet -B "$target_branch" "origin/$target_branch" || return 1
fi
git branch --quiet -D "$temp_branch" >/dev/null 2>&1 || true
git submodule update --init --recursive
return 0
fi
echo "Submodule pointer changes:"
git diff --cached --submodule=short
if ! git commit -m "Update submodules for $target_branch release $RELEASE_NUMBER"; then
echo -e "${RED}Unable to commit updated submodule pointers.${NC}"
git checkout --quiet "$previous_branch" || true
return 1
fi
if ! git_push --set-upstream origin "$temp_branch"; then
git checkout --quiet "$previous_branch" || true
return 1
fi
if ! execute_merge_request "$temp_branch" "$target_branch" \
"Update submodule pointers on $target_branch for release $RELEASE_NUMBER" \
"$WAIT_TIME" true; then
echo -e "${RED}Unable to merge updated submodule pointers into $target_branch.${NC}"
git checkout --quiet "$previous_branch" || true
return 1
fi
if ! git fetch --quiet origin "$target_branch"; then
echo -e "${RED}Submodule pointer PR merged, but origin/$target_branch could not be fetched.${NC}"
return 1
fi
# Refresh the local parent target branch to the merged remote state.
if git show-ref --verify --quiet "refs/heads/$target_branch"; then
if ! git checkout --quiet "$target_branch" || ! git reset --quiet --hard "origin/$target_branch"; then
echo -e "${RED}Unable to refresh local branch $target_branch after the submodule pointer merge.${NC}"
return 1
fi
else
if ! git checkout --quiet -b "$target_branch" "origin/$target_branch"; then
echo -e "${RED}Unable to create local branch $target_branch after the submodule pointer merge.${NC}"
return 1
fi
fi
if ! git submodule update --init --recursive; then
echo -e "${RED}Parent branch was updated, but its submodules could not be synchronized to the committed pointers.${NC}"
return 1
fi
echo -e "${GREEN}Submodule pointers on $target_branch were updated successfully.${NC}"
return 0
}
#-----------------------------------------
# Function: manual_submodule_pause
# Used instead of process_submodules unless --automatic-submodules is set
# (manual is the default). Rather than updating submodule pointers
# automatically, this pauses so the user can update them by hand — via a
# feature branch and PR, since the target branch is protected — then continue.
#
# Arguments:
# $1 - Branch the repo is currently checked out on (the one whose submodule
# pointers need updating — e.g. ngwpc-candidate, ngwpc-release, or the
# selected development branch)
#
# Behavior:
# - No-ops, like process_submodules, if there's no .gitmodules file.
# - Otherwise blocks with no timeout (this is a real manual task) until the
# user presses Enter/C to continue, or chooses (S)kip or (Q)uit, matching
# the same convention used by the per-repo Continue/Skip/Quit prompt.
#
# Returns: 0 to continue, 1 to skip this repo, 2 if the user chose Quit.
#-----------------------------------------
manual_submodule_pause() {
local branch="$1"
if [[ ! -f .gitmodules ]]; then
echo -e "${YELLOW}has_submodules=true, but this repository has no .gitmodules file. Nothing to update.${NC}"
return 0
fi
echo
echo -e "${YELLOW}Manual submodule update (pass --automatic-submodules to update pointers automatically instead):${NC}"
echo -e "This repository is currently checked out on ${GREEN}$branch${NC}."
echo "'$branch' is protected, so you can't push to it directly. Instead:"
echo " 1. Create a new branch from here, e.g.: git checkout -b update-submodules-$branch"
echo " 2. Update each submodule to the commit it should point to, then commit that change."
echo " 3. Push the new branch, then open and merge a pull request into '$branch'."
echo " 4. Check '$branch' back out (git checkout $branch && git pull) before continuing below."
echo
while true; do
echo -e "${YELLOW}(C)ontinue once done, (S)kip this repository, (Q)uit:${NC}"
read -n 1 -s -r user_input
echo
user_input="${user_input:-C}"
user_input=$(echo "$user_input" | tr '[:lower:]' '[:upper:]')
case "$user_input" in
C)
echo -e "${GREEN}Continuing.${NC}"
return 0
;;
S)
echo -e "${YELLOW}Skipping this repository.${NC}"
return 1
;;
Q)
echo -e "${YELLOW}Quit requested. No further repositories will be processed.${NC}"
return 2
;;
*)
echo "Please press C, S, or Q."
;;
esac
done
}
#-----------------------------------------
# Function: process_repo
# Processes a single repository given its directory, a base release number and release notes.