diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml index cb4a286..0f69c3d 100644 --- a/.gitea/workflows/lint.yml +++ b/.gitea/workflows/lint.yml @@ -67,6 +67,21 @@ jobs: export PATH="/opt/venv/bin:$PATH" pre-commit run --all-files --show-diff-on-failure + # Image versions and pins (scripts/check_image_versions.py): a change to an image's + # inputs needs a higher version in image.yml, and a pin in a workflow must name an + # image of the matrix. Not a pre-commit hook: a change to .pre-commit-config.yaml + # is itself an input of the ci image and would force an image rebuild. + - name: Check image pins + run: | + export PATH="/opt/venv/bin:$PATH" + python3 scripts/check_image_versions.py pins + + - name: Check image versions were bumped + if: github.event_name == 'pull_request' + run: | + export PATH="/opt/venv/bin:$PATH" + python3 scripts/check_image_versions.py bump origin/main + - name: Test the repository scripts run: | export PATH="/opt/venv/bin:$PATH" diff --git a/changelogs/fragments/image-version-and-pin-check.yml b/changelogs/fragments/image-version-and-pin-check.yml new file mode 100644 index 0000000..a462d1e --- /dev/null +++ b/changelogs/fragments/image-version-and-pin-check.yml @@ -0,0 +1,9 @@ +trivial: + - >- + Add scripts/check_image_versions.py and its tests, and run them in the Lint workflow: + image pins must name an image of the build matrix, and a pull request that changes an + image's inputs must bump its version. + - >- + scripts/check_image_versions.py reports a pin written in any case, with a port, in a nested path or without a tag; fails closed (naming + file and line) on a Dockerfile COPY source with a variable, quote or comment character and on a RUN --mount of the build context; says so + for a non-UTF-8 diff path and an empty image.yml; requires lint.yml and lists the consumer files it checked. diff --git a/galaxy.yml b/galaxy.yml index 1232eda..4cd3995 100644 --- a/galaxy.yml +++ b/galaxy.yml @@ -37,9 +37,9 @@ build_ignore: - extensions - images - scripts + - tests/scripts - requirements-dev.txt - gitleaks-report.json - importer_result.json - - tests/scripts - 'roles/*/molecule' - '*.tar.gz' diff --git a/scripts/check_image_versions.py b/scripts/check_image_versions.py new file mode 100644 index 0000000..d514485 --- /dev/null +++ b/scripts/check_image_versions.py @@ -0,0 +1,344 @@ +# SPDX-FileCopyrightText: Defame1297 and contributors +# SPDX-License-Identifier: GPL-3.0-or-later +"""Keep image versions and image pins honest (ADR 0004, Image distribution). + + python3 scripts/check_image_versions.py pins + python3 scripts/check_image_versions.py bump + +The matrix of .gitea/workflows/image.yml is the registry of images: name, version, +build context (subpath) and Dockerfile. A published version tag is never moved (Gitea +cannot make a tag immutable), so an image whose content changes under an unchanged +version is pushed as sha-*/latest only, and a hand-pasted @ pin +would pair a tag with a digest it does not point to. + +pins Every `git.rkdr.net/mortis/:@sha256:` in the consumer + workflows must name an image of the matrix, with a well-formed digest and a + version that is not newer than the matrix (a pin lags the matrix between the PR + that bumps the version and the PR that moves the pin; it can never lead it). + Offline: whether the tag points at the digest is a registry fact, see the + "unverified" note in the PR description. +bump Fails when the diff ...HEAD touches an input of an image without a + higher version for it in the matrix. Inputs of an image: its build context + directory (the Dockerfile's directory, or the subpath), plus, for a repository- + root context, every file the Dockerfile COPYs from the context. + +Known limits: + * is compared through the merge-base, so a bump that collides with a newer + bump already on the base branch (two branches bumping to the same version) is not + detected here; the second one to merge has to rebase and bump again. + * Whether a version tag points at the digest of a pin is a registry fact and is not + verified offline; only the shape of the pin and the version order are checked. + * Renaming an image in the matrix in the same PR skips the bump check for it (the new + name has no base entry); the pins check still catches a consumer pin left on the old + name, because that name is no longer in the matrix. + * 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 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. +""" +import fnmatch +import json +import pathlib +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"] +PIN_RE = re.compile(r"git\.rkdr\.net/mortis/(?P[a-z0-9._-]+):(?P[^@\s]+)@(?Psha256:[0-9a-f]{64})") +# A mention of the registry's mortis namespace in any spelling: host in any case, optional +# :port, any case or nested path, tagged or not. It ends at whitespace, quotes or closing +# punctuation, so a pin followed by `,` `)` `]` `}` parses. Not a mention: a URL +# (https://git.rkdr.net/mortis/kamino) or an SSH remote (git@git.rkdr.net). +ANY_PIN_RE = re.compile( + r"""(?:@sha256:<64 hex> pin") + for m in PIN_RE.finditer(text): + name, version = m["name"], m["version"] + if name not in matrix: + errors.append(f"{fname}: image '{name}' is not in the matrix of {MATRIX_FILE}") + continue + try: + if parse_version(version) > parse_version(matrix[name]["version"]): + errors.append(f"{fname}: pin {name}:{version} is newer than the matrix version " + f"{matrix[name]['version']}") + except ValueError as exc: + errors.append(f"{fname}: {name}: {exc}") + return errors + + +def check_bump(base_matrix, head_matrix, changed, read_head_file): + errors = [] + 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 + 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 " + 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(): + old = base_matrix.get(name) + if old and parse_version(entry["version"]) < parse_version(old["version"]): + errors.append(f"image '{name}' version went backwards: {old['version']} -> {entry['version']}") + return errors + + +def git(*args, raw=False): + """Stdout of a git command: text, or bytes with raw=True (for paths, which need not be UTF-8).""" + try: + 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 + + +def run(argv): + if len(argv) >= 2 and argv[1] == "pins" and len(argv) == 2: + matrix = matrix_of(pathlib.Path(MATRIX_FILE).read_text()) + if not pathlib.Path(REQUIRED_CONSUMER).exists(): + raise CheckError(f"{REQUIRED_CONSUMER} is missing: it runs this check and is a required consumer") + texts = {f: pathlib.Path(f).read_text() for f in CONSUMERS if pathlib.Path(f).exists()} + errors = check_pins(matrix, texts) + note = " (checked: " + ", ".join(texts) + ")" + 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 + try: + base_text = git("show", f"{base}:{MATRIX_FILE}") + except CheckError: + base_text = None # no matrix at the base: every image is new + base_matrix = matrix_of(base_text) if base_text is not None else {} + head_matrix = matrix_of(pathlib.Path(MATRIX_FILE).read_text()) + errors = check_bump(base_matrix, head_matrix, changed, lambda p: pathlib.Path(p).read_text()) + note = "" + else: + sys.stderr.write(__doc__) + return None, "" + return errors, note + + +def main(argv): + note = "" + try: + errors, note = run(argv) + except CheckError as exc: + errors = [str(exc)] + except UnicodeDecodeError as exc: # before ValueError, which it subclasses + errors = [f"a file is not valid UTF-8: {exc}"] + except ValueError as exc: # parse_version + errors = [f"cannot parse a version: {exc}"] + except OSError as exc: + errors = [f"cannot read a file: {exc}"] + if errors is None: + return 2 + for e in errors: + sys.stderr.write(f"::error::{e}\n") + if not errors: + print(f"image versions and pins: ok{note}") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/tests/scripts/test_check_image_versions.py b/tests/scripts/test_check_image_versions.py new file mode 100644 index 0000000..877eac5 --- /dev/null +++ b/tests/scripts/test_check_image_versions.py @@ -0,0 +1,363 @@ +# 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 check_image_versions as civ # noqa: E402 + +DIGEST = "sha256:" + "a" * 64 +IMAGE_YML = """\ +jobs: + image: + strategy: + matrix: + include: + - name: mol + version: {mol} + 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 ./\nCOPY --from=b /a /b\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_copy_sources_skip_from_stage(self): + self.assertEqual(civ.copy_sources(CI_DOCKERFILE), ["requirements-dev.txt", ".pre-commit-config.yaml"]) + + def test_copy_sources_json_form_and_directories(self): + self.assertEqual(civ.copy_sources('COPY ["a.txt", "b/", "/dst/"]\n'), ["a.txt", "b/"]) + self.assertEqual(civ.touched(["conf/x.cfg", "other"], [], ["conf/"]), ["conf/x.cfg"]) + self.assertEqual(civ.touched(["a.txt", "b.txt", "c.md"], [], ["*.txt"]), ["a.txt", "b.txt"]) + self.assertEqual(civ.touched(["anything"], [], ["."]), ["anything"]) + + def test_version_order(self): + self.assertGreater(civ.parse_version("0.10.0"), civ.parse_version("0.9.0")) + self.assertGreater(civ.parse_version("1.0.0"), civ.parse_version("1.0.0-rc.1")) + with self.assertRaises(ValueError): + civ.parse_version("1.0.0+build") + + def test_prerelease_precedence_per_semver(self): + order = ["1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-alpha.beta", "1.0.0-beta", "1.0.0-beta.2", + "1.0.0-beta.11", "1.0.0-rc.1", "1.0.0"] + keys = [civ.parse_version(v) for v in order] + self.assertEqual(keys, sorted(keys)) + self.assertEqual(len(set(keys)), len(keys)) + self.assertLess(civ.parse_version("1.0.0-2"), civ.parse_version("1.0.0-10")) + self.assertLess(civ.parse_version("1.0.0-9"), civ.parse_version("1.0.0-a")) + with self.assertRaises(ValueError): + civ.parse_version("1.0.0-a..b") + + def test_whole_line_comments_are_not_pins(self): + m = self.matrix() + text = f"# was git.rkdr.net/mortis/zzz:0.1.0@{DIGEST}\n # see git.rkdr.net/mortis/ci:9.9.9\n" + self.assertEqual(civ.check_pins(m, {"f": text}), []) + both = text + f"image: git.rkdr.net/mortis/zzz:0.1.0@{DIGEST} # trailing\n" + self.assertEqual(len(civ.check_pins(m, {"f": both})), 1) + + def matrix(self, mol="0.1.0", ci="0.2.0"): + return civ.matrix_of(IMAGE_YML.format(mol=mol, ci=ci)) + + def test_pins_ok_and_lagging(self): + pin = f"image: git.rkdr.net/mortis/ci:0.1.0@{DIGEST}\n" + self.assertEqual(civ.check_pins(self.matrix(), {"lint.yml": pin}), []) + + def test_pin_ahead_of_matrix_unknown_image_and_malformed(self): + m = self.matrix() + self.assertEqual(len(civ.check_pins(m, {"f": f"git.rkdr.net/mortis/ci:0.3.0@{DIGEST}"})), 1) + self.assertEqual(len(civ.check_pins(m, {"f": f"git.rkdr.net/mortis/zzz:0.1.0@{DIGEST}"})), 1) + self.assertEqual(len(civ.check_pins(m, {"f": "git.rkdr.net/mortis/ci:0.2.0"})), 1) + self.assertEqual(len(civ.check_pins(m, {"f": "git.rkdr.net/mortis/ci@sha256:abc"})), 1) + + def test_pin_spellings_are_reported(self): + m = self.matrix() + spellings = [ + f"Git.rkdr.net/mortis/ci:0.1.0@{DIGEST}", + f"git.rkdr.net/Mortis/ci:0.1.0@{DIGEST}", + f"git.rkdr.net:443/mortis/ci:0.1.0@{DIGEST}", + f"git.rkdr.net/mortis/ci/sub:0.1.0@{DIGEST}", + f"GIT.RKDR.NET/mortis/CI:0.1.0@{DIGEST}", + "git.rkdr.net/mortis/ci", + "git.rkdr.net/mortis/ci:0.1.0", + ] + for spelling in spellings: + errors = civ.check_pins(m, {"f": f"image: {spelling}\n"}) + self.assertEqual(len(errors), 1, f"{spelling}: {errors}") + self.assertIn("not a :@sha256", errors[0]) + valid = f"image: git.rkdr.net/mortis/ci:0.1.0@{DIGEST}\n" + self.assertEqual(civ.check_pins(m, {"f": valid}), []) + + def test_urls_and_ssh_remotes_are_not_pin_mentions(self): + m = self.matrix() + text = ("url: https://git.rkdr.net/mortis/kamino\nurl2: http://git.rkdr.net/mortis/kamino.git\n" + "ssh: git@git.rkdr.net:mortis/kamino.git\n") + self.assertEqual(civ.check_pins(m, {"f": text}), []) + + def test_copy_source_fails_closed(self): + cases = { + "COPY $FILE /dst/\n": "'$'", + 'COPY "a b" /dst/\n': "'\"'", + "COPY 'a' /dst/\n": "\"'\"", + "COPY a#b /dst/\n": "'#'", + 'COPY ["$X", "/dst/"]\n': "'$'", + "COPY [\"a\", unquoted]\n": "JSON form", + "RUN --mount=type=bind,source=src,target=/s make\n": "RUN --mount binds the build context", + "RUN --mount=source=src,target=/s make\n": "RUN --mount binds the build context", + "FROM x\nRUN --mount=type=bind,target=/s \\\n make\n": "Dockerfile:2:", + } + for text, expected in cases.items(): + with self.assertRaises(civ.CheckError, msg=text) as ctx: + civ.copy_sources(text, "images/ci/Dockerfile") + message = str(ctx.exception) + self.assertIn(expected, message, text) + self.assertIn("images/ci/Dockerfile:", message) + self.assertNotIn("\n", message) + + def test_copy_source_ok_cases_still_pass(self): + ok = ("RUN --mount=type=cache,target=/c make\nRUN --mount=type=bind,from=b,source=/x,target=/y make\n" + "# COPY $IGNORED /x\nCOPY --chown=1:1 a b/ /dst/\nCOPY https://example.org/x /dst/\n") + self.assertEqual(civ.copy_sources(ok), ["a", "b/"]) + + def test_continuation_with_trailing_blanks_is_joined(self): + text = "COPY a.txt \\ \n b.txt /dst/\n" + self.assertEqual(civ.copy_sources(text), ["a.txt", "b.txt"]) + text = "COPY a.txt \\\n# a comment\n b.txt /dst/\n" + self.assertEqual(civ.copy_sources(text), ["a.txt", "b.txt"]) + + def test_empty_or_non_mapping_matrix_file(self): + 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)) + + 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"): + with self.assertRaises(ValueError, msg=repr(bad)): + civ.parse_version(bad) + for good in ("0.0.0", "1.0.0-0", "1.0.0-0a", "1.0.0-rc.0", "10.20.30"): + civ.parse_version(good) + + def test_pin_followed_by_punctuation_is_parsed(self): + m = self.matrix() + for tail in (",", ")", "]", "}", "'", '"', ";"): + text = f"x: [git.rkdr.net/mortis/ci:0.1.0@{DIGEST}{tail if tail != ';' else ''} y]\n" + self.assertEqual(civ.check_pins(m, {"f": text}), [], tail) + ahead = f"x: (git.rkdr.net/mortis/ci:0.3.0@{DIGEST}), z\n" + self.assertEqual(len(civ.check_pins(m, {"f": ahead})), 1) + 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" + + entry = "{name: a, version: '0.1.0', dockerfile: D" + 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'", + } + 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)) + self.assertNotIn("\n", str(ctx.exception)) + self.assertEqual(civ.matrix_of(doc("[" + entry + ", subpath: }]"))["a"]["subpath"], "") + with self.assertRaises(civ.CheckError) as ctx: + civ.matrix_of("jobs: [unclosed\n") + self.assertNotIn("\n", str(ctx.exception)) + + def test_bump_logic(self): + def read(_path): + return CI_DOCKERFILE + + base = self.matrix() + same = self.matrix() + for path in ("images/mol/Dockerfile", "images/ci/Dockerfile", "requirements-dev.txt", ".pre-commit-config.yaml"): + self.assertTrue(civ.check_bump(base, same, [path], read), path) + self.assertEqual(civ.check_bump(base, same, ["README.md", "images/other/x", ".gitea/workflows/lint.yml"], read), []) + self.assertEqual(civ.check_bump(base, self.matrix(ci="0.2.1"), ["requirements-dev.txt"], read), []) + self.assertTrue(civ.check_bump(base, self.matrix(ci="0.1.9"), [], read)) # backwards + + +class GitTest(unittest.TestCase): + """Run the script as CI does, in a throwaway repository.""" + + 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", "t@example.org") + 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 bump(self): + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_image_versions.py"), "bump", "main"], + cwd=self.repo, capture_output=True, text=True, check=False) + return proc.returncode, proc.stderr + + def bump_args(self, *args, cwd=None): + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_image_versions.py"), *args], + cwd=cwd or self.repo, capture_output=True, text=True, check=False) + return proc.returncode, proc.stderr + + def assert_clean_failure(self, result, text): + code, err = result + self.assertEqual(code, 1, err) + self.assertNotIn("Traceback", err) + self.assertIn(text, err) + self.assertEqual(len(err.strip().splitlines()), 1, err) + + def test_moved_input_out_of_the_set_fails(self): + run(self.repo, "git", "mv", "images/mol/Dockerfile", "elsewhere.dockerfile") + self.commit("move out") + code, err = self.bump() + self.assertEqual(code, 1) + self.assertIn("image 'mol'", err) + + def test_renamed_pinned_input_fails(self): + run(self.repo, "git", "mv", "requirements-dev.txt", "req2.txt") + self.commit("rename") + code, err = self.bump() + self.assertEqual(code, 1) + self.assertIn("image 'ci'", err) + + def test_option_like_base_ref_is_rejected(self): + for ref in ("--output=/tmp/x", "-h", "a b", "main\n"): + self.assert_clean_failure(self.bump_args("bump", ref), "not a plain ref name") + + def test_unknown_base_ref_is_one_line(self): + self.assert_clean_failure(self.bump_args("bump", "nope"), "git merge-base failed") + + 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") + self.assert_clean_failure(self.bump(), "'latest' is not MAJOR.MINOR.PATCH") + + def test_missing_matrix_keys_is_one_line(self): + self.write(".gitea/workflows/image.yml", IMAGE_YML.replace(" version: {mol}\n", "") + .format(mol="", ci="0.2.0")) + self.commit("no version") + self.assert_clean_failure(self.bump(), "lacks the key") + self.write(".gitea/workflows/image.yml", "jobs: {}\n") + self.commit("no matrix") + self.assert_clean_failure(self.bump(), "no jobs.image.strategy.matrix.include") + + def test_pins_mode_missing_matrix_file_is_one_line(self): + run(self.repo, "git", "rm", "-q", ".gitea/workflows/image.yml") + self.assert_clean_failure(self.bump_args("pins"), "cannot read a file") + + def test_non_ascii_input_path_counts(self): + self.write("images/mol/caf\u00e9", "x\n") + self.commit("non-ascii input") + code, err = self.bump() + self.assertEqual(code, 1, err) + self.assertIn("image 'mol'", err) + self.assertIn("caf\u00e9", err) + + def test_non_utf8_path_in_the_diff_is_named(self): + path = os.fsencode(str(self.repo)) + b"/images/mol/caf\xe9" + try: + with open(path, "wb") as handle: + handle.write(b"x\n") + except OSError: + self.skipTest("the file system does not accept a non-UTF-8 name") + self.commit("non-utf8 input") + self.assert_clean_failure(self.bump(), "path is not valid UTF-8") + + 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") + + def test_unsupported_dockerfile_source_fails_with_file_and_line(self): + self.write("images/ci/Dockerfile", "FROM x\nCOPY $SRC ./\n") + self.commit("variable source") + self.assert_clean_failure(self.bump(), "images/ci/Dockerfile:2:") + + def test_pins_mode_requires_lint_yml_and_lists_checked_consumers(self): + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_image_versions.py"), "pins"], + cwd=self.repo, capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 1, proc.stdout) + self.assertIn("lint.yml is missing", proc.stderr) + self.write(".gitea/workflows/lint.yml", f"image: git.rkdr.net/mortis/ci:0.1.0@{DIGEST}\n") + proc = subprocess.run([sys.executable, str(SCRIPTS / "check_image_versions.py"), "pins"], + cwd=self.repo, capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn("(checked: .gitea/workflows/lint.yml)", proc.stdout) + self.assertNotIn("build.yml", proc.stdout) + + def test_unrelated_change_passes(self): + self.write("README.md", "x\n") + self.commit("docs") + self.assertEqual(self.bump()[0], 0) + + def test_pinned_input_without_bump_fails(self): + self.write("requirements-dev.txt", "a==2\n") + self.commit("deps") + code, err = self.bump() + self.assertEqual(code, 1) + self.assertIn("image 'ci'", err) + self.assertNotIn("image 'mol'", err) + + def test_pinned_input_with_bump_passes(self): + self.write("requirements-dev.txt", "a==2\n") + self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.1.0", ci="0.2.1")) + self.commit("deps and bump") + self.assertEqual(self.bump()[0], 0) + + def test_dockerfile_change_of_molecule_image_fails(self): + self.write("images/mol/Dockerfile", "FROM y\n") + self.commit("mol") + code, err = self.bump() + self.assertEqual(code, 1) + self.assertIn("image 'mol'", err) + + def test_bump_survives_main_moving_on(self): + run(self.repo, "git", "checkout", "-q", "main") + self.write("README.md", "newer main\n") + self.commit("main moves") + run(self.repo, "git", "checkout", "-q", "feature") + self.write("images/mol/Dockerfile", "FROM y\n") + self.write(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.2.0", ci="0.2.0")) + self.commit("mol with bump") + self.assertEqual(self.bump()[0], 0) + + +if __name__ == "__main__": + unittest.main()