Conghao97's picture tcftrees's picture
ProgramGen release
d086025
|
Raw History Blame Contribute Delete
91.2 kB
# adoptium/containers ## Project Overview The adoptium/containers repository holds the Dockerfiles that build the official Adoptium images of the Eclipse Temurin distribution of OpenJDK, published on Docker Hub. Its purpose is to keep a large family of Java runtime images — spanning JDK and JRE variants of Temurin 8, 11, 17, 21, 25 and 26 — continuously up to date across Alpine, UBI, Ubuntu and Windows base operating systems and many CPU architectures, while delegating the actual image building and publishing to Docker Hub via the official-images manifest. The repository is primarily a generation pipeline rather than hand-maintained Dockerfiles. The central script, generate_dockerfiles.py, renders Dockerfiles from Jinja2 templates in docker_templates/, driven by per-version configuration in config/ that defines defaults and overrides for architectures, OS variants, package handling, and version conditions. It queries the Adoptium API (via adoptium_api.py) for the latest published release binaries for each supported version, caches responses, resolves effective architecture lists by applying version-conditioned include/exclude rules, and writes the resulting Dockerfiles into the <version>/<jdk|jre>/<alpine|ubi|ubuntu|windows>/<os-version> directory tree. eol_checker.py supplements this by warning when releases near end-of-life. Automation is provided by GitHub Actions: an updater workflow runs roughly every half hour, invoking generate_dockerfiles.py to open 'Update Dockerfiles' pull requests whenever new Temurin binaries appear. After maintainers review and merge, dockerhub_doc_config_update.py regenerates the official Docker Hub manifest file (_eclipse-temurin) describing tags and architectures, which maintainers submit to docker-library/official-images so Docker Hub rebuilds and publishes the images. Supporting tooling includes sanity.sh, tests such as test_generate_dockerfiles.py and test_eol_checker.py, and documentation (CONTRIBUTING.md, DISTRO_MAINTENANCE.md) describing release cadence, quarterly PSU updates, security rebuild policy, and distro-specific maintenance practices. Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance. ## Submission Constraints (read carefully — the evaluation depends on these) This is a **closed-book** task. The graded test suite is **hidden** and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules: 1. **Do NOT create or modify any files under the test directories** (e.g. `tests/`, `test/`, `testing/`, or files named `test_*.py` / `conftest.py`). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement **only** the library/source code — never the tests. 2. **Your package MUST be importable by the name the tests use.** The hidden tests `import` your package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a valid `pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that `pip install -e .` succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0. 3. **Match the documented module paths and public API exactly** (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like. ## Install / Reconstruction Contract Follow this contract before implementing the documented APIs: - **Project root**: `/workspace/repo` at runtime; the submitted repository root is `.`. - **Package/distribution name**: `(unnamed project)` - **Package roots**: `.` - **Install strategy**: `source-roots` - **Import/entry**: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package. - **Provision commands**: ```bash python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2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BpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))' programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; } export -f programgen_pip_install programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel ``` - **Runtime setup**: ```bash export PYTHONPATH="$PWD:${PYTHONPATH:-}" ``` - **Project root for installation**: `.` - **Build-version environment**: `SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0`, `PDM_BUILD_SCM_VERSION=0.0.0`, `POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0`, `UV_DYNAMIC_VERSIONING_BYPASS=0.0.0` - **Test directory**: `(not available)` - **Test command**: `bash -lc 'exec python3 -c '"'"'import json, os, sys, unittest from collections import defaultdict contract = json.loads(sys.argv[1]) limit = int(sys.argv[2]) coverage = None if os.environ.get('"'"'"'"'"'"'"'"'COVERAGE_FILE'"'"'"'"'"'"'"'"'): from coverage import Coverage coverage = Coverage(source=['"'"'"'"'"'"'"'"'.'"'"'"'"'"'"'"'"']) coverage.start() class Result(unittest.TextTestResult): outcomes = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.outcomes = {} def record(self, test, outcome): identity = '"'"'"'"'"'"'"'"'unittest::'"'"'"'"'"'"'"'"' + test.id() self.outcomes[identity] = outcome status = {'"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'PASSED'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'FAILED'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'ERROR'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'SKIPPED'"'"'"'"'"'"'"'"'}[outcome] print('"'"'"'"'"'"'"'"'\n'"'"'"'"'"'"'"'"' + identity + '"'"'"'"'"'"'"'"' '"'"'"'"'"'"'"'"' + status, flush=True) def addSuccess(self, test): super().addSuccess(test) self.record(test, '"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"') def addFailure(self, test, error): super().addFailure(test, error) self.record(test, '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"') def addError(self, test, error): super().addError(test, error) self.record(test, '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"') def addSkip(self, test, reason): super().addSkip(test, reason) self.record(test, '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"') def addExpectedFailure(self, test, error): super().addExpectedFailure(test, error) self.record(test, '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"') def addUnexpectedSuccess(self, test): super().addUnexpectedSuccess(test) self.record(test, '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"') def addSubTest(self, test, subtest, error): super().addSubTest(test, subtest, error) if error is not None: self.record(test, '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"' if issubclass(error[0], test.failureException) else '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"') def flatten(suite): for item in suite: if isinstance(item, unittest.TestSuite): yield from flatten(item) else: yield item try: loader = unittest.TestLoader() suite = loader.discover(**contract) if loader.errors: for error in loader.errors: print(error, file=sys.stderr) print('"'"'"'"'"'"'"'"'[programgen] test collection failed with exit code 2'"'"'"'"'"'"'"'"', file=sys.stderr) raise SystemExit(2) tests = list(flatten(suite)) if len({test.id() for test in tests}) != len(tests): raise RuntimeError('"'"'"'"'"'"'"'"'duplicate unittest identities cannot be measured independently'"'"'"'"'"'"'"'"') if limit > 0 and len(tests) > limit: groups = defaultdict(list) for index, test in enumerate(tests): groups[type(test).__module__].append(index) selected, depth = [], 0 while len(selected) < limit: for indices in groups.values(): if depth < len(indices): selected.append(indices[depth]) if len(selected) == limit: break depth += 1 tests = [tests[index] for index in sorted(selected)] result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2, resultclass=Result).run(unittest.TestSuite(tests)) payload = {name: sorted(identity for identity, value in result.outcomes.items() if value == name) for name in ('"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"')} print('"'"'"'"'"'"'"'"'PROGRAMGEN_UNITTEST_RESULT='"'"'"'"'"'"'"'"' + json.dumps(payload), flush=True) print('"'"'"'"'"'"'"'"'%d passed, %d failed, %d errors, %d skipped'"'"'"'"'"'"'"'"' % tuple(len(payload[name]) for name in ('"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"')), flush=True) measured = sum(len(payload[name]) for name in ('"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"')) raise SystemExit(5 if not measured else 0 if result.wasSuccessful() else 1) finally: if coverage: coverage.stop() coverage.save() '"'"' '"'"'{"pattern": "test_*.py", "start_dir": ".", "top_level_dir": null}'"'"' 500'` - **Test startup**: run the exact test command above from the project root after installation; hidden tests are injected separately. ## Environment & Project Structure - **Language**: python - **Build system**: python - **Test command**: `bash -lc exec python3 -c 'import json, os, sys, unittest from collections import defaultdict contract = json.loads(sys.argv[1]) limit = int(sys.argv[2]) coverage = None if os.environ.get('"'"'COVERAGE_FILE'"'"'): from coverage import Coverage coverage = Coverage(source=['"'"'.'"'"']) coverage.start() class Result(unittest.TextTestResult): outcomes = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.outcomes = {} def record(self, test, outcome): identity = '"'"'unittest::'"'"' + test.id() self.outcomes[identity] = outcome status = {'"'"'passed'"'"': '"'"'PASSED'"'"', '"'"'failed'"'"': '"'"'FAILED'"'"', '"'"'errors'"'"': '"'"'ERROR'"'"', '"'"'skipped'"'"': '"'"'SKIPPED'"'"'}[outcome] print('"'"'\n'"'"' + identity + '"'"' '"'"' + status, flush=True) def addSuccess(self, test): super().addSuccess(test) self.record(test, '"'"'passed'"'"') def addFailure(self, test, error): super().addFailure(test, error) self.record(test, '"'"'failed'"'"') def addError(self, test, error): super().addError(test, error) self.record(test, '"'"'errors'"'"') def addSkip(self, test, reason): super().addSkip(test, reason) self.record(test, '"'"'skipped'"'"') def addExpectedFailure(self, test, error): super().addExpectedFailure(test, error) self.record(test, '"'"'skipped'"'"') def addUnexpectedSuccess(self, test): super().addUnexpectedSuccess(test) self.record(test, '"'"'failed'"'"') def addSubTest(self, test, subtest, error): super().addSubTest(test, subtest, error) if error is not None: self.record(test, '"'"'failed'"'"' if issubclass(error[0], test.failureException) else '"'"'errors'"'"') def flatten(suite): for item in suite: if isinstance(item, unittest.TestSuite): yield from flatten(item) else: yield item try: loader = unittest.TestLoader() suite = loader.discover(**contract) if loader.errors: for error in loader.errors: print(error, file=sys.stderr) print('"'"'[programgen] test collection failed with exit code 2'"'"', file=sys.stderr) raise SystemExit(2) tests = list(flatten(suite)) if len({test.id() for test in tests}) != len(tests): raise RuntimeError('"'"'duplicate unittest identities cannot be measured independently'"'"') if limit > 0 and len(tests) > limit: groups = defaultdict(list) for index, test in enumerate(tests): groups[type(test).__module__].append(index) selected, depth = [], 0 while len(selected) < limit: for indices in groups.values(): if depth < len(indices): selected.append(indices[depth]) if len(selected) == limit: break depth += 1 tests = [tests[index] for index in sorted(selected)] result = unittest.TextTestRunner(stream=sys.stdout, verbosity=2, resultclass=Result).run(unittest.TestSuite(tests)) payload = {name: sorted(identity for identity, value in result.outcomes.items() if value == name) for name in ('"'"'passed'"'"', '"'"'failed'"'"', '"'"'errors'"'"', '"'"'skipped'"'"')} print('"'"'PROGRAMGEN_UNITTEST_RESULT='"'"' + json.dumps(payload), flush=True) print('"'"'%d passed, %d failed, %d errors, %d skipped'"'"' % tuple(len(payload[name]) for name in ('"'"'passed'"'"', '"'"'failed'"'"', '"'"'errors'"'"', '"'"'skipped'"'"')), flush=True) measured = sum(len(payload[name]) for name in ('"'"'passed'"'"', '"'"'failed'"'"', '"'"'errors'"'"')) raise SystemExit(5 if not measured else 0 if result.wasSuccessful() else 1) finally: if coverage: coverage.stop() coverage.save() ' '{"pattern": "test_*.py", "start_dir": ".", "top_level_dir": null}' 500` ### Project Directory Structure ``` .gitattributes .github/ISSUE_TEMPLATE/bug.yml .github/ISSUE_TEMPLATE/new-distro.yml .github/agents/agentic-workflows.md .github/aw/actions-lock.json .github/dependabot.yml .github/skills/agentic-workflows/SKILL.md .github/workflows/auto-merge.yml .github/workflows/check-eol.yml .github/workflows/ci.yml .github/workflows/code-freeze.yml .github/workflows/codeql.yml .github/workflows/copilot-setup-steps.yml .github/workflows/dependabot-auto-merge.yml .github/workflows/dockerfile-readiness.lock.yml .github/workflows/dockerfile-readiness.md .github/workflows/sanity.yml .github/workflows/scorecards.yml .github/workflows/test-pr.yml .github/workflows/updater.yml .gitignore .test/config.sh 11/jdk/alpine/3.21/Dockerfile 11/jdk/alpine/3.21/entrypoint.sh 11/jdk/alpine/3.22/Dockerfile 11/jdk/alpine/3.22/entrypoint.sh 11/jdk/alpine/3.23/Dockerfile 11/jdk/alpine/3.23/entrypoint.sh 11/jdk/alpine/3.24/Dockerfile 11/jdk/alpine/3.24/entrypoint.sh 11/jdk/ubi/ubi10-minimal/Dockerfile 11/jdk/ubi/ubi10-minimal/entrypoint.sh 11/jdk/ubi/ubi9-minimal/Dockerfile 11/jdk/ubi/ubi9-minimal/entrypoint.sh 11/jdk/ubuntu/jammy/Dockerfile 11/jdk/ubuntu/jammy/entrypoint.sh 11/jdk/ubuntu/noble/Dockerfile 11/jdk/ubuntu/noble/entrypoint.sh 11/jdk/ubuntu/resolute/Dockerfile 11/jdk/ubuntu/resolute/entrypoint.sh 11/jdk/windows/nanoserver-ltsc2022/Dockerfile 11/jdk/windows/nanoserver-ltsc2025/Dockerfile 11/jdk/windows/windowsservercore-ltsc2022/Dockerfile 11/jdk/windows/windowsservercore-ltsc2025/Dockerfile 11/jre/alpine/3.21/Dockerfile 11/jre/alpine/3.21/entrypoint.sh 11/jre/alpine/3.22/Dockerfile 11/jre/alpine/3.22/entrypoint.sh 11/jre/alpine/3.23/Dockerfile 11/jre/alpine/3.23/entrypoint.sh 11/jre/alpine/3.24/Dockerfile 11/jre/alpine/3.24/entrypoint.sh 11/jre/ubi/ubi10-minimal/Dockerfile 11/jre/ubi/ubi10-minimal/entrypoint.sh 11/jre/ubi/ubi9-minimal/Dockerfile 11/jre/ubi/ubi9-minimal/entrypoint.sh 11/jre/ubuntu/jammy/Dockerfile 11/jre/ubuntu/jammy/entrypoint.sh 11/jre/ubuntu/noble/Dockerfile 11/jre/ubuntu/noble/entrypoint.sh 11/jre/ubuntu/resolute/Dockerfile 11/jre/ubuntu/resolute/entrypoint.sh 11/jre/windows/nanoserver-ltsc2022/Dockerfile 11/jre/windows/nanoserver-ltsc2025/Dockerfile 11/jre/windows/windowsservercore-ltsc2022/Dockerfile 11/jre/windows/windowsservercore-ltsc2025/Dockerfile 17/jdk/alpine/3.21/Dockerfile 17/jdk/alpine/3.21/entrypoint.sh 17/jdk/alpine/3.22/Dockerfile 17/jdk/alpine/3.22/entrypoint.sh 17/jdk/alpine/3.23/Dockerfile 17/jdk/alpine/3.23/entrypoint.sh 17/jdk/alpine/3.24/Dockerfile 17/jdk/alpine/3.24/entrypoint.sh 17/jdk/ubi/ubi10-minimal/Dockerfile 17/jdk/ubi/ubi10-minimal/entrypoint.sh 17/jdk/ubi/ubi9-minimal/Dockerfile 17/jdk/ubi/ubi9-minimal/entrypoint.sh 17/jdk/ubuntu/jammy/Dockerfile 17/jdk/ubuntu/jammy/entrypoint.sh ... ``` ## API Usage Guide Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely. ### Capability: Adoptium release metadata access # Adoptium release metadata access ## Purpose This capability is the repository's single source of truth for *which* OpenJDK feature numbers exist upstream. Two thin functions wrap one Adoptium endpoint, `https://api.adoptium.net/v3/info/available_releases`, and everything downstream — the `<version>/...` Dockerfile tree, the Docker Hub tag manifest, and end-of-life warnings — derives its version universe from them. A re-implementation must reproduce their filtering, ordering, and transport behavior exactly, because tests stub the endpoint and assert on the returned shapes. ## Transport contract (shared by both functions) Each call to either public function performs a fresh, independent `urllib.request` GET. This module itself has no cache, memoization, retry, or timeout; the "request caching" attributed to the capability happens at the caller level (results are fetched once per run and reused), never inside `adoptium_api`. The request carries the literal `User-Agent: Adoptium Dockerfile Updater` header and no auth or query parameters. Response bytes are decoded UTF-8 and parsed with `json.loads`, so: - network problems surface as `urllib.error.URLError`/`HTTPError`; - a non-JSON body raises `json.JSONDecodeError`; - a JSON body missing any expected key raises `KeyError`; - the context-manager style (`with urlopen(...) as response:`) plus `response.read().decode("utf-8")` means a stubbed response must support `__enter__`/`__exit__` and its `read()` must return **bytes** — a `str` breaks the `.decode` call. Four payload keys are consumed: `available_lts_releases`, `available_releases`, `most_recent_lts`, `most_recent_feature_release`. ## `get_supported_versions` semantics A deterministic three-step reduction of one payload: 1. Start with `set(available_lts_releases)`. 2. Add every integer `v` with `most_recent_lts < v <= most_recent_feature_release` that is present in `available_releases`. 3. Return `sorted(versions)` — an ascending list of `int`, never a set. Edge cases that tests can pin down: - Non-LTS feature numbers **at or below** `most_recent_lts` are never included (the loop's lower bound), even if they appear in `available_releases`. - Non-LTS numbers above `most_recent_lts` are included **only if** present in `available_releases`; a skipped or withdrawn feature number is silently excluded. - Members of `available_lts_releases` are trusted as-is and need not appear in `available_releases`. - If `most_recent_feature_release <= most_recent_lts`, the loop body never runs and the result is exactly the sorted LTS list — no error is raised. - Set semantics collapse duplicates in the LTS list; the numeric sort makes output order deterministic regardless of API list order. ## `get_latest_lts` semantics Returns the payload's `most_recent_lts` integer unchanged. No validation against `available_lts_releases` or `available_releases` occurs; whatever the API claims is passed through. ## Workflow role and ordering Generation entry points import both names (`from adoptium_api import get_latest_lts, get_supported_versions`) and call them at run start: `get_supported_versions()` enumerates the target version directories, and `get_latest_lts()` drives default/latest tag decisions. Because each call refetches, the two calls can in principle observe different live API states within one run; deterministic tests avoid this by stubbing the transport once and asserting both functions against the same fixture. `dockerhub_doc_config_update` re-imports the same functions, so `dockerhub_doc_config_update.get_supported_versions` and `.get_latest_lts` are the identical function objects. ## Non-obvious, test-sensitive behavior Patch the seam `adoptium_api._fetch_release_data`, not the public names. Importing modules bind the public functions by value, so patching `adoptium_api.get_supported_versions` does not affect an already-imported `generate_dockerfiles.get_supported_versions` — but patching `_fetch_release_data` affects every caller, because it is resolved inside the defining module at call time. That makes the private fetcher the stable injection point for fixtures like the example below, and it also means a re-implementation must keep the fetch step as a separate module-level function for the same reason. #### Exact API Reference #### `adoptium_api.get_supported_versions` - **Import Path**: `from adoptium_api import get_supported_versions` - **Required Test Import Paths**: - adoptium_api.get_supported_versions - dockerhub_doc_config_update.get_supported_versions - **Exact Test Import Statements**: - from adoptium_api import get_latest_lts, get_supported_versions - **Kind**: function - **Signature**: ```python def get_supported_versions() ``` - **Behavior**: Fetch supported versions from the Adoptium API. #### `adoptium_api.get_latest_lts` - **Import Path**: `from adoptium_api import get_latest_lts` - **Required Test Import Paths**: - adoptium_api.get_latest_lts - dockerhub_doc_config_update.get_latest_lts - **Exact Test Import Statements**: - from adoptium_api import get_latest_lts, get_supported_versions - **Kind**: function - **Signature**: ```python def get_latest_lts() ``` - **Behavior**: Return the most recent LTS version number. ### Capability: OS end-of-life checking and warnings # OS end-of-life checking and warnings This capability answers one question for every base OS the images target: *when does that distro stop receiving support, and is that date already here?* It is a read-only advisory layer: it changes no state and writes no files. Lookups that fail for environmental reasons — an `os` value with no product mapping, an image whose version cannot be extracted, or a network/API error — degrade to `None`, so EOL data never breaks Dockerfile generation through those paths. The one exception is a malformed hardcoded `eol` override: a truthy, non-date value that does not match `%Y-%m-%d` raises an uncaught `ValueError` that propagates to callers, including `dockerhub_doc_config_update.main()`, where the EOL check runs before manifest generation and would abort it. ## The lookup chain `get_eol_date(configuration)` is the entry point for a single entry of `config/temurin.yml`. It applies a strict precedence: 1. **Hardcoded override.** If the config entry carries a *truthy* `eol` key, it wins and no network call is made. A `datetime.date` is returned as-is; anything else is stringified and parsed with the exact format `"%Y-%m-%d"`. A malformed string raises `ValueError` — this is *not* caught, unlike network failures. Falsy values (empty string, `None`, `false`) do **not** trigger the override; the entry falls through to the mapped-lookup path. 2. **Product mapping.** `OS_TO_PRODUCT` translates the config `os` value to an endoflife.date product slug: `ubuntu → ubuntu`, `alpine-linux → alpine`, `ubi-minimal → rhel`. Any other `os` (notably `servercore`/Windows) short-circuits to `None` with no HTTP request. 3. **Cycle extraction.** `_extract_cycle(image)` pulls the version out of the image reference using two regexes, tried in order — but only the first is `$`-anchored: a trailing numeric tag `:(\d[\d.]*)$` (`ubuntu:26.04` → `26.04`, `alpine:3.21` → `3.21`). The second is an unanchored `search` for `/ubi(\d+)` that requires a literal `/` immediately before `ubi`, so only prefixed references match (`redhat/ubi9-minimal` → `9`, `redhat/ubi10-minimal` → `10`); a bare `ubi10-minimal` matches neither pattern and returns `None`. Non-numeric tags also return `None`: `scratch` (no match) and `...servercore:ltsc2022` (tag starts with a letter) both fail. Note the UBI pattern yields only the major version — endoflife.date models RHEL cycles as majors. 4. **HTTP fetch.** `fetch_eol_date(product, cycle)` GETs `https://endoflife.date/api/{product}/{cycle}.json` with `User-Agent: Adoptium EOL Checker` and a 10-second timeout. The JSON body's `eol` field decides the result: a `bool` (i.e. `false`, "not yet EOL") maps to `None`; a `"YYYY-MM-DD"` string becomes a `date`. Every exception — network errors, bad JSON, timeouts — is swallowed and yields `None`. Tests patch `eol_checker.urllib.request.urlopen` with a context-manager mock whose `read()` returns JSON bytes, so the implementation must go through `urllib.request` with `with ... as resp:` semantics. ## Scanning a whole config `check_eol_configs(config)` walks `config.get("configurations", {})` — a mapping of OS family (e.g. `linux`, `windows`) to lists of config dicts — calls `get_eol_date` on each, and returns a list of `(configuration, eol_date)` tuples where `eol_date <= date.today()`. The comparison is inclusive: a distro expires *on* its EOL date. Entries with no resolvable date are silently skipped. Because the truthy `eol` override is checked before the os mapping, a Windows (unmapped-os) entry is skipped only when it lacks such an override; with a truthy `eol` it resolves to a date and can appear in the expired list like any other entry. A missing `configurations` key is tolerated (empty result). ## Warnings and CI gating `print_eol_warnings(config, file=sys.stderr)` is the warning-emission contract. It delegates to `check_eol_configs` and, when anything is expired, prints a header `\n⚠ N distro(s) past EOL:` followed by one line per entry, ` - {image} ({directory}) expired {eol_date}` (falling back to the directory name, then `unknown`, when no image is set). It always returns the expired list. It defaults to stderr and is invoked by `dockerhub_doc_config_update.main()` before `generate_manifest`, so warnings land on stderr while the manifest is written separately; there the warnings are purely advisory, but a malformed `eol` override would raise through it and abort generation. The module's `__main__` block loads `config/temurin.yml`, prints every image's EOL date (or `unknown`), calls `print_eol_warnings` with `file=sys.stdout` so the same warnings go to stdout, prints `All distros are within their EOL dates.` when nothing expired, and exits `1` if any expired else `0` — useful as a CI gate. ## Supporting lookups from the manifest generator Two helpers re-exported from `dockerhub_doc_config_update.py` let tooling bridge between config entries, Dockerfiles, and the tag names users see: - `get_distro_name(os_family, directory)` derives the distro tag from a config directory path: the last path segment, with `alpine-linux` prefixed as `alpine-{name}` (e.g. `3.21/alpine/3.21` → `alpine-3.21`; `24/noble/ubuntu` → `noble`). - `get_dockerfile_arches(dockerfile_path)` parses multi-arch `case` labels out of a rendered Dockerfile, translates each through `DOCKERFILE_ARCH_MAP`, drops unmapped tokens, and returns a sorted, de-duplicated list. Together they support the realistic workflow: enumerate temurin.yml configurations, resolve each image's cycle, fetch its EOL date, and report which distros need deprecation attention — with `get_distro_name`/`get_dockerfile_arches` providing the tag and architecture context when surfacing or acting on those warnings. ## Edge cases that tests pin down - Only the tag pattern in `_extract_cycle` is `$`-anchored; the UBI pattern is an unanchored search needing `/` before `ubi`. Image references must end with the numeric tag for the first pattern to hit (`ubuntu:26.04` works; a suffix after the tag would not), and a bare `ubi10-minimal` returns `None`. - `get_eol_date` on an unmapped `os` makes **no** fetch call; on a mapped `os` with an unparseable image it also returns `None` without fetching. - The truthy hardcoded `eol` override applies even when `os`/`image` would map and fetch successfully — and it is checked *before* the os mapping, so it can carry Windows entries into the expired list. A malformed value raises `ValueError`. - `fetch_eol_date` returning `None` is indistinguishable between "no data", "network down", and "eol reported as boolean" — callers treat all as unknown. - The integration-style test requires every non-`windows` OS family entry in temurin.yml to have a product mapping, an extractable cycle, and a fetchable date, so adding a new distro requires updating `OS_TO_PRODUCT` (or adding a truthy `eol` override) and keeping image tags numeric. #### Exact API Reference #### `dockerhub_doc_config_update.get_distro_name` - **Import Path**: `from dockerhub_doc_config_update import get_distro_name` - **Required Test Import Paths**: - dockerhub_doc_config_update.get_distro_name - **Exact Test Import Statements**: - from dockerhub_doc_config_update import ( find_manifest_block, format_ojdk_version, get_block_gitcommit, get_distro_name, get_dockerfile_arches, get_java_version, generate_manifest, ) - **Kind**: function - **Signature**: ```python def get_distro_name(os_family, directory) ``` - **Behavior**: Derive the distro tag name from the config directory. #### `dockerhub_doc_config_update.get_dockerfile_arches` - **Import Path**: `from dockerhub_doc_config_update import get_dockerfile_arches` - **Required Test Import Paths**: - dockerhub_doc_config_update.get_dockerfile_arches - **Exact Test Import Statements**: - from dockerhub_doc_config_update import ( find_manifest_block, format_ojdk_version, get_block_gitcommit, get_distro_name, get_dockerfile_arches, get_java_version, generate_manifest, ) - **Kind**: function - **Signature**: ```python def get_dockerfile_arches(dockerfile_path) ``` - **Behavior**: Parse architectures from the case statement in a Dockerfile. #### `eol_checker._extract_cycle` - **Import Path**: `from eol_checker import _extract_cycle` - **Required Test Import Paths**: - eol_checker._extract_cycle - **Exact Test Import Statements**: - from eol_checker import ( OS_TO_PRODUCT, _extract_cycle, check_eol_configs, fetch_eol_date, get_eol_date, ) - **Kind**: function - **Signature**: ```python def _extract_cycle(image) ``` - **Behavior**: Extract the version/cycle string from a Docker image reference. #### `eol_checker.fetch_eol_date` - **Import Path**: `from eol_checker import fetch_eol_date` - **Required Test Import Paths**: - eol_checker.fetch_eol_date - **Exact Test Import Statements**: - from eol_checker import ( OS_TO_PRODUCT, _extract_cycle, check_eol_configs, fetch_eol_date, get_eol_date, ) - **Kind**: function - **Signature**: ```python def fetch_eol_date(product, cycle) ``` - **Behavior**: Fetch the EOL date for a product cycle from endoflife.date. #### `eol_checker.get_eol_date` - **Import Path**: `from eol_checker import get_eol_date` - **Required Test Import Paths**: - eol_checker.get_eol_date - **Exact Test Import Statements**: - from eol_checker import ( OS_TO_PRODUCT, _extract_cycle, check_eol_configs, fetch_eol_date, get_eol_date, ) - **Kind**: function - **Signature**: ```python def get_eol_date(configuration) ``` - **Behavior**: Get the EOL date for a configuration entry. #### `eol_checker.check_eol_configs` - **Import Path**: `from eol_checker import check_eol_configs` - **Required Test Import Paths**: - eol_checker.check_eol_configs - **Exact Test Import Statements**: - from eol_checker import ( OS_TO_PRODUCT, _extract_cycle, check_eol_configs, fetch_eol_date, get_eol_date, ) - **Kind**: function - **Signature**: ```python def check_eol_configs(config) ``` - **Behavior**: Check all configurations for EOL status. #### `eol_checker.OS_TO_PRODUCT` - **Import Path**: `from eol_checker import OS_TO_PRODUCT` - **Required Test Import Paths**: - eol_checker.OS_TO_PRODUCT - **Exact Test Import Statements**: - from eol_checker import ( OS_TO_PRODUCT, _extract_cycle, check_eol_configs, fetch_eol_date, get_eol_date, ) - **Kind**: constant - **Signature**: ```python OS_TO_PRODUCT: dict ``` - **Behavior**: Module-level value required by the test import contract. ### Capability: Version-aware architecture resolution # Version-aware architecture resolution ## Purpose `resolve_architectures(default_architectures, overrides, version)` is the single decision point that turns a configuration's base architecture list into the architecture list actually used to build images for one JDK feature version. It exists because supported CPU targets are not static across the Temurin family: s390x has no JIT for JDK 8, riscv64 only ships from JDK 17, and arm32 stops at JDK 20. Rather than duplicating per-version architecture lists in every OS configuration, the config declares a default list plus condition-scoped overrides, and this function computes the effective list per version. ## Inputs and output - `default_architectures`: a list of raw Adoptium binary architecture names (`aarch64`, `arm`, `ppc64le`, `riscv64`, `s390x`, `x64`). Note these are the API-side names; the Debian display names (`arm64`, `ppc64el`, `amd64`) are produced later by a different helper and are not this function's concern. - `overrides`: a list of dicts, each with a `versions` key and one or more of `architectures`, `exclude`, `include`. - `version`: an integer feature version (8, 11, 17, 21, ...). - Returns a list of architecture names. ## Pipeline position For each (OS family, configuration, version) triple the generator calls it once, passing the configuration's `architectures` as the default and the concatenation of global config overrides followed by the configuration's local overrides. The resolved list is then used to filter `binary["architecture"]` values from the Adoptium release payload. If nothing matches after filtering, the Dockerfile for that version/image type is skipped entirely — an over-aggressive exclude silently removes images rather than raising. If no overrides exist for a configuration, the default list is returned as-is. ## Condition grammar and matching Each override's `versions` string is stripped, then must match `^(==|!=|>=|<=|>|<)(\d+)$` — an operator from `==`, `!=`, `>=`, `<=`, `>`, `<` immediately followed by one or more digits. The target is parsed as `int` and compared against `version` with the corresponding operator from the `operator` module, so matching is integer-based: `"<17"` matches 8 and 11 but not 17; `">=21"` matches 21, 25, 26. Any other shape — bare `"8"`, internal whitespace as in `"== 8"`, an empty string — raises `ValueError: Invalid version condition: '<condition>'` with the stripped condition embedded in single quotes. A leading-zero target like `"==08"` is accepted and parses to 8. Validation happens per-override in iteration order, before the match test; an invalid condition in a later override aborts the whole call even if earlier overrides already matched. `version` must be an int for the ordering operators: with a non-int `version` against an int target, `<`, `<=`, `>`, and `>=` raise `TypeError` from the comparison, not `ValueError`, while `==` and `!=` do not raise — `operator.eq` returns `False` and `operator.ne` returns `True` for mismatched types, so a `==` condition silently never matches and a `!=` condition silently always matches, and resolution proceeds with a wrong-version result instead of erroring. ## Application order — the test-sensitive core 1. If `overrides` is falsy, `default_architectures` is returned **by identity** — no copy. Mutating the return value in that case mutates the caller's config list; treat the result as read-only or copy defensively. 2. Otherwise the function works on a shallow copy of the default and applies **every matching override in list order** (earlier list entries first; global overrides before local ones, so a local override can undo a global exclusion). 3. Within one matching override, the three actions run in a fixed sequence: full replacement (`architectures`) first, then `exclude`, then `include`. A single override may therefore reset the list, trim it, and extend it. 4. Replacement is absolute: `result = list(override["architectures"])`. It does not intersect the current list, so arches removed by an earlier override can be restored by a later replacement. 5. `exclude` is a membership filter: entries absent from the list are ignored silently. 6. `include` appends `override["include"]` entries not already present, preserving include-list order at the end of the result. Deduplication is only against the current result, not within the include list itself — a repeated entry inside one include list is appended twice, while an entry already in the list is skipped. 7. Non-matching overrides are skipped entirely; their action keys are never inspected. An override with a valid matching condition but none of the three action keys is a no-op. A missing `versions` key raises `KeyError`. ## Worked example from the shipped config Global overrides: `==8` excludes `s390x`, `<17` excludes `riscv64`, `>=21` excludes `arm`. For the noble Ubuntu configuration with default `[aarch64, arm, ppc64le, riscv64, s390x, x64]`: version 8 matches the first two, yielding `[aarch64, arm, ppc64le, x64]`; version 11 matches only `<17`, yielding `[aarch64, arm, ppc64le, s390x, x64]`; version 21+ matches only `>=21`, yielding `[aarch64, ppc64le, riscv64, s390x, x64]`. Later matching overrides always win over earlier ones for the same arch because they observe and transform the accumulated result. #### Exact API Reference #### `generate_dockerfiles.resolve_architectures` - **Import Path**: `from generate_dockerfiles import resolve_architectures` - **Required Test Import Paths**: - generate_dockerfiles.resolve_architectures - **Exact Test Import Statements**: - from generate_dockerfiles import resolve_architectures - **Kind**: function - **Signature**: ```python def resolve_architectures(default_architectures, overrides, version) ``` - **Behavior**: Resolve effective architectures for a given version by applying overrides. ### Capability: Templated Dockerfile and entrypoint generation ## Purpose and shape of the pipeline A single run of `generate_dockerfiles.py` regenerates the whole `<version>/<jdk|jre>/<directory>` tree. For each supported Temurin version, image type (jdk, jre) and configured OS variant it renders a Jinja2 template with data taken from the Adoptium release API and writes `Dockerfile` — plus `entrypoint.sh` on non-Windows. Generation is per-pair and skip-based, not incremental: each (version, image_type, configuration) either emits a fresh file pair or is skipped under well-defined conditions. ## Ordering and state changes 1. `--force` is the only destructive path: top-level directories whose names are digits are removed for a clean regeneration. Without it the run is additive — files are overwritten only when new data is produced. 2. `config/temurin.yml` is loaded once; global `architecture_overrides` are prepended to each configuration's local overrides, so rule order decides which include/exclude/replacement wins. 3. `get_supported_versions()` supplies the default version list; a configuration may pin its own `versions`. 4. `print_eol_warnings(config)` runs before generation and is advisory only — near-EOL distros are still generated. 5. Loop order: OS family → configuration → version (skipping `version >= deprecated`) → image type, `jdk` before `jre`. Output directories are created with `exist_ok=True` before any request is made. ## Template selection and context The environment is a `FileSystemLoader` rooted at `docker_templates` with `trim_blocks=False, lstrip_blocks=False`, so template whitespace passes verbatim into the output; formatting is entirely the template's job. The Dockerfile template is chosen by name alone: `f"{os_name}.Dockerfile.j2"` where `os_name` is the configuration's `os` value (`ubuntu`, `ubi-minimal`, `alpine-linux`, `nanoserver`, `servercore`). Two identifiers must not be confused: `os_family` is the `configurations` map key used in the Adoptium query (`&os={os_family}`) and to accept binaries (`binary["os"] == os_family`), while `os` names the template and drives per-distro behaviour inside it. The full render context is `base_image`, `image_type`, `java_version`, `version` (integer major, so templates can branch 8 vs 11+), `arch_data`, `os_family`, `os`. `arch_data` is sorted by key before rendering, so identical inputs yield byte-identical Dockerfiles — this keeps updater PR diffs stable. ## Version strings and arch_data For version 8, `java_version` is the release `release_name` verbatim (`jdk8u292-b10`). Otherwise it is rebuilt as `"jdk-" + version_data["openjdk_version"]` with any `-LTS` stripped (`jdk-11.0.28+6`). On Linux-style families each qualifying binary contributes `archHelper(arch, os_name) → {"download_url", "checksum"}` from `binary["package"]`; the Ubuntu renames (aarch64→arm64, ppc64le→ppc64el, x64→amd64), `arm→armhf` everywhere, and `x64→x86_64` elsewhere let templates emit distro-correct names. Windows is the special case: `arch_data` is a single flat dict, not keyed by architecture, built from the binary's `installer` link/checksum plus a `copy_from` tag: strip `jdk`; for versions above 8 also drop `-` and turn `+` into `_` (`jdk-11.0.28+6` → `11.0.28_9`); append `-<image_type>-windowsservercore-<tag part of base_image>`. Windows gets no `entrypoint.sh` — CA-certificate handling is Linux-only. ## Skip rules and errors - HTTP 404 → print and skip that (version, image_type); any other HTTP error propagates via `raise_for_status()`. - Empty `arch_data` (no binary matched) → nothing is written; a Dockerfile from an earlier run therefore survives unchanged, so stale architectures persist until `--force` or a matching release appears. - `version >= deprecated` → skipped before any API call. - Responses are disk-cached for one hour, so rapid reruns see a snapshot; newly published binaries can lag by up to the cache TTL. ## Closing the loop with get_java_version `dockerhub_doc_config_update.get_java_version` reads a rendered Dockerfile back, tying generated artifacts to Docker Hub manifest generation. Its parsing contract is exact: it scans the file line by line and returns on the FIRST line merely containing the substring `JAVA_VERSION=` — a substring test, not anchored to `ENV`, so an `ARG JAVA_VERSION=...` line or a comment containing the substring wins if it appears first. The returned value is the second `=`-delimited field, stripped of surrounding whitespace (`line.split("=")[1].strip()`); anything after a second `=` on that line is discarded. When no line matches it returns `None`, which downstream manifest generation treats as a skip of that directory — no manifest entry is emitted for it. The round-trip contract is marker presence, not value format: `get_java_version` is convention-agnostic and parses whatever follows `JAVA_VERSION=`, succeeding on any naming scheme. The actual parse-breaking change is removing or renaming the `JAVA_VERSION=` marker line — that yields `None` and a skipped manifest entry. The `jdk-`/`8u` value conventions are load-bearing only further downstream, in `format_ojdk_version`, which converts `JAVA_VERSION` into a Docker tag-compatible string by stripping a leading `jdk`/`jdk-` prefix and replacing `+` with `_`; deviating there corrupts generated tags, not parsing. ## entrypoint.sh specifics Rendered per output directory from `entrypoint.sh.j2` with only `image_type`, `os`, `version` — no architecture data — so all architectures sharing a directory get identical entrypoints. It is written as a plain file immediately after the Dockerfile in the same directory; the generator performs no `chmod`. #### Exact API Reference #### `dockerhub_doc_config_update.get_java_version` - **Import Path**: `from dockerhub_doc_config_update import get_java_version` - **Required Test Import Paths**: - dockerhub_doc_config_update.get_java_version - **Exact Test Import Statements**: - from dockerhub_doc_config_update import ( find_manifest_block, format_ojdk_version, get_block_gitcommit, get_distro_name, get_dockerfile_arches, get_java_version, generate_manifest, ) - **Kind**: function - **Signature**: ```python def get_java_version(dockerfile_path) ``` - **Behavior**: Extract JAVA_VERSION from a Dockerfile. ### Capability: Dockerfile metadata extraction and tag derivation ## Dockerfile metadata extraction and tag derivation This capability turns the contents of generated Dockerfiles into the fields the `docker-library/official-images` manifest requires: a Docker-tag-compatible OpenJDK version, distro tag names, architecture labels, and (via `generate_manifest`) full manifest entries. It is the read-side twin of the Dockerfile generator: the updater workflow merges new Dockerfiles, then `dockerhub_doc_config_update.py` scans them to regenerate `_eclipse-temurin`. ### Version extraction and formatting `get_java_version(dockerfile_path)` is the entry point for metadata extraction. It streams the Dockerfile line by line and returns the text after the first `=` on the **first line that merely contains the substring** `JAVA_VERSION=` — the line does not have to be an `ENV` instruction, and no other parsing is attempted. The extracted value is whitespace-stripped (`.strip()` is applied to the text after the first `=`), so a trailing newline or padding on the matched line never leaks into the version or tag strings. If no line matches it returns `None`; callers in `generate_manifest` treat that as "skip this image". Two non-obvious behaviors matter for tests: the split is `line.split("=")[1]`, so a value containing a further `=` is silently truncated at the first one, and because matching is substring-based, a comment or `ARG` line mentioning `JAVA_VERSION=` would be picked up if it appeared first. `format_ojdk_version(full_version)` converts the raw `JAVA_VERSION` into a tag-safe string: it strips a leading `jdk` or `jdk-` prefix (regex `^jdk-?`) and replaces `+` with `_`. `jdk8u482-b08` → `8u482-b08`; `jdk-25.0.1+9` → `25.0.1_9`. It performs no validation and never raises for string input. An input that still carries the prefix has it removed by the regex; a version already lacking the `jdk`/`jdk-` prefix passes through with only the `+` → `_` substitution, so the function is idempotent. An empty string returns empty. The result feeds two tags per image: `{ojdk_version}-{pkg}-{distro}` (full version) and `{ver}-{pkg}-{distro}` (major version), where `pkg` is `jdk` or `jre`. ### Distro and architecture names `get_distro_name(os_family, directory)` derives the tag suffix from the config directory by taking its last `/`-separated component (e.g. `ubuntu/noble` → `noble`, `windows/nanoserver-1809` → `nanoserver-1809`). The `alpine-` prefix is added **only** when `os_family` equals the exact string `alpine-linux`; `linux` and `windows` families pass the component through unchanged. `generate_manifest` also uses this function with the literal family `"linux"` to identify the default Linux image (the first entry of `config["configurations"]["linux"]`), which decides which entry gets a `SharedTags:` line. `get_dockerfile_arches(dockerfile_path)` parses the multi-arch `case` statement: a line matches when it is whitespace, a word, `)`, and an optional trailing backslash (`\s+(\w+)\)\s*\\?\s*$`). Only words present in `DOCKERFILE_ARCH_MAP` survive and are translated to Docker Hub labels — `x86_64`/`amd64` → `amd64`, `arm64`/`aarch64` → `arm64v8`, `armhf` → `arm32v7`, `ppc64el`/`ppc64le` → `ppc64le`, plus identity mappings for `s390x` and `riscv64`. Unknown arms are silently dropped, results are deduplicated and **lexicographically sorted** (`sorted(set(...))`), and an unparseable Dockerfile yields `[]`, which renders as an empty `Architectures:` field. Two spellings of the same Hub arch (e.g. `amd64` and `x86_64`) collapse to one entry. ### Tag assembly in `generate_manifest` `generate_manifest(config, output_file)` walks versions from `get_supported_versions()`, then `jre` after `jdk`, then OS families in the fixed order `alpine-linux`, `linux`, `windows`. A configuration entry is skipped when the version is absent from its `versions` list (defaulting to all supported versions), when `deprecated` is set and `ver >= deprecated`, when the Dockerfile does not exist under `{ver}/{pkg}/{directory}`, or when `get_java_version` finds nothing. This ordering is test-sensitive: alpine entries precede their Ubuntu/UBI siblings for the same package. Tag derivation for a jdk image additionally adds `{ver}-{distro}`; a `latest` **shared** tag is appended only for the `jdk` package, only when the version equals `get_latest_lts()`, and never for `alpine-linux`. Shared tags are computed by string-replacing every occurrence of `-{distro}` in the tag list — a mechanism that relies on distro names not being suffixes of one another. Windows entries split the distro on the first `-`: `nanoserver` images get `Constraints: {distro}, windowsservercore-{number}` and their `SharedTags:` list contains **only** the windows-version tags (each tag with the distro name replaced by the windows version; never `latest`), while other Windows variants get `Constraints: {distro}` and a `SharedTags:` list that concatenates both sets: the windows-version tags followed by the distro-stripped shared tags, plus `, latest` when the package is `jdk` at the latest LTS. Manifest diffing happens **before** alpine alias tags are appended: `find_manifest_block(official_manifest, all_tags)` returns the first blank-line-separated block whose text contains the tag string as a substring (`None` for an empty manifest or no match), and `get_block_gitcommit(block)` reads the `GitCommit:` line. If a matching official commit exists and `has_changed` reports the Dockerfile (and `entrypoint.sh`, when present) is identical between that commit and HEAD, the official `GitCommit` is reused; otherwise the current HEAD commit is written. `has_changed` fails open — any git error, missing commit, or diff returns "changed". The default alpine image (first `alpine-linux` configuration) alone receives alias tags: each shared tag gets `-alpine` appended (built by replacing `", "` with `"-alpine, "`), and these aliases join the `Tags:` line. Every generated file opens with a fixed header: the comment `# Eclipse Temurin OpenJDK images provided by the Eclipse Foundation.`, a two-line `Maintainers:` field naming `George Adams <george.adams@microsoft.com> (@gdams)` and `Stewart Addison <sxa@redhat.com> (@sxa)`, `GitRepo: https://github.com/adoptium/containers.git`, `GitFetch: refs/heads/main`, and `Builder: buildkit`. Each version section is introduced by the separator comment `#------------------------------v{ver} images---------------------------------`, and every image entry is followed by a blank line, so manifest blocks are blank-line separated — the property `find_manifest_block`'s `\n\n` split depends on. Per-entry lines are `Tags:`, `SharedTags:` (only for Windows or the default Linux image), `Architectures:` (`windows-amd64` for Windows, else the parsed arch list), `GitCommit:`, `Directory:`, and, for Windows, `Builder: classic` (overriding the header's `Builder: buildkit`) plus `Constraints:`. Blank trailing lines are trimmed and a single final newline is written. ### Workflow ordering Typical flow: merge the generated-Dockerfile PR → run `main()` → `load_config()` reads `config/temurin.yml`, EOL warnings print, and `generate_manifest` writes the target file (first CLI argument, default `eclipse-temurin`). The helpers are order-independent, so they can be unit-tested against fixture Dockerfiles and manifest blocks in isolation. Only `find_manifest_block`/`get_block_gitcommit` are None-tolerant, returning `None` on falsy input; the file-backed helpers `get_java_version` and `get_dockerfile_arches` open the given path and raise `FileNotFoundError` when it does not exist, returning `None`/`[]` only when the existing file has no matching line or case arm. Only `generate_manifest` touches git, the network, and the filesystem together. #### Exact API Reference #### `dockerhub_doc_config_update.format_ojdk_version` - **Import Path**: `from dockerhub_doc_config_update import format_ojdk_version` - **Required Test Import Paths**: - dockerhub_doc_config_update.format_ojdk_version - **Exact Test Import Statements**: - from dockerhub_doc_config_update import ( find_manifest_block, format_ojdk_version, get_block_gitcommit, get_distro_name, get_dockerfile_arches, get_java_version, generate_manifest, ) - **Kind**: function - **Signature**: ```python def format_ojdk_version(full_version) ``` - **Behavior**: Convert JAVA_VERSION to Docker tag-compatible version string. ### Capability: Official Docker Hub manifest generation # API Guide — Official Docker Hub manifest generation ## Purpose and workflow position After Dockerfiles are regenerated, `generate_manifest` renders the `_eclipse-temurin` manifest consumed by docker-library/official-images: a fixed header plus one block per (version, package, OS config) that is actually buildable on disk, each block carrying `Tags`, `Architectures`, `GitCommit`, and `Directory`, plus `SharedTags` on Windows blocks and default-Linux-distro blocks and, for Windows only, `Builder: classic` plus `Constraints`. The CLI wrapper loads `config/temurin.yml` from the CWD, prints EOL warnings, and writes the file named by the first argument (default `eclipse-temurin`). `find_manifest_block` and `get_block_gitcommit` exist so regeneration can reuse the upstream GitCommit instead of churning every block. ## Execution flow and ordering One pass, no cross-call state; the output file is written once at the end. 1. **Capture the environment:** the local HEAD commit (`git rev-parse HEAD` with `check=True` — an unresolvable HEAD, e.g. a non-git temp tree, raises and nothing is written; tests must mock this lookup or run inside a repo) and the upstream manifest text (network fetch; any failure yields an empty string). These two values drive every GitCommit decision downstream. 2. **Read versions once:** supported versions are enumerated once; the latest LTS version is read once — only that version earns the `latest` shared tag. 3. **Resolve defaults:** the distro of the *first* config entry under `linux` and under `alpine-linux`. Only Windows blocks and blocks whose distro equals the default Linux distro get a `SharedTags:` line (default alpine does not), and only the default alpine distro receives `-alpine` alias tags. 4. **Loop order:** version → `jdk`, `jre` → OS family in the fixed order alpine-linux, linux, windows → config entries in file order. This exact order fixes block order in the output. ## Skip rules (test-sensitive) An entry is skipped silently when: the `windows` family is absent from the config's `configurations` (only `windows` may be absent — `linux` and `alpine-linux` must be non-empty or defaults resolution raises pre-loop); the version is not in the entry's `versions` allow-list (which defaults to all supported versions); `deprecated` is set and `ver >= deprecated` (numeric, forward-looking comparison); the `<ver>/<pkg>/<directory>/Dockerfile` file does not exist relative to the CWD; or the Dockerfile lacks a `JAVA_VERSION=` line. Existence is CWD-relative, so run from the repository root — tests chdir into a temp tree (mocking the HEAD lookup), and a config entry with no generated Dockerfile produces no block. ## Block assembly Version and distro strings come from the tag-derivation helpers (documented separately). Base tags are `{tag_version}-{pkg}-{distro}, {ver}-{pkg}-{distro}`; for JDK, the `{ver}-{distro}` mid tag is added. For JDK on the latest LTS *and* non-alpine, `", latest"` is staged separately — it lands only in the shared-tags string, never on `Tags:`. Shared tags are every listed tag minus its `-{distro}` suffix; for a JDK noble entry that yields `25.0.2_10-jdk, 25-jdk, 25` (the bare `25` emerges when `25-noble` loses its suffix). The `SharedTags:` line is emitted for every Windows block and every block whose distro equals the default Linux distro, regardless of package — a default-Linux JRE block emits `SharedTags: <full>-jre, <ver>-jre` (never `latest`), as does every Windows JRE block; it is omitted for default-alpine and non-default Linux distro blocks. The default Linux distro's shared tags end with `latest` when applicable. **Windows:** the distro splits at the first `-` into family and year. Shared tags replace the whole distro with just the family. For `nanoserver-*`, constraints are `{distro}, windowsservercore-{year}` and shared tags stay Windows-family-only; for servercore, constraints are the distro itself and the shared tags concatenate Windows-family tags, the normal shared tags, and `latest`. Every Windows block hardcodes `Architectures: windows-amd64` and `Builder: classic`. **Alpine aliases:** when the distro equals the default alpine distro, `Tags:` is extended with the `-alpine` aliases derived from the shared-tags string (tags whose `-{distro}` suffix is already stripped): `-alpine` is inserted before each comma separator and appended to the last tag — equivalently, each tag's `-{distro}` suffix is replaced by `-alpine` (for JDK: `<full>-jdk-alpine, <ver>-jdk-alpine, <ver>-alpine`). This happens *after* the GitCommit comparison, so alias tags never influence upstream block matching. ## GitCommit reuse (the non-obvious part) Before aliasing, the full tag list is looked up in the upstream manifest via `find_manifest_block`: the manifest is split on blank lines and the first block *containing the tag string as a substring* wins; empty or missing input, or no match, yields `None`. `get_block_gitcommit` reads that block's `GitCommit:` line (`None` if absent). If an upstream commit exists and the Dockerfile (plus `entrypoint.sh`, when present) is byte-identical between local HEAD and that commit, the block reuses the upstream commit; otherwise it uses local HEAD. The diff check conservatively forces the local commit whenever the git diff command fails. Offline — upstream text empty — every block gets the local commit, which is exactly what the mocked integration tests assert. ## Architectures For non-Windows entries, architectures are parsed from the Dockerfile's case statement (mapped to Hub names, deduplicated, sorted) — never taken from the config's `architectures` list, which only feeds Dockerfile generation. A staggered release with fewer case labels emits fewer architectures. ## Output invariants Blocks are separated by exactly one blank line within a version; at a version boundary the finished block's trailing blank line plus the next version's separator blank line yield two blank lines before the per-version banner `# ...v{ver} images...`, which is emitted for every supported version before any skip check and is immediately followed by that version's first block's `Tags:` line with no blank in between. Trailing blank lines are popped, the lines are joined with newlines, and exactly one final newline is appended — the file must never end in `\n\n`. The header (Maintainers, `GitRepo: https://github.com/adoptium/containers.git`, `GitFetch: refs/heads/main`, `Builder: buildkit`) is unconditional, so a zero-eligible run yields the header plus one banner comment per supported version, not a header-only file. `Directory:` is `<ver>/<pkg>/<directory>` with forward slashes. #### Exact API Reference #### `dockerhub_doc_config_update.find_manifest_block` - **Import Path**: `from dockerhub_doc_config_update import find_manifest_block` - **Required Test Import Paths**: - dockerhub_doc_config_update.find_manifest_block - **Exact Test Import Statements**: - from dockerhub_doc_config_update import ( find_manifest_block, format_ojdk_version, get_block_gitcommit, get_distro_name, get_dockerfile_arches, get_java_version, generate_manifest, ) - **Kind**: function - **Signature**: ```python def find_manifest_block(official_manifest, tags_str) ``` - **Behavior**: Find the manifest block matching the given tags in the official manifest. #### `dockerhub_doc_config_update.generate_manifest` - **Import Path**: `from dockerhub_doc_config_update import generate_manifest` - **Required Test Import Paths**: - dockerhub_doc_config_update.generate_manifest - **Exact Test Import Statements**: - from dockerhub_doc_config_update import ( find_manifest_block, format_ojdk_version, get_block_gitcommit, get_distro_name, get_dockerfile_arches, get_java_version, generate_manifest, ) - **Kind**: function - **Signature**: ```python def generate_manifest(config, output_file) ``` ### Capability: Upstream manifest comparison and GitCommit reconciliation ## Upstream manifest comparison and GitCommit reconciliation ### Purpose `generate_manifest` stamps every tag block of the emitted `_eclipse-temurin` manifest with a `GitCommit:` line. Docker Hub rebuilds a tag whenever that hash changes, so a regeneration that altered nothing would still force a full rebuild of every image. Reconciliation prevents that churn: compare the freshly generated manifest against the manifest currently published upstream, and wherever an image's Dockerfile (and entrypoint script, when present) is byte-identical between the upstream commit and local HEAD, emit the upstream hash instead of local HEAD. Only genuinely changed or unknown images keep local HEAD and trigger rebuilds. ### Pipeline shape At the top of `generate_manifest` exactly two values are captured once, before any per-version work: - `local = get_git_commit()` — HEAD of this repository via `git rev-parse HEAD`, stripped of whitespace. - `upstream_text = fetch_official_manifest()` — the UTF-8 decoded body of `OFFICIAL_MANIFEST_URL` (the raw `library/eclipse-temurin` file in docker-library/official-images on the `master` branch). Then, per image entry (version × jdk/jre × OS family × config, only where `Dockerfile` exists on disk): 1. `find_manifest_block(upstream_text, all_tags)` locates the upstream block. The manifest is split on blank lines (`\n\n`) into blocks; the first block whose text *contains* the full comma-joined `all_tags` string wins. Ordering note that is easy to get wrong: this lookup happens **before** the alpine alias tags are appended to `all_tags`, because upstream blocks will not contain the locally derived `-alpine` alias list. A falsy manifest or no match yields `None`. 2. `official = get_block_gitcommit(block)` extracts reconciliation's target: the first line starting with `GitCommit:`, taking the text between the first and second colon, stripped. A `None` block, or one without such a line, yields `None`. 3. `has_changed(local, official, dfdir)` decides whether the image content moved (semantics below). 4. `commit = official if official and not has_changed(...) else local`, and the block is written with `GitCommit: {commit}`. ### Failure philosophy: default to "changed" Every uncertainty resolves to local HEAD, never to an error: - **Fetch failure**: `fetch_official_manifest()` wraps the whole request in `try/except Exception` and returns `""`. It never raises. An empty manifest makes every `find_manifest_block` lookup return `None`, so all blocks fall back to local HEAD — publishing still succeeds; the worst case is redundant Docker Hub rebuilds. - **New tag**: never published upstream, so no matching block → `None` → local HEAD (which is what forces the first build). - **Upstream block without a `GitCommit:` line** → `None` → local HEAD. - **Falsy upstream hash on a direct `has_changed` call**: a falsy `official_gitcommit` returns True immediately, before any git invocation — no diff subprocess is run. In the pipeline this path is masked by `generate_manifest`'s `official and` guard (a `None` hash already forces local HEAD without calling `has_changed`), but it is reachable on direct calls. - **`git diff` nonzero exit** (e.g., the Dockerfile blob is missing in either commit) → treated as changed. - **Any exception inside the diff step** → treated as changed. The asymmetry is deliberate and test-visible: fetching is soft-fail, but `get_git_commit()` has *no* fallback — it uses `check=True`, so running outside a git checkout raises `CalledProcessError` and aborts manifest generation. ### `has_changed` semantics Before any git invocation, a falsy upstream hash short-circuits to changed: `if not official_gitcommit: return True`, so `has_changed(local, None, dfdir)` returns True without running a single subprocess. Given a truthy hash, the function diffs blobs across commits, not the working tree: `git diff local:<dfdir>/Dockerfile official:<dfdir>/Dockerfile`. A nonzero returncode means changed; otherwise the stdout line count is accumulated. If `<dfdir>/entrypoint.sh` exists (checked with `os.path.exists` against the *current* checkout, not the commits), the same diff runs for it and its line count is added. The image counts as unchanged only when the upstream hash is truthy *and* the summed diff output is zero lines — i.e., both files identical between the two commits. Any single differing line, a falsy hash, or any failure, forces local HEAD. ### State, ordering, and idempotence The four reconciliation helpers (`get_git_commit`, `fetch_official_manifest`, `get_block_gitcommit`, `has_changed`) are read-only; `generate_manifest`'s only mutation is writing the assembled manifest lines to `output_file` (a truncating write) — its sole persisted side effect. Fetch once, reuse for every block — per-block re-fetching is never done. Ordering constraints: (a) both captures precede the version loop; (b) block matching precedes alpine alias appending. Re-running the script on an unchanged tree converges: unchanged images keep referencing the upstream hash, so the emitted manifest stays stable across regenerations. ### Matching is substring-based `find_manifest_block` does not compare tag *sets*; it checks whether the exact `all_tags` string appears anywhere inside a block. Re-implementations must therefore build tags in the same order and formatting `generate_manifest` does (full version tag, version tag, then the jdk-only shared tag, comma+space separated), or upstream blocks will silently not match and every image degrades to local HEAD — still valid output, just extra rebuilds. ### Test-sensitive behavior - Tests patch module-level attributes `dockerhub_doc_config_update.get_git_commit` and `fetch_official_manifest` (e.g., `""` and `"abc123"`) and assert the output contains `GitCommit: abc123` — exercising the empty-upstream fallback without git or network. - `get_block_gitcommit`: `None` → `None`; block lacking the line → `None`; otherwise the stripped hash (e.g., `abc123def`). - `find_manifest_block`: no match → `None`; `""` and `None` manifests → `None` (falsy check, not an exception). - `fetch_official_manifest` must swallow *all* exceptions and return `""`; raising would break the documented degradation path. - `has_changed`: a falsy `official` returns True immediately without invoking git — no subprocess is run; only a truthy hash reaches the diff path. - `get_git_commit` returns stripped stdout; unpatched tests require a real git checkout. #### Exact API Reference #### `dockerhub_doc_config_update.get_block_gitcommit` - **Import Path**: `from dockerhub_doc_config_update import get_block_gitcommit` - **Required Test Import Paths**: - dockerhub_doc_config_update.get_block_gitcommit - **Exact Test Import Statements**: - from dockerhub_doc_config_update import ( find_manifest_block, format_ojdk_version, get_block_gitcommit, get_distro_name, get_dockerfile_arches, get_java_version, generate_manifest, ) - **Kind**: function - **Signature**: ```python def get_block_gitcommit(block) ``` - **Behavior**: Extract GitCommit from a manifest block. #### `dockerhub_doc_config_update.fetch_official_manifest` - **Import Path**: `from dockerhub_doc_config_update import fetch_official_manifest` - **Required Test Import Paths**: - dockerhub_doc_config_update.fetch_official_manifest - **Exact Test Import Statements**: - from dockerhub_doc_config_update import fetch_official_manifest - **Kind**: function - **Signature**: ```python def fetch_official_manifest() ``` - **Behavior**: Fetch the current official manifest for diff comparison. #### `dockerhub_doc_config_update.get_git_commit` - **Import Path**: `from dockerhub_doc_config_update import get_git_commit` - **Required Test Import Paths**: - dockerhub_doc_config_update.get_git_commit - **Exact Test Import Statements**: - from dockerhub_doc_config_update import get_git_commit - **Kind**: function - **Signature**: ```python def get_git_commit() ``` ## Detailed Implementation Nodes ### Node: Adoptium release metadata access ## Functional constraints - Endpoint constant `ADOPTIUM_API_URL = "https://api.adoptium.net/v3/info/available_releases"`; GET with `User-Agent: Adoptium Dockerfile Updater`; body is UTF-8 JSON. - No caching, retries, or timeout inside the module; every public call performs its own fetch. - Required payload keys: `available_lts_releases`, `available_releases`, `most_recent_lts`, `most_recent_feature_release` (missing key raises `KeyError`). - `get_supported_versions()` = `sorted(set(available_lts_releases) | {v for most_recent_lts < v <= most_recent_feature_release if v in available_releases})`; returns an ascending list of `int`. - Non-LTS versions `<= most_recent_lts` are excluded; non-LTS versions above `most_recent_lts` are included only when listed in `available_releases`; `most_recent_feature_release <= most_recent_lts` degenerates to the sorted LTS list without error. - `get_latest_lts()` returns `most_recent_lts` unchanged. - `response.read()` must yield bytes (module UTF-8-decodes it); the response is used as a context manager. `URLError`, `HTTPError`, and `JSONDecodeError` propagate uncaught. - For deterministic tests, stub `adoptium_api._fetch_release_data`; public names are bound by value in importing modules, so patching them there does not redirect the underlying fetch. ## Example ```python from unittest.mock import patch from adoptium_api import get_supported_versions, get_latest_lts FAKE = { "available_lts_releases": [8, 11, 17, 21, 25], "available_releases": [8, 11, 16, 17, 21, 25, 26], "most_recent_lts": 25, "most_recent_feature_release": 26, } with patch("adoptium_api._fetch_release_data", return_value=FAKE): assert get_supported_versions() == [8, 11, 17, 21, 25, 26] # 16 dropped, 26 kept assert get_latest_lts() == 25 ``` ### Node: OS end-of-life checking and warnings ## Functional constraints - `get_eol_date(cfg)`: truthy hardcoded `eol` first (`date` passed through; other values stringified and parsed `%Y-%m-%d`, with an uncaught `ValueError` on malformed input; falsy values fall through to the lookup path), else `OS_TO_PRODUCT["os"]` → `_extract_cycle(image)` → `fetch_eol_date`. Unmapped `os` or unextractable cycle ⇒ `None`, no HTTP call. - `OS_TO_PRODUCT`: `ubuntu→ubuntu`, `alpine-linux→alpine`, `ubi-minimal→rhel`; anything else absent. - `_extract_cycle`: try `$`-anchored `:(\d[\d.]*)$` then unanchored `/ubi(\d+)` (requires `/` before `ubi`); `ubuntu:26.04`→`26.04`, `redhat/ubi9-minimal`→`9`; bare `ubi10-minimal`, `scratch`, `ltsc2022` → `None`. - `fetch_eol_date`: `GET {ENDOFLIFE_API}/{product}/{cycle}.json`, `User-Agent: Adoptium EOL Checker`, timeout 10s; `eol` bool → `None`, `"YYYY-MM-DD"` → `date`; any exception → `None` (never raises). - `check_eol_configs(config)`: iterate `config.get("configurations", {})` per OS family; collect `(cfg, eol_date)` where `eol_date <= date.today()` (inclusive); undated entries skipped; entries with a truthy `eol` override still count even when `os` is unmapped (e.g. Windows), because the override is evaluated before the os mapping. - `print_eol_warnings(config, file=sys.stderr)`: delegates to `check_eol_configs`; on expiry prints `\n⚠ {N} distro(s) past EOL:` then ` - {image} ({directory}) expired {eol_date}` per entry (image falls back to directory, then `unknown`); always returns the expired list. Called by `dockerhub_doc_config_update.main()` (default stderr, before `generate_manifest`) and by `eol_checker.__main__` with `file=sys.stdout`. - `get_distro_name(os_family, directory)`: last `/` segment; `alpine-linux` → `alpine-{name}`. - `get_dockerfile_arches(path)`: case-label regex per line, mapped via `DOCKERFILE_ARCH_MAP`, unmapped dropped, `sorted(set(...))`. - Tests patch `eol_checker.urllib.request.urlopen` (context manager, `read()` → JSON bytes) and `eol_checker.get_eol_date`/`fetch_eol_date` directly; integration test requires fetchable dates for all non-`windows` temurin.yml entries. ## Example ```python from datetime import date from unittest.mock import patch from eol_checker import check_eol_configs, get_eol_date cfg = {"configurations": {"linux": [ {"os": "ubuntu", "image": "ubuntu:24.04", "directory": "ubuntu/noble"}]}} with patch("eol_checker.get_eol_date", return_value=date(2020, 1, 1)): expired = check_eol_configs(cfg) # [(cfg_entry, date(2020, 1, 1))] get_eol_date({"os": "ubi-minimal", "image": "redhat/ubi9-minimal"}) # -> fetch_eol_date("rhel", "9") ``` ### Node: Version-aware architecture resolution ## Functional constraints - Pure function over lists; no I/O, no API access. - Falsy `overrides` → returns `default_architectures` itself (same object, not a copy). - Otherwise operates on a shallow copy; never mutates the inputs. - Condition must fully match `^(==|!=|>=|<=|>|<)(\d+)$` after `.strip()`; integer comparison via `operator` module against the int-parsed target. - Invalid condition → `ValueError: Invalid version condition: '<condition>'` (condition in single quotes); raised in iteration order, aborts the call. - All matching overrides apply in list order; each later override sees the accumulated result. - Within a matching override, actions run in fixed order: `architectures` (full replacement, no intersection) → `exclude` (membership filter) → `include` (append entries not already present, keep include order, dedupe only against current result). - Caller composes overrides as global-list + per-config-list; resolution is per (configuration, version). - Result feeds binary filtering under raw Adoptium arch names; a fully filtered result causes downstream skip, not an error. - `versions` key required (`KeyError` if absent); a matching override with no action keys is a no-op; a non-int `version` raises `TypeError` only under the ordering operators (`<`, `<=`, `>`, `>=`), while `==` and `!=` comparisons with a non-int `version` do not raise — `==` never matches and `!=` always matches. ## Example ```python from generate_dockerfiles import resolve_architectures default = ["aarch64", "arm", "ppc64le", "riscv64", "s390x", "x64"] overrides = [ {"versions": "==8", "exclude": ["s390x"]}, {"versions": "<17", "exclude": ["riscv64"]}, {"versions": ">=21", "exclude": ["arm"]}, ] resolve_architectures(default, overrides, 8) # ['aarch64', 'arm', 'ppc64le', 'x64'] resolve_architectures(default, overrides, 21) # ['aarch64', 'ppc64le', 'riscv64', 's390x', 'x64'] ``` Avoid mutating the returned list when passing an empty override list; the original default object is returned unchanged. ### Node: Templated Dockerfile and entrypoint generation ## Functional constraints - Jinja2 `FileSystemLoader` rooted at `docker_templates/`; the Dockerfile template name is exactly `f"{os}.Dockerfile.j2"` from the configuration's `os`; a missing template raises `TemplateNotFound` uncaught. `trim_blocks=False, lstrip_blocks=False`. - Dockerfile context keys: `base_image`, `image_type`, `java_version`, `version` (integer major), `arch_data`, `os_family`, `os`. `os_family` is used both in the release query (`&os=`) and to filter binaries. - Linux `arch_data`: `{archHelper(arch, os_name): {"download_url", "checksum"}}` from `binary["package"]`, restricted to binaries with `binary["os"] == os_family` and architecture in the resolved list; the dict is sorted by key before rendering. - Windows `arch_data`: one flat dict from `binary["installer"]` (`download_url`, `checksum`) plus `copy_from` = version string with `jdk` stripped (and, for version != 8, `-` removed and `+`→`_`), suffixed `-<image_type>-windowsservercore-<base_image tag>`. - `java_version`: 8 → `release_name` verbatim; else `"jdk-" + openjdk_version` with `-LTS` removed. - Entrypoint: `entrypoint.sh.j2` rendered only when `os_family != "windows"`, context exactly `image_type`, `os`, `version`; written beside the Dockerfile, no chmod. - Skips, in order: `version >= deprecated` (before any request), HTTP 404 (print + continue), empty `arch_data` (no write; previously generated files persist). Non-404 HTTP errors propagate via `raise_for_status`. - `get_java_version` parsing (the round-trip contract): scans the Dockerfile line by line; the FIRST line containing the substring `JAVA_VERSION=` wins — a substring match, not anchored to `ENV`, so `ARG` or comment lines containing the substring match first; the value is `line.split("=")[1].strip()`, the second `=`-delimited field, with any trailing `=`-separated parts of the line discarded; returns `None` when no line matches. Downstream manifest generation treats `None` as a skip of that directory, so the parse-breaking change is losing or renaming the `JAVA_VERSION=` marker line; the `jdk-`/`8u` value conventions matter only to `format_ojdk_version` tag formatting (strip a leading `jdk`/`jdk-`, `+`→`_`). - `--force` removes top-level digit-named directories; API responses are disk-cached for 3600 s. ## Usage ```python from jinja2 import Environment, FileSystemLoader env = Environment(loader=FileSystemLoader("docker_templates"), trim_blocks=False, lstrip_blocks=False) arch_data = {"amd64": {"download_url": "https://.../OpenJDK11U-jdk_x64_linux_hotspot.tar.gz", "checksum": "abc123"}} dockerfile = env.get_template("ubuntu.Dockerfile.j2").render( base_image="ubuntu:24.04", image_type="jdk", java_version="jdk-11.0.28+6", version=11, arch_data=arch_data, os_family="linux", os="ubuntu") open("11/jdk/ubuntu/noble/Dockerfile", "w").write(dockerfile) entrypoint = env.get_template("entrypoint.sh.j2").render( image_type="jdk", os="ubuntu", version=11) open("11/jdk/ubuntu/noble/entrypoint.sh", "w").write(entrypoint) ``` ### Node: Dockerfile metadata extraction and tag derivation ## Functional constraints - `get_java_version` returns the whitespace-stripped substring after the **first** `=` on the first line containing `JAVA_VERSION=`; `None` if absent; extra `=` truncates the value; `.strip()` is applied before returning. - `format_ojdk_version` strips regex `^jdk-?`, then maps `+` → `_`; no validation, never raises for `str`; idempotent for already-stripped versions. - `get_distro_name` returns the last `/` component of `directory`; prefixes `alpine-` only for the exact family string `alpine-linux`. - `get_dockerfile_arches` matches case arms `\s+(\w+)\)\s*\\?\s*$`, keeps only names in `DOCKERFILE_ARCH_MAP`, translates to Hub labels, returns `sorted(set(...))`; `[]` on no matches. - `find_manifest_block` splits on `\n\n`, returns the first block containing `tags_str` as a substring, else `None`; falsy manifest → `None`. - `get_block_gitcommit` reads a line starting with `GitCommit:`, value after first colon, stripped; `None` for falsy block or no line. - `generate_manifest` skips entries with no Dockerfile or no `JAVA_VERSION`; family order is alpine-linux, linux, windows; jre after jdk; `latest` shared tag only for jdk, non-alpine, latest LTS; non-nanoserver Windows `SharedTags:` = windows-version tags + distro-stripped tags (+ `latest` for jdk latest LTS), while nanoserver shares the windows-version tags only; alpine alias tags apply only to the default alpine image, and `SharedTags:` lines are emitted for every Windows entry and the default Linux image; manifest-block lookup occurs before alias tags are appended. ### Example ```python from dockerhub_doc_config_update import ( format_ojdk_version, get_java_version, get_distro_name, get_dockerfile_arches, ) df = "21/jdk/ubuntu/noble/Dockerfile" full = get_java_version(df) # "jdk-21.0.5+11" tag = format_ojdk_version(full) # "21.0.5_11" distro = get_distro_name("linux", "ubuntu/noble") # "noble" print(f"{tag}-jdk-{distro}, 21-jdk-{distro}, 21") arches = get_dockerfile_arches(df) # e.g. ['amd64', 'arm64v8'] ``` ### Node: Official Docker Hub manifest generation ## Functional constraints - **CWD-sensitive:** `git rev-parse HEAD`, the `config/temurin.yml` load, and Dockerfile existence checks all resolve relative to the process CWD; run from the repository root. `git rev-parse HEAD` runs with `check=True`: an unresolvable HEAD (e.g. a non-git temp tree) makes `generate_manifest` raise and write nothing; only the upstream manifest fetch degrades silently to an empty string, so tests must mock the git lookup or run inside a repo. - **Config contract:** `config["configurations"]` keyed by `linux`, `alpine-linux`, `windows`; `linux` and `alpine-linux` must exist and be non-empty because the defaults are dereferenced pre-loop (`configurations["linux"][0]`, `configurations["alpine-linux"][0]` — a missing key raises `KeyError`, an empty list `IndexError`, before any output); only `windows` may be absent. Every entry must carry both `directory` and `architectures` keys even though the `architectures` value is unused here; optional `versions` (integer list restricting blocks) and `deprecated` (version number where blocks stop). The first `linux` and first `alpine-linux` entries define default-image behavior. - **Matching is substring-based:** `find_manifest_block` returns the first blank-line-separated block containing the tag string, not an exact tag-list equality check; pass the exact comma-joined tag list that generation builds. Empty/`None` manifest or no match yields `None`. - **Commit extraction is tolerant:** `get_block_gitcommit` accepts `None` and blocks without a `GitCommit:` line; both yield `None`. - **Reuse rule:** the upstream commit is kept only when both the Dockerfile diff and (when the file exists) the entrypoint.sh diff are empty and the git diff exits 0; any failure forces the local HEAD commit. - **Output invariants:** exactly one blank line between blocks inside a version; two blank lines plus the version banner comment at version boundaries, with no blank line between the banner and that version's first block; no trailing blank lines, exactly one final newline, header always present even with zero blocks (a zero-block file is header + one banner comment per supported version). - **Ordering guarantees:** ascending version, `jdk` before `jre`, then alpine-linux → linux → windows, then config file order. - **SharedTags scope:** the `SharedTags:` line is emitted for every Windows block and every block whose distro equals the default Linux distro, regardless of package (a default-Linux JRE block emits `SharedTags: <full>-jre, <ver>-jre`, never `latest`); it is omitted for default-alpine and non-default Linux blocks; `latest` only for JDK on the latest LTS, never on alpine; `-alpine` aliases are appended to `Tags:` only for the default alpine distro and only after commit comparison, formed from the distro-stripped shared tags each suffixed `-alpine`. ## Example ```python import dockerhub_doc_config_update as d d.get_git_commit = lambda: "0" * 40 # mock the HEAD lookup or run inside a git repo d.fetch_official_manifest = lambda: "" # offline: every block uses local GitCommit d.generate_manifest(d.load_config(), "eclipse-temurin") with open("eclipse-temurin") as f: content = f.read() assert content.endswith("\n") and not content.endswith("\n\n") assert "Builder: buildkit" in content # header survives even with no Dockerfiles ``` ### Node: Upstream manifest comparison and GitCommit reconciliation ## Functional constraints - `get_git_commit()` — runs `git rev-parse HEAD` (`capture_output=True, text=True, check=True`); returns stripped stdout. No fallback: raises outside a git repo, aborting generation. - `fetch_official_manifest()` — GETs `OFFICIAL_MANIFEST_URL` (raw `library/eclipse-temurin` from docker-library/official-images@master), returns decoded UTF-8 text. Catches **every** exception and returns `""`; never raises. `""` is the "no upstream data" sentinel. - `get_block_gitcommit(block)` — pure extraction: falsy block → `None`; first line with prefix `GitCommit:` → text between first and second colon, stripped; otherwise `None`. No I/O. - Reconciliation in `generate_manifest`: capture HEAD and upstream text once before the version loop. Per entry (only if `Dockerfile` exists): match the upstream block by substring containment of the comma-joined `all_tags` **before** alpine alias tags are appended; adopt the upstream commit only if a hash was extracted *and* `has_changed(local, official, dfdir)` is false; every other outcome writes local HEAD. The assembled lines are written to `output_file` (truncating write) — the pipeline's only mutation. - `has_changed` — default-changed. A falsy `official_gitcommit` returns True immediately, before any git invocation (no subprocess is run). Given a truthy hash, `git diff local:<dir>/Dockerfile official:<dir>/Dockerfile`: nonzero exit → changed; else accumulate stdout line count. If `dfdir/entrypoint.sh` exists in the working tree, add its diff count too. Unchanged ⇔ the upstream hash is truthy and total diff lines == 0. Any exception → changed. - Consequence: fetch errors, missing upstream blocks, missing `GitCommit:` lines, falsy hashes passed directly to `has_changed`, and diff failures all degrade to local HEAD (extra Docker Hub rebuilds at worst, never failed publishing). ### Example ```python from dockerhub_doc_config_update import ( get_git_commit, fetch_official_manifest, find_manifest_block, get_block_gitcommit, has_changed) local = get_git_commit() # HEAD sha; raises if not a repo upstream = fetch_official_manifest() # "" on any fetch failure block = find_manifest_block(upstream, "25.0.2_10-jdk-noble, 25-jdk-noble") official = get_block_gitcommit(block) # None if block/line missing if official and not has_changed(local, official, "25/jdk/ubuntu/noble"): commit = official # unchanged -> reuse upstream sha else: commit = local # changed/unknown -> force rebuild print(f"GitCommit: {commit}") ```
# adoptium/containers
## Project Overview
The adoptium/containers repository holds the Dockerfiles that build the official Adoptium images of the Eclipse Temurin distribution of OpenJDK, published on Docker Hub. Its purpose is to keep a large family of Java runtime images — spanning JDK and JRE variants of Temurin 8, 11, 17, 21, 25 and 26 — continuously up to date across Alpine, UBI, Ubuntu and Windows base operating systems and many CPU architectures, while delegating the actual image building and publishing to Docker Hub via the official-images manifest.
The repository is primarily a generation pipeline rather than hand-maintained Dockerfiles. The central script, generate_dockerfiles.py, renders Dockerfiles from Jinja2 templates in docker_templates/, driven by per-version configuration in config/ that defines defaults and overrides for architectures, OS variants, package handling, and version conditions. It queries the Adoptium API (via adoptium_api.py) for the latest published release binaries for each supported version, caches responses, resolves effective architecture lists by applying version-conditioned include/exclude rules, and writes the resulting Dockerfiles into the <version>/<jdk|jre>/<alpine|ubi|ubuntu|windows>/<os-version> directory tree. eol_checker.py supplements this by warning when releases near end-of-life.
Automation is provided by GitHub Actions: an updater workflow runs roughly every half hour, invoking generate_dockerfiles.py to open 'Update Dockerfiles' pull requests whenever new Temurin binaries appear. After maintainers review and merge, dockerhub_doc_config_update.py regenerates the official Docker Hub manifest file (_eclipse-temurin) describing tags and architectures, which maintainers submit to docker-library/official-images so Docker Hub rebuilds and publishes the images. Supporting tooling includes sanity.sh, tests such as test_generate_dockerfiles.py and test_eol_checker.py, and documentation (CONTRIBUTING.md, DISTRO_MAINTENANCE.md) describing release cadence, quarterly PSU updates, security rebuild policy, and distro-specific maintenance practices.
Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.
## Submission Constraints (read carefully — the evaluation depends on these)
This is a **closed-book** task. The graded test suite is **hidden** and will be
injected into the workspace at evaluation time. To be scored correctly you MUST
follow these rules:
1. **Do NOT create or modify any files under the test directories** (e.g.
`tests/`, `test/`, `testing/`, or files named `test_*.py` / `conftest.py`).
The grader injects its own test files at those paths; any file you place
there will collide with the injected suite and cause the whole evaluation to
score 0. Implement **only** the library/source code — never the tests.
2. **Your package MUST be importable by the name the tests use.** The hidden
tests `import` your package by its documented top-level name (see the
Project Directory Structure and API Usage Guide below). Provide a valid
`pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that
`pip install -e .` succeeds and the package imports cleanly. If your package
is not installable/importable, every test errors out and the reward is 0.
3. **Match the documented module paths and public API exactly** (names,
signatures, and any literal error/exception strings). Internal helpers not
listed in the API guide may be implemented however you like.
## Install / Reconstruction Contract
Follow this contract before implementing the documented APIs:
- **Project root**: `/workspace/repo` at runtime; the submitted repository root is `.`.
- **Package/distribution name**: `(unnamed project)`
- **Package roots**: `.`
- **Install strategy**: `source-roots`
- **Import/entry**: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
- **Provision commands**:
```bash
python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuK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$@"; }
export -f programgen_pip_install
programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel
```
- **Runtime setup**:
```bash
export PYTHONPATH="$PWD:${PYTHONPATH:-}"
```
- **Project root for installation**: `.`
- **Build-version environment**: `SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0`, `PDM_BUILD_SCM_VERSION=0.0.0`, `POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0`, `UV_DYNAMIC_VERSIONING_BYPASS=0.0.0`
- **Test directory**: `(not available)`
- **Test command**: `bash -lc 'exec python3 -c '"'"'import json, os, sys, unittest
from collections import defaultdict
contract = json.loads(sys.argv[1])
limit = int(sys.argv[2])
coverage = None
if os.environ.get('"'"'"'"'"'"'"'"'COVERAGE_FILE'"'"'"'"'"'"'"'"'):
from coverage import Coverage
coverage = Coverage(source=['"'"'"'"'"'"'"'"'.'"'"'"'"'"'"'"'"'])
coverage.start()
class Result(unittest.TextTestResult):
outcomes = None
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.outcomes = {}
def record(self, test, outcome):
identity = '"'"'"'"'"'"'"'"'unittest::'"'"'"'"'"'"'"'"' + test.id()
self.outcomes[identity] = outcome
status = {'"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'PASSED'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'FAILED'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'ERROR'"'"'"'"'"'"'"'"', '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"': '"'"'"'"'"'"'"'"'SKIPPED'"'"'"'"'"'"'"'"'}[outcome]
print('"'"'"'"'"'"'"'"'\n'"'"'"'"'"'"'"'"' + identity + '"'"'"'"'"'"'"'"' '"'"'"'"'"'"'"'"' + status, flush=True)
def addSuccess(self, test):
super().addSuccess(test)
self.record(test, '"'"'"'"'"'"'"'"'passed'"'"'"'"'"'"'"'"')
def addFailure(self, test, error):
super().addFailure(test, error)
self.record(test, '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"')
def addError(self, test, error):
super().addError(test, error)
self.record(test, '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"')
def addSkip(self, test, reason):
super().addSkip(test, reason)
self.record(test, '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"')
def addExpectedFailure(self, test, error):
super().addExpectedFailure(test, error)
self.record(test, '"'"'"'"'"'"'"'"'skipped'"'"'"'"'"'"'"'"')
def addUnexpectedSuccess(self, test):
super().addUnexpectedSuccess(test)
self.record(test, '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"')
def addSubTest(self, test, subtest, error):
super().addSubTest(test, subtest, error)
if error is not None:
self.record(test, '"'"'"'"'"'"'"'"'failed'"'"'"'"'"'"'"'"' if issubclass(error[0], test.failureException) else '"'"'"'"'"'"'"'"'errors'"'"'"'"'"'"'"'"')