Repository navigation
Expand file tree
/
Copy pathdockerhub_doc_config_update.py
More file actions
executable file
·1627 lines (1478 loc) · 70.6 KB
/
Copy pathdockerhub_doc_config_update.py
File metadata and controls
executable file
·1627 lines (1478 loc) · 70.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Script that generates the `eclipse-temurin` config file for the official docker
# image github repo and the doc updates for the unofficial docker image repo.
# Process to update the official docker image repo
# 1. Run generate_dockerfiles.py to update all the dockerfiles in the current repo.
# 2. Submit PR to push the newly generated dockerfiles to the current repo.
# 3. After above PR is merged, git pull the latest changes.
# 4. Run this command
import argparse
import base64
import difflib
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import textwrap
import urllib.request
from urllib.parse import urlencode
from dataclasses import dataclass, field
from pathlib import Path
import yaml
from adoptium_api import get_latest_lts, get_supported_versions
from architecture_config import resolve_architectures
from eol_checker import print_eol_warnings
OFFICIAL_MANIFEST_URL = (
"https://raw.githubusercontent.com/docker-library/official-images/"
"master/library/eclipse-temurin"
)
OFFICIAL_IMAGES_API = "https://api.github.com/repos/docker-library/official-images"
def load_config():
with open("config/temurin.yml", "r") as f:
return yaml.safe_load(f)
def get_git_commit():
result = subprocess.run(
["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True
)
return result.stdout.strip()
def fetch_official_manifest():
"""Fetch the current official manifest for diff comparison."""
try:
req = urllib.request.Request(OFFICIAL_MANIFEST_URL)
with urllib.request.urlopen(req) as response:
return response.read().decode("utf-8")
except (OSError, UnicodeError) as error:
print(f"Warning: cannot compare with the official manifest: {error}", file=sys.stderr)
return None
@dataclass
class PublicationPR:
url: str
releases: set[str]
removed_directories: set[str] = field(default_factory=set)
updated_directories: set[str] = field(default_factory=set)
@dataclass
class PublicationPRHead:
repository: str
branch: str
sha: str
manifest: str
@dataclass
class PublicationPRUpdate:
"""Binaries that became available after an open publication PR was created."""
pr: PublicationPR
head: PublicationPRHead
releases: dict[int, str]
added_architectures: dict[int, list[str]]
directories: dict[int, set[str]]
deferred_architectures: dict[int, list[str]] = field(default_factory=dict)
held_back_directories: dict[int, set[str]] = field(default_factory=dict)
@dataclass
class PublicationPlan:
upstream_manifest: str | None
manifest: str
ready_releases: dict[int, str]
open_prs_available: bool = True
cleanup_directories: set[str] = field(default_factory=set)
added_architectures: dict[int, list[str]] = field(default_factory=dict)
deferred_architectures: dict[int, list[str]] = field(default_factory=dict)
follow_up_directories: dict[int, set[str]] = field(default_factory=dict)
held_back_directories: dict[int, set[str]] = field(default_factory=dict)
pr_updates: list[PublicationPRUpdate] = field(default_factory=list)
def get_github_token() -> str | None:
token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN")
if token:
return token
if not shutil.which("gh"):
return None
result = subprocess.run(
["gh", "auth", "token", "--hostname", "github.com"],
capture_output=True, text=True,
)
if result.returncode == 0 and result.stdout.strip():
return result.stdout.strip()
print(
"Warning: GitHub CLI authentication unavailable; API requests are unauthenticated. "
"Run 'gh auth login' or set GH_TOKEN to avoid rate limits.",
file=sys.stderr,
)
return None
def github_request(url):
headers = {"Accept": "application/vnd.github+json", "User-Agent": "Adoptium Dockerfile Updater"}
token = get_github_token()
if token:
headers["Authorization"] = f"Bearer {token}"
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request, timeout=30) as response:
return json.loads(response.read().decode("utf-8"))
def github_pages(url, items_key=None):
page = 1
while True:
separator = "&" if "?" in url else "?"
data = github_request(f"{url}{separator}per_page=100&page={page}")
if items_key and data.get("incomplete_results"):
raise ValueError("GitHub returned incomplete PR search results")
items = data[items_key] if items_key else data
yield from items
if len(items) < 100:
break
page += 1
def fetch_open_publication_prs():
"""Match upstream PRs by release tags, changed commits, and removed directories."""
query = urlencode({
"q": "repo:docker-library/official-images is:pr is:open eclipse-temurin in:title,body",
})
try:
prs = []
for issue in github_pages(f"https://api.github.com/search/issues?{query}", "items"):
releases = set()
removed_directories = set()
added_directories = set()
updated_directories = set()
for change in github_pages(f"{OFFICIAL_IMAGES_API}/pulls/{issue['number']}/files"):
if change["filename"] != "library/eclipse-temurin":
continue
if "patch" not in change:
raise ValueError(f"GitHub omitted the manifest diff for {issue['html_url']}")
changed_commit = False
changed_tags = False
for line in change["patch"].splitlines():
if line.startswith(("@@", " Tags: ")):
if changed_commit and not changed_tags:
raise ValueError(f"GitHub omitted the directory for a changed commit in {issue['html_url']}")
changed_commit = False
changed_tags = False
elif line.startswith("+Tags: "):
changed_tags = True
tag = line.removeprefix("+Tags: ").split(", ", 1)[0]
match = re.match(r"^(.+?)-(?:jdk|jre)-", tag)
if match:
releases.add(match.group(1))
elif line.startswith("-Tags: "):
changed_tags = True
elif line.startswith("+GitCommit: "):
changed_commit = True
elif line.startswith("-Directory: "):
removed_directories.add(line.removeprefix("-Directory: "))
elif line.startswith((" Directory: ", "+Directory: ")):
directory = line.split(": ", 1)[1]
if line.startswith("+"):
added_directories.add(directory)
if changed_commit and not changed_tags:
updated_directories.add(directory)
changed_commit = False
changed_tags = False
if changed_commit and not changed_tags:
raise ValueError(f"GitHub omitted the directory for a changed commit in {issue['html_url']}")
removed_directories -= added_directories
if releases or removed_directories or updated_directories:
prs.append(PublicationPR(
issue["html_url"], releases, removed_directories, updated_directories,
))
return prs
except (OSError, ValueError) as error:
print(f"Warning: cannot check open upstream publication PRs: {error}", file=sys.stderr)
return None
def fetch_publication_pr_head(pr):
"""Fetch the head branch and manifest of an open upstream publication PR."""
number = pr.url.rstrip("/").rsplit("/", 1)[-1]
try:
head = github_request(f"{OFFICIAL_IMAGES_API}/pulls/{number}")["head"]
repository = head["repo"]["full_name"]
content = github_request(
f"https://api.github.com/repos/{repository}/contents/library/eclipse-temurin?ref={head['sha']}"
)
if content.get("encoding") != "base64":
raise ValueError("GitHub did not return the PR manifest content")
manifest = base64.b64decode(content["content"]).decode("utf-8")
return PublicationPRHead(repository, head["ref"], head["sha"], manifest)
except (OSError, ValueError, KeyError, TypeError) as error:
print(f"Warning: cannot read the head of open upstream PR {pr.url}: {error}", file=sys.stderr)
return None
def get_java_version(dockerfile_path):
"""Extract JAVA_VERSION from a Dockerfile."""
with open(dockerfile_path, "r") as f:
for line in f:
if "JAVA_VERSION=" in line:
return line.split("=")[1].strip()
return None
def format_ojdk_version(full_version):
"""Convert JAVA_VERSION to Docker tag-compatible version string.
Examples:
jdk8u482-b08 -> 8u482-b08
jdk-25.0.1+9 -> 25.0.1_9
"""
version = re.sub(r"^jdk-?", "", full_version)
version = version.replace("+", "_")
return version
def get_distro_name(os_family, directory):
"""Derive the distro tag name from the config directory."""
name = directory.split("/")[-1]
if os_family == "alpine-linux":
return f"alpine-{name}"
return name
# Map Dockerfile arch names to Docker Hub official image architecture names
DOCKERFILE_ARCH_MAP = {
"x64": "amd64",
"amd64": "amd64",
"x86_64": "amd64",
"arm64": "arm64v8",
"aarch64": "arm64v8",
"armhf": "arm32v7",
"arm": "arm32v7",
"ppc64el": "ppc64le",
"ppc64le": "ppc64le",
"s390x": "s390x",
"riscv64": "riscv64",
}
DOCKERFILE_ARCH_RE = re.compile(r'\s+(\w+)\)\s*\\?\s*$')
PENDING_ARCH_MARKER = "TODO: This configured architecture is pending upstream binary availability"
def get_dockerfile_arches(dockerfile_path):
"""Parse architectures from the case statement in a Dockerfile."""
arches = []
with open(dockerfile_path, "r") as f:
for line in f:
match = DOCKERFILE_ARCH_RE.match(line)
if match:
arch = match.group(1)
if arch in DOCKERFILE_ARCH_MAP:
arches.append(DOCKERFILE_ARCH_MAP[arch])
return sorted(set(arches))
def parse_pending_arches(lines):
pending = set()
arch = None
for line in lines:
match = DOCKERFILE_ARCH_RE.match(line)
if match:
arch = DOCKERFILE_ARCH_MAP.get(match.group(1))
elif line.strip().startswith((";;", "*)", "esac")):
arch = None
elif arch and PENDING_ARCH_MARKER in line:
pending.add(arch)
return sorted(pending)
def get_pending_arches(dockerfile_path):
"""Find architectures whose generated branches have no upstream binary yet."""
with open(dockerfile_path) as f:
return parse_pending_arches(f)
def read_git_file(commit, path):
result = subprocess.run(
["git", "show", f"{commit}:{path}"], capture_output=True, text=True,
)
return result.stdout if result.returncode == 0 else None
def get_published_pending_arches(commit, dockerfile_path):
"""Find architectures that were still pending in the published upstream commit."""
content = read_git_file(commit, dockerfile_path) if commit else None
return parse_pending_arches(content.splitlines()) if content is not None else None
@dataclass
class ImageReadiness:
directory: str
java_version: str | None = None
blockers: list[str] = field(default_factory=list)
updated: bool = False
published: bool = False
held_back: bool = False
deferred_arches: list[str] = field(default_factory=list)
added_arches: list[str] = field(default_factory=list)
arches: list[str] = field(default_factory=list)
pending_arches: list[str] = field(default_factory=list)
pr_added_arches: list[str] = field(default_factory=list)
def java_version_key(release):
version, _, build = release.replace("-b", "+").replace("_", "+").partition("+")
parts = tuple(int(n) for n in re.findall(r"\d+", version))
return parts + (0,) * max(0, 4 - len(parts)), int(build or 0)
def matching_publication_prs(release, open_prs, directories=None):
directories = directories or set()
return [
pr for pr in open_prs
if directories & pr.updated_directories
or any(java_version_key(tag) == java_version_key(release) for tag in pr.releases)
]
def get_entry_release(entry):
tag = entry.get("Tags", "").split(", ", 1)[0]
match = re.match(r"^(.+?)-(?:jdk|jre)-", tag)
return match.group(1) if match else None
def covered_by_open_pr(images, entries, latest):
"""Check that an open PR publishes every image at the local release or keeps it held back."""
for image in images:
entry = entries.get(image.directory)
release = get_entry_release(entry) if entry else None
if not image.java_version or release is None:
return False
local_key = java_version_key(image.java_version)
if local_key == java_version_key(latest):
if java_version_key(release) != local_key:
return False
elif not (image.published and java_version_key(release) == local_key):
return False
return True
def apply_open_pr_baselines(readiness, open_prs):
"""Use open publication PRs as the baseline for binaries that were pending when they were opened."""
candidates = {}
for version, images in readiness.items():
latest = max(
(image.java_version for image in images if image.java_version),
key=java_version_key, default=None,
)
if not latest or not any(image.updated for image in images):
continue
prs = [
pr for pr in open_prs
if any(java_version_key(tag) == java_version_key(latest) for tag in pr.releases)
]
if len(prs) == 1:
candidates[version] = (prs[0], latest)
baselines = {}
for url in {pr.url for pr, _ in candidates.values()}:
versions = {version for version, (pr, _) in candidates.items() if pr.url == url}
pr = candidates[next(iter(versions))][0]
pr_versions = {int(re.match(r"\d+", tag).group()) for tag in pr.releases if re.match(r"\d+", tag)}
# The PR description is regenerated, so every release in it must be accounted for.
if pr_versions != versions:
continue
head = fetch_publication_pr_head(pr)
if head is None:
continue
entries = get_manifest_entries(head.manifest)
if not all(covered_by_open_pr(readiness[v], entries, candidates[v][1]) for v in versions):
continue
for version in versions:
latest_key = java_version_key(candidates[version][1])
for image in readiness[version]:
if java_version_key(image.java_version) < latest_key:
image.held_back = True
continue
if not image.arches:
continue
pr_pending = get_published_pending_arches(
entries[image.directory].get("GitCommit"), f"{image.directory}/Dockerfile",
)
if pr_pending is None:
image.blockers.append("cannot read Dockerfile at open PR GitCommit")
continue
still_pending = set(image.pending_arches) | set(image.deferred_arches)
# Binaries already pending when the PR was opened are follow-ups, not blockers.
carried = set(image.pending_arches) & set(pr_pending)
image.deferred_arches = sorted(set(image.deferred_arches) | carried)
image.pending_arches = sorted(set(image.pending_arches) - carried)
image.pr_added_arches = sorted((set(pr_pending) & set(image.arches)) - still_pending)
if not set(image.arches) - set(image.deferred_arches) and "no available binaries" not in image.blockers:
image.blockers.append("no available binaries")
baselines[version] = (pr, head)
return baselines
def print_table(headers, rows, max_widths):
widths = [
min(limit, max(len(row[index]) for row in [headers, *rows]))
for index, limit in enumerate(max_widths)
]
separator = "+-" + "-+-".join("-" * width for width in widths) + "-+"
def print_row(row):
cells = [textwrap.wrap(cell, width=width) or [""] for cell, width in zip(row, widths)]
for line in range(max(len(cell) for cell in cells)):
values = [
(cell[line] if line < len(cell) else "").ljust(width)
for cell, width in zip(cells, widths)
]
print("| " + " | ".join(values) + " |", file=sys.stderr)
print(separator, file=sys.stderr)
print_row(headers)
print(separator, file=sys.stderr)
for row in rows:
print_row(row)
print(separator, file=sys.stderr)
def format_image_targets(paths):
packages_by_distro = {}
for path in paths:
_, package, distro = path.split("/", 2)
packages_by_distro.setdefault(distro, set()).add(package)
distros_by_packages = {}
for distro, packages in packages_by_distro.items():
distros_by_packages.setdefault(tuple(sorted(packages)), []).append(distro)
return "; ".join(
f"{'+'.join(packages).upper()} {', '.join(distros)}"
for packages, distros in distros_by_packages.items()
)
def print_publish_summary(readiness, output_file, upstream_available, open_prs, pr_baselines=None):
pr_baselines = pr_baselines or {}
print("\nUpstream publish readiness (JDK + JRE, all required architectures):", file=sys.stderr)
ready_versions = {}
statuses = {}
open_versions = []
summary_rows = {}
blocker_rows = []
deferred_rows = []
linked_prs = {}
for version, images in readiness.items():
releases = [image.java_version for image in images if image.java_version]
latest = max(
releases,
key=java_version_key,
default=None,
)
blocked = {}
deferred = {}
for image in images:
if image.held_back:
continue
if image.deferred_arches:
deferred.setdefault(", ".join(image.deferred_arches), []).append(image.directory)
reasons = list(image.blockers)
if image.java_version and java_version_key(image.java_version) < java_version_key(latest):
reasons.append(f"stale release {image.java_version}; expected {latest}")
if reasons:
blocked.setdefault("; ".join(reasons), []).append(image.directory)
ready = bool(images) and not blocked
blocked_count = sum(len(paths) for paths in blocked.values())
updated = any(image.updated for image in images)
affected = {image.directory for image in images if image.added_arches}
matching_prs = (
matching_publication_prs(latest, open_prs or [], affected)
if updated and latest else []
)
pr_labels = []
for pr in matching_prs:
label = f"#{pr.url.rsplit('/', 1)[-1]}"
linked_prs[label] = pr.url
pr_labels.append(label)
if not ready:
status = "BLOCKED"
elif not upstream_available:
status = "UNKNOWN"
elif updated and open_prs is None:
status = "UNKNOWN"
elif matching_prs:
if version in pr_baselines and any(
image.pr_added_arches for image in images if not image.held_back
):
status = "PR UPDATE"
else:
status = "PR OPEN"
elif updated:
status = "READY"
ready_versions[version] = format_ojdk_version(latest)
else:
status = "UP TO DATE"
statuses[version] = status
summary_rows[version] = [
str(version),
format_ojdk_version(latest) if latest else "-",
status,
f"{len(images) - blocked_count}/{len(images)}",
", ".join(pr_labels) or "-",
]
if not images:
blocker_rows.append([str(version), "No configured images", "-"])
for reasons, paths in blocked.items():
blocker_rows.append([str(version), reasons, format_image_targets(paths)])
for arches, paths in deferred.items():
deferred_rows.append([str(version), arches, format_image_targets(paths)])
update_versions = []
for version, status in statuses.items():
if status == "PR UPDATE":
url = pr_baselines[version][0].url
group = [v for v, (pr, _) in pr_baselines.items() if pr.url == url]
# Only update a PR when every release in it can still be published.
if any(statuses[v] not in ("PR OPEN", "PR UPDATE") for v in group):
status = statuses[version] = summary_rows[version][2] = "PR OPEN"
if status == "PR UPDATE":
update_versions.append(str(version))
elif status == "PR OPEN":
open_versions.append(str(version))
if readiness:
print_table(
["Java", "Release", "Status", "Complete", "Upstream PR"],
list(summary_rows.values()), [4, 18, 10, 8, 18],
)
else:
print(" No supported Java versions to assess", file=sys.stderr)
if blocker_rows:
print("\nPublication blockers:", file=sys.stderr)
print_table(["Java", "Blocker", "Affected images"], blocker_rows, [4, 48, 54])
if deferred_rows:
print("\nDeferred binaries (non-blocking; publish in a follow-up):", file=sys.stderr)
print_table(["Java", "Architecture", "Affected images"], deferred_rows, [4, 16, 54])
if linked_prs:
print("\nOpen upstream PRs:", file=sys.stderr)
for label, url in linked_prs.items():
print(f" {label}: {url}", file=sys.stderr)
print(file=sys.stderr)
if not upstream_available:
print("Upstream comparison unavailable; publication readiness cannot be confirmed.", file=sys.stderr)
elif open_prs is None:
print("Open upstream PRs could not be checked; check GitHub before opening a new PR.", file=sys.stderr)
elif ready_versions or update_versions:
if ready_versions:
print(
f"Ready for upstream publish: Java {', '.join(map(str, ready_versions))}. "
f"Publish only these versions from {output_file}; leave other upstream entries unchanged.",
file=sys.stderr,
)
if update_versions:
print(
f"Open upstream PRs need updates: Java {', '.join(update_versions)}. "
"Binaries pending when those PRs were opened are now available.",
file=sys.stderr,
)
print(
"To open an upstream PR for all READY versions and pending cleanup, "
"and push newly available binaries to open PRs:\n"
" python3 dockerhub_doc_config_update.py --create-pr\n"
"Preview without making changes:\n"
" python3 dockerhub_doc_config_update.py --dry-run",
file=sys.stderr,
)
elif open_versions:
print(
f"Publication already in progress: Java {', '.join(open_versions)}. "
"See the open upstream PRs above.",
file=sys.stderr,
)
else:
print("No updated Java versions are ready for upstream publish.", file=sys.stderr)
return ready_versions, statuses
def check_forced_versions(readiness, force_versions, statuses):
"""Print the binaries still missing for forced versions and reject unpublishable ones."""
rows = []
for version in sorted(force_versions):
images = readiness[version]
release = max(
(image.java_version for image in images if image.java_version),
key=java_version_key, default=None,
)
missing = {}
held = {}
for image in images:
if image.held_back:
key = f"held at {format_ojdk_version(image.java_version)}"
held.setdefault(key, []).append(image.directory)
continue
for arch in image.deferred_arches:
missing.setdefault(arch, []).append(image.directory)
cells = [str(version), format_ojdk_version(release) if release else "-", statuses[version]]
if not missing and not held:
rows.append([*cells, "none", "-"])
for arch, paths in sorted(missing.items()) + sorted(held.items()):
rows.append([*cells, arch, format_image_targets(paths)])
print(
"\nForced partial publication plan (missing binaries have pending Dockerfile case branches; "
"their manifest architectures are retained for a follow-up. Images held at an older, "
"already-published release keep their current upstream entries):",
file=sys.stderr,
)
print_table(
["Java", "Release", "Status", "Missing binary", "Affected images"],
rows, [4, 18, 10, 18, 54],
)
for version in sorted(force_versions):
if statuses[version] in ("UP TO DATE", "PR OPEN"):
print(f"Java {version} is {statuses[version]}; nothing to force-publish.", file=sys.stderr)
unpublishable = [
f"Java {version} is {statuses[version]}" for version in sorted(force_versions)
if statuses[version] in ("BLOCKED", "UNKNOWN")
]
if unpublishable:
raise ValueError(
"Cannot force-publish: " + "; ".join(unpublishable) + ". "
"--force only defers architectures whose Dockerfile case branch is marked pending; "
"resolve the other publication blockers reported above."
)
def confirm_publication(prompt: str) -> bool:
# The prompt goes to stderr so stdout stays clean for manifest output.
print(prompt, end="", file=sys.stderr, flush=True)
answer = sys.stdin.readline()
if not answer:
print(file=sys.stderr)
return answer.strip().lower() in ("y", "yes")
def print_deprecated_upstream_images(directories):
retired = {}
for directory in sorted(directories, key=lambda path: (int(path.split("/", 1)[0]), path)):
version, package, distro = directory.split("/", 2)
retired.setdefault((version, distro), set()).add(package)
if not retired:
return
print(
"\nWarning: Deprecated or removed images still in the upstream official manifest:",
file=sys.stderr,
)
rows = [
[version, f"{'+'.join(sorted(packages)).upper()} {distro}"]
for (version, distro), packages in retired.items()
]
print_table(["Java", "Affected upstream images"], rows, [4, 80])
print(
"These entries can be cleaned up independently of release readiness.",
file=sys.stderr,
)
def get_block_fields(block):
return dict(
line.split(": ", 1) for line in block.splitlines()
if ": " in line and not line.startswith("#")
)
def get_manifest_entries(manifest):
"""Return the current entry for each directory, ignoring older-release backfill entries."""
entries = {}
for block in (manifest or "").split("\n\n"):
fields = get_block_fields(block)
directory = fields.get("Directory")
if not directory:
continue
current = entries.get(directory)
release, current_release = get_entry_release(fields), current and get_entry_release(current)
if current is None or (
release and current_release and java_version_key(release) > java_version_key(current_release)
):
entries[directory] = fields
return entries
def get_entry_tags(fields, names=("Tags", "SharedTags")):
return [tag for name in names for tag in fields.get(name, "").split(", ") if tag]
def is_windows_entry(fields):
return fields.get("Architectures", "").startswith("windows-")
def get_backfill_blocks(upstream_blocks, final_blocks):
"""Re-add replaced non-Windows entries whose shared tags would otherwise be Windows-only."""
final_entries = [get_block_fields(block) for block in final_blocks]
claimed = {tag for fields in final_entries for tag in get_entry_tags(fields)}
non_windows = {
tag for fields in final_entries if not is_windows_entry(fields) for tag in get_entry_tags(fields)
}
backfills = []
for block in upstream_blocks:
fields = get_block_fields(block)
release = get_entry_release(fields)
if is_windows_entry(fields) or fields in final_entries or not release:
continue
orphans = [
tag for tag in get_entry_tags(fields, ("SharedTags",))
if tag in claimed and tag not in non_windows
]
if not orphans:
continue
tags = [
tag for tag in get_entry_tags(fields, ("Tags",))
if tag.startswith(f"{release}-") and tag not in claimed
]
if not tags:
raise ValueError(f"Cannot backfill {fields.get('Directory')}: no unclaimed {release} tags")
lines = [
f"# backfill: keep the previous Linux {release} around so "
+ ", ".join(f'"{tag}"' for tag in orphans)
+ f" does not end up Windows-only while the Windows images are still on {release}",
f"Tags: {', '.join(tags)}",
f"SharedTags: {', '.join(orphans)}",
]
lines += [
line for line in block.splitlines()
if not line.startswith(("#", "Tags: ", "SharedTags: "))
]
backfills.append(("\n".join(lines), set(orphans)))
claimed.update(tags)
non_windows.update(orphans)
return backfills
def get_backfilled_tags(manifest):
"""Return shared tags kept on older-release backfill entries, by Java version."""
current = get_manifest_entries(manifest)
backfilled = {}
for block in (manifest or "").split("\n\n"):
fields = get_block_fields(block)
directory = fields.get("Directory")
if directory and current[directory] != fields:
version = int(directory.split("/", 1)[0])
backfilled.setdefault(version, set()).update(get_entry_tags(fields, ("SharedTags",)))
return {version: sorted(tags) for version, tags in backfilled.items()}
def merge_publication_manifest(
upstream: str, generated: str, versions: list[int],
cleanup_directories: set[str] | None = None,
follow_up_directories: dict[int, set[str]] | None = None,
held_back_directories: set[str] | None = None,
) -> str:
cleanup_directories = cleanup_directories or set()
follow_up_directories = follow_up_directories or {}
held_back_directories = held_back_directories or set()
upstream_entries = get_manifest_entries(upstream)
generated_entries = get_manifest_entries(generated)
missing = held_back_directories - upstream_entries.keys()
if missing:
raise ValueError("Held-back images are absent from upstream manifest: " + ", ".join(sorted(missing)))
upstream_blocks = {
directory: block.strip("\n")
for block in upstream.split("\n\n")
for directory, fields in get_manifest_entries(block).items()
if fields == upstream_entries[directory]
}
missing = cleanup_directories - upstream_entries.keys()
if missing:
raise ValueError("Cleanup targets are absent from upstream manifest: " + ", ".join(sorted(missing)))
active = cleanup_directories & generated_entries.keys()
if active:
raise ValueError("Cleanup targets still have generated manifest entries: " + ", ".join(sorted(active)))
for version, directories in follow_up_directories.items():
if (
version not in versions or not directories
or any(not directory.startswith(f"{version}/") for directory in directories)
):
raise ValueError(f"Invalid follow-up directories for Java {version}")
follow_up_targets = {directory for directories in follow_up_directories.values() for directory in directories}
missing = follow_up_targets - upstream_entries.keys()
if missing:
raise ValueError("Follow-up targets are absent from upstream manifest: " + ", ".join(sorted(missing)))
missing = follow_up_targets - generated_entries.keys()
if missing:
raise ValueError("Follow-up targets are absent from generated manifest: " + ", ".join(sorted(missing)))
replacements: dict[int, list[str]] = {
version: [] for version in versions if version not in follow_up_directories
}
for block in generated.split("\n\n"):
for directory in get_manifest_entries(block):
version = int(directory.split("/", 1)[0])
if version in replacements:
if directory in held_back_directories:
block = upstream_blocks[directory]
replacements[version].append(block.rstrip("\n"))
if any(not blocks for blocks in replacements.values()):
raise ValueError("A selected Java version has no generated manifest entries")
for version, version_blocks in replacements.items():
previous = [
block.strip("\n") for block in upstream.split("\n\n")
if get_block_fields(block).get("Directory", "").startswith(f"{version}/")
]
for backfill, orphans in get_backfill_blocks(previous, version_blocks):
index = next(
index for index, block in enumerate(version_blocks)
if orphans & set(get_entry_tags(get_block_fields(block)))
)
version_blocks.insert(index, backfill)
blocks = []
replaced = set()
preserved_tags = set()
for block in upstream.split("\n\n"):
entries = get_manifest_entries(block)
version = int(next(iter(entries)).split("/", 1)[0]) if entries else None
if version in replacements:
if version not in replaced:
blocks.extend(replacements[version])
replaced.add(version)
elif follow_up_targets.intersection(entries) and all(
fields == upstream_entries[directory] for directory, fields in entries.items()
):
directory = next(iter(entries))
commit = generated_entries[directory].get("GitCommit")
if not commit or not entries[directory].get("GitCommit"):
raise ValueError(f"Follow-up target has no GitCommit: {directory}")
block, count = re.subn(r"(?m)^GitCommit: .+$", f"GitCommit: {commit}", block)
if count != 1:
raise ValueError(f"Follow-up target must have exactly one GitCommit: {directory}")
blocks.append(block)
preserved_tags.update(get_entry_tags(get_block_fields(block)))
elif not cleanup_directories.intersection(entries):
blocks.append(block)
preserved_tags.update(get_entry_tags(get_block_fields(block)))
for version in replacements:
if version not in replaced:
blocks.extend(replacements[version])
selected_tags = {
tag
for version_blocks in replacements.values()
for block in version_blocks
for tag in get_entry_tags(get_block_fields(block))
}
conflicts = selected_tags & preserved_tags
if conflicts:
raise ValueError(
"Selected versions would conflict with preserved upstream tags: "
+ ", ".join(sorted(conflicts))
)
merged = "\n\n".join(blocks)
if follow_up_targets and not replacements and not cleanup_directories:
return merged
return merged.rstrip("\n") + "\n"
def run_publication_command(*args: str, cwd: Path | None = None) -> str:
return subprocess.run(
args, cwd=cwd, capture_output=True, text=True, check=True,
).stdout.strip()
def prepare_publication_source(plan: PublicationPlan, versions=None) -> tuple[str, str]:
versions = plan.ready_releases if versions is None else versions
commit = github_request("https://api.github.com/repos/adoptium/containers/commits/main")
if not isinstance(commit, dict) or not isinstance(commit.get("sha"), str) or not commit["sha"]:
raise ValueError("GitHub did not return the published containers main commit")
published_commit = commit["sha"]
tree = github_request(
f"https://api.github.com/repos/adoptium/containers/git/trees/{published_commit}?recursive=1"
)
if not isinstance(tree, dict) or tree.get("truncated") or not isinstance(tree.get("tree"), list):
raise ValueError("GitHub did not return a complete published containers source tree")
published_files = {
entry["path"]: entry["sha"] for entry in tree["tree"] if entry.get("type") == "blob"
}
source_paths = {"config/temurin.yml"}
blocks = []
for block in plan.manifest.split("\n\n"):
entries = get_manifest_entries(block)
selected = [
directory for directory in entries
if int(directory.split("/", 1)[0]) in versions
]
for directory in selected:
source_paths.add(f"{directory}/Dockerfile")
entrypoint = f"{directory}/entrypoint.sh"
if entrypoint in published_files or Path(entrypoint).exists():
source_paths.add(entrypoint)
if selected:
block = re.sub(r"(?m)^GitCommit: .+$", f"GitCommit: {published_commit}", block)
blocks.append(block)
paths = sorted(source_paths)
for path in paths:
if path not in published_files or not Path(path).is_file():
raise ValueError(f"Publication source is missing or not merged upstream: {path}")
hashes = run_publication_command("git", "hash-object", "--", *paths).splitlines()
if len(hashes) != len(paths):
raise ValueError("Git did not return a hash for every publication source file")
for path, blob in zip(paths, hashes):
if blob != published_files[path]:
raise ValueError(
f"Publication source differs from published upstream main: {path}. "
"Merge image and configuration changes before publishing."
)
return published_commit, "\n\n".join(blocks)
def describe_publication(
published_commit, releases, added, deferred_architectures, held_back_directories, cleanup,
added_since_opened=None, backfilled_tags=None,
):
"""Build the upstream PR title and description."""
added_since_opened = added_since_opened or {}
backfilled_tags = backfilled_tags or {}
title = ", ".join(
f"{version} {release} add {', '.join(added[version])}" if version in added
else f"{version} to {release}"
for version, release in releases.items()
)
if cleanup:
title = f"{title}; remove deprecated images" if title else "remove deprecated images"
title = "eclipse-temurin: " + title
body = f"Update Eclipse Temurin from adoptium/containers commit {published_commit}.\n\n"
new_releases = {v: r for v, r in releases.items() if v not in added}
if new_releases:
body += "Publish READY releases:\n"
for version, release in new_releases.items():
deferred = deferred_architectures.get(version)
if deferred:
body += (
f"- Temurin {version}: `{release}` (JDK and JRE). {', '.join(deferred)} "
"binaries are not released yet, so those builds cannot install Temurin; "
"a follow-up PR will publish them once the binaries are available.\n"
)
else:
body += f"- Temurin {version}: `{release}` (JDK and JRE, all required architectures)\n"
held = held_back_directories.get(version)
if held:
body += (
f" - Not yet updated to `{release}`, so these images keep their current "
f"upstream entries: {format_image_targets(held)}\n"
)
backfilled = backfilled_tags.get(version)
if backfilled:
body += (
" - The previous Linux entries are kept for "
+ ", ".join(f"`{tag}`" for tag in backfilled)
+ " so those shared tags do not become Windows-only.\n"
)
arches = added_since_opened.get(version)
if arches:
body += (
f" - {', '.join(arches)} binaries became available after this PR was opened; "
"the affected entries now point at the commit that adds them.\n"
)
body += "\n"
follow_ups = {v: r for v, r in releases.items() if v in added}