### Basic CLI usage examples Source: https://github.com/adoptium/containers Run from repo root to write manifest to ./eclipse-temurin, print to stdout, or preview with --dry-run. ```bash cd /workspace/home/containers python3 dockerhub_doc_config_update.py # writes ./eclipse-temurin python3 dockerhub_doc_config_update.py /dev/stdout # print manifest to stdout python3 dockerhub_doc_config_update.py --dry-run # preview only ``` -------------------------------- ### get_supported_versions() error handling example Source: https://github.com/adoptium/containers Example of catching URLError and KeyError when calling get_supported_versions(). Exits with SystemExit(1) on failure. ```python from adoptium_api import get_supported_versions import urllib.error try: versions = get_supported_versions() except urllib.error.URLError as error: print(f"cannot reach the Adoptium API: {error.reason}") raise SystemExit(1) except KeyError as error: print(f"unexpected API response, missing key: {error}") raise SystemExit(1) ``` -------------------------------- ### Generate Dockerfiles Locally Source: https://github.com/adoptium/containers/blob/main/DISTRO_MAINTENANCE.md Commands to install requirements and run the Dockerfile generator with --force. Verify that Dockerfiles are generated in expected directories. ```bash pip3 install -r requirements.txt python3 generate_dockerfiles.py --force ``` -------------------------------- ### get_latest_lts() example Source: https://github.com/adoptium/containers Example of calling get_latest_lts() and printing the latest LTS version. ```python from adoptium_api import get_latest_lts latest = get_latest_lts() print(f"latest LTS is Java {latest}") ``` -------------------------------- ### get_supported_versions() basic call example Source: https://github.com/adoptium/containers Example of calling get_supported_versions() and iterating over the returned versions. The comment shows a sample output when LTS are [8, 11, 17, 21, 25] and the most recent feature release is 27. ```python from adoptium_api import get_supported_versions versions = get_supported_versions() # e.g. [8, 11, 17, 21, 25, 27] when LTS are [8, 11, 17, 21, 25] # and the most recent feature release is 27 for version in versions: print(f"building Dockerfiles for Java {version}") ``` -------------------------------- ### CLI usage examples Source: https://github.com/adoptium/containers Shows common invocations: default manifest generation, piping to stdout, dry-run preview, creating a PR, and forcing partial publication for specific versions. ```bash python3 dockerhub_doc_config_update.py # generate manifest + report python3 dockerhub_doc_config_update.py /dev/stdout # manifest to stdout python3 dockerhub_doc_config_update.py --dry-run # preview a PR python3 dockerhub_doc_config_update.py --create-pr # open one PR for all READY versions python3 dockerhub_doc_config_update.py --force 17,21,25 # force partial publication ``` -------------------------------- ### Example temurin.yml configuration entry Source: https://github.com/adoptium/containers/blob/main/DISTRO_MAINTENANCE.md Defines a Linux distribution configuration in config/temurin.yml. The directory field becomes part of the Dockerfile output path, and the os field must match a Jinja2 template in docker_templates/. ```yaml configurations: linux: - directory: ubuntu/noble image: ubuntu:24.04 architectures: [aarch64, arm, ppc64le, riscv64, s390x, x64] os: ubuntu ``` -------------------------------- ### Programmatic usage example Source: https://github.com/adoptium/containers Shows how to use check_eol_configs and get_eol_date programmatically. Loads config/temurin.yml and prints the EOL date for the first linux configuration and the count of expired distros. ```python import yaml from eol_checker import check_eol_configs, get_eol_date config = yaml.safe_load(open("config/temurin.yml")) eol = get_eol_date(config["configurations"]["linux"][0]) print("ubuntu EOL:", eol) expired = check_eol_configs(config) print("expired distros:", len(expired)) ``` -------------------------------- ### Example usage of archHelper and add_missing_architectures Source: https://github.com/adoptium/containers Shows basic calls to archHelper and add_missing_architectures. The archHelper calls return 'amd64', 'x86_64', and 'arm64' respectively; add_missing_architectures adds 'arm64' with {'pending': True} to the input dict. ```python from generate_dockerfiles import archHelper, add_missing_architectures archHelper("x64", "ubuntu") # 'amd64' archHelper("x64", "alpine-linux") # 'x86_64' archHelper("aarch64", "ubuntu") # 'arm64' arch_data = { "amd64": {"download_url": "...", "checksum": "..."}, } add_missing_architectures(arch_data, ["x64", "aarch64"], "ubuntu") # -> {'amd64': {...}, 'arm64': {'pending': True}} ``` -------------------------------- ### Add Configuration Entry to temurin.yml Source: https://github.com/adoptium/containers/blob/main/DISTRO_MAINTENANCE.md YAML entry for a new distribution in config/temurin.yml. Place it under the appropriate OS family, ordered with newest/preferred distro first. Example shows Ubuntu 28.04 (Xenial Xerus) with EOL April 2033. ```yaml linux: # EOL April 2033 - directory: ubuntu/xenial-xerus image: ubuntu:28.04 architectures: [aarch64, arm, ppc64le, riscv64, s390x, x64] os: ubuntu ``` -------------------------------- ### Error handling example for resolve_architectures Source: https://github.com/adoptium/containers Demonstrates the ValueError raised when an override's 'versions' string does not match the expected pattern. The error message includes the invalid condition text. ```python from architecture_config import resolve_architectures try: resolve_architectures( ["x64"], [{"versions": "between 8 and 11", "exclude": ["s390x"]}], 8, ) except ValueError as error: print(error) # Invalid version condition: 'between 8 and 11' ``` -------------------------------- ### Basic call example for resolve_architectures Source: https://github.com/adoptium/containers Shows typical usage with version-specific exclusions. For version 8, s390x is excluded; for 21 and 25, arm is excluded. The function returns the effective architecture list after applying all matching overrides in order. ```python from architecture_config import resolve_architectures defaults = ["aarch64", "arm", "ppc64le", "s390x", "x64"] overrides = [ {"versions": "==8", "exclude": ["s390x"]}, # no s390x JIT for JDK 8 {"versions": "<17", "exclude": ["riscv64"]}, # riscv64 only for 17+ {"versions": ">=21", "exclude": ["arm"]}, # no arm32 for 21+ ] resolve_architectures(defaults, overrides, 8) # ['aarch64', 'arm', 'ppc64le', 'x64'] resolve_architectures(defaults, overrides, 21) # ['aarch64', 'ppc64le', 's390x', 'x64'] resolve_architectures(defaults, overrides, 25) # ['aarch64', 'ppc64le', 's390x', 'x64'] ``` -------------------------------- ### Python CLI entry point for generate_dockerfiles.py Source: https://github.com/adoptium/containers Sets up argument parsing for the Dockerfile generator. Installs a requests cache with a 3600-second expiry, configures a Jinja2 environment with the docker_templates loader, and defines a --force flag to remove old version directories before regeneration. ```python if __name__ == "__main__": requests_cache.install_cache("adoptium_cache", expire_after=3600) parser = argparse.ArgumentParser( description="Generate Dockerfiles for Eclipse Temurin images" ) # Setup the Jinja2 environment env = Environment( loader=FileSystemLoader("docker_templates"), trim_blocks=False, lstrip_blocks=False ) headers = { "User-Agent": "Adoptium Dockerfile Updater", } # Flag for force removing old Dockerfiles parser.add_argument("--force", action="store_true", help="Force remove old Dockerfiles") args = parser.parse_args() ``` -------------------------------- ### Programmatic use of archHelper for architecture mapping Source: https://github.com/adoptium/containers Shows how to call archHelper from generate_dockerfiles to map an architecture and OS family to the expected arch key. For example, aarch64 maps to 'arm64' on ubuntu but stays 'aarch64' on alpine-linux. ```python from generate_dockerfiles import archHelper arches_by_os = { "ubuntu": archHelper("aarch64", "ubuntu"), # 'arm64' "alpine-linux": archHelper("aarch64", "alpine-linux"), # 'aarch64' } ``` -------------------------------- ### ADOPTIUM_API_URL constant Source: https://github.com/adoptium/containers Base endpoint for the Adoptium available_releases info resource. Used by _fetch_release_data() to perform the HTTP GET. ```python ADOPTIUM_API_URL = "https://api.adoptium.net/v3/info/available_releases" ``` -------------------------------- ### Fetch release assets from Adoptium API with 404 handling Source: https://github.com/adoptium/containers Performs an HTTP GET to the Adoptium API for a specific version, image type, and OS family. On HTTP 404, prints a skip message and continues; other non-2xx responses raise an HTTPError via raise_for_status(). On success, uses the first item of the JSON array as the release. ```python url = f"https://api.adoptium.net/v3/assets/feature_releases/{version}/ga?page=0&image_type={image_type}&os={os_family}&page_size=1&vendor=eclipse" response = requests.get(url, headers=headers) # Handle 404 errors gracefully - skip this version if not available if response.status_code == 404: print(f"Version {version} not available for {image_type} on {os_family}, skipping...") continue response.raise_for_status() data = response.json() release = response.json()[0] ``` -------------------------------- ### format_ojdk_version(full_version) - Convert JAVA_VERSION to Docker tag-compatible string Source: https://github.com/adoptium/containers Strips a leading 'jdk' or 'jdk-' and replaces '+' with '_' to produce a tag-safe version. For example, jdk8u482-b08 becomes 8u482-b08 and jdk-25.0.1+9 becomes 25.0.1_9. ```python def format_ojdk_version(full_version): """Convert JAVA_VERSION to Docker tag-compatible version string. Examples: jdk8u482-b08 -> 8u482-b08 jdk-25.0.1+9 -> 25.0.1_9 """ version = re.sub(r"^jdk-?", "", full_version) version = version.replace("+", "_") return version ``` -------------------------------- ### get_entry_release(entry) - Extract release portion from first tag Source: https://github.com/adoptium/containers Takes the first tag from the entry's Tags field (split on ', ') and extracts the text before '-jdk-' or '-jre-'. Returns None if no match is found. Example: 25.0.1_9. ```python def get_entry_release(entry): tag = entry.get("Tags", "").split(", ", 1)[0] match = re.match(r"^(.+?)-(?:jdk|jre)-", tag) return match.group(1) if match else None ``` -------------------------------- ### _fetch_release_data() internal function Source: https://github.com/adoptium/containers Internal function that performs the HTTP GET to the Adoptium API. Sends a User-Agent header 'Adoptium Dockerfile Updater' and returns the parsed JSON. No exception handling is done here. ```python def _fetch_release_data(): """Fetch release info from the Adoptium API.""" req = urllib.request.Request( ADOPTIUM_API_URL, headers={"User-Agent": "Adoptium Dockerfile Updater"}, ) with urllib.request.urlopen(req) as response: return json.loads(response.read().decode("utf-8")) ``` -------------------------------- ### github_request(url) Source: https://github.com/adoptium/containers Performs a GitHub REST API GET request with optional authentication and returns the parsed JSON response. Raises OSError/URLError on network issues and JSONDecodeError on invalid JSON. ```APIDOC ## github_request(url) ### Description Performs a GitHub REST API GET request with optional authentication and returns the parsed JSON response. Raises OSError/URLError on network issues and JSONDecodeError on invalid JSON. ### Method Function ### Signature ```python def github_request(url): ``` ### Parameters - **url** (str) - Required - GitHub REST API URL. ### Return Type Parsed JSON (`dict`/`list`) ### Headers - `Accept: application/vnd.github+json` - `User-Agent: Adoptium Dockerfile Updater` - Optional `Authorization: Bearer ` ### Timeout 30 seconds ### Raises - `OSError`/`urllib.error.URLError` - `json.JSONDecodeError` ### Source `dockerhub_doc_config_update.py:138` ``` -------------------------------- ### Deprecating UBI 9 Minimal starting from Java 25 in temurin.yml Source: https://github.com/adoptium/containers/blob/main/DISTRO_MAINTENANCE.md Add a `deprecated` field to the distribution's entry in `temurin.yml`. The value is the Java major version at which to stop generating Dockerfiles. Java versions below the threshold continue to receive Dockerfile updates, while the specified version and later do not generate Dockerfiles. ```yaml - directory: ubi/ubi9-minimal architectures: [aarch64, ppc64le, s390x, x64] image: redhat/ubi9-minimal deprecated: 25 os: ubi-minimal ``` -------------------------------- ### Create PR for all unpublished READY Java versions and retired image cleanup Source: https://github.com/adoptium/containers/blob/main/README.md Run without version selection to open one PR for all unpublished READY Java versions and retired image cleanup. BLOCKED, UNKNOWN, UP TO DATE, and PR OPEN versions are excluded; if no releases are READY, a cleanup-only PR is still created. Requires Git and an authenticated GitHub CLI. ```bash python3 dockerhub_doc_config_update.py --create-pr ``` -------------------------------- ### Dockerfile: Deploy Java via COPY from eclipse-temurin Source: https://github.com/adoptium/containers/blob/main/DISTRO_MAINTENANCE.md Encourages flexible deployment by copying the Temurin JDK from an official image onto any base image. Sets JAVA_HOME and PATH to the copied OpenJDK location. ```dockerfile FROM your-choice-of-base-image COPY --from=eclipse-temurin:21-jdk /opt/java/openjdk /opt/java/openjdk ENV JAVA_HOME=/opt/java/openjdk ENV PATH="${JAVA_HOME}/bin:${PATH}" ``` -------------------------------- ### Usage commands for generate_dockerfiles.py Source: https://github.com/adoptium/containers Shows how to run the script from the containers directory. Without --force, existing version directories are overwritten in place; with --force, stale version directories are removed first. ```bash cd /workspace/home/containers python3 generate_dockerfiles.py # update in place python3 generate_dockerfiles.py --force # remove stale version dirs first ``` -------------------------------- ### get_eol_date(configuration) Source: https://github.com/adoptium/containers Get the EOL date for a configuration entry. It first checks for a hardcoded 'eol' field, then falls back to querying the endoflife.date API based on the OS and image. ```APIDOC ## get_eol_date(configuration) ### Description Get the EOL date for a configuration entry. It first checks for a hardcoded 'eol' field, then falls back to querying the endoflife.date API based on the OS and image. ### Parameters - **configuration** (dict) - Required - One config entry dict (from `configurations[os_family]`). Reads keys `eol`, `os`, `image`. ### Return Type `datetime.date | None` — the EOL date, or `None` when it cannot be determined (no `eol` field, unknown `os` product, image version not extractable, or API lookup fails). ### Raises - **ValueError** - The hardcoded `eol` string is not parseable with `%Y-%m-%d` (this branch does not catch exceptions, unlike the API path). ### Example ```python def get_eol_date(configuration): """Get the EOL date for a configuration entry. Priority: 1. Hardcoded 'eol' field in the config (as fallback/override) 2. Lookup from endoflife.date API based on os + image """ # Check for hardcoded override first eol_str = configuration.get("eol") if eol_str: if isinstance(eol_str, date): return eol_str return datetime.strptime(str(eol_str), "%Y-%m-%d").date() os_name = configuration.get("os", "") image = configuration.get("image", "") product = OS_TO_PRODUCT.get(os_name) if not product: return None cycle = _extract_cycle(image) if not cycle: return None return fetch_eol_date(product, cycle) ``` ``` -------------------------------- ### main() Source: https://github.com/adoptium/containers CLI entry point that generates the Temurin manifest and reports publication readiness and retired-image cleanup. Supports options for creating a PR, dry-run preview, and forcing partial publication. ```APIDOC ## main() ### Description CLI entry point that generates the Temurin manifest and reports publication readiness and retired-image cleanup. Supports options for creating a PR, dry-run preview, and forcing partial publication. ### CLI Options - `output_file` (positional str) - Default: `eclipse-temurin` - Manifest output path (`/dev/stdout` to pipe). - `--create-pr` (flag) - Default: `False` - Open an upstream PR for all READY versions + retired-image cleanup (requires `git` and authenticated `gh`). - `--dry-run` (flag) - Default: `False` - Preview only; writes nothing, pushes nothing. - `--force VERSIONS` (set[int] comma-separated) - Default: `set()` - Force partial publication for the listed versions; prints the forced-publication plan and prompts `Open this upstream PR? [y/N]`. ### Exit Behaviour On `OSError`, `ValueError`, or `subprocess.CalledProcessError`, prints `Error: ...` (appending `CalledProcessError.stderr` when present) and exits `1`. Plain runs only write the manifest and report; `--create-pr`/`--dry-run`/`--force` also run the PR stage (`update_publication_prs` then `create_publication_pr`). ### Examples ```bash python3 dockerhub_doc_config_update.py # generate manifest + report python3 dockerhub_doc_config_update.py /dev/stdout # manifest to stdout python3 dockerhub_doc_config_update.py --dry-run # preview a PR python3 dockerhub_doc_config_update.py --create-pr # open one PR for all READY versions python3 dockerhub_doc_config_update.py --force 17,21,25 # force partial publication ``` ``` -------------------------------- ### OS_TO_PRODUCT mapping Source: https://github.com/adoptium/containers Maps configuration os values to endoflife.date product names. Note that ubi-minimal maps to the rhel product. ```python OS_TO_PRODUCT = { "ubuntu": "ubuntu", "alpine-linux": "alpine", "ubi-minimal": "rhel", } ``` -------------------------------- ### main() CLI entry point Source: https://github.com/adoptium/containers Builds the argument parser, loads config, generates the manifest, and optionally runs the PR stage. Exits with code 1 and prints 'Error: ...' on OSError, ValueError, or subprocess.CalledProcessError. ```python def main(): parser = argparse.ArgumentParser(description="Generate the Temurin manifest and report publication readiness and retired-image cleanup.") parser.add_argument("output_file", nargs="?", default="eclipse-temurin") parser.add_argument( "--create-pr", action="store_true", help="open an upstream PR for all unpublished READY Java versions and retired image cleanup (requires git and authenticated gh)", ) parser.add_argument( "--dry-run", action="store_true", help="preview READY release updates and retired image cleanup without writing files or creating a PR", ) parser.add_argument( "--force", type=parse_java_versions, default=set(), metavar="VERSIONS", help="comma-separated Java versions (e.g. 17,21,25) to publish while binaries are still pending " "for some architectures; prints the missing binaries and PR preview, then asks y/n before opening the PR", ) args = parser.parse_args() try: config = load_config() print_eol_warnings(config) plan = generate_manifest( config, args.output_file, dry_run=args.dry_run, force_versions=args.force, ) if args.create_pr or args.dry_run or args.force: confirm = confirm_publication if args.force else None update_publication_prs(plan, dry_run=args.dry_run, confirm=confirm) create_publication_pr(plan, dry_run=args.dry_run, confirm=confirm) except (OSError, ValueError, subprocess.CalledProcessError) as error: details = error.stderr if isinstance(error, subprocess.CalledProcessError) else str(error) parser.exit(1, f"Error: {details or str(error)}\n") ``` -------------------------------- ### CLI entry point (__main__ block) Source: https://github.com/adoptium/containers Command-line interface that loads config/temurin.yml, prints EOL dates for each distro, then prints warnings and exits with code 1 if any distro is expired, otherwise 0. The config path is hardcoded to the current working directory. ```python if __name__ == "__main__": import yaml with open("config/temurin.yml") as f: config = yaml.safe_load(f) print("Distro EOL dates:") for os_family, configurations in config.get("configurations", {}).items(): for cfg in configurations: image = cfg.get("image", cfg.get("directory", "unknown")) eol = get_eol_date(cfg) eol_str = str(eol) if eol else "unknown" print(f" {image}: {eol_str}") print() expired = print_eol_warnings(config, file=sys.stdout) if not expired: print("All distros are within their EOL dates.") sys.exit(1 if expired else 0) ``` -------------------------------- ### Run dockerhub_doc_config_update.py to update Docker Hub manifest Source: https://github.com/adoptium/containers/blob/main/README.md Fetch latest changes, checkout main, and run the script to update the official Docker Hub manifest. The script creates a file called _eclipse-temurin_ by default and prints a publication-readiness summary to stderr. ```bash # Get the latest changes git fetch --all # Checkout the main branch git checkout main python3 dockerhub_doc_config_update.py ``` -------------------------------- ### Run Sanity Checks Source: https://github.com/adoptium/containers/blob/main/DISTRO_MAINTENANCE.md Runs ./sanity.sh to verify there are no empty checksums or download URLs in the generated Dockerfiles. ```bash ./sanity.sh ``` -------------------------------- ### get_git_commit() - Get current HEAD commit SHA Source: https://github.com/adoptium/containers Runs 'git rev-parse HEAD' to retrieve the current commit SHA. Returns the stripped stdout as a string, and raises subprocess.CalledProcessError if the checkout has no HEAD or git is unavailable. ```python def get_git_commit(): result = subprocess.run( ["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True ) return result.stdout.strip() ``` -------------------------------- ### format_image_targets function Source: https://github.com/adoptium/containers Formats image directory paths into a summary string like 'JDK+JRE ubuntu/resolute, ubuntu/noble'. Packages are uppercased and '+'-joined, distros comma-joined. Input paths have the form '//'. ```python def format_image_targets(paths): packages_by_distro = {} for path in paths: _, package, distro = path.split("/", 2) packages_by_distro.setdefault(distro, set()).add(package) distros_by_packages = {} for distro, packages in packages_by_distro.items(): distros_by_packages.setdefault(tuple(sorted(packages)), []).append(distro) return "; ".join( f"{'+'.join(packages).upper()} {', '.join(distros)}" for packages, distros in distros_by_packages.items() ) ``` -------------------------------- ### CLI usage command Source: https://github.com/adoptium/containers Run the script from the containers directory. Expects config/temurin.yml in the current working directory. ```bash cd /workspace/home/containers python3 eol_checker.py ``` -------------------------------- ### github_request(url) - perform GitHub REST API request Source: https://github.com/adoptium/containers Performs a GitHub REST API GET request with required headers and optional Bearer token. Returns parsed JSON. Raises OSError/URLError on network issues and JSONDecodeError on invalid JSON. ```python def github_request(url): headers = {"Accept": "application/vnd.github+json", "User-Agent": "Adoptium Dockerfile Updater"} token = get_github_token() if token: headers["Authorization"] = f"Bearer {token}" request = urllib.request.Request(url, headers=headers) with urllib.request.urlopen(request, timeout=30) as response: return json.loads(response.read().decode("utf-8")) ``` -------------------------------- ### Force publication of specific Java versions Source: https://github.com/adoptium/containers/blob/main/README.md Pass versions to --force to publish while some architecture binaries are pending upstream. Architectures with the pending-binary TODO marker are deferred, and held-back images are listed in the PR description. Unsupported versions are rejected. ```bash python3 dockerhub_doc_config_update.py --force 17,21,25,27 ``` -------------------------------- ### apply_open_pr_baselines - use open PRs as publication baseline Source: https://github.com/adoptium/containers Uses open publication PRs as the baseline for binaries that were pending when they were opened. Returns per Java version the open PR usable as publication baseline, verifying version set and head manifest coverage, then recomputes per-image deferrals, pending arches, and pr_added_arches. Reads the PR-head Dockerfile via get_published_pending_arches; an unreadable file appends the blocker 'cannot read Dockerfile at open PR GitCommit' and skips that image. ```python def apply_open_pr_baselines(readiness, open_prs): """Use open publication PRs as the baseline for binaries that were pending when they were opened.""" ``` -------------------------------- ### Generated Dockerfile output path pattern Source: https://github.com/adoptium/containers/blob/main/DISTRO_MAINTENANCE.md Shows the output path pattern for generated Dockerfiles. The directory field from the configuration is used in the path. ```text ///Dockerfile ``` -------------------------------- ### Command-line interface Source: https://github.com/adoptium/containers Runs the EOL checker from the command line, reading `config/temurin.yml` and printing EOL dates and warnings. Exits with code 0 if no distro is past EOL, 1 otherwise. ```APIDOC ## Command-line interface ### Description Runs the EOL checker from the command line, reading `config/temurin.yml` and printing EOL dates and warnings. Exits with code 0 if no distro is past EOL, 1 otherwise. ### Usage ```bash cd /workspace/home/containers python3 eol_checker.py ``` ### Behaviour - **Input**: `config/temurin.yml` in the current working directory (hardcoded path) - **Stdout**: One line per configured distro with its EOL date (or `unknown`), then the summary/warnings - **Exit code**: `0` when no distro is past EOL, `1` when at least one expired entry was found ``` -------------------------------- ### get_supported_versions() Source: https://github.com/adoptium/containers Fetches the list of supported Java versions from the Adoptium API. Returns the sorted union of all LTS versions plus the most recent feature release if available. ```APIDOC ## get_supported_versions() ### Description Fetches the list of supported Java versions from the Adoptium API. Returns the sorted union of all LTS versions plus the most recent feature release if available. ### Method GET ### Endpoint https://api.adoptium.net/v3/info/available_releases ### Parameters None ### Response #### Success Response (200) - **list[int]** - Sorted union of available LTS releases and the most recent feature release (if present in available_releases) ### Request Example ```python from adoptium_api import get_supported_versions versions = get_supported_versions() # e.g. [8, 11, 17, 21, 25, 27] when LTS are [8, 11, 17, 21, 25] # and the most recent feature release is 27 for version in versions: print(f"building Dockerfiles for Java {version}") ``` ### Error Handling - **urllib.error.URLError / OSError** - Network failure or non-2xx response from the Adoptium API - **json.JSONDecodeError** - Response body is not valid JSON - **KeyError** - Response JSON is missing `available_lts_releases`, `most_recent_feature_release`, or `available_releases` ``` -------------------------------- ### prepare_publication_source function Source: https://github.com/adoptium/containers Verifies that all publication source files match the published adoptium/containers main commit and rewrites GitCommit lines for selected versions. Raises ValueError on missing or mismatched files. Returns the published commit SHA and updated manifest. ```python def prepare_publication_source(plan: PublicationPlan, versions=None) -> tuple[str, str]: versions = plan.ready_releases if versions is None else versions commit = github_request("https://api.github.com/repos/adoptium/containers/commits/main") if not isinstance(commit, dict) or not isinstance(commit.get("sha"), str) or not commit["sha"]: raise ValueError("GitHub did not return the published containers main commit") published_commit = commit["sha"] tree = github_request( f"https://api.github.com/repos/adoptium/containers/git/trees/{published_commit}?recursive=1" ) if not isinstance(tree, dict) or tree.get("truncated") or not isinstance(tree.get("tree"), list): raise ValueError("GitHub did not return a complete published containers source tree") published_files = { entry["path"]: entry["sha"] for entry in tree["tree"] if entry.get("type") == "blob" } source_paths = {"config/temurin.yml"} blocks = [] for block in plan.manifest.split("\n\n"): entries = get_manifest_entries(block) selected = [ directory for directory in entries if int(directory.split("/", 1)[0]) in versions ] for directory in selected: source_paths.add(f"{directory}/Dockerfile") entrypoint = f"{directory}/entrypoint.sh" if entrypoint in published_files or Path(entrypoint).exists(): source_paths.add(entrypoint) if selected: block = re.sub(r"(?m)^GitCommit: .+$", f"GitCommit: {published_commit}", block) blocks.append(block) paths = sorted(source_paths) for path in paths: if path not in published_files or not Path(path).is_file(): raise ValueError(f"Publication source is missing or not merged upstream: {path}") hashes = run_publication_command("git", "hash-object", "--", *paths).splitlines() if len(hashes) != len(paths): raise ValueError("Git did not return a hash for every publication source file") for path, blob in zip(paths, hashes): if blob != published_files[path]: raise ValueError( f"Publication source differs from published upstream main: {path}. " "Merge image and configuration changes before publishing." ) return published_commit, "\n\n".join(blocks) ``` -------------------------------- ### prepare_publication_source(plan, versions=None) Source: https://github.com/adoptium/containers Verifies that the publication source files match the published upstream main commit and rewrites the manifest GitCommit entries for selected versions. Returns the published commit SHA and the updated manifest. ```APIDOC ## prepare_publication_source(plan, versions=None) ### Description Verifies that the publication source files match the published upstream main commit and rewrites the manifest GitCommit entries for selected versions. Returns the published commit SHA and the updated manifest. ### Method Function call ### Parameters #### Parameters - **plan** (PublicationPlan) - Required - Plan from `generate_manifest`. - **versions** (collection of int) - Optional - Subset of versions whose manifest entries are rewritten with the published commit. Default: `plan.ready_releases`. ### Response #### Return Type `tuple[str, str]` — `(published_commit, manifest)` where `published_commit` is the current `adoptium/containers` `main` SHA and `manifest` has every selected entry's `GitCommit:` rewritten to it. #### Raises - `ValueError` - `GitHub did not return the published containers main commit` - `ValueError` - `GitHub did not return a complete published containers source tree` (truncated or missing tree) - `ValueError` - `Publication source is missing or not merged upstream: {path}` (a required path is absent from the published tree or the working copy) - `ValueError` - `Git did not return a hash for every publication source file` - `ValueError` - `Publication source differs from published upstream main: {path}. Merge image and configuration changes before publishing.` (blob hash mismatch) ``` -------------------------------- ### matching_publication_prs - filter open PRs by directories or release Source: https://github.com/adoptium/containers Returns open PRs that touch any of the given directories or publish a release with an equal java_version_key. The directories parameter defaults to an empty set when None. ```python def matching_publication_prs(release, open_prs, directories=None): directories = directories or set() return [ pr for pr in open_prs if directories & pr.updated_directories or any(java_version_key(tag) == java_version_key(release) for tag in pr.releases) ] ``` -------------------------------- ### Preview PR without changes using --dry-run Source: https://github.com/adoptium/containers/blob/main/README.md Dry runs show the proposed title, description, branch, and manifest diff on stderr without writing the local manifest, cloning, forking, pushing, or opening a PR. They use read-only Git and GitHub API requests and do not require the GitHub CLI when an API token is provided. ```bash python3 dockerhub_doc_config_update.py --dry-run ``` ```bash # Equivalent: python3 dockerhub_doc_config_update.py --create-pr --dry-run ``` -------------------------------- ### Catch standard exceptions from generate_manifest and load_config Source: https://github.com/adoptium/containers Consumers should catch standard types since no custom classes exist. The first except handles ValueError for configuration/manifest logic errors; the second handles OSError and subprocess.CalledProcessError for environment/git errors. ```python from dockerhub_doc_config_update import generate_manifest, load_config import subprocess try: plan = generate_manifest(load_config(), "eclipse-temurin") except ValueError as error: print("configuration/manifest logic error:", error) except (OSError, subprocess.CalledProcessError) as error: print("environment/git error:", error) ``` -------------------------------- ### archHelper function definition Source: https://github.com/adoptium/containers Maps Adoptium binary architecture names to Debian/Ubuntu convention names for use in generated Dockerfiles. Only 'ubuntu' changes the mapping; other OS values return 'x86_64' for 'x64' or the original architecture otherwise. ```python def archHelper(arch, os_name): if arch == "aarch64" and os_name == "ubuntu": return "arm64" elif arch == "ppc64le" and os_name == "ubuntu": return "ppc64el" elif arch == "arm": return "armhf" elif arch == "x64": if os_name == "ubuntu": return "amd64" else: return "x86_64" else: return arch ``` -------------------------------- ### archHelper(arch, os_name) Source: https://github.com/adoptium/containers Maps an Adoptium binary architecture name and OS name to the Debian/Ubuntu convention architecture name used inside generated Dockerfiles. This function is importable from the generate_dockerfiles module. ```APIDOC ## archHelper(arch, os_name) ### Description Maps an Adoptium binary architecture name and OS name to the Debian/Ubuntu convention architecture name used inside generated Dockerfiles. ### Parameters - **arch** (str) - Required - Adoptium binary architecture name (e.g. `x64`, `aarch64`, `ppc64le`, `arm`, `s390x`, `riscv64`). - **os_name** (str) - Required - The configuration `os` value (e.g. `ubuntu`, `alpine-linux`, `ubi-minimal`). Only `ubuntu` changes the mapping. ### Return Type - **str** - The Debian/Ubuntu convention architecture name used inside generated Dockerfiles. ### Mapping Table | Input | Result | |-------|--------| | `aarch64` + `ubuntu` | `arm64` | | `ppc64le` + `ubuntu` | `ppc64el` | | `arm` (any OS) | `armhf` | | `x64` + `ubuntu` | `amd64` | | `x64` + other OS | `x86_64` | | anything else | returned unchanged | ### Example ```python from generate_dockerfiles import archHelper archHelper("x64", "ubuntu") # 'amd64' archHelper("x64", "alpine-linux") # 'x86_64' archHelper("aarch64", "ubuntu") # 'arm64' ``` ``` -------------------------------- ### IMAGE_VERSION_PATTERNS regex list Source: https://github.com/adoptium/containers Ordered regexes to extract a version/cycle string from a Docker image reference, e.g., ubuntu:26.04 → 26.04, redhat/ubi9-minimal → 9, alpine:3.24 → 3.24. ```python IMAGE_VERSION_PATTERNS = [ # standard image:tag format re.compile(r":(\d[\d.]*)$"), # UBI images like redhat/ubi9-minimal -> extract major version re.compile(r"/ubi(\d+)"), ] ``` -------------------------------- ### load_config() - Load config/temurin.yml Source: https://github.com/adoptium/containers Opens and parses the YAML configuration file 'config/temurin.yml' using yaml.safe_load. Returns a dict, raises OSError if the file is missing, and yaml.YAMLError on invalid YAML. ```python def load_config(): with open("config/temurin.yml", "r") as f: return yaml.safe_load(f) ``` -------------------------------- ### describe_publication function Source: https://github.com/adoptium/containers Builds the upstream PR title and description for a publication. Returns a tuple of title and body strings. ```python def describe_publication( published_commit, releases, added, deferred_architectures, held_back_directories, cleanup, added_since_opened=None, ): """Build the upstream PR title and description.""" ``` -------------------------------- ### Decision Flowchart for Adding a New Distribution Source: https://github.com/adoptium/containers/blob/main/DISTRO_MAINTENANCE.md Mermaid flowchart used to evaluate whether and how to add a new distribution. It checks LTS policy, C library (glibc/musl), existing templates, and whether a COPY --from approach suffices. ```mermaid flowchart TD A[New distro request] --> B{Does this distro have an LTS policy?} B -- No --> C[Reject — we only support LTS distros] B -- Yes --> D{What C library does it use?} D -- glibc --> E{Is there an existing Dockerfile template that works? e.g. ubuntu.Dockerfile.j2} D -- musl --> F{Is there an existing musl template that works? e.g. alpine-linux.Dockerfile.j2} D -- Other/Unknown --> G[Evaluate feasibility with PMC — may need new Temurin builds] E -- Yes --> H[Add entry to temurin.yml using existing template] E -- No --> I{Can the user use COPY --from to get Temurin onto their preferred base image?} F -- Yes --> J[Add entry to temurin.yml using existing template] F -- No --> I I -- Yes --> K[Document COPY --from approach — no new official image needed] I -- No --> L[Create a new Dockerfile template in docker_templates/] L --> M{Does Docker accept this base image as an official image source?} M -- Yes --> N[Proceed with PMC approval and implement] M -- No --> K H --> O[Generate Dockerfiles, run tests, submit PR] J --> O N --> O ``` -------------------------------- ### java_version_key(release) - Build sortable version key Source: https://github.com/adoptium/containers Normalizes '-b', '_', and '+' to '+', then partitions on '+' to separate the build number. Pads numeric segments to 4 and returns a tuple of ((major, minor, patch, build?), build_number). Used as the comparison key in max(...) calls and matching_publication_prs. ```python def java_version_key(release): version, _, build = release.replace("-b", "+").replace("_", "+").partition("+") parts = tuple(int(n) for n in re.findall(r"\d+", version)) return parts + (0,) * max(0, 4 - len(parts)), int(build or 0) ``` -------------------------------- ### get_supported_versions() function signature Source: https://github.com/adoptium/containers Public function that returns the sorted union of LTS versions plus the most recent feature release. Takes no arguments. ```python def get_supported_versions(): ``` -------------------------------- ### describe_publication(published_commit, releases, added, deferred_architectures, held_back_directories, cleanup, added_since_opened=None) Source: https://github.com/adoptium/containers Builds the upstream PR title and description for a publication. Returns a tuple containing the title and body. ```APIDOC ## describe_publication(published_commit, releases, added, deferred_architectures, held_back_directories, cleanup, added_since_opened=None) ### Description Builds the upstream PR title and description for a publication. Returns a tuple containing the title and body. ### Method Function call ### Parameters #### Parameters - **published_commit** (str) - Required - The published commit SHA. - **releases** (list) - Required - List of releases. - **added** (list) - Required - Versions that are added. - **deferred_architectures** (list) - Required - Deferred architectures. - **held_back_directories** (list) - Required - Held-back directories. - **cleanup** (list) - Required - Cleanup list. - **added_since_opened** (optional) - Optional - Architecture notes for added versions. ### Response #### Return Type `tuple[str, str]` — `(title, body)`. - **Title:** `eclipse-temurin: ` + per-version `"{version} {release} add {archs}"` (when the version is in `added`) or `"{version} to {release}"`; `; remove deprecated images` appended for cleanup. - **Body:** starts `Update Eclipse Temurin from adoptium/containers commit {published_commit}.`, then `Publish READY releases:` entries (each listing deferred-architecture notes, held-back images via `format_image_targets`, and `added_since_opened` architecture notes), a `Follow-up for releases already published upstream:` section for versions in `added`, a `Remove deprecated, removed, or version-excluded image entries:` list for cleanup, and closes with `All other upstream manifest entries are preserved.` ``` -------------------------------- ### fetch_official_manifest() - Fetch official manifest for diff Source: https://github.com/adoptium/containers Fetches the official manifest from OFFICIAL_MANIFEST_URL and decodes it as UTF-8. Returns the raw manifest string, or None on network/OSError or decode error, printing a warning to stderr. A None result later produces an UNKNOWN readiness status and blocks PR creation. ```python def fetch_official_manifest(): """Fetch the current official manifest for diff comparison.""" try: req = urllib.request.Request(OFFICIAL_MANIFEST_URL) with urllib.request.urlopen(req) as response: return response.read().decode("utf-8") except (OSError, UnicodeError) as error: print(f"Warning: cannot compare with the official manifest: {error}", file=sys.stderr) return None ``` -------------------------------- ### run_publication_command wrapper Source: https://github.com/adoptium/containers Wrapper for every git/gh invocation. Returns trimmed stdout; raises subprocess.CalledProcessError with populated stderr on non-zero exit. ```python def run_publication_command(*args: str, cwd: Path | None = None) -> str: return subprocess.run( args, cwd=cwd, capture_output=True, text=True, check=True, ).stdout.strip() ``` -------------------------------- ### github_pages(url, items_key=None) - paginate GitHub API results Source: https://github.com/adoptium/containers Yields items from paginated GitHub API responses, appending per_page=100&page=N. Raises ValueError if search results are incomplete. ```python def github_pages(url, items_key=None): page = 1 while True: separator = "&" if "?" in url else "?" data = github_request(f"{url}{separator}per_page=100&page={page}") if items_key and data.get("incomplete_results"): raise ValueError("GitHub returned incomplete PR search results") items = data[items_key] if items_key else data yield from items if len(items) < 100: break page += 1 ```