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:
1 parent
c03e492f81
commit
a57714342b
4 files changed
+194
-24
No files matched your search
@@ -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()))
|
||||
|
||||
|
||||
@@ -297,13 +297,20 @@ def git(*args, raw=False):
|
||||
out = subprocess.run(["git", *args], capture_output=True, check=True).stdout
|
||||
return out if raw else out.decode("utf-8", errors="replace")
|
||||
except subprocess.CalledProcessError as exc:
|
||||
detail = (exc.stderr or "").strip().splitlines()
|
||||
raise CheckError(f"git {args[0]} failed: {detail[-1] if detail else 'exit ' + str(exc.returncode)}") from exc
|
||||
stderr = exc.stderr.decode("utf-8", errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
|
||||
detail = stderr.strip().splitlines()
|
||||
raise CheckError(f"git {args[0]} failed: {detail[-1].strip() 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()
|
||||
try:
|
||||
base = git("merge-base", "--end-of-options", base_ref, "HEAD").strip()
|
||||
except CheckError as exc:
|
||||
if git("rev-parse", "--is-shallow-repository").strip() == "true":
|
||||
raise CheckError(f"no merge-base with {base_ref!r} in a shallow clone: run `git fetch --unshallow` "
|
||||
"or pass a ref that exists") from exc
|
||||
raise
|
||||
# --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
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
"""Run with: python3 -m unittest discover -s tests/scripts"""
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -55,6 +56,42 @@ class PureTest(unittest.TestCase):
|
||||
biv.rewrite(IMAGE_YML.format(mol="0.1.0", ci="0.2.0"), {"nope": "1.0.0"})
|
||||
|
||||
|
||||
SHUFFLED_YML = """\
|
||||
jobs:
|
||||
image:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- version: {mol}
|
||||
subpath: images/mol
|
||||
name: mol
|
||||
dockerfile: Dockerfile
|
||||
- subpath: ""
|
||||
version: "{ci}"
|
||||
dockerfile: images/ci/Dockerfile
|
||||
name: ci
|
||||
"""
|
||||
|
||||
|
||||
class EntryAttributionTest(unittest.TestCase):
|
||||
def test_version_before_name_is_attributed_to_its_own_entry(self):
|
||||
text = SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0")
|
||||
out = biv.rewrite(text, {"ci": "0.2.1"})
|
||||
self.assertEqual(out, SHUFFLED_YML.format(mol="0.1.0", ci="0.2.1"))
|
||||
out = biv.rewrite(text, {"mol": "0.1.1"})
|
||||
self.assertEqual(out, SHUFFLED_YML.format(mol="0.1.1", ci="0.2.0"))
|
||||
|
||||
def test_entry_without_its_own_version_never_borrows_another(self):
|
||||
text = SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0").replace(' version: "0.2.0"\n', "")
|
||||
with self.assertRaises(biv.civ.CheckError):
|
||||
biv.rewrite(text, {"mol": "0.1.1"})
|
||||
|
||||
def test_flow_style_entry_is_refused(self):
|
||||
text = SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0") + " - {name: x, version: 1.0.0}\n"
|
||||
with self.assertRaises(biv.civ.CheckError):
|
||||
biv.rewrite(text, {"ci": "0.2.1"})
|
||||
|
||||
|
||||
class RepoTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
@@ -141,6 +178,57 @@ class RepoTest(unittest.TestCase):
|
||||
self.assertNotIn("Traceback", err)
|
||||
self.assertEqual(len(err.strip().splitlines()), 1, err)
|
||||
|
||||
def test_shuffled_key_order_bumps_the_right_entry_end_to_end(self):
|
||||
self.write(".gitea/workflows/image.yml", SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0"))
|
||||
self.commit("shuffle")
|
||||
self.write("requirements-dev.txt", "a==2\n") # an input of ci only
|
||||
code, out, err = self.bump()
|
||||
self.assertEqual((code, out), (0, "image versions: bumped ci 0.2.0 -> 0.2.1\n"), err)
|
||||
self.assertEqual(self.versions(), SHUFFLED_YML.format(mol="0.1.0", ci="0.2.1"))
|
||||
|
||||
def test_unparseable_entry_is_a_one_line_failure(self):
|
||||
flow = SHUFFLED_YML.format(mol="0.1.0", ci="0.2.0") + " - {name: x, version: 1.0.0}\n"
|
||||
self.write(".gitea/workflows/image.yml", flow)
|
||||
self.commit("flow")
|
||||
self.write("requirements-dev.txt", "a==2\n")
|
||||
code, _, err = self.bump()
|
||||
self.assertEqual(code, 1)
|
||||
self.assertEqual(len(err.strip().splitlines()), 1, err)
|
||||
self.assertEqual(self.versions(), flow)
|
||||
|
||||
def test_crlf_line_endings_are_preserved(self):
|
||||
crlf = IMAGE_YML.format(mol="0.1.0", ci="0.2.0").replace("\n", "\r\n").encode("utf-8")
|
||||
path = self.repo / ".gitea/workflows/image.yml"
|
||||
path.write_bytes(crlf)
|
||||
self.commit("crlf")
|
||||
self.write("requirements-dev.txt", "a==2\n")
|
||||
self.assertEqual(self.bump()[0], 0)
|
||||
self.assertEqual(path.read_bytes(), crlf.replace(b'"0.2.0"', b'"0.2.1"'))
|
||||
|
||||
def test_ignored_cache_under_images_is_not_an_input(self):
|
||||
self.write(".gitignore", "__pycache__/\n")
|
||||
self.commit("ignore")
|
||||
self.write("images/mol/__pycache__/x.pyc", "cache\n")
|
||||
self.assertEqual(self.bump()[1], "image versions: nothing to bump\n")
|
||||
self.write("images/mol/real-file", "x\n")
|
||||
self.assertEqual(self.bump()[1], "image versions: bumped mol 0.1.0 -> 0.1.1\n")
|
||||
|
||||
def test_shallow_clone_names_the_fix(self):
|
||||
clone = self.repo.parent / (self.repo.name + "-shallow")
|
||||
self.addCleanup(shutil.rmtree, clone, True)
|
||||
self.write("images/mol/Dockerfile", "FROM y\n")
|
||||
self.commit("two")
|
||||
self.write("images/mol/Dockerfile", "FROM z\n")
|
||||
self.commit("three")
|
||||
run(self.repo.parent, "git", "clone", "-q", "--depth", "1", "--branch", "feature", f"file://{self.repo}",
|
||||
str(clone))
|
||||
run(clone, "git", "fetch", "-q", "--depth", "1", "origin", "main:refs/remotes/origin/main")
|
||||
proc = subprocess.run([sys.executable, str(SCRIPTS / "bump_image_versions.py"), "origin/main"], cwd=clone,
|
||||
capture_output=True, text=True, check=False)
|
||||
self.assertEqual(proc.returncode, 1)
|
||||
self.assertEqual(len(proc.stderr.strip().splitlines()), 1, proc.stderr)
|
||||
self.assertIn("git fetch --unshallow", proc.stderr)
|
||||
|
||||
def test_usage(self):
|
||||
self.assertEqual(self.bump("a", "b")[0], 2)
|
||||
|
||||
|
||||
@@ -280,6 +280,13 @@ class GitTest(unittest.TestCase):
|
||||
def test_unknown_base_ref_is_one_line(self):
|
||||
self.assert_clean_failure(self.bump_args("bump", "nope"), "git merge-base failed")
|
||||
|
||||
def test_git_errors_are_decoded_text_not_a_bytes_repr(self):
|
||||
code, err = self.bump_args("bump", "nope")
|
||||
self.assertEqual(code, 1)
|
||||
self.assertNotIn("b'", err)
|
||||
self.assertNotIn('b"', err)
|
||||
self.assertIn("fatal:", err)
|
||||
|
||||
def test_bad_version_in_matrix_is_one_line(self):
|
||||
self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="latest", ci="0.2.0"))
|
||||
self.commit("bad version")
|
||||
|
||||
Reference in new issue
Block a user