feat(scripts): add bump_image_versions.py for the image version bump
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
This commit is contained in:
1 parent
ce0a98a471
commit
ec15abf400
3 files changed
+311
-19
No files matched your search
@@ -0,0 +1,123 @@
|
||||
# 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))
|
||||
@@ -246,21 +246,29 @@ def check_pins(matrix, consumer_texts):
|
||||
return errors
|
||||
|
||||
|
||||
def check_bump(base_matrix, head_matrix, changed, read_head_file):
|
||||
errors = []
|
||||
def changed_images(head_matrix, changed, read_head_file):
|
||||
"""{name: sorted touched inputs} for each image of the matrix whose inputs are in `changed`."""
|
||||
result = {}
|
||||
for name, entry in head_matrix.items():
|
||||
# With a subpath the Dockerfile is relative to it and the whole directory is the
|
||||
# context; only a repository-root context needs the Dockerfile read.
|
||||
text = "" if entry["subpath"] else read_head_file(entry["dockerfile"])
|
||||
dirs, files = inputs_of(entry, text)
|
||||
hits = touched(changed, dirs, files)
|
||||
if not hits:
|
||||
continue
|
||||
if hits:
|
||||
result[name] = sorted(hits)
|
||||
return result
|
||||
|
||||
|
||||
def check_bump(base_matrix, head_matrix, changed, read_head_file):
|
||||
errors = []
|
||||
for name, hits in changed_images(head_matrix, changed, read_head_file).items():
|
||||
entry = head_matrix[name]
|
||||
old = base_matrix.get(name)
|
||||
if old is None:
|
||||
continue # a new image has no earlier version to collide with
|
||||
if parse_version(entry["version"]) <= parse_version(old["version"]):
|
||||
errors.append(f"image '{name}' changed ({', '.join(sorted(hits)[:5])}) but its version in "
|
||||
errors.append(f"image '{name}' changed ({', '.join(hits[:5])}) but its version in "
|
||||
f"{MATRIX_FILE} is still {entry['version']} (base: {old['version']}); bump it, "
|
||||
"otherwise the build is pushed as sha-*/latest only")
|
||||
for name, entry in head_matrix.items():
|
||||
@@ -280,6 +288,31 @@ def git(*args, raw=False):
|
||||
raise CheckError(f"git {args[0]} failed: {detail[-1] if detail else 'exit ' + str(exc.returncode)}") from exc
|
||||
|
||||
|
||||
def changed_paths(base_ref, target="HEAD"):
|
||||
"""(merge-base, changed paths) between base_ref and target; target None means the working tree."""
|
||||
base = git("merge-base", "--end-of-options", base_ref, "HEAD").strip()
|
||||
# --no-renames: a moved input file shows as a deletion at the old path and an addition
|
||||
# at the new one, so the old path still counts as touched.
|
||||
# -z: NUL-separated, unquoted paths, so a non-ASCII name (images/x/café) is compared as is
|
||||
# and not as the "caf\303\251" quoted form.
|
||||
changed = []
|
||||
end = [target] if target else []
|
||||
for raw_path in git("-c", "core.quotePath=false", "diff", "--name-only", "-z", "--no-renames",
|
||||
"--end-of-options", base, *end, raw=True).split(b"\0"):
|
||||
if not raw_path:
|
||||
continue
|
||||
try:
|
||||
changed.append(raw_path.decode("utf-8"))
|
||||
except UnicodeDecodeError as exc:
|
||||
raise CheckError(f"a changed path is not valid UTF-8: {raw_path.decode('utf-8', 'backslashreplace')}") from exc
|
||||
if not target: # the working tree also holds files git does not track yet
|
||||
for raw_path in git("-c", "core.quotePath=false", "ls-files", "--others", "--exclude-standard",
|
||||
"-z", raw=True).split(b"\0"):
|
||||
if raw_path:
|
||||
changed.append(raw_path.decode("utf-8", errors="backslashreplace"))
|
||||
return base, changed
|
||||
|
||||
|
||||
def run(argv):
|
||||
if len(argv) >= 2 and argv[1] == "pins" and len(argv) == 2:
|
||||
matrix = matrix_of(pathlib.Path(MATRIX_FILE).read_text())
|
||||
@@ -291,20 +324,7 @@ def run(argv):
|
||||
elif len(argv) == 3 and argv[1] == "bump":
|
||||
if not REF_RE.fullmatch(argv[2]):
|
||||
raise CheckError(f"{argv[2]!r} is not a plain ref name (letters, digits, . _ / -, no leading '-')")
|
||||
base = git("merge-base", "--end-of-options", argv[2], "HEAD").strip()
|
||||
# --no-renames: a moved input file shows as a deletion at the old path and an addition
|
||||
# at the new one, so the old path still counts as touched.
|
||||
# -z: NUL-separated, unquoted paths, so a non-ASCII name (images/x/café) is compared as is
|
||||
# and not as the "caf\303\251" quoted form.
|
||||
changed = []
|
||||
for raw_path in git("-c", "core.quotePath=false", "diff", "--name-only", "-z", "--no-renames",
|
||||
"--end-of-options", base, "HEAD", raw=True).split(b"\0"):
|
||||
if not raw_path:
|
||||
continue
|
||||
try:
|
||||
changed.append(raw_path.decode("utf-8"))
|
||||
except UnicodeDecodeError as exc:
|
||||
raise CheckError(f"a changed path is not valid UTF-8: {raw_path.decode('utf-8', 'backslashreplace')}") from exc
|
||||
base, changed = changed_paths(argv[2])
|
||||
try:
|
||||
base_text = git("show", f"{base}:{MATRIX_FILE}")
|
||||
except CheckError:
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
# SPDX-FileCopyrightText: Defame1297 and contributors
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Run with: python3 -m unittest discover -s tests/scripts"""
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts"
|
||||
sys.path.insert(0, str(SCRIPTS))
|
||||
import bump_image_versions as biv # noqa: E402
|
||||
|
||||
IMAGE_YML = """\
|
||||
# header comment
|
||||
jobs:
|
||||
image:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- name: mol
|
||||
version: {mol} # keep me
|
||||
subpath: images/mol
|
||||
dockerfile: Dockerfile
|
||||
- name: ci
|
||||
version: "{ci}"
|
||||
subpath: ""
|
||||
dockerfile: images/ci/Dockerfile
|
||||
"""
|
||||
CI_DOCKERFILE = "FROM x AS b\nCOPY requirements-dev.txt .pre-commit-config.yaml ./\n"
|
||||
|
||||
|
||||
def run(cwd, *cmd):
|
||||
return subprocess.run(cmd, cwd=cwd, check=True, capture_output=True, text=True,
|
||||
env={**os.environ, "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"})
|
||||
|
||||
|
||||
class PureTest(unittest.TestCase):
|
||||
def test_next_patch(self):
|
||||
self.assertEqual(biv.next_patch("0.2.9"), "0.2.10")
|
||||
self.assertEqual(biv.next_patch("1.0.0-rc.1"), "1.0.1")
|
||||
with self.assertRaises(ValueError):
|
||||
biv.next_patch("latest")
|
||||
|
||||
def test_rewrite_changes_only_the_version_line(self):
|
||||
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
|
||||
out = biv.rewrite(text, {"mol": "0.1.1", "ci": "0.2.1"})
|
||||
self.assertEqual(out, IMAGE_YML.format(mol="0.1.1", ci="0.2.1"))
|
||||
self.assertIn("version: 0.1.1 # keep me\n", out)
|
||||
self.assertIn('version: "0.2.1"\n', out)
|
||||
|
||||
def test_rewrite_unknown_image_fails(self):
|
||||
with self.assertRaises(biv.civ.CheckError):
|
||||
biv.rewrite(IMAGE_YML.format(mol="0.1.0", ci="0.2.0"), {"nope": "1.0.0"})
|
||||
|
||||
|
||||
class RepoTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.repo = pathlib.Path(self.tmp.name)
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
run(self.repo, "git", "init", "-q", "-b", "main")
|
||||
run(self.repo, "git", "config", "user.email", "[email protected]")
|
||||
run(self.repo, "git", "config", "user.name", "t")
|
||||
self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.1.0", ci="0.2.0"))
|
||||
self.write("images/ci/Dockerfile", CI_DOCKERFILE)
|
||||
self.write("images/mol/Dockerfile", "FROM x\n")
|
||||
self.write("requirements-dev.txt", "a==1\n")
|
||||
self.write(".pre-commit-config.yaml", "repos: []\n")
|
||||
self.commit("base")
|
||||
run(self.repo, "git", "checkout", "-q", "-b", "feature")
|
||||
|
||||
def write(self, rel, text):
|
||||
p = self.repo / rel
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
p.write_text(text)
|
||||
|
||||
def commit(self, msg):
|
||||
run(self.repo, "git", "add", "-A")
|
||||
run(self.repo, "git", "commit", "-q", "-m", msg)
|
||||
|
||||
def script(self, name, *args):
|
||||
proc = subprocess.run([sys.executable, str(SCRIPTS / name), *args], cwd=self.repo,
|
||||
capture_output=True, text=True, check=False)
|
||||
return proc.returncode, proc.stdout, proc.stderr
|
||||
|
||||
def bump(self, *args):
|
||||
return self.script("bump_image_versions.py", *(args or ("main",)))
|
||||
|
||||
def versions(self):
|
||||
return (self.repo / ".gitea/workflows/image.yml").read_text()
|
||||
|
||||
def test_nothing_changed(self):
|
||||
code, out, _ = self.bump()
|
||||
self.assertEqual((code, out), (0, "image versions: nothing to bump\n"))
|
||||
self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.0", ci="0.2.0"))
|
||||
|
||||
def test_bumps_exactly_the_changed_image_and_check_passes(self):
|
||||
self.write("requirements-dev.txt", "a==2\n") # an input of ci only
|
||||
code, out, err = self.bump()
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(out, "image versions: bumped ci 0.2.0 -> 0.2.1\n")
|
||||
self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.0", ci="0.2.1"))
|
||||
self.commit("deps and bump")
|
||||
self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 0)
|
||||
|
||||
def test_check_fails_without_the_bump(self):
|
||||
self.write("images/mol/Dockerfile", "FROM y\n")
|
||||
self.commit("input only")
|
||||
self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 1)
|
||||
self.assertEqual(self.bump()[0], 0)
|
||||
self.commit("bump")
|
||||
self.assertEqual(self.script("check_image_versions.py", "bump", "main")[0], 0)
|
||||
|
||||
def test_idempotent_and_committed_changes_count(self):
|
||||
self.write("images/mol/Dockerfile", "FROM y\n")
|
||||
self.commit("input")
|
||||
first = self.bump()
|
||||
self.assertEqual(first[1], "image versions: bumped mol 0.1.0 -> 0.1.1\n")
|
||||
second = self.bump()
|
||||
self.assertEqual(second[1], "image versions: nothing to bump\n")
|
||||
self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.1.1", ci="0.2.0"))
|
||||
|
||||
def test_higher_version_already_present_is_kept(self):
|
||||
self.write("images/mol/Dockerfile", "FROM y\n")
|
||||
self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.3.0", ci="0.2.0"))
|
||||
self.assertEqual(self.bump()[1], "image versions: nothing to bump\n")
|
||||
self.assertEqual(self.versions(), IMAGE_YML.format(mol="0.3.0", ci="0.2.0"))
|
||||
|
||||
def test_both_images_and_untracked_input(self):
|
||||
self.write("images/mol/new-file", "x\n") # untracked
|
||||
self.write("requirements-dev.txt", "a==2\n")
|
||||
out = self.bump()[1]
|
||||
self.assertEqual(out, "image versions: bumped ci 0.2.0 -> 0.2.1, mol 0.1.0 -> 0.1.1\n")
|
||||
|
||||
def test_bad_base_ref_is_a_clean_failure(self):
|
||||
for ref in ("--output=x", "nope"):
|
||||
code, _, err = self.bump(ref)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertNotIn("Traceback", err)
|
||||
self.assertEqual(len(err.strip().splitlines()), 1, err)
|
||||
|
||||
def test_usage(self):
|
||||
self.assertEqual(self.bump("a", "b")[0], 2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user