fix(scripts): read the image matrix without PyYAML
Dry run 2453 ran the bump post-upgrade task in the Renovate image and it failed with ModuleNotFoundError: yaml, so every bump PR would have opened without the version bump. matrix_of() is now a small block-style reader that fails closed on anything else; a test compares it with PyYAML on the real image.yml and another forbids importing yaml in the scripts. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
This commit is contained in:
1 parent
c8c23687e2
commit
eaa38cb03a
3 files changed
+141
-51
No files matched your search
@@ -124,7 +124,7 @@ protection, or create tags: those are the operator's.
|
||||
the required `Lint` and `Build` never start, automerge cannot work); (4) that bot PRs are held by
|
||||
`main`'s required status checks (check the branch protection). Also confirm in the log: Renovate clones
|
||||
blobless with full history, so `origin/main` exists for the script (source-based); `python3` is in the
|
||||
image; `github.head_ref` is populated (the gate fails closed on an empty one, via `EVENT_NAME`). Safety
|
||||
image (no PyYAML: the scripts the bump step imports use the standard library only, dry run 2453); `github.head_ref` is populated (the gate fails closed on an empty one, via `EVENT_NAME`). Safety
|
||||
net: a failing or disallowed post-upgrade command opens the PR WITHOUT the bump plus a red
|
||||
`renovate/artifacts` status, and `check_image_versions.py bump` then fails lint.
|
||||
- **The workflow holds the runner's slot:** the `kamino-runner` host has a single slot (the label is
|
||||
|
||||
@@ -37,7 +37,9 @@ Known limits:
|
||||
* Of the consumer files, only lint.yml is required (it runs this check); build.yml and
|
||||
molecule.yml are skipped when absent, and the success line lists the files that were
|
||||
actually checked, so a consumer that vanished is visible.
|
||||
* Duplicate YAML keys inside a matrix entry are accepted (PyYAML keeps the last one).
|
||||
* The matrix is read by a small block-style reader (the Renovate image has no PyYAML), not
|
||||
a YAML parser: flow style, anchors, tags, block scalars and escapes are errors, and so is
|
||||
a duplicate key inside an entry. Tests compare it with PyYAML on the real file.
|
||||
* The Dockerfile COPY/ADD reader is not a Dockerfile parser: it fails closed (an error
|
||||
naming the file and line) on a source with `$`, a quote or `#`, and on a RUN
|
||||
--mount bind of the build context, instead of guessing which files are inputs.
|
||||
@@ -49,8 +51,6 @@ import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
import yaml
|
||||
|
||||
MATRIX_FILE = ".gitea/workflows/image.yml"
|
||||
REQUIRED_CONSUMER = ".gitea/workflows/lint.yml" # runs this check; its absence is an error
|
||||
CONSUMERS = [REQUIRED_CONSUMER, ".gitea/workflows/build.yml", ".gitea/workflows/molecule.yml"]
|
||||
@@ -88,45 +88,104 @@ def parse_version(text):
|
||||
return (int(m[1]), int(m[2]), int(m[3]), 0 if m[4] else 1, ids)
|
||||
|
||||
|
||||
_INCLUDE_RE = re.compile(r"^(?P<ind>\s*)include:\s*(?:#.*)?$")
|
||||
_ITEM_RE = re.compile(r"^(?P<ind>\s*)-(?P<gap>\s+)(?P<rest>\S.*)$")
|
||||
_KEY_RE = re.compile(r"^(?P<key>[A-Za-z_][A-Za-z0-9_-]*):(?:\s+(?P<value>.*))?$")
|
||||
_NUMBER_RE = re.compile(r"^[-+]?[0-9][0-9_]*(?:\.[0-9_]*)?$")
|
||||
|
||||
|
||||
def _scalar(raw, where):
|
||||
"""The string a block-style YAML scalar stands for. Only what image.yml uses is accepted: a
|
||||
plain scalar, or a quoted one without escapes or inner quotes, then an optional comment.
|
||||
Anything else (flow collections, anchors, tags, block scalars, escapes) is an error, so
|
||||
this reader fails closed instead of guessing what a YAML parser would make of it."""
|
||||
value = (raw or "").strip()
|
||||
if not value or value.startswith("#"):
|
||||
return ""
|
||||
if value[0] in "\"'":
|
||||
m = re.fullmatch(r"(?P<q>[\"'])(?P<body>[^\"'\\]*)(?P=q)\s*(?:#.*)?", value)
|
||||
if not m:
|
||||
raise CheckError(f"{where}: cannot read the quoted value {value!r} (escapes and inner quotes are not supported)")
|
||||
return m["body"]
|
||||
if value[0] in "[{&*!|>%@`" or "\t" in value:
|
||||
raise CheckError(f"{where}: cannot read the value {value!r} (only plain and quoted scalars are supported)")
|
||||
value = re.split(r"\s+#", value, maxsplit=1)[0].strip()
|
||||
if ": " in value or value.endswith(":"):
|
||||
raise CheckError(f"{where}: cannot read the value {value!r} (a plain scalar cannot contain ': ')")
|
||||
return value
|
||||
|
||||
|
||||
def matrix_of(text):
|
||||
"""Return {name: {version, subpath, dockerfile}} from the text of image.yml."""
|
||||
try:
|
||||
doc = yaml.safe_load(text)
|
||||
except yaml.YAMLError as exc:
|
||||
raise CheckError(f"{MATRIX_FILE} is not valid YAML: {' '.join(str(exc).split())}") from exc
|
||||
if not isinstance(doc, dict):
|
||||
raise CheckError(f"{MATRIX_FILE} is empty or not a mapping")
|
||||
try:
|
||||
entries = doc["jobs"]["image"]["strategy"]["matrix"]["include"]
|
||||
except (KeyError, TypeError) as exc:
|
||||
"""Return {name: {version, subpath, dockerfile}} from the text of image.yml.
|
||||
|
||||
A purpose-built block-style reader, not a YAML parser: the Renovate image has no PyYAML
|
||||
and the bump step runs there. It reads the single `include:` list and its entries'
|
||||
`name`, `version`, `subpath` and `dockerfile`, and fails closed (one-line error) on
|
||||
any other shape, so a file it cannot read is never half-understood."""
|
||||
lines = text.splitlines()
|
||||
heads = [n for n, line in enumerate(lines) if _INCLUDE_RE.match(line)]
|
||||
if len(heads) != 1:
|
||||
raise CheckError(f"{MATRIX_FILE} has no jobs.image.strategy.matrix.include list "
|
||||
f"(missing key {exc})") from exc
|
||||
if not isinstance(entries, list) or not entries:
|
||||
"(expected exactly one `include:` line)")
|
||||
include_indent = len(_INCLUDE_RE.match(lines[heads[0]])["ind"])
|
||||
entries, current, dash_indent = [], None, None
|
||||
for n in range(heads[0] + 1, len(lines)):
|
||||
line = lines[n]
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
indent = len(line) - len(line.lstrip())
|
||||
if indent <= include_indent and not (dash_indent is not None and indent == dash_indent):
|
||||
break # the list ended
|
||||
item = _ITEM_RE.match(line)
|
||||
if dash_indent is None:
|
||||
if not item:
|
||||
raise CheckError(f"{MATRIX_FILE}: matrix.include must be a non-empty block list of mappings")
|
||||
dash_indent = indent
|
||||
if indent < dash_indent:
|
||||
break
|
||||
if indent == dash_indent:
|
||||
if not item:
|
||||
raise CheckError(f"{MATRIX_FILE}: cannot read the matrix.include list at line {n + 1}")
|
||||
key_col = indent + 1 + len(item["gap"])
|
||||
current = {"keys": {}, "line": n + 1, "col": key_col}
|
||||
entries.append(current)
|
||||
body = item["rest"]
|
||||
else:
|
||||
if current is None or indent < current["col"]:
|
||||
raise CheckError(f"{MATRIX_FILE}: cannot read the matrix.include list at line {n + 1}")
|
||||
if indent > current["col"]:
|
||||
continue # a nested value of an entry key; none of the keys read here is nested
|
||||
body = line.strip()
|
||||
key = _KEY_RE.match(body)
|
||||
if not key:
|
||||
raise CheckError(f"{MATRIX_FILE}: matrix.include entry {len(entries)} is not a mapping (line {n + 1})")
|
||||
if key["key"] in current["keys"]:
|
||||
raise CheckError(f"{MATRIX_FILE}: duplicate key '{key['key']}' in matrix.include entry {len(entries)}")
|
||||
current["keys"][key["key"]] = (key["value"], n + 1)
|
||||
if not entries:
|
||||
raise CheckError(f"{MATRIX_FILE}: matrix.include must be a non-empty list of mappings")
|
||||
matrix = {}
|
||||
for n, e in enumerate(entries, 1):
|
||||
if not isinstance(e, dict):
|
||||
raise CheckError(f"{MATRIX_FILE}: matrix.include entry {n} is not a mapping")
|
||||
for key in ("name", "version", "dockerfile"):
|
||||
if key not in e:
|
||||
raise CheckError(f"a matrix entry of {MATRIX_FILE} lacks the key '{key}' "
|
||||
for n, entry in enumerate(entries, 1):
|
||||
keys = entry["keys"]
|
||||
for required in ("name", "version", "dockerfile"):
|
||||
if required not in keys:
|
||||
raise CheckError(f"a matrix entry of {MATRIX_FILE} lacks the key '{required}' "
|
||||
"(name, version and dockerfile are required)")
|
||||
name = e["name"]
|
||||
if not isinstance(name, str) or not name:
|
||||
values = {k: _scalar(v[0], f"{MATRIX_FILE} line {v[1]}") for k, v in keys.items()
|
||||
if k in ("name", "version", "dockerfile", "subpath")}
|
||||
name = values["name"]
|
||||
if not name or (keys["name"][0].strip()[:1] not in "\"'" and _NUMBER_RE.match(name)):
|
||||
raise CheckError(f"{MATRIX_FILE}: matrix.include entry {n}: name must be a non-empty string")
|
||||
if name in matrix:
|
||||
raise CheckError(f"{MATRIX_FILE}: duplicate image name '{name}' in matrix.include")
|
||||
# A YAML number (0.1) would silently become a string; versions must be written as strings.
|
||||
# A YAML number (0.1) would silently become a float; versions must be written as strings.
|
||||
for key in ("version", "dockerfile"):
|
||||
if not isinstance(e[key], str):
|
||||
raw = (keys[key][0] or "").strip()
|
||||
if not values[key] or (raw[:1] not in "\"'" and _NUMBER_RE.match(values[key])):
|
||||
raise CheckError(f"{MATRIX_FILE}: image '{name}': {key} must be a string "
|
||||
f"(quote it in the YAML), got {e[key]!r}")
|
||||
subpath = e.get("subpath")
|
||||
if subpath is None:
|
||||
subpath = ""
|
||||
elif not isinstance(subpath, str):
|
||||
raise CheckError(f"{MATRIX_FILE}: image '{name}': subpath must be a string, got {subpath!r}")
|
||||
matrix[name] = {"version": e["version"], "subpath": subpath, "dockerfile": e["dockerfile"]}
|
||||
f"(quote it in the YAML), got {values[key]!r}")
|
||||
matrix[name] = {"version": values["version"], "subpath": values.get("subpath", ""),
|
||||
"dockerfile": values["dockerfile"]}
|
||||
return matrix
|
||||
|
||||
|
||||
|
||||
@@ -151,7 +151,7 @@ class PureTest(unittest.TestCase):
|
||||
for text in ("", "# only a comment\n", "- a\n- b\n", "just a string\n"):
|
||||
with self.assertRaises(civ.CheckError, msg=repr(text)) as ctx:
|
||||
civ.matrix_of(text)
|
||||
self.assertIn("image.yml is empty or not a mapping", str(ctx.exception))
|
||||
self.assertIn("no jobs.image.strategy.matrix.include list", str(ctx.exception))
|
||||
|
||||
def test_semver_is_strict(self):
|
||||
for bad in ("0.1.0\n", "01.0.0", "1.02.0", "1.0.00", "1.0.0-01", "1.0.0-rc.01", "1.0.0 ", "v1.0.0"):
|
||||
@@ -170,30 +170,61 @@ class PureTest(unittest.TestCase):
|
||||
self.assertEqual(len(civ.check_pins(m, {"f": "x: [git.rkdr.net/mortis/ci:0.1.0@sha256:abc, y]"})), 1)
|
||||
|
||||
def test_matrix_shape_errors(self):
|
||||
def doc(include):
|
||||
return "jobs:\n image:\n strategy:\n matrix:\n include: " + include + "\n"
|
||||
def doc(body):
|
||||
return "jobs:\n image:\n strategy:\n matrix:\n include:\n" + body
|
||||
|
||||
entry = "{name: a, version: '0.1.0', dockerfile: D"
|
||||
entry = " - name: a\n version: '0.1.0'\n dockerfile: D\n"
|
||||
cases = {
|
||||
"[]": "non-empty list",
|
||||
"{}": "non-empty list",
|
||||
"[1]": "not a mapping",
|
||||
"[{name: 1, version: '0.1.0', dockerfile: D}]": "name must be a non-empty string",
|
||||
"[" + entry + ", subpath: 5}]": "subpath must be a string",
|
||||
"[" + entry + ", subpath: [x]}]": "subpath must be a string",
|
||||
"[{name: a, version: 0.1, dockerfile: D}]": "version must be a string",
|
||||
"[" + entry + "}, " + entry + "}]": "duplicate image name 'a'",
|
||||
"": "non-empty list",
|
||||
" []\n": "non-empty block list",
|
||||
" - 1\n": "not a mapping",
|
||||
" - name: 1\n version: '0.1.0'\n dockerfile: D\n": "name must be a non-empty string",
|
||||
entry + " subpath: [x]\n": "cannot read the value",
|
||||
entry.replace("'0.1.0'", "0.1") + "": "version must be a string",
|
||||
entry + entry: "duplicate image name 'a'",
|
||||
entry + " version: '0.2.0'\n": "duplicate key 'version'",
|
||||
entry.replace("version: '0.1.0'", "version: *anchor"): "cannot read the value",
|
||||
entry.replace("version: '0.1.0'", "version: \"0\\x2e1.0\""): "cannot read the quoted value",
|
||||
entry.replace(" - name: a\n", " - name: ''\n"): "name must be a non-empty string",
|
||||
" - name: a\n dockerfile: D\n": "lacks the key 'version'",
|
||||
}
|
||||
for include, text in cases.items():
|
||||
with self.assertRaises(civ.CheckError, msg=include) as ctx:
|
||||
civ.matrix_of(doc(include))
|
||||
self.assertIn(text, str(ctx.exception))
|
||||
for body, text in cases.items():
|
||||
with self.assertRaises(civ.CheckError, msg=body) as ctx:
|
||||
civ.matrix_of(doc(body))
|
||||
self.assertIn(text, str(ctx.exception), body)
|
||||
self.assertNotIn("\n", str(ctx.exception))
|
||||
self.assertEqual(civ.matrix_of(doc("[" + entry + ", subpath: }]"))["a"]["subpath"], "")
|
||||
self.assertEqual(civ.matrix_of(doc(entry + " subpath:\n"))["a"]["subpath"], "")
|
||||
with self.assertRaises(civ.CheckError) as ctx:
|
||||
civ.matrix_of("jobs: [unclosed\n")
|
||||
self.assertNotIn("\n", str(ctx.exception))
|
||||
|
||||
def test_matrix_reader_accepts_comments_quotes_and_key_order(self):
|
||||
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
|
||||
text = text.replace(" - name: ci\n version: 0.2.0\n",
|
||||
" # the ci image\n - version: \"0.2.0\" # bumped by the bot\n"
|
||||
" name: ci\n")
|
||||
self.assertEqual(civ.matrix_of(text)["ci"]["version"], "0.2.0")
|
||||
self.assertEqual(civ.matrix_of(text)["mol"]["subpath"], "images/mol")
|
||||
|
||||
def test_matrix_reader_agrees_with_pyyaml_on_the_real_file(self):
|
||||
# The reader replaces PyYAML in the Renovate image (which has none); here PyYAML is the oracle.
|
||||
import yaml
|
||||
real = (pathlib.Path(__file__).resolve().parents[2] / civ.MATRIX_FILE).read_text()
|
||||
want = {e["name"]: {"version": e["version"], "subpath": e.get("subpath") or "", "dockerfile": e["dockerfile"]}
|
||||
for e in yaml.safe_load(real)["jobs"]["image"]["strategy"]["matrix"]["include"]}
|
||||
self.assertEqual(civ.matrix_of(real), want)
|
||||
self.assertEqual(civ.matrix_of(IMAGE_YML.format(mol="0.1.0", ci="0.2.0")),
|
||||
{e["name"]: {"version": e["version"], "subpath": e.get("subpath") or "",
|
||||
"dockerfile": e["dockerfile"]}
|
||||
for e in yaml.safe_load(IMAGE_YML.format(mol="0.1.0", ci="0.2.0"))
|
||||
["jobs"]["image"]["strategy"]["matrix"]["include"]})
|
||||
|
||||
def test_scripts_do_not_import_yaml(self):
|
||||
# The bump step runs in the Renovate image, whose python3 has no PyYAML (dry run 2453).
|
||||
for script in ("check_image_versions.py", "bump_image_versions.py"):
|
||||
source = (pathlib.Path(__file__).resolve().parents[2] / "scripts" / script).read_text()
|
||||
self.assertNotRegex(source, r"(?m)^\s*(import|from)\s+yaml\b", script)
|
||||
|
||||
def test_bump_logic(self):
|
||||
def read(_path):
|
||||
return CI_DOCKERFILE
|
||||
@@ -326,7 +357,7 @@ class GitTest(unittest.TestCase):
|
||||
def test_empty_image_yml_says_so(self):
|
||||
self.write(".gitea/workflows/image.yml", "")
|
||||
self.commit("empty matrix")
|
||||
self.assert_clean_failure(self.bump(), "image.yml is empty or not a mapping")
|
||||
self.assert_clean_failure(self.bump(), "no jobs.image.strategy.matrix.include list")
|
||||
|
||||
def test_unsupported_dockerfile_source_fails_with_file_and_line(self):
|
||||
self.write("images/ci/Dockerfile", "FROM x\nCOPY $SRC ./\n")
|
||||
|
||||
Reference in new issue
Block a user