Factor the changed-path listing and the per-image input detection out of check_image_versions.py (changed_paths, changed_images) and reuse them in a new script that bumps the PATCH version of every image whose inputs changed. It is meant to run later as a Renovate postUpgradeTasks command. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
124 lines
5.2 KiB
Python
124 lines
5.2 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).
|
|
|
|
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; comments, quoting and the rest of the file are kept.
|
|
|
|
It is meant to run later as a Renovate `postUpgradeTasks` command (Phase 2/3 of the
|
|
Renovate plan; renovate.json does not enable it yet), 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"
|
|
NAME_LINE_RE = re.compile(r"^(\s*-\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 rewrite(text, new_versions):
|
|
"""The text with the `version:` line of each named matrix entry replaced; only that line changes."""
|
|
lines = text.splitlines(keepends=True)
|
|
current = None
|
|
done = set()
|
|
for n, line in enumerate(lines):
|
|
body = line.rstrip("\r\n")
|
|
m = NAME_LINE_RE.match(body)
|
|
if m:
|
|
current = m["name"].strip("\"'")
|
|
continue
|
|
v = VERSION_LINE_RE.match(body)
|
|
if v and current in new_versions and current not in done:
|
|
q = v["q"]
|
|
lines[n] = f"{v['head']}{q}{new_versions[current]}{q}{v['tail']}" + line[len(body):]
|
|
done.add(current)
|
|
missing = sorted(set(new_versions) - done)
|
|
if missing:
|
|
raise civ.CheckError(f"no `version:` line found for image {', '.join(missing)} in {civ.MATRIX_FILE}")
|
|
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 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 = path.read_text()
|
|
head_matrix = civ.matrix_of(text)
|
|
new_versions = plan(base_matrix, head_matrix, changed, lambda p: pathlib.Path(p).read_text())
|
|
if not new_versions:
|
|
return "image versions: nothing to bump"
|
|
path.write_text(rewrite(text, new_versions))
|
|
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))
|