-
Notifications
You must be signed in to change notification settings - Fork 13
1099 lines (977 loc) · 48.2 KB
/
update-plugins-repo-refs.yaml
File metadata and controls
1099 lines (977 loc) · 48.2 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: Update plugins repository references
on:
workflow_call:
inputs:
regexps:
type: string
required: true
overlay-repo:
type: string
required: true
release-branch-pattern:
type: string
required: true
single-branch:
type: string
required: false
default: ""
verbose:
type: boolean
required: false
default: false
debug:
type: boolean
required: false
default: false
allow-workspace-addition:
type: boolean
pr-to-update:
type: string
required: false
default: ""
workspace-path:
type: string
required: false
default: ""
exclude-workspaces:
type: string
required: false
default: ""
force:
type: boolean
required: false
default: false
jobs:
prepare:
runs-on: ubuntu-latest
name: Prepare
outputs:
workspace-keys: ${{ steps.inject-backstage.outputs.workspace-keys }}
steps:
- name: Setup Node.js 24.x
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
with:
node-version: 24.x
registry-url: https://registry.npmjs.org/ # Needed for auth
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Get published community plugins
id: get-published-community-plugins
shell: bash {0}
env:
INPUT_REGEXPS: ${{ inputs.regexps }}
INPUT_OVERLAY_REPO: ${{ inputs.overlay-repo }}
INPUT_RELEASE_BRANCH_PATTERN: ${{ inputs.release-branch-pattern }}
INPUT_WORKSPACE_PATH: ${{ inputs.workspace-path }}
INPUT_SINGLE_BRANCH: ${{ inputs.single-branch }}
INPUT_ALLOW_WORKSPACE_ADDITION: ${{ inputs.allow-workspace-addition }}
INPUT_VERBOSE: ${{ inputs.verbose }}
INPUT_DEBUG: ${{ inputs.debug }}
GH_TOKEN: ${{ github.token }}
run: |
# Plugin Retrieval
function message() {
echo "$1" >&2
}
function verbose() {
if [[ "${INPUT_VERBOSE}" == "true" ]]
then
message "$1"
fi
}
if [[ "${INPUT_DEBUG}" == "true" ]]
then
set -x
fi
set -o pipefail
npm install semver -g
overlayRepoBranchesString=$(gh api repos/${INPUT_OVERLAY_REPO}/branches --paginate | jq -r --arg INPUT_RELEASE_BRANCH_PATTERN "${INPUT_RELEASE_BRANCH_PATTERN}" --arg INPUT_SINGLE_BRANCH "${INPUT_SINGLE_BRANCH}" '.[].name | select(. == $INPUT_SINGLE_BRANCH or test($INPUT_RELEASE_BRANCH_PATTERN))')
if [ $? -ne 0 ]
then
message "Failed fetching branches"
exit 1
fi
declare -A overlayRepoBranchToBackstageVersion=()
for overlayRepoBranch in ${overlayRepoBranchesString}
do
targetBackstageVersion=$(gh api --header 'Accept: application/vnd.github.v3.raw' "repos/${INPUT_OVERLAY_REPO}/contents/versions.json?ref=${overlayRepoBranch}" --jq .backstage)
if [ $? -ne 0 ]
then
message "Failed fetching supported backstage version"
exit 1
fi
overlayRepoBranchToBackstageVersion[${overlayRepoBranch}]="${targetBackstageVersion}"
done
minimalBackstageVersion=$(IFS=$'\n' && echo "${overlayRepoBranchToBackstageVersion[*]}" | sort -V | head -n1)
message "Minimal considered backstage version: ${minimalBackstageVersion}"
if [[ "${INPUT_SINGLE_BRANCH}" != "" ]]
then
singleBranchBackstageVersion="${overlayRepoBranchToBackstageVersion[${INPUT_SINGLE_BRANCH}]}"
overlayRepoBranchToBackstageVersion=()
overlayRepoBranchToBackstageVersion[${INPUT_SINGLE_BRANCH}]="${singleBranchBackstageVersion}"
fi
message "Watched overlay branches:"
for overlayRepoBranch in "${!overlayRepoBranchToBackstageVersion[@]}"
do
message " - ${overlayRepoBranch} -> Backstage ${overlayRepoBranchToBackstageVersion[${overlayRepoBranch}]}"
done
echo -n '{' > branch-versions.json
bvComma=''
for branch in "${!overlayRepoBranchToBackstageVersion[@]}"; do
echo -n "${bvComma}\"${branch}\":\"${overlayRepoBranchToBackstageVersion[${branch}]}\"" >> branch-versions.json
bvComma=','
done
echo '}' >> branch-versions.json
if [[ "${INPUT_WORKSPACE_PATH}" == "workspaces/backstage" ]]; then
message "Backstage workspace uses release manifest discovery, skipping NPM scanning"
echo '[]' > published-plugins.json
exit 0
fi
# Discovers all plugin packages from a source repo tree.
# Args: gitRepo, gitRef, workspacePath (empty string for flat repos)
# Output: one JSON object per line: {"name":"...","directory":"..."}
discoverPluginPackagesFromTree() {
local gitRepo=$1
local gitRef=$2
local wsPath=$3
local pluginPackageFiles=$(gh api -X GET "repos/${gitRepo}/git/trees/${gitRef}" --paginate -F recursive=true --jq "[ .tree[] | select(.type == \"blob\" and (.path | test(\"^${wsPath}[^/]+(/[^/]+)*/package.json$\"))) | select(.path | test(\"(-node|-common|-react)/package.json$\") | not) | select(.path | test(\"/packages/(app|backend)/package.json$\") | not) | .path ]")
if [ $? -ne 0 ]; then return 1; fi
if [[ "$(echo "$pluginPackageFiles" | jq 'length')" == "0" ]]; then return 0; fi
local query=$(echo "${pluginPackageFiles}" | jq -r --arg gitRef "${gitRef}" '
to_entries
| map("f\(.key): object(expression: \"\($gitRef):\(.value)\") { ... on Blob { text } }")
| "query($owner: String!, $repo: String!) { repository(owner: $owner, name: $repo) { \(join(" ")) } }"
')
gh api graphql -F owner="${gitRepo%/*}" -F repo="${gitRepo#*/}" -f query="${query}" | jq -c --argjson paths "$pluginPackageFiles" '
.data.repository | to_entries
| map({
"content": (.value.text | fromjson),
"directory": ($paths[(.key | ltrimstr("f") | tonumber)] | sub("/package.json$"; ""))
})
| .[]
| select((.content.backstage.role? // "") | contains("-plugin"))
| { "name": .content.name, "directory": .directory }
'
}
npmPackages=()
declare -A packageToWorkspace=()
declare -A packageToDirectory=()
# ===== Overlay-first package discovery =====
# Enumerate existing workspaces from the overlay repo and discover
# their plugin packages by scanning the source repo tree.
# This avoids depending on `npm search` for updates and fixes workspace name mismatches.
# Mutates npmPackages, packageToWorkspace, and packageToDirectory globals
# (same pattern as processPackage mutating publishedPlugins and missingPackages).
enumerateOverlayWorkspace() {
local branch=$1
local wsName=$2
local sourceJsonContent
sourceJsonContent=$(gh api --header 'Accept: application/vnd.github.v3.raw' "repos/${INPUT_OVERLAY_REPO}/contents/workspaces/${wsName}/source.json?ref=${branch}" 2>/dev/null)
if [ $? -ne 0 ] || [[ -z "$sourceJsonContent" ]]; then
verbose " Could not read source.json for workspace ${wsName} on branch ${branch}"
return 1
fi
local sourceRepo sourceRef sourceFlat
sourceRepo=$(echo "$sourceJsonContent" | jq -r '.repo' | sed 's|^https://github.com/||; s|\.git$||')
sourceRef=$(echo "$sourceJsonContent" | jq -r '."repo-ref"')
sourceFlat=$(echo "$sourceJsonContent" | jq -r '."repo-flat" // "false"')
local treeScanPath=""
if [[ "${sourceFlat}" != "true" ]]; then
treeScanPath="workspaces/${wsName}/"
fi
message " Scanning source repo ${sourceRepo} at ${sourceRef} (flat: ${sourceFlat})"
local discoveredPackages
discoveredPackages=$(discoverPluginPackagesFromTree "${sourceRepo}" "${sourceRef}" "${treeScanPath}")
if [ $? -ne 0 ]; then
message " Failed to discover packages from source repo for workspace ${wsName}"
return 1
fi
local count=0
while IFS= read -r line; do
[[ -z "$line" ]] && continue
local pkg=$(echo "$line" | jq -r '.name')
local dir=$(echo "$line" | jq -r '.directory')
local alreadyFound="false"
for existing in "${npmPackages[@]}"; do
if [[ "$existing" == "$pkg" ]]; then
alreadyFound="true"
break
fi
done
if [[ "$alreadyFound" == "false" ]]; then
npmPackages+=("$pkg")
fi
packageToWorkspace["$pkg"]="${wsName}"
packageToDirectory["$pkg"]="${dir}"
count=$((count + 1))
done <<< "$discoveredPackages"
verbose " Discovered ${count} plugin packages in workspace ${wsName}"
}
if [[ "${INPUT_WORKSPACE_PATH}" != "" ]]; then
# Scoped overlay-first: enumerate just the specified workspace
overlayWorkspaceName=$(echo "${INPUT_WORKSPACE_PATH}" | sed 's|^workspaces/||')
message "Overlay-first discovery for workspace: ${overlayWorkspaceName}"
firstBranch=""
for b in "${!overlayRepoBranchToBackstageVersion[@]}"; do
firstBranch="$b"
break
done
enumerateOverlayWorkspace "${firstBranch}" "${overlayWorkspaceName}"
else
# Full overlay-first: enumerate ALL existing workspaces from the overlay
message "Overlay-first discovery: enumerating all existing workspaces"
firstBranch=""
for b in "${!overlayRepoBranchToBackstageVersion[@]}"; do
firstBranch="$b"
break
done
overlayTreeJson=$(gh api "repos/${INPUT_OVERLAY_REPO}/git/trees/${firstBranch}:workspaces" 2>/dev/null)
if [ $? -eq 0 ] && [[ -n "$overlayTreeJson" ]]; then
overlayWorkspaceDirs=$(echo "$overlayTreeJson" | jq -r '.tree[] | select(.type == "tree") | .path')
for wsDir in ${overlayWorkspaceDirs}; do
if [[ "$wsDir" == "backstage" ]]; then
verbose " Skipping backstage workspace (handled by release manifest injection)"
continue
fi
message "Enumerating overlay workspace: ${wsDir}"
enumerateOverlayWorkspace "${firstBranch}" "${wsDir}"
done
else
message "Warning: could not enumerate overlay workspaces, falling back to npm search only"
fi
# Also run npm search for discovery of new workspaces not yet in the overlay.
# Skipped when allow-workspace-addition is false since new workspaces would be rejected later.
if [[ "${INPUT_ALLOW_WORKSPACE_ADDITION}" == "true" ]]; then
for regexp in ${INPUT_REGEXPS}
do
if [[ "${regexp}" == \'*\' ]]
then
message "Using raw plugin name: ${regexp}"
pkgName="$(echo ${regexp} | sed -e 's/^.//' -e 's/.$//')"
alreadyFound="false"
for existing in "${npmPackages[@]}"; do
if [[ "$existing" == "$pkgName" ]]; then
alreadyFound="true"
break
fi
done
if [[ "$alreadyFound" == "false" ]]; then
npmPackages+=("$pkgName")
fi
else
message "Searching plugins for regexp: ${regexp}"
while IFS= read -r pkgName; do
[[ -z "$pkgName" ]] && continue
alreadyFound="false"
for existing in "${npmPackages[@]}"; do
if [[ "$existing" == "$pkgName" ]]; then
alreadyFound="true"
break
fi
done
if [[ "$alreadyFound" == "false" ]]; then
npmPackages+=("$pkgName")
fi
done < <(npm search "/^(${regexp})/" --searchlimit=1000 --json --no-description --searchexclude "/^(?!(${regexp}))/" | jq -r '.[].name' | sort)
fi
done
fi
fi
readarray -t npmPackages < <(printf '%s\n' "${npmPackages[@]}" | sort)
missingPackages=()
publishedPlugins=()
processPackage() {
local packageName=$1
local searchForMissingPackages=$2
if [[ "${packageName}" == *"-node" ]] || [[ "${packageName}" == *"-common" ]] || [[ "${packageName}" == *"-react" ]]
then
verbose " Skipping published package ${packageName}: not a plugin"
return
fi
npmPackage=$(npm view --json ${packageName} name backstage versions)
if [[ "$(echo ${npmPackage} | jq -r '.backstage.role')" != *"-plugin"* ]]
then
verbose " Skipping published package ${packageName}: not a plugin"
return
fi
firstVersionAnalyzed=false
message " Fetching published versions of plugin ${packageName}"
for version in $(echo ${npmPackage} | jq -r '.versions | if type == "string" then . else .[] end | select(test("[^-]+-.+")|not)' | sort -Vr)
do
pluginInfo=$(npm view --json ${packageName}@${version} name version gitHead repository | jq '. | {name, version, directory: (.repository.directory // "."), url: (.repository.url // ""), gitHead }')
gitRepo=$(echo ${pluginInfo} | jq -r '.url |
if (. | startswith("https://github.com/")) then (. | sub("https://github.com/(?<name>.*)"; "\(.name)"))
elif (. | startswith("git+https://github.com/")) then (. | sub("git\\+https://github.com/(?<name>[^.]+)(\\.git)?"; "\(.name)"))
elif (. | startswith("git+ssh://git@github.com/")) then (. | sub("git\\+ssh://git@github.com/(?<name>[^.]+)(\\.git)?"; "\(.name)"))
elif (. | startswith("github:")) then (. | sub("github:(?<name>.*)"; "\(.name)"))
elif (. | test("[^:/]+/[^:/]+")) then .
else ""
end')
if [[ "${gitRepo}" == "" ]]
then
message " Skipping published plugin ${packageName}@${version}, since sources are not on GitHub."
continue
fi
flat="false"
workspace=$(echo ${pluginInfo} | jq -r '.directory |
if (. | startswith("workspaces/"))
then (. | sub("workspaces/(?<name>[^/]*)/plugins/.*"; "\(.name)"))
else ""
end')
workspacePath="workspaces/${workspace}/"
backstageJsonPath="${workspacePath}backstage.json"
if [[ "${workspace}" == "" ]]
then
workspacePath=""
workspace=$(echo ${gitRepo} | sed 's:.*/\([^/]*\)$:\1:')
backstageJsonPath="backstage.json"
if [[ "${gitRepo}" == "backstage/backstage" ]]
then
backstageJsonPath="package.json"
fi
flat="true"
fi
# If the overlay enumeration already determined the workspace name for
# this package, use it (overrides the name derived from npm metadata).
if [[ -n "${packageToWorkspace[${packageName}]+x}" ]]; then
workspace="${packageToWorkspace[${packageName}]}"
if [[ "${flat}" == "true" ]]; then
workspacePath=""
else
workspacePath="workspaces/${workspace}/"
fi
fi
# Override npm repository.directory with tree-discovered path when they differ
# (fixes flat repos like gitlab where npm metadata has no directory field).
if [[ -n "${packageToDirectory[${packageName}]+x}" ]]; then
npmDirectory=$(echo ${pluginInfo} | jq -r '.directory')
treeDirectory="${packageToDirectory[${packageName}]}"
if [[ "${npmDirectory}" != "${treeDirectory}" ]]; then
message " Warning: npm repository.directory for ${packageName} is '${npmDirectory}' but source tree shows '${treeDirectory}' — using tree-discovered path"
pluginInfo=$(echo "${pluginInfo}" | jq --arg dir "${treeDirectory}" '.directory = $dir')
fi
fi
if [[ "${INPUT_WORKSPACE_PATH}" != "" && "${INPUT_WORKSPACE_PATH}" != "workspaces/${workspace}" ]]
then
message " Skipping published plugin ${packageName}: not part of workspace ${INPUT_WORKSPACE_PATH}"
break
fi
gitHead=$(echo ${pluginInfo} | jq -r '.gitHead // ""')
if [[ "${gitHead}" == "" ]]
then
message " Skipping published plugin ${packageName}@${version}: gitHead is not set on the NPM package"
continue
fi
backstageVersion=$(gh api --header 'Accept: application/vnd.github.v3.raw' "repos/${gitRepo}/contents/${backstageJsonPath}?ref=${gitHead}" --jq .version)
if [ $? -ne 0 ]
then
message " Skipping published plugin ${packageName}@${version}: Cannot check backstage version "
continue
fi
if [[ "${backstageVersion}" != "${minimalBackstageVersion}" && "${backstageVersion} ${minimalBackstageVersion}" == "$(echo $(semver ${backstageVersion} ${minimalBackstageVersion}))" ]]
then
message " Skipping published plugin ${packageName}@${version} and earlier: Backstage version ${backstageVersion} too old"
break
fi
# Missed-packages discovery: find sibling
# plugin packages in the same workspace. Now delegates to
# discoverPluginPackagesFromTree() instead of inlining the tree-scan
# + GraphQL logic.
if [[ "${searchForMissingPackages}" == "true" && ${firstVersionAnalyzed} == "false" ]]
then
foundPackageNames=$(discoverPluginPackagesFromTree "${gitRepo}" "${gitHead}" "${workspacePath}")
if [ $? -ne 0 ]
then
message " Failed fetching contents for missed packages discovery"
else
while IFS= read -r line
do
[[ -z "$line" ]] && continue
foundPackageName=$(echo "$line" | jq -r '.name')
found="false"
for pkg in "${npmPackages[@]}" "${missingPackages[@]}"; do
if [[ "$pkg" == "$foundPackageName" ]]
then
found="true"
break
fi
done
if [[ "$found" == "false" ]]
then
message " Adding a missed package: ${foundPackageName}"
missingPackages+=("${foundPackageName}")
fi
done <<< "${foundPackageNames}"
fi
fi
firstVersionAnalyzed=true
verbose " Adding plugin ${packageName}@${version} to the list of published plugins"
addedFields="{\"workspace\":\"$workspace\", \"backstageVersion\": \"$backstageVersion\", \"repo\": \"$gitRepo\", \"flat\": $flat}"
publishedPlugin=$(echo "${pluginInfo}" | jq ".+= $addedFields")
publishedPlugins+=("${publishedPlugin}")
done
}
for packageName in "${npmPackages[@]}"
do
if [[ "${packageName}" == "" ]]
then
continue
fi
# Always pass 'true': overlay enumeration provides the workspace name
# mapping, but missed-packages detection must still scan at gitHead
# (the latest published commit) to catch newly-added sibling packages.
processPackage ${packageName} 'true'
done
message "Processing missed packages"
for packageName in "${missingPackages[@]}"
do
if [[ "${packageName}" == "" ]]
then
continue
fi
processPackage ${packageName} 'false'
done
plugins=$(
echo '['
for overlayRepoBranch in "${!overlayRepoBranchToBackstageVersion[@]}"
do
targetBackstageVersion="${overlayRepoBranchToBackstageVersion[${overlayRepoBranch}]}"
declare -A matchTypes=()
declare -A matchBackstageVersions=()
for plugin in "${publishedPlugins[@]}"
do
pluginName=$(echo ${plugin} | jq -r '.name')
backstageVersion=$(echo ${plugin} | jq -r '.backstageVersion')
version=$(echo ${plugin} | jq -r '.version')
matchType=""
if [[ "${targetBackstageVersion}" == "$(semver -r ~${backstageVersion} ${targetBackstageVersion})" ]]
then
matchType="exact"
elif [[ "${targetBackstageVersion}" == "$(semver -r ^${backstageVersion} ${targetBackstageVersion})" ]]
then
matchType="best-effort"
fi
if [[ "${matchType}" == "" ]]
then
verbose " Skipping published plugin ${pluginName}@${version} for branch ${overlayRepoBranch}, since the underlying Backstage version ${backstageVersion} is not compatible"
continue
fi
if [[ "${matchTypes[${pluginName}]}" == "" ]]
then
matchTypes[${pluginName}]="${matchType}"
matchBackstageVersions[${pluginName}]="${backstageVersion}"
elif [[ "${matchTypes[${pluginName}]}" != "${matchType}" ]]
then
verbose " Skipping published plugin ${pluginName}@${version} for branch ${overlayRepoBranch} (with '${matchType}' backstage compatibility type), because a newer plugin version has already been selected with a different backstage compatibility type (${matchTypes[${pluginName}]})"
continue
elif [[ "${backstageVersion}" != "${matchBackstageVersions[${pluginName}]}" ]]
then
verbose " Skipping published plugin ${pluginName}@${version} for branch ${overlayRepoBranch} (compatible with backstage ${targetBackstageVersion}), because a newer plugin version has already been selected with a different underlying Backstage version (${matchBackstageVersions[${pluginName}]})"
continue
fi
message " Plugin ${pluginName}@${version} selected for export for branch ${overlayRepoBranch} and backstage ${targetBackstageVersion}"
pluginWithBranch=$(echo ${plugin} | jq ".+= {\"branch\": \"${overlayRepoBranch}\", \"matchType\": \"${matchType}\", \"targetBackstageVersion\": \"${targetBackstageVersion}\"}")
echo -n "${comma} ${pluginWithBranch}"
comma=','
done
done
echo ']'
)
echo "::group::Plugins to analyze"
echo "$plugins"
echo "::endgroup::"
echo "$plugins" | jq -c > published-plugins.json
- name: Gather Workspaces
id: gather-workspaces
shell: bash
env:
INPUT_EXCLUDE_WORKSPACES: ${{ inputs.exclude-workspaces }}
run: |
if [[ "${{ inputs.debug }}" == "true" ]]
then
set -x
fi
# Gather the plugins per workspace and overlay branch,
# selecting the latest semantic version of each plugin.
plugins=$(cat published-plugins.json)
# Check for mixed match types among the plugins of each workspace,
# and output an error if mixed match types are found.
echo "${plugins}" | jq -r '
group_by(.branch + "__" + .workspace)
| map(
select(
(
group_by(.name) | map(sort_by(.version | split(".") | map(tonumber)) | last)
| group_by(.directory)| map(sort_by(.version | split(".") | map(tonumber)) | last)
| map(.matchType) | unique | length
) > 1
)
| "::warning title="
+ (.[0].branch + "__" + .[0].workspace)
+ "::mixed match types in workspace plugins: "
+ (
group_by(.name) | map(sort_by(.version | split(".") | map(tonumber)) | last)
| group_by(.directory)| map(sort_by(.version | split(".") | map(tonumber)) | last)
| map(.matchType) | unique | join(", ")
)
)
| .[]
'
# Check for mixed backstage versions among the plugins of each workspace,
# and output a warning if mixed backstage versions are found.
echo "${plugins}" | jq -r '
group_by(.branch + "__" + .workspace)
| map(
select(
(
group_by(.name) | map(sort_by(.version | split(".") | map(tonumber)) | last)
| group_by(.directory)| map(sort_by(.version | split(".") | map(tonumber)) | last)
| map(.backstageVersion) | unique | length
) > 1
)
| "::warning title="
+ (.[0].branch + "__" + .[0].workspace)
+ "::mixed backstage versions in workspace plugins: "
+ (
group_by(.name) | map(sort_by(.version | split(".") | map(tonumber)) | last)
| group_by(.directory)| map(sort_by(.version | split(".") | map(tonumber)) | last)
| map(.backstageVersion) | unique | join(", ")
)
)
| .[]
'
# Then, group the plugins by workspace and branch, and
# bring back at the workspace level some fields common to all plugins.
# The top-level backstage version is the latest backstage version of all plugins.
workspaces=$(echo "$plugins" | jq '
group_by(.branch + "__" + .workspace)
| map({
((.[0].branch + "__" + .[0].workspace)): {
"workspace": .[0].workspace,
"branch": .[0].branch,
"backstageVersion":
(
group_by(.name) | map(sort_by(.version | split(".") | map(tonumber)) | last)
| group_by(.directory)| map(sort_by(.version | split(".") | map(tonumber)) | last)
| map(.backstageVersion) | unique | sort_by(split(".") | map(tonumber)) | last
),
"repo": .[0].repo,
"flat": .[0].flat,
"matchType": .[0].matchType,
"targetBackstageVersion": .[0].targetBackstageVersion,
"plugins":
(
group_by(.name) | map(sort_by(.version | split(".") | map(tonumber)) | last)
| group_by(.directory)| map(sort_by(.version | split(".") | map(tonumber)) | last)
)
}
}
) | add
')
# Filter out excluded workspaces
if [[ -n "${INPUT_EXCLUDE_WORKSPACES}" && "$workspaces" != "null" ]]; then
workspaces=$(echo "$workspaces" | jq --arg exclude "${INPUT_EXCLUDE_WORKSPACES}" '
with_entries(
select(
.value.workspace as $name |
($exclude | split(" ") | map(select(. != "")) | any(. as $pat | $name | test($pat))) | not
)
) | if length == 0 then null else . end
')
fi
# Finally, prepare outputs for the next steps.
if [[ "$workspaces" == "null" ]]
then
echo "No workspace found"
echo "{}" > workspaces.json
echo "workspace-keys=[]" >> $GITHUB_OUTPUT
echo "#### No workspace found" >> $GITHUB_STEP_SUMMARY
echo "The workflow didn't find any workspace compatible with the expected backstage version and elligible for dynamic plugin export." >> $GITHUB_STEP_SUMMARY
echo "For more details about the reason, look into the logs of the \`Update\` job." >> $GITHUB_STEP_SUMMARY
else
echo "::group::Workspaces"
echo "$workspaces"
echo "::endgroup::"
echo "$workspaces" | jq -c > workspaces.json
echo "workspace-keys=$(echo $workspaces | jq -c keys)" >> $GITHUB_OUTPUT
fi
- name: Inject backstage workspaces from release manifest
id: inject-backstage
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
env:
INPUT_OVERLAY_REPO: ${{ inputs.overlay-repo }}
INPUT_WORKSPACE_PATH: ${{ inputs.workspace-path }}
INPUT_EXCLUDE_WORKSPACES: ${{ inputs.exclude-workspaces }}
with:
script: |
const fs = require('fs');
const overlayRepo = core.getInput('overlay_repo');
const [overlayOwner, overlayName] = overlayRepo.split('/');
const workspacePathFilter = core.getInput('workspace_path');
const excludeWorkspaces = core.getInput('exclude_workspaces');
const branchVersions = JSON.parse(fs.readFileSync('branch-versions.json', 'utf8'));
const workspaces = JSON.parse(fs.readFileSync('workspaces.json', 'utf8') || '{}');
if (workspacePathFilter && workspacePathFilter !== 'workspaces/backstage') {
core.info('workspace-path filter does not match backstage workspace, skipping injection');
core.setOutput('workspace-keys', JSON.stringify(Object.keys(workspaces)));
return;
}
if (excludeWorkspaces) {
const patterns = excludeWorkspaces.split(' ').filter(Boolean);
if (patterns.some(pat => 'backstage'.match(new RegExp(pat)))) {
core.info('backstage workspace is excluded, skipping injection');
core.setOutput('workspace-keys', JSON.stringify(Object.keys(workspaces)));
return;
}
}
let injected = false;
for (const [branch, targetVersion] of Object.entries(branchVersions)) {
const wsKey = `${branch}__backstage`;
if (workspaces[wsKey]) {
core.info(`${wsKey} already discovered via NPM, skipping manifest injection`);
continue;
}
// Check if the backstage workspace exists in the overlay for this branch
let sourceJsonText, pluginsListText;
try {
const response = await github.graphql(`
query($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
sourceJson: object(expression: "${branch}:workspaces/backstage/source.json") {
... on Blob { text }
}
pluginsList: object(expression: "${branch}:workspaces/backstage/plugins-list.yaml") {
... on Blob { text }
}
}
}`, { owner: overlayOwner, repo: overlayName });
sourceJsonText = response.repository?.sourceJson?.text;
pluginsListText = response.repository?.pluginsList?.text;
} catch (e) {
core.warning(`Failed to check backstage workspace on branch ${branch}: ${e.message}`);
continue;
}
if (!sourceJsonText || !pluginsListText) {
core.info(`No backstage workspace found on branch ${branch}, skipping`);
continue;
}
const sourceJson = JSON.parse(sourceJsonText);
if (!sourceJson.repo?.includes('backstage/backstage')) {
core.info(`backstage workspace on ${branch} does not point to backstage/backstage, skipping`);
continue;
}
// Fetch the release manifest
const tag = `v${targetVersion}`;
let manifest;
try {
const manifestResponse = await fetch(
`https://versions.backstage.io/v1/releases/${targetVersion}/manifest.json`
);
if (!manifestResponse.ok) {
core.warning(`Release manifest not found for backstage ${targetVersion} (HTTP ${manifestResponse.status}), skipping branch ${branch}`);
continue;
}
manifest = await manifestResponse.json();
} catch (e) {
core.warning(`Failed to fetch release manifest for ${targetVersion}: ${e.message}`);
continue;
}
const manifestVersions = {};
for (const pkg of manifest.packages) {
manifestVersions[pkg.name] = pkg.version;
}
// Discover plugin directories from the backstage repo tree at the tag
let treeResponse;
try {
treeResponse = await github.graphql(`
query($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
tree: object(expression: "${tag}:plugins") {
... on Tree {
entries { name, type }
}
}
}
}`, { owner: 'backstage', repo: 'backstage' });
} catch (e) {
core.warning(`Failed to list plugins/ tree from backstage/backstage at ${tag}: ${e.message}`);
continue;
}
const pluginDirs = (treeResponse.repository?.tree?.entries || [])
.filter(e => e.type === 'tree')
.filter(e => !e.name.endsWith('-node') && !e.name.endsWith('-common') && !e.name.endsWith('-react'))
.map(e => `plugins/${e.name}`);
if (pluginDirs.length === 0) {
core.warning(`No plugin directories found in backstage/backstage at ${tag}`);
continue;
}
core.info(`Found ${pluginDirs.length} candidate plugin directories at ${tag}`);
// Batch-fetch package.json files from the backstage repo at the tag ref
// to resolve actual package names from directories
const queryFields = pluginDirs
.map((dir, i) => `f${i}: object(expression: "${tag}:${dir}/package.json") { ... on Blob { text } }`)
.join('\n');
let packageJsonResponses;
try {
packageJsonResponses = await github.graphql(`
query($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
${queryFields}
}
}`, { owner: 'backstage', repo: 'backstage' });
} catch (e) {
core.warning(`Failed to fetch package.json files from backstage/backstage at ${tag}: ${e.message}`);
continue;
}
const plugins = [];
for (let i = 0; i < pluginDirs.length; i++) {
const field = `f${i}`;
const dir = pluginDirs[i];
const blob = packageJsonResponses.repository?.[field];
if (!blob?.text) {
core.warning(` No package.json found at ${tag}:${dir}/package.json, skipping`);
continue;
}
let pkgJson;
try {
pkgJson = JSON.parse(blob.text);
} catch (e) {
core.warning(` Invalid package.json at ${dir}: ${e.message}`);
continue;
}
if (!pkgJson.name?.startsWith('@backstage/')) continue;
if (!(pkgJson.backstage?.role || '').includes('-plugin')) continue;
const packageName = pkgJson.name;
const version = manifestVersions[packageName];
if (!version) {
core.warning(` Package ${packageName} (from ${dir}) not found in release manifest, skipping`);
continue;
}
core.info(` ${packageName}@${version} from ${dir}`);
plugins.push({
name: packageName,
version,
directory: dir,
gitHead: tag,
url: 'https://github.com/backstage/backstage',
workspace: 'backstage',
backstageVersion: targetVersion,
repo: 'backstage/backstage',
flat: true,
branch,
matchType: 'exact',
targetBackstageVersion: targetVersion,
});
}
if (plugins.length === 0) {
core.warning(`No plugins resolved for backstage workspace on branch ${branch}`);
continue;
}
core.info(`Injecting backstage workspace for branch ${branch} with ${plugins.length} plugins at ${tag}`);
workspaces[wsKey] = {
workspace: 'backstage',
branch,
backstageVersion: targetVersion,
repo: 'backstage/backstage',
flat: true,
matchType: 'exact',
targetBackstageVersion: targetVersion,
plugins,
};
injected = true;
}
fs.writeFileSync('workspaces.json', JSON.stringify(workspaces));
core.setOutput('workspace-keys', JSON.stringify(Object.keys(workspaces)));
if (injected) {
core.info('Backstage workspace(s) injected from release manifest');
} else {
core.info('No backstage workspaces injected');
}
- name: Upload workspaces json file
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: workspaces
path: workspaces.json
update:
name: Update
needs: prepare
runs-on: ubuntu-latest
if: ${{ needs.prepare.outputs.workspace-keys != '[]' }}
strategy:
fail-fast: false
matrix:
workspace: ${{ fromJSON(needs.prepare.outputs.workspace-keys) }}
max-parallel: 1
steps:
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Download workspaces json file
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
with:
name: workspaces
- name: Get workspace JSON
id: get-workspace-json
shell: bash
run: |
workspace="$(cat workspaces.json | jq '.["${{ matrix.workspace }}"]')"
echo "Workspace:"
echo "${workspace}"
echo workspace=$(echo "${workspace}" | jq -c) >> $GITHUB_OUTPUT
- name: Get workspace Commit ID
id: get-workspace-commit-id
shell: bash {0}
env:
INPUT_WORKSPACE: ${{ steps.get-workspace-json.outputs.workspace }}
run: |
if [[ "${{ inputs.debug }}" == "true" ]]
then
set -x
fi
repository=$(echo "${INPUT_WORKSPACE}" | jq -r '.repo')
if [[ "${repository}" == "backstage/backstage" ]]; then
backstageVersion=$(echo "${INPUT_WORKSPACE}" | jq -r '.backstageVersion')
tag="v${backstageVersion}"
echo "Using backstage release tag: ${tag}"
echo "workspace-commit=${tag}" >> $GITHUB_OUTPUT
exit 0
fi
commits=$(echo "${INPUT_WORKSPACE}" | jq -r '[ .plugins[] | .gitHead ] | unique | .[]')
pluginDirectories=$(echo "${INPUT_WORKSPACE}" | jq -r '.plugins[] | .directory')
numCommits=$(echo ${commits} | wc -w)
if [[ ${numCommits} == 1 ]]
then
workspaceCommit="${commits}"
else
workspaceCommit=""
for commit in ${commits}
do
for pluginDirectory in ${pluginDirectories}
do
workspaceVersion=$(echo "${INPUT_WORKSPACE}" | jq -r ".plugins[] | select(.directory == \"${pluginDirectory}\") | .version")
pluginName=$(echo "${INPUT_WORKSPACE}" | jq -r ".plugins[] | select(.directory == \"${pluginDirectory}\") | .name")
url="https://raw.githubusercontent.com/${repository}/${commit}/${pluginDirectory}/package.json"
packageJson=$(curl -fs ${url})
if [ $? -ne 0 ]
then
echo "Failed fetching : '${url}'"
echo "Skipping plugin '${pluginName}' since its source package description is not found"
continue
fi
version=$(echo "${packageJson}" | jq -r '.version')
if [[ "${version}" != "${workspaceVersion}" ]]
then
echo "Skipping commit ${commit}: plugin ${pluginName} version not the latest version: ${version} != ${workspaceVersion}"
continue 2
fi
done
if [[ "${workspaceCommit}" != "" ]]
then
echo "Cannot decide between workspace commits: ${commit} and ${workspaceCommit}"
break 2
fi
workspaceCommit="${commit}"
done
fi
if [[ "${workspaceCommit}" == "" && ${numCommits} -gt 1 ]]
then
echo "No single commit has all plugins at their latest version. Scoring each candidate..."
declare -A commitScores=()
declare -A commitDetails=()
totalPlugins=$(echo ${pluginDirectories} | wc -w)
for commit in ${commits}
do
score=0
matched=""
mismatched=""
for pluginDirectory in ${pluginDirectories}
do