fix(scripts): attribute bumped versions to their own matrix entry

bump_image_versions.py now locates each matrix.include entry and rewrites the
version: line of the entry whose name: it is, whatever the key order; an entry
it cannot parse unambiguously is a one-line error, and the rewrite is verified
against the YAML before it is written. Files are read and written as UTF-8 with
newline="" so CRLF survives. A shallow clone without a merge-base names the fix
(git fetch --unshallow). check_image_versions.py decodes git's stderr, so errors
no longer print a bytes repr. Untracked files that git ignores were already
skipped; a test now pins that.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
This commit is contained in:
Defame1297andClaude Sonnet 5.5 committed 2026-10-26 06:39:11 +00:00
1 parent c03e492f81
commit a57714342b
4 files changed
+194 -24

No files matched your search

+89 -21
View File
@@ -11,7 +11,10 @@ with <base-ref>, so committed, staged, unstaged and new files all count) and, fo
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.
`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 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
@@ -29,7 +32,9 @@ 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*(?:#.*)?$")
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>.*)$")
@@ -40,25 +45,77 @@ def next_patch(version):
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("\"'")
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
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)
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)
@@ -75,6 +132,12 @@ def plan(base_matrix, head_matrix, changed, read_head_file):
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)
@@ -88,12 +151,17 @@ def run(argv):
except civ.CheckError:
base_matrix = {} # no matrix at the base: every image is new
path = pathlib.Path(civ.MATRIX_FILE)
text = path.read_text()
text = read_text(path)
head_matrix = civ.matrix_of(text)
new_versions = plan(base_matrix, head_matrix, changed, lambda p: pathlib.Path(p).read_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"
path.write_text(rewrite(text, new_versions))
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()))