-
Notifications
You must be signed in to change notification settings - Fork 0
3044 lines (2778 loc) · 150 KB
/
Copy pathpost-release.yml
File metadata and controls
3044 lines (2778 loc) · 150 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
name: Post Release
# Names each run for what it targets, so the Actions list distinguishes runs at a glance
# instead of showing a column of identical "Post Release" rows:
#
# Post Release - 2025.1.2
# Post Release - 2024.0.8 (commercial)
# Post Release - 2025.1.2 [spring-cloud-config,spring-cloud-build] - Dry Run
#
# (commercial) is shown only when `projects` is empty. With a filter the input is ignored -
# the type is derived from the names - so printing it could contradict the run, and the
# -commercial suffix in the listed names already says which line it is.
run-name: "Post Release - ${{ inputs.release_version }}${{ inputs.projects != '' && format(' [{0}]', inputs.projects) || (inputs.commercial == true && ' (commercial)' || '') }}${{ inputs.dry_run == true && ' - Dry Run' || '' }}"
# Performs the chores that follow a Spring Cloud release train, in order:
#
# 1. setup — read the jenkins-releaser-config properties file, validate, filter
# 2. verify-tags — every project version must have a v<version> tag (hard gate)
# 3. next-snapshot-config — write the next <train>-snapshot.properties file
# 4. new-milestones — open a milestone for each new snapshot version
# 5. merge-back-and-update — merge release/<version> back into .x, bump to snapshots, push,
# and push the release tag into this repository
# 6. milestones-and-releases — close the release milestone, publish the GitHub release
# (skip_close_milestones leaves the milestones open and still
# publishes the releases)
# 7. website-pr — open a PR against spring-website-content: the release blog post
# and the documentation.json version bumps (OSS trains only)
# 8. summary — one report covering everything above
#
# release/<version> and the v<version> tag only ever exist in the commercial repository - an OSS
# release is built there too, on a branch cut from <major>.<minor>.x-internal. So step 5 merges
# across repositories, and it pushes the tag into the OSS repo once the merge has made the
# tagged commit reachable there. Step 6 has to follow it for that reason: POST /releases with a
# tag_name that does not exist creates the tag at the default branch head, so publishing before
# the tag arrives would stamp v<version> onto whatever main happened to be.
#
# Every mutating step is gated on existence rather than on any attempt to work out whether a
# project was really part of this train. A version carried over from an earlier release already
# has its release and a closed milestone, so those steps become no-ops on their own.
#
# Hotfix releases (a 4-segment release_version, e.g. 2025.1.2.1) run only steps 1, 2 and 6:
# there is no next snapshot train, no new milestone, and no branch to merge a hotfix back into
# (release/<version> is itself the hotfix line).
#
# See README-post-release.md for details.
on:
workflow_dispatch:
inputs:
dry_run:
description: 'Dry run, if checked nothing is created, committed or pushed, but you can see what would happen'
required: false
type: boolean
default: true
release_version:
description: 'Spring Cloud release train version that was just released (e.g. 2025.1.2, or 2025.1.2.1 for a commercial hotfix)'
required: true
type: string
commercial:
description: 'Was this a commercial release? Ignored when projects is supplied - the -commercial suffix on the project names decides.'
required: false
type: boolean
default: false
projects:
description: 'Comma-separated list of projects to run against, including the -commercial suffix where applicable (e.g. spring-cloud-config,spring-cloud-build). Must be all OSS or all commercial. When empty, every project in the properties file is processed.'
required: false
type: string
default: ''
skip_close_milestones:
description: 'Skip closing the release milestones. Everything else - including publishing the releases - still runs.'
required: false
type: boolean
default: false
skip_website_pr:
description: 'Skip creating a website (for OSS or commercial) PR.'
required: false
type: boolean
default: false
skip_start_site_pr:
description: 'Skip the start.spring.io PR that bumps the Spring Cloud version. OSS releases only.'
required: false
type: boolean
default: false
token:
description: 'GitHub token with write access to all target repos. Falls back to GH_ACTIONS_REPO_TOKEN.'
required: false
type: string
default: ''
permissions:
contents: read
jobs:
setup:
name: Setup
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.parse.outputs.matrix }}
count: ${{ steps.parse.outputs.count }}
hotfix: ${{ steps.parse.outputs.hotfix }}
commercial: ${{ steps.parse.outputs.commercial }}
release-repo: ${{ steps.parse.outputs.release-repo }}
props-file: ${{ steps.parse.outputs.props-file }}
next-version: ${{ steps.parse.outputs.next-version }}
next-file: ${{ steps.parse.outputs.next-file }}
entries: ${{ steps.parse.outputs.entries }}
steps:
- name: Parse releaser config and build matrix
id: parse
env:
GH_TOKEN: ${{ inputs.token || secrets.GH_ACTIONS_REPO_TOKEN }}
RELEASE_VERSION: ${{ inputs.release_version }}
COMMERCIAL: ${{ inputs.commercial }}
PROJECTS_FILTER: ${{ inputs.projects }}
run: |
node - << 'JSEOF'
const fs = require('fs');
const { execFileSync } = require('child_process');
const releaseVersion = (process.env.RELEASE_VERSION || '').trim();
const projectsRaw = (process.env.PROJECTS_FILTER || '').trim();
const commercialInput = (process.env.COMMERCIAL || 'false') === 'true';
const fail = (...msg) => { for (const m of msg) console.error(m); process.exit(1); };
// Pre-release qualifiers are rejected rather than half-handled: bumping the patch of
// something like 2025.1.0-RC1 produces a version nobody wants, and post-release chores
// are not run for milestones or release candidates anyway.
if (!/^\d+(\.\d+){2,3}$/.test(releaseVersion)) {
fail(`ERROR: release_version must be a plain numeric version with 3 or 4 segments ` +
`(e.g. 2025.1.2 or 2025.1.2.1); got '${releaseVersion}'.`);
}
// A 4-segment version is a commercial hotfix: only the tag gate and the
// milestone/release step apply to it.
const hotfix = releaseVersion.split('.').length === 4;
// ── projects filter ─────────────────────────────────────────────────────────
// Commerciality comes from the names, not from the commercial input, because the
// names are what the caller actually typed. That derived value also selects which
// properties file is read, which is why a mixed list cannot be allowed: one
// release_version cannot address both the OSS train (2025.1.2) and the commercial
// one (2025.1.2.1), so a mix would silently resolve every project to a wrong version.
// Empty entries are dropped, not rejected: a trailing comma has only one sensible
// reading, and this is how ci-status-report.yml:74 and rollout-deploy-docs.yml:84
// parse the same input.
const names = projectsRaw
? projectsRaw.split(',').map(s => s.trim()).filter(Boolean)
: [];
let commercial = commercialInput;
if (names.length) {
const suffixed = names.filter(n => n.endsWith('-commercial'));
const unsuffixed = names.filter(n => !n.endsWith('-commercial'));
if (suffixed.length && unsuffixed.length) {
fail(
'ERROR: projects mixes commercial and OSS projects.',
` commercial: ${suffixed.join(', ')}`,
` oss: ${unsuffixed.join(', ')}`,
'A run targets one release train, so every project must be the same type.');
}
commercial = suffixed.length > 0;
if (commercial !== commercialInput) {
console.log(`Note: the commercial input (${commercialInput}) is ignored when ` +
`projects is supplied; derived commercial=${commercial} from the project names.`);
}
}
// Always spring-cloud-release-commercial, for OSS trains too: that repository holds
// the releaser config for every train now, so this is deliberately NOT derived from
// `commercial`. That input still decides everything else - which project repos are
// acted on, whether release notes are sanitized, and the OSS tag fallback.
const releaseRepo = 'spring-cloud/spring-cloud-release-commercial';
const propsFile = releaseVersion.replace(/\./g, '_') + '.properties';
// ── read the properties file ────────────────────────────────────────────────
console.log(`Reading ${propsFile} from ${releaseRepo}@jenkins-releaser-config...`);
let content;
try {
const b64 = execFileSync('gh', ['api',
`repos/${releaseRepo}/contents/${propsFile}?ref=jenkins-releaser-config`,
'--jq', '.content'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
content = Buffer.from(b64.replace(/\s/g, ''), 'base64').toString('utf8');
} catch (err) {
fail(`ERROR: could not read ${propsFile} from ${releaseRepo}@jenkins-releaser-config.`,
'Check that release_version matches a properties file on that branch, and that the',
'token has read access to the repository.');
}
const ENTRY_RE = /^releaser\.fixed-versions\[([^\]]+)\]=(.+)$/;
const entries = [];
for (const line of content.split('\n')) {
const m = line.match(ENTRY_RE);
if (m) entries.push({ key: m[1].trim(), version: m[2].trim() });
}
if (!entries.length) {
fail(`ERROR: ${propsFile} contains no releaser.fixed-versions[...] entries.`);
}
console.log(`Found ${entries.length} version entries.`);
// spring-boot lives in the properties file but is not a Spring Cloud repository, so it
// has no tag, milestone or release of ours. It is still bumped in the snapshot file.
const NON_REPO_KEYS = new Set(['spring-boot']);
let wanted = null;
if (names.length) {
wanted = new Set(names.map(n => n.replace(/-commercial$/, '')));
const known = new Set(entries.map(e => e.key));
const unknown = [...wanted].filter(k => !known.has(k));
if (unknown.length) {
fail(`ERROR: not found in ${propsFile}: ${unknown.join(', ')}`,
`Known projects: ${[...known].sort().join(', ')}`);
}
const nonRepo = [...wanted].filter(k => NON_REPO_KEYS.has(k));
if (nonRepo.length) {
fail(`ERROR: ${nonRepo.join(', ')} is not a Spring Cloud project repository ` +
'and cannot be targeted directly.');
}
}
const matrix = entries
.filter(e => !NON_REPO_KEYS.has(e.key))
.filter(e => !wanted || wanted.has(e.key))
.map(e => ({
project: e.key,
repo: commercial ? `spring-cloud/${e.key}-commercial` : `spring-cloud/${e.key}`,
ossRepo: `spring-cloud/${e.key}`,
// Carried on every entry, including OSS runs, because that is where the release
// branch and the tag always live - see verify-tags and merge-back-and-update.
// On a commercial run this is the same value as repo.
commercialRepo: `spring-cloud/${e.key}-commercial`,
version: e.version,
tag: `v${e.version}`,
}))
.sort((a, b) => a.project.localeCompare(b.project));
// ── next snapshot train version ─────────────────────────────────────────────
const bump = v => {
const parts = v.split('.');
const last = parts[parts.length - 1];
if (!/^\d+$/.test(last)) return null;
parts[parts.length - 1] = String(Number(last) + 1);
return parts.join('.');
};
let nextVersion = '';
let nextFile = '';
if (!hotfix) {
const unbumpable = entries.filter(e => bump(e.version) === null);
if (unbumpable.length) {
fail('ERROR: these versions do not end in a numeric segment and cannot be bumped:',
...unbumpable.map(e => ` ${e.key}=${e.version}`));
}
nextVersion = bump(releaseVersion);
nextFile = nextVersion.replace(/\./g, '_') + '-snapshot.properties';
}
console.log('');
console.log(`commercial: ${commercial}`);
console.log(`hotfix: ${hotfix}`);
console.log(`release repo: ${releaseRepo}`);
console.log(`properties file: ${propsFile}`);
if (!hotfix) console.log(`next snapshot: ${nextVersion} (${nextFile})`);
console.log('');
console.log(`Projects to process: ${matrix.length}`);
for (const e of matrix) console.log(` ${e.repo} @ ${e.tag}`);
const out = process.env.GITHUB_OUTPUT;
fs.appendFileSync(out, `matrix=${JSON.stringify({ include: matrix })}\n`);
fs.appendFileSync(out, `count=${matrix.length}\n`);
fs.appendFileSync(out, `hotfix=${hotfix}\n`);
fs.appendFileSync(out, `commercial=${commercial}\n`);
fs.appendFileSync(out, `release-repo=${releaseRepo}\n`);
fs.appendFileSync(out, `props-file=${propsFile}\n`);
fs.appendFileSync(out, `next-version=${nextVersion}\n`);
fs.appendFileSync(out, `next-file=${nextFile}\n`);
fs.appendFileSync(out, `entries=${JSON.stringify(entries)}\n`);
JSEOF
# ── Hard gate ────────────────────────────────────────────────────────────────────────
# One job rather than a matrix so an incomplete release produces a single consolidated
# failure naming every missing tag, instead of N separately-red matrix legs.
verify-tags:
name: Verify Tags
needs: setup
if: needs.setup.outputs.count != '0'
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.verify.outputs.matrix }}
steps:
- name: Verify a tag exists for every project version
id: verify
env:
GH_TOKEN: ${{ inputs.token || secrets.GH_ACTIONS_REPO_TOKEN }}
MATRIX: ${{ needs.setup.outputs.matrix }}
COMMERCIAL: ${{ needs.setup.outputs.commercial }}
run: |
node - << 'JSEOF'
const fs = require('fs');
const { execFileSync } = require('child_process');
const entries = JSON.parse(process.env.MATRIX).include;
const commercial = process.env.COMMERCIAL === 'true';
// matching-refs returns an array, so an exact comparison is required: a plain
// git/refs/tags/v5.0.2 lookup also prefix-matches v5.0.20.
const tagExists = (repo, tag) => {
try {
const refs = execFileSync('gh', ['api',
`repos/${repo}/git/matching-refs/tags/${tag}`, '--jq', '.[].ref'],
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
return refs.split('\n').map(r => r.trim()).includes(`refs/tags/${tag}`);
} catch (err) {
return false;
}
};
const resolved = [];
const missing = [];
// Tags are only ever created on a release/<version> branch, and those only ever exist
// in the commercial repo - an OSS release is built there too, from the -internal
// branch. So the commercial repo is where the gate really looks, for both flavours;
// the difference is what a hit means afterwards.
for (const e of entries) {
if (commercial) {
if (tagExists(e.commercialRepo, e.tag)) {
console.log(`✓ ${e.commercialRepo} ${e.tag}`);
resolved.push({ ...e, resolvedIn: 'commercial' });
continue;
}
// A commercial project with no tag of its own has had no commercial release since
// the last OSS one - its properties entry carries the plain OSS version (e.g.
// spring-cloud-bus=5.0.2 in 2025_1_2_1.properties). The OSS tag satisfies the
// gate, but there is nothing in the commercial repo to attach a release to.
if (tagExists(e.ossRepo, e.tag)) {
console.log(`✓ ${e.ossRepo} ${e.tag} (no commercial tag - OSS fallback)`);
resolved.push({ ...e, resolvedIn: 'oss-fallback' });
continue;
}
} else {
// Checked first only because a hit here means there is nothing left to do: the
// tag is already where this run needs it, either from a re-run of this workflow
// or because the version was carried over from an earlier train.
if (tagExists(e.ossRepo, e.tag)) {
console.log(`✓ ${e.ossRepo} ${e.tag}`);
resolved.push({ ...e, resolvedIn: 'oss' });
continue;
}
// The normal path for an OSS release: the tag exists only on the release branch
// in the commercial repo. merge-back-and-update pushes it to the OSS repo once
// the tagged commit is reachable there, which is why that job now runs before
// milestones-and-releases.
if (tagExists(e.commercialRepo, e.tag)) {
console.log(`✓ ${e.commercialRepo} ${e.tag} ` +
`(not in ${e.ossRepo} yet - the merge back will push it)`);
resolved.push({ ...e, resolvedIn: 'commercial-pending' });
continue;
}
}
console.log(`✗ ${e.tag} - MISSING`);
missing.push(e);
}
fs.appendFileSync(process.env.GITHUB_OUTPUT,
`matrix=${JSON.stringify({ include: resolved })}\n`);
if (missing.length) {
console.error('');
console.error(`ERROR: ${missing.length} tag(s) do not exist:`);
for (const e of missing) {
console.error(` ${e.tag} (${e.project}) - not found in ` +
`${e.commercialRepo} or ${e.ossRepo}`);
}
console.error('');
console.error('The release is not complete. Nothing else has been touched.');
process.exit(1);
}
console.log('');
console.log(`All ${resolved.length} tags verified.`);
JSEOF
next-snapshot-config:
name: Next Snapshot Config
needs: [setup, verify-tags]
if: needs.setup.outputs.hotfix != 'true'
runs-on: ubuntu-latest
outputs:
status: ${{ steps.write.outputs.status }}
available: ${{ steps.write.outputs.available }}
versions: ${{ steps.write.outputs.versions }}
steps:
- name: Write the next snapshot properties file
id: write
env:
GH_TOKEN: ${{ inputs.token || secrets.GH_ACTIONS_REPO_TOKEN }}
RELEASE_REPO: ${{ needs.setup.outputs.release-repo }}
PROPS_FILE: ${{ needs.setup.outputs.props-file }}
NEXT_FILE: ${{ needs.setup.outputs.next-file }}
NEXT_VERSION: ${{ needs.setup.outputs.next-version }}
DRY_RUN: ${{ inputs.dry_run }}
run: |
node - << 'JSEOF'
const fs = require('fs');
const { execFileSync } = require('child_process');
const releaseRepo = process.env.RELEASE_REPO;
const propsFile = process.env.PROPS_FILE;
const nextFile = process.env.NEXT_FILE;
const nextVersion = process.env.NEXT_VERSION;
const dryRun = process.env.DRY_RUN === 'true';
const BRANCH = 'jenkins-releaser-config';
const gh = args => execFileSync('gh', args,
{ encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });
// Returns {content, sha} - the sha is needed to update an existing file via the
// Contents API, which rejects a PUT over an existing path without it.
const readFile = file => {
try {
const raw = JSON.parse(gh(['api',
`repos/${releaseRepo}/contents/${file}?ref=${BRANCH}`]));
return {
content: Buffer.from((raw.content || '').replace(/\s/g, ''), 'base64').toString('utf8'),
sha: raw.sha,
};
} catch (err) { return null; }
};
const ENTRY_RE = /^releaser\.fixed-versions\[([^\]]+)\]=(.+)$/;
const parse = text => {
const map = {};
for (const line of text.split('\n')) {
const m = line.match(ENTRY_RE);
if (m) map[m[1].trim()] = m[2].trim();
}
return map;
};
// The correct contents are always computed from the release file and written, whether
// or not the target already exists. An existing snapshot file may have been seeded by
// hand or by an earlier run against a different release, so trusting it would leave
// every downstream project bumped to the wrong versions.
const source = readFile(propsFile);
if (source === null) {
console.error(`ERROR: could not re-read ${propsFile}.`);
process.exit(1);
}
const bump = v => {
const parts = v.split('.');
parts[parts.length - 1] = String(Number(parts[parts.length - 1]) + 1);
return parts.join('.');
};
// Rewritten line by line so ordering and any non-fixed-versions lines survive. Every
// entry is bumped, including spring-boot, and including projects this run is not
// otherwise touching - the file is train-wide and update-project-versions needs the
// complete map to update each project's dependency versions.
const content = source.content.split('\n').map(line => {
const m = line.match(ENTRY_RE);
if (!m) return line;
return `releaser.fixed-versions[${m[1]}]=${bump(m[2].trim())}-SNAPSHOT`;
}).join('\n');
const existing = readFile(nextFile);
console.log(`Target ${nextFile}:`);
console.log('---');
console.log(content);
console.log('---');
let status;
if (existing && existing.content === content) {
// Byte-identical, so there is nothing to commit. Skipping the PUT avoids an empty
// commit on the branch, the same way sync-deploy-docs-workflow does.
console.log(`${nextFile} already has exactly these versions - nothing to change.`);
status = 'unchanged';
} else if (dryRun) {
if (existing) {
console.log('[dry run] would UPDATE the existing file. Current contents:');
console.log('---');
console.log(existing.content);
console.log('---');
}
console.log('[dry run] not committing.');
status = existing ? 'would-update' : 'would-create';
} else {
const payload = {
message: existing
? `Updating ${nextVersion} snapshot versions`
: `Adding ${nextVersion} snapshot versions`,
content: Buffer.from(content, 'utf8').toString('base64'),
branch: BRANCH,
};
// The blob sha is what tells the Contents API to replace rather than create, and it
// also makes the write fail rather than clobber if someone else changed the file
// between the read above and this PUT.
if (existing) payload.sha = existing.sha;
fs.writeFileSync('payload.json', JSON.stringify(payload));
gh(['api', `repos/${releaseRepo}/contents/${nextFile}`,
'--method', 'PUT', '--input', 'payload.json']);
console.log(`${existing ? 'Updated' : 'Committed'} ${nextFile} on ` +
`${releaseRepo}@${BRANCH}.`);
status = existing ? 'updated' : 'created';
}
// update-project-versions resolves versions over raw.githubusercontent.com, which is
// CDN-cached, so a file committed seconds ago may not be served yet. Wait for it - but
// only when this job actually wrote something.
let available = status === 'unchanged';
if (status === 'created' || status === 'updated') {
const url = `https://raw.githubusercontent.com/${releaseRepo}/${BRANCH}/${nextFile}`;
console.log(`Waiting for ${url} to serve these contents...`);
for (let attempt = 1; attempt <= 30; attempt++) {
let served = null;
try {
// The commercial release repo is private, so raw needs the same bearer token
// update-project-versions sends.
served = execFileSync('curl', ['-s', '-f',
'-H', 'Cache-Control: no-cache',
'-H', `Authorization: Bearer ${process.env.GH_TOKEN}`, url],
{ encoding: 'utf8' });
} catch (err) { /* not served yet */ }
// Compares contents rather than just the status code. An updated file returns 200
// immediately while the CDN is still serving the previous version, so a status
// check would wave through exactly the stale read this wait exists to prevent.
if (served !== null && served.trim() === content.trim()) {
console.log(`Serving the new contents after ${attempt} attempt(s).`);
available = true;
break;
}
console.log(`Attempt ${attempt}: ` +
(served === null ? 'not served yet' : 'still serving older contents') +
', waiting 10s...');
execFileSync('sleep', ['10']);
}
if (!available) {
console.log('WARNING: the raw URL never served the new contents. Version updates ' +
'will be skipped rather than applied from a stale file - re-run this workflow ' +
'with the same inputs once the CDN catches up.');
}
}
const out = process.env.GITHUB_OUTPUT;
fs.appendFileSync(out, `status=${status}\n`);
fs.appendFileSync(out, `available=${available}\n`);
fs.appendFileSync(out, `versions=${JSON.stringify(parse(content))}\n`);
fs.writeFileSync('result-snapshot-config.json', JSON.stringify({
phase: 'next-snapshot-config',
releaseRepo, nextFile, nextVersion, status, available,
}));
JSEOF
- name: Upload result
if: always()
uses: actions/upload-artifact@v4
with:
name: result-snapshot-config
path: result-snapshot-config.json
if-no-files-found: ignore
new-milestones:
name: "New Milestone — ${{ matrix.project }}"
needs: [setup, verify-tags, next-snapshot-config]
runs-on: ubuntu-latest
strategy:
fail-fast: false
max-parallel: 8
matrix: ${{ fromJson(needs.verify-tags.outputs.matrix) }}
steps:
- name: Checkout
uses: actions/checkout@v4
# Done as a separate read-only step so a dry run can report what would happen. The
# create-milestone action performs the same check itself, so this is also what keeps the
# non-dry-run path idempotent for versions carried over from an earlier train.
- name: Resolve the new milestone title
id: resolve
env:
GH_TOKEN: ${{ inputs.token || secrets.GH_ACTIONS_REPO_TOKEN }}
PROJECT: ${{ matrix.project }}
REPO: ${{ matrix.repo }}
VERSIONS: ${{ needs.next-snapshot-config.outputs.versions }}
run: |
set -euo pipefail
TITLE=$(echo "$VERSIONS" | jq -r --arg k "$PROJECT" '.[$k] // ""' | sed 's/-SNAPSHOT$//')
if [[ -z "$TITLE" ]]; then
echo "No snapshot version for ${PROJECT} - nothing to create."
echo "title=" >> "$GITHUB_OUTPUT"
echo "exists=unknown" >> "$GITHUB_OUTPUT"
exit 0
fi
echo "New milestone title: ${TITLE}"
echo "title=${TITLE}" >> "$GITHUB_OUTPUT"
# Piped through jq rather than gh's --jq, which takes no --arg. Same shape as the
# lookup in the create-milestone action.
NUMBER=$(gh api "repos/${REPO}/milestones?state=all&per_page=100" 2>/dev/null \
| jq -r --arg t "$TITLE" '.[] | select(.title == $t) | .number' || echo "")
if [[ -n "$NUMBER" ]]; then
echo "Milestone '${TITLE}' already exists (#${NUMBER})."
echo "exists=true" >> "$GITHUB_OUTPUT"
else
echo "exists=false" >> "$GITHUB_OUTPUT"
fi
- name: Create milestone
if: steps.resolve.outputs.exists == 'false' && inputs.dry_run != true
uses: ./.github/actions/create-milestone
with:
repo: ${{ matrix.repo }}
version: ${{ steps.resolve.outputs.title }}
token: ${{ inputs.token || secrets.GH_ACTIONS_REPO_TOKEN }}
- name: Record result
if: always()
id: record
env:
PROJECT: ${{ matrix.project }}
REPO: ${{ matrix.repo }}
TITLE: ${{ steps.resolve.outputs.title }}
EXISTS: ${{ steps.resolve.outputs.exists }}
OUTCOME: ${{ steps.resolve.outcome }}
DRY_RUN: ${{ inputs.dry_run }}
run: |
set -euo pipefail
SAFE="${REPO//\//-}"
echo "safe-name=${SAFE}" >> "$GITHUB_OUTPUT"
if [[ "$OUTCOME" != "success" ]]; then
STATUS="error"
elif [[ -z "${TITLE:-}" ]]; then
STATUS="no-version"
elif [[ "$EXISTS" == "true" ]]; then
STATUS="already-exists"
elif [[ "$DRY_RUN" == "true" ]]; then
STATUS="would-create"
else
STATUS="created"
fi
jq -n \
--arg phase "new-milestones" \
--arg project "$PROJECT" \
--arg repo "$REPO" \
--arg title "${TITLE:-}" \
--arg status "$STATUS" \
'{phase: $phase, project: $project, repo: $repo, title: $title, status: $status}' \
> "result-newmilestone-${SAFE}.json"
- name: Upload result
if: always()
uses: actions/upload-artifact@v4
with:
name: result-newmilestone-${{ steps.record.outputs.safe-name || matrix.project }}
path: result-newmilestone-*.json
if-no-files-found: ignore
# ── Merge back, bump versions, nudge Dependabot ──────────────────────────────────────
# All of these share one matrix leg per project, and one clone. That is required rather
# than tidy: a project whose release branch will not merge cleanly has to skip everything
# that follows, and per-step conditionals are the only way to express that.
merge-back-and-update:
name: "Merge Back + Bump — ${{ matrix.project }}"
needs: [setup, verify-tags, next-snapshot-config]
runs-on: ubuntu-latest
strategy:
fail-fast: false
max-parallel: 8
matrix: ${{ fromJson(needs.verify-tags.outputs.matrix) }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
# Do not persist this repository's GITHUB_TOKEN as a git extraheader; it would
# override the credentials baked into the target repo's remote URL below.
persist-credentials: false
# ── 5a. resolve the branch to work on ─────────────────────────────────────────────
- name: Resolve target branch
id: branch
env:
GH_TOKEN: ${{ inputs.token || secrets.GH_ACTIONS_REPO_TOKEN }}
PROJECT: ${{ matrix.project }}
REPO: ${{ matrix.repo }}
COMMERCIAL: ${{ needs.setup.outputs.commercial }}
VERSIONS: ${{ needs.next-snapshot-config.outputs.versions }}
run: |
node - << 'JSEOF'
const fs = require('fs');
const { execFileSync } = require('child_process');
const project = process.env.PROJECT;
const repo = process.env.REPO;
const commercial = process.env.COMMERCIAL === 'true';
const versions = JSON.parse(process.env.VERSIONS);
const out = process.env.GITHUB_OUTPUT;
const emit = (k, v) => fs.appendFileSync(out, `${k}=${v}\n`);
const stop = (status, message) => {
console.log(message);
emit('status', status);
emit('branch', '');
process.exit(0);
};
const snapshot = versions[project];
if (!snapshot) stop('no-version', `No snapshot version for ${project}.`);
// Drop the last segment and append .x. Works for both lines: OSS 5.0.3 -> 5.0.x, and
// 3-part commercial 4.2.8 -> 4.2.x.
const plain = snapshot.replace(/-SNAPSHOT$/, '');
const parts = plain.split('.');
const target = parts.slice(0, -1).join('.') + '.x';
const branchExists = branch => {
try {
execFileSync('gh', ['api', `repos/${repo}/branches/${branch}`, '--jq', '.name'],
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
return true;
} catch (err) { return false; }
};
if (branchExists(target)) {
console.log(`Target branch: ${target}`);
emit('status', 'ok');
emit('branch', target);
process.exit(0);
}
// Commercial repos have no main branch at all - spring-cloud-config-commercial's
// default is 4.3.x - so there is no sane fallback to make.
if (commercial) {
stop('branch-not-found',
`ERROR: ${repo} has no ${target} branch, and commercial repos have no main to ` +
'fall back to. Skipping this project.');
}
if (!branchExists('main')) {
stop('branch-not-found', `ERROR: ${repo} has neither ${target} nor main.`);
}
// Falling back to main is only safe if main really is the line this version belongs
// to - otherwise we would bump an unrelated major.minor to these versions.
const expected = parts.slice(0, 2).join('.');
let pom;
try {
const b64 = execFileSync('gh', ['api',
`repos/${repo}/contents/pom.xml?ref=main`, '--jq', '.content'],
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
pom = Buffer.from(b64.replace(/\s/g, ''), 'base64').toString('utf8');
} catch (err) {
stop('branch-not-found', `ERROR: no ${target} branch and could not read pom.xml on main.`);
}
// The root <version> is the project's own; fall back to <parent><version> when the
// root pom inherits it.
const withoutParent = pom.replace(/<parent>[\s\S]*?<\/parent>/, '');
let m = withoutParent.match(/<version>([^<]+)<\/version>/);
if (!m) {
const parent = pom.match(/<parent>[\s\S]*?<\/parent>/);
if (parent) m = parent[0].match(/<version>([^<]+)<\/version>/);
}
const pomVersion = m ? m[1].trim() : '';
if (!pomVersion.startsWith(`${expected}.`)) {
stop('version-mismatch',
`ERROR: ${repo} has no ${target} branch, and main is at '${pomVersion}', which is ` +
`not on the ${expected} line. Refusing to bump main to ${snapshot}.`);
}
console.log(`No ${target} branch; main is at ${pomVersion} - using main.`);
emit('status', 'ok');
emit('branch', 'main');
JSEOF
# ── 5b. merge release/<version> back into the .x branch ──────────────────────────
- name: Merge release branch back
id: merge
if: steps.branch.outputs.status == 'ok'
env:
GH_TOKEN: ${{ inputs.token || secrets.GH_ACTIONS_REPO_TOKEN }}
REPO: ${{ matrix.repo }}
COMMERCIAL_REPO: ${{ matrix.commercialRepo }}
VERSION: ${{ matrix.version }}
BRANCH: ${{ steps.branch.outputs.branch }}
run: |
set -uo pipefail
RELEASE_BRANCH="release/${VERSION}"
REMOTE="https://x-access-token:${GH_TOKEN}@github.com/${REPO}.git"
# The release branch always lives in the commercial repo, for OSS releases too: they
# are built on release/<version>, cut from the -internal branch in <project>-commercial
# (create-oss-release-branch.yml), and merged back here afterwards. On a commercial run
# this is the same repository as REMOTE, so one code path covers both.
COMMERCIAL_REMOTE="https://x-access-token:${GH_TOKEN}@github.com/${COMMERCIAL_REPO}.git"
# Sixteen legs clone a private repo apiece, at once, every run. github.com fails
# often enough at that rate to be worth retrying rather than reporting: an HTTP 401
# or a 5xx during ref advertisement is a blip, not an answer. Retried here, and every
# remote read below is routed through this.
#
# Note that the step runs under `bash -e` whatever this script sets, so an unguarded
# git failure aborts it - and a step that aborts records no status at all, which the
# summary can only report as "skipped". Anything that can fail on the network has to
# end in an explicit status, or it is invisible in the report.
ATTEMPTS=3
retry() {
local what="$1"; shift
local attempt
for attempt in $(seq 1 $ATTEMPTS); do
if "$@"; then
return 0
fi
if [[ $attempt -lt $ATTEMPTS ]]; then
echo "${what}: failed, attempt ${attempt}/${ATTEMPTS} - waiting $((attempt * 10))s..."
sleep $((attempt * 10))
fi
done
echo "::error::${what}: failed ${ATTEMPTS} times."
return 1
}
# A half-written clone would make the next attempt fail on the directory rather than
# on the network, so each attempt starts from nothing.
clone_repo() {
rm -rf project
git clone --quiet "$REMOTE" --branch "$BRANCH" project
}
if ! retry "Cloning ${REPO}@${BRANCH}" clone_repo; then
echo "status=clone-failed" >> "$GITHUB_OUTPUT"
exit 0
fi
cd project
git config user.name "Spring Builds"
git config user.email "svc.spring-builds@broadcom.com"
git remote add commercial "$COMMERCIAL_REMOTE"
# --exit-code exits 2 when the remote answered and has no such branch. That is a real
# answer and the common one; any other non-zero is a transport failure, and reading
# that as "no release branch" would skip the merge and call the run a success.
LS_RC=0
list_release_branch() {
git ls-remote --exit-code --heads commercial "refs/heads/${RELEASE_BRANCH}" >/dev/null 2>&1
LS_RC=$?
[[ $LS_RC -eq 0 || $LS_RC -eq 2 ]]
}
if ! retry "Looking for ${RELEASE_BRANCH} in ${COMMERCIAL_REPO}" list_release_branch; then
echo "status=branch-fetch-failed" >> "$GITHUB_OUTPUT"
exit 0
fi
if [[ $LS_RC -eq 2 ]]; then
# Expected for a version carried over from an earlier train, for an OSS-fallback
# entry, and for a release branch that was already merged and deleted.
echo "No ${RELEASE_BRANCH} branch in ${COMMERCIAL_REPO} - nothing to merge."
echo "status=no-release-branch" >> "$GITHUB_OUTPUT"
exit 0
fi
fetch_release_branch() {
git fetch --quiet commercial "refs/heads/${RELEASE_BRANCH}:refs/remotes/commercial/${RELEASE_BRANCH}"
}
if ! retry "Fetching ${RELEASE_BRANCH} from ${COMMERCIAL_REPO}" fetch_release_branch; then
echo "status=branch-fetch-failed" >> "$GITHUB_OUTPUT"
exit 0
fi
if git merge-base --is-ancestor "commercial/${RELEASE_BRANCH}" HEAD; then
echo "${RELEASE_BRANCH} is already merged into ${BRANCH}."
echo "status=already-merged" >> "$GITHUB_OUTPUT"
exit 0
fi
# The release branch has its CI and PR workflows deleted on purpose when it is created
# (see spring-release-train-project-ready), so merging it back would carry that
# deletion onto the maintenance branch and leave it with no CI. Keep a copy of
# whatever this branch has, outside the clone so the merge cannot touch it.
BACKUP=$(mktemp -d)
SAVED=()
for f in ci.yml ci.yaml pr.yml pr.yaml; do
if [[ -f ".github/workflows/${f}" ]]; then
cp ".github/workflows/${f}" "${BACKUP}/${f}"
SAVED+=("$f")
echo "Saved .github/workflows/${f}"
else
echo ".github/workflows/${f} not on ${BRANCH} - skipping."
fi
done
AUTO_RESOLVED=()
if ! git merge --no-edit -m "Merge ${RELEASE_BRANCH} into ${BRANCH}" "commercial/${RELEASE_BRANCH}"; then
# ls-files --unmerged reads the index stages directly, so it lists modify/delete
# conflicts as reliably as content conflicts. Read with a loop rather than mapfile,
# which does not exist in bash 3.2 and so cannot be exercised outside a runner.
CONFLICTED=()
while IFS= read -r p; do
[[ -n "$p" ]] && CONFLICTED+=("$p")
done < <(git ls-files --unmerged | awk '{print $4}' | sort -u)
echo "Conflicting paths: ${CONFLICTED[*]:-none}"
# A conflict on a ci/pr workflow file is the predictable one: the release branch
# deleted the file and this branch has changed it since, so git cannot decide. The
# maintenance branch's version is always the one to keep, so resolve it here rather
# than blocking the project on a merge a human would resolve the same way.
REMAINING=()
for p in ${CONFLICTED[@]+"${CONFLICTED[@]}"}; do
case "$p" in
.github/workflows/ci.yml|.github/workflows/ci.yaml|.github/workflows/pr.yml|.github/workflows/pr.yaml)
# HEAD is still the .x tip mid-merge, so HEAD:<path> is this branch's version.
# Absent from HEAD means this branch had deleted it - keep it deleted.
if git cat-file -e "HEAD:${p}" 2>/dev/null; then
git show "HEAD:${p}" > "$p"
git add "$p"
echo "Auto-resolved ${p} - kept the ${BRANCH} version."
else
git rm -f --quiet --ignore-unmatch "$p"
echo "Auto-resolved ${p} - not on ${BRANCH}, left deleted."
fi
AUTO_RESOLVED+=("$p")
;;
*)
REMAINING+=("$p")
;;
esac
done
if [[ ${#REMAINING[@]} -gt 0 ]]; then
# Anything else needs a human. Abort so the clone is left clean, and stop this
# project here - the version bump must not be layered on an unresolved merge.
echo "::error::Cannot merge ${RELEASE_BRANCH} into ${BRANCH} in ${REPO} without conflicts."
git merge --abort || true
echo "status=merge-conflict" >> "$GITHUB_OUTPUT"
echo "conflicts=${REMAINING[*]}" >> "$GITHUB_OUTPUT"
exit 0
fi
git commit --quiet --no-edit
echo "auto-resolved=${AUTO_RESOLVED[*]:-}" >> "$GITHUB_OUTPUT"
fi
echo "Merged ${RELEASE_BRANCH} into ${BRANCH}."
# Restore only what the merge actually removed. A workflow file the release branch
# modified rather than deleted is a real change and is left alone.
RESTORED=()
if [[ ${#SAVED[@]} -gt 0 ]]; then
for f in "${SAVED[@]}"; do
if [[ ! -f ".github/workflows/${f}" ]]; then
mkdir -p .github/workflows
cp "${BACKUP}/${f}" ".github/workflows/${f}"
git add ".github/workflows/${f}"
RESTORED+=("$f")
echo "Restored .github/workflows/${f} - the merge removed it."
fi
done
fi
if [[ ${#RESTORED[@]} -gt 0 ]]; then
# A separate commit rather than amending the merge, so the log shows plainly that
# these files came back and why.
git commit --quiet -m "Restoring ${RESTORED[*]} removed by the ${RELEASE_BRANCH} merge"
echo "restored=${RESTORED[*]}" >> "$GITHUB_OUTPUT"
else
echo "The merge removed no ci/pr workflow files - nothing to restore."
fi
echo "status=merged" >> "$GITHUB_OUTPUT"
# ── 5c. apply the new snapshot versions ──────────────────────────────────────────
# release-train-version rather than the explicit versions input: only that path applies
# project-version-substitutions, which is what maps spring-cloud-dependencies-parent to
# spring-cloud-build, verifierVersion to spring-cloud-contract, and so on.
- name: Apply new snapshot versions
id: bump
# The available check keeps a dry run honest: nothing was committed, so there is no
# snapshot file to resolve versions from and this is reported as skipped, not failed.
if: |
needs.next-snapshot-config.outputs.available == 'true' &&
(steps.merge.outputs.status == 'merged' ||
steps.merge.outputs.status == 'already-merged' ||
steps.merge.outputs.status == 'no-release-branch')
continue-on-error: true
uses: ./.github/actions/update-project-versions
with:
release-train-version: ${{ needs.setup.outputs.next-version }}-SNAPSHOT
# Hardcoded true, not the run's commercial flavour. This input does one thing in the
# action - pick which repo the releaser config is fetched from