Files
Kamino/scripts/next_image_version.py
T
Defame1297 b12c990b6a
Build / build (pull_request) Canceled after 0s
Lint / lint (pull_request) Canceled after 0s
Molecule / molecule (pull_request) Canceled after 0s
ci(images): assign image versions in CI and open the pin PR right after a push
The image.yml matrix holds a hand-edited base (MAJOR.MINOR) per image instead
of a version. On main, scripts/next_image_version.py compares a checksum of the
image's inputs with the inputs-sha256 label of the newest published <base>.N
and the job publishes <base>.N+1 when they differ, or builds nothing when they
match. A published tag is still never moved.

renovate.yml runs live on the successful completion of Images (workflow_run),
so the pin pull request opens minutes after a push instead of on the schedule.

Removed: bump_image_versions.py and its tests, check_image_versions.py bump,
Lint's bump step, Renovate's postUpgradeTasks, and the bot-diff allowance for
matrix version lines.

Closes #165

Assisted-by: Claude Code:claude-opus-5-5
2026-11-23 21:15:16 +00:00

137 lines
4.7 KiB
Python

# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Choose the version an image build publishes, or none.
python3 scripts/next_image_version.py <source-dir> <image-name> <registry-host>
Prints "<version> <checksum>" when the image's inputs differ from the newest published
<base>.N (its input-checksum label), and nothing when they match.
"""
import hashlib
import json
import os
import pathlib
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
import check_image_versions as civ
def input_checksum(root, entry):
"""sha256 over the path, executable bit and content of every input file of the image."""
root = pathlib.Path(root)
context = root / entry["subpath"] if entry["subpath"] else root
dockerfile = (context / entry["dockerfile"]).read_text(encoding="utf-8")
dirs, files = civ.inputs_of(entry, dockerfile)
paths = sorted(
p.relative_to(root).as_posix()
for p in root.rglob("*")
if (p.is_file() or p.is_symlink()) and ".git" not in p.relative_to(root).parts
)
digest = hashlib.sha256()
for path in civ.touched(paths, dirs, files):
full = root / path
if full.is_symlink():
kind, body = "l", os.readlink(full).encode()
else:
kind, body = ("x" if os.access(full, os.X_OK) else "f"), full.read_bytes()
digest.update(f"{path}\0{kind}\0{hashlib.sha256(body).hexdigest()}\n".encode())
return digest.hexdigest()
def next_version(base, tags, checksum, label_of):
"""The next <base>.N, or None when the newest one was built from these inputs."""
patches = [
int(m[1])
for t in tags
if (m := re.fullmatch(re.escape(base) + r"\.(0|[1-9][0-9]*)", t))
]
if not patches:
return f"{base}.0"
newest = max(patches)
if label_of(f"{base}.{newest}") == checksum:
return None
return f"{base}.{newest + 1}"
LABEL = "net.rkdr.mortis.inputs-sha256"
MANIFEST_TYPES = (
"application/vnd.oci.image.manifest.v1+json",
"application/vnd.docker.distribution.manifest.v2+json",
)
class Registry:
"""Anonymous reads of one image in an OCI registry: the images are public."""
def __init__(self, host, image):
self.host, self.image, self.token = host, image, None
def _get(self, path, accept="application/json"):
url = f"https://{self.host}/v2/{self.image}/{path}"
headers = {"Accept": accept}
if self.token:
headers["Authorization"] = f"Bearer {self.token}"
try:
with urllib.request.urlopen(
urllib.request.Request(url, headers=headers), timeout=30
) as resp:
return json.load(resp), resp.headers
except urllib.error.HTTPError as exc:
if exc.code != 401 or self.token:
raise
challenge = dict(
re.findall(r'(\w+)="([^"]*)"', exc.headers.get("WWW-Authenticate", ""))
)
query = urllib.parse.urlencode(
{
"service": challenge.get("service", ""),
"scope": f"repository:{self.image}:pull",
}
)
with urllib.request.urlopen(
f"{challenge['realm']}?{query}", timeout=30
) as resp:
self.token = json.load(resp)["token"]
return self._get(path, accept)
def tags(self):
tags, path = [], "tags/list"
while path:
body, headers = self._get(path)
tags += body.get("tags") or []
link = re.search(r"<[^>]*/tags/list(\?[^>]*)>", headers.get("Link", ""))
path = f"tags/list{link[1]}" if link else None
return tags
def label(self, tag):
manifest = self._get(f"manifests/{tag}", ", ".join(MANIFEST_TYPES))[0]
if manifest.get("mediaType") not in MANIFEST_TYPES:
raise ValueError(
f"{self.image}:{tag} is not a single-platform image manifest"
)
config = self._get(f"blobs/{manifest['config']['digest']}")[0]
return (config.get("config", {}).get("Labels") or {}).get(LABEL)
def main(argv):
if len(argv) != 4:
sys.stderr.write(__doc__)
return 2
root, name, host = pathlib.Path(argv[1]), argv[2], argv[3]
entry = civ.matrix_of((root / civ.MATRIX_FILE).read_text(encoding="utf-8"))[name]
checksum = input_checksum(root, entry)
registry = Registry(host, f"mortis/{name}")
version = next_version(entry["base"], registry.tags(), checksum, registry.label)
if version:
print(version, checksum)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))