Files
Kamino/scripts/bump_image_versions.py
T
Defame1297andClaude Sonnet 5.5 bbb4f1f888
Build / build (pull_request) Successful in 15s
Lint / lint (pull_request) Successful in 39s
Molecule / molecule (pull_request) Successful in 2s
fix(renovate): run the image bump task on every branch
The postUpgradeTasks lived in a packageRule matching package "*". Branch
renovate/pip-compile-refresh (a lock regeneration, no package upgrade) did not
get the task, so its requirements-dev.lock change reached the lint check
without the ci image version bump and failed `check_image_versions.py bump`.
A top-level postUpgradeTasks applies to every branch.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_014uGZTNmHMc85bomfevwUDG
2026-11-16 07:13:53 +00:00

228 lines
9.0 KiB
Python

# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Bump the PATCH version of every image whose inputs changed (ADR 0004, Image distribution, in the
maintainer's environment repository).
python3 scripts/bump_image_versions.py [<base-ref>] (default: origin/main)
The counterpart of `check_image_versions.py bump`: that one fails a pull request whose
image inputs changed under an unchanged version, this one makes the edit. It finds the
changed images with the same input detection (the working tree against the merge-base
with <base-ref>, so committed, staged, unstaged and new files all count) and, for each,
sets `version:` in the build matrix of .gitea/workflows/image.yml to the PATCH successor
of the base's version, unless the file already holds a higher one. Running it twice
changes nothing the second time. An image that is new at the base is left alone. Only the
`version:` line is rewritten (attributed to the `name:` of its own matrix entry, whatever the key
order; an entry that cannot be parsed unambiguously is an error); comments, quoting, line endings and
the rest of the file are kept. Untracked files count as inputs unless git ignores them, so a cache
under images/ must be in .gitignore.
It runs as a Renovate `postUpgradeTasks` command: renovate.json sets it at the top level
(so it runs on every branch, a lock refresh with no package included), with executionMode branch and fileFilters limited to
.gitea/workflows/image.yml,
allowed by RENOVATE_ALLOWED_COMMANDS of .gitea/workflows/renovate.yml. It is a no-op when no image
input changed, so a dependency bump that changes an image input carries its version bump and
passes the `bump` check without a human edit.
Moving the consumers' pins to the digest the build produces stays a separate, later pull
request (build on main, then the pin follow-up).
Prints one line. Exits 1 with an `::error::` line on a failure, 2 on bad usage.
"""
import pathlib
import re
import sys
import check_image_versions as civ
DEFAULT_BASE = "origin/main"
USAGE = "usage: bump_image_versions.py [<base-ref>]\n"
INCLUDE_RE = re.compile(r"^\s*include:\s*(?:#.*)?$")
ITEM_RE = re.compile(r"^(?P<dash>\s*)-(?P<gap>\s+)(?P<rest>\S.*)$")
NAME_KEY_RE = re.compile(
r"^(?P<ind>\s*)name:\s*[\"']?(?P<name>[^\"'\s#]+)[\"']?\s*(?:#.*)?$"
)
VERSION_LINE_RE = re.compile(
r"^(?P<head>\s*(?:-\s*)?version:\s*)(?P<q>[\"']?)(?P<value>[^\"'\s#]+)(?P=q)(?P<tail>.*)$"
)
def next_patch(version):
"""The PATCH successor of a MAJOR.MINOR.PATCH[-prerelease] version (a prerelease is dropped)."""
civ.parse_version(version)
major, minor, patch = civ.SEMVER_RE.fullmatch(version).group(1, 2, 3)
return f"{major}.{minor}.{int(patch) + 1}"
def _entries(lines):
"""[(start, end)] line ranges of the matrix.include entries (end exclusive); an error when the
list cannot be located unambiguously."""
heads = [n for n, line in enumerate(lines) if INCLUDE_RE.match(line.rstrip("\r\n"))]
if len(heads) != 1:
raise civ.CheckError(
f"cannot find exactly one `include:` list in {civ.MATRIX_FILE}"
)
starts, dash_indent = [], None
end = len(lines)
for n in range(heads[0] + 1, len(lines)):
body = lines[n].rstrip("\r\n")
if not body.strip() or body.lstrip().startswith("#"):
continue
m = ITEM_RE.match(body)
indent = len(body) - len(body.lstrip())
if dash_indent is None:
if not m:
raise civ.CheckError(
f"the `include:` list of {civ.MATRIX_FILE} is not a block list of mappings"
)
dash_indent = indent
if indent < dash_indent:
end = n
break
if indent == dash_indent:
if not m:
raise civ.CheckError(
f"cannot parse the `include:` list of {civ.MATRIX_FILE}"
)
starts.append(n)
if not starts:
raise civ.CheckError(f"the `include:` list of {civ.MATRIX_FILE} is empty")
return list(zip(starts, starts[1:] + [end]))
def _entry_lines(lines, start, end):
"""(name, index of the version line) of one entry, from lines normalised so the first key sits
at the same column as the others."""
first = ITEM_RE.match(lines[start].rstrip("\r\n"))
key_col = len(first["dash"]) + 1 + len(first["gap"])
names, versions = [], []
for n in range(start, end):
body = lines[n].rstrip("\r\n")
if n == start:
body = " " * key_col + first["rest"]
if len(body) - len(body.lstrip()) != key_col:
continue # a comment, a blank line or a nested key
m = NAME_KEY_RE.match(body)
if m:
names.append(m["name"])
elif VERSION_LINE_RE.match(body):
versions.append(n)
if len(names) != 1 or len(versions) != 1:
raise civ.CheckError(
f"cannot parse a matrix entry of {civ.MATRIX_FILE} (line {start + 1}) "
"unambiguously: expected one `name:` and one `version:`"
)
return names[0], versions[0]
def rewrite(text, new_versions):
"""The text with the `version:` line of each named matrix entry replaced; only that line changes.
A `version:` is attributed to the `name:` of the SAME matrix entry, whatever the key order."""
lines = text.splitlines(keepends=True)
targets = {}
for start, end in _entries(lines):
name, version_index = _entry_lines(lines, start, end)
if name in new_versions:
targets[name] = version_index
missing = sorted(set(new_versions) - set(targets))
if missing:
raise civ.CheckError(
f"no `version:` line found for image {', '.join(missing)} in {civ.MATRIX_FILE}"
)
for name, n in targets.items():
line = lines[n]
body = line.rstrip("\r\n")
v = VERSION_LINE_RE.match(body)
q = v["q"]
lines[n] = (
f"{v['head']}{q}{new_versions[name]}{q}{v['tail']}" + line[len(body) :]
)
return "".join(lines)
def plan(base_matrix, head_matrix, changed, read_head_file):
"""{name: new version} for the images that need a bump, and the list of images already bumped."""
new_versions = {}
for name in civ.changed_images(head_matrix, changed, read_head_file):
old = base_matrix.get(name)
if old is None:
continue # a new image has no earlier version to collide with
if civ.parse_version(head_matrix[name]["version"]) > civ.parse_version(
old["version"]
):
continue # already bumped
new_versions[name] = next_patch(old["version"])
return new_versions
def read_text(path):
"""The file as UTF-8 text with its line endings (CRLF included) untouched."""
with open(path, encoding="utf-8", newline="") as handle:
return handle.read()
def run(argv):
if len(argv) > 2:
sys.stderr.write(USAGE)
return None
ref = argv[1] if len(argv) == 2 else DEFAULT_BASE
if not civ.REF_RE.fullmatch(ref):
raise civ.CheckError(
f"{ref!r} is not a plain ref name (letters, digits, . _ / -, no leading '-')"
)
base, changed = civ.changed_paths(ref, target=None)
try:
base_matrix = civ.matrix_of(civ.git("show", f"{base}:{civ.MATRIX_FILE}"))
except civ.CheckError:
base_matrix = {} # no matrix at the base: every image is new
path = pathlib.Path(civ.MATRIX_FILE)
text = read_text(path)
head_matrix = civ.matrix_of(text)
new_versions = plan(
base_matrix, head_matrix, changed, lambda p: read_text(pathlib.Path(p))
)
if not new_versions:
return "image versions: nothing to bump"
new_text = rewrite(text, new_versions)
expected = {
name: new_versions.get(name, entry["version"])
for name, entry in head_matrix.items()
}
if {
name: entry["version"] for name, entry in civ.matrix_of(new_text).items()
} != expected:
raise civ.CheckError(
f"the rewrite of {civ.MATRIX_FILE} would not give the planned versions; edit it by hand"
)
with open(path, "w", encoding="utf-8", newline="") as handle:
handle.write(new_text)
return "image versions: bumped " + ", ".join(
f"{name} {head_matrix[name]['version']} -> {new}"
for name, new in sorted(new_versions.items())
)
def main(argv):
try:
message = run(argv)
except civ.CheckError as exc:
sys.stderr.write(f"::error::{exc}\n")
return 1
except UnicodeDecodeError as exc: # before ValueError, which it subclasses
sys.stderr.write(f"::error::a file is not valid UTF-8: {exc}\n")
return 1
except ValueError as exc: # parse_version
sys.stderr.write(f"::error::cannot parse a version: {exc}\n")
return 1
except OSError as exc:
sys.stderr.write(f"::error::cannot read or write a file: {exc}\n")
return 1
if message is None:
return 2
print(message)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))