fix(scripts): read the image matrix without PyYAML
Molecule / molecule (pull_request) Skipped
Build / build (pull_request) Successful in 11s
Lint / lint (pull_request) Successful in 12s

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:
Defame1297andClaude Sonnet 5.5 committed 2026-10-26 16:57:08 +00:00
1 parent c8c23687e2
commit eaa38cb03a
3 files changed
+141 -51

No files matched your search

+91 -32
View File
@@ -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