ci(images): assign image versions in CI and open the pin PR right after a push #340

Merged
Defame1297 merged 2 commits from ci/165-image-versions-in-ci into main 2026-11-23 21:34:28 +00:00
23 changed files with 484 additions and 1064 deletions

No files matched your search

+2 -3
View File
@@ -34,13 +34,12 @@ issue.
- **Judge scripts:** a script that judges a pull request's own diff runs from `main`'s copy; a
content or artefact check runs from the pull request's copy. `check_bot_pr_diff.py` (Lint) and
`select_molecule_scenarios.py` (Molecule) run from `origin/main`; the pull request that adds
such a script runs its own copy once, with a notice. Exception until #165 removes it:
`check_image_versions.py bump` (Lint) judges the diff but runs from the pull request's copy.
such a script runs its own copy once, with a notice.
*Why:* a pull request that could edit the rules it is judged by could pass by weakening them,
while a content check must see the content it is given. *Held:* review (`CODEOWNERS`).
- **A pull request from a `renovate/` branch changes only version, tag, digest and pin lines**
(tool pins with their lock entries and hashes, hook `rev:` lines, Dockerfile `FROM` tags and
digests, matrix `version:` lines, `job_image:` pins, consumer image pins).
digests, `job_image:` pins, consumer image pins).
*Why:* the bot's minor and patch pull requests automerge, so they must not be able to change
anything else. *Held:* control: the Lint check's "Check a bot pull request only moves pins"
step, `scripts/check_bot_pr_diff.py` run from `main`'s copy. The branch name is chosen by the
+61 -46
View File
@@ -65,29 +65,27 @@ jobs:
# One job at a time on the single-capacity runner. An empty subpath means the
# repository root is the build context.
#
# version: the semver tag of the image, independent of the Collection's releases.
# Bump it in the same PR as an image change you want to publish under a new tag.
# A version that is already in the registry is never moved and never rebuilt (see the
# prepare step): that job ends without building, so every digest belongs to exactly one
# version tag. A new version is pushed as <version> and latest. Pin consumers as
# image:<version>@sha256:<digest>; the digest is what is enforced.
# base: MAJOR.MINOR of the image's semver tags, independent of the Collection's releases;
# edit it by hand only for a minor or major. The job publishes the next <base>.N when the
# image's inputs differ from the newest one's (scripts/next_image_version.py), as <version>
# and latest; a published tag is never moved. Pin consumers as image:<version>@sha256:<digest>.
strategy:
fail-fast: false
max-parallel: 1
matrix:
include:
- name: molecule-ubuntu2404
version: 0.1.9
base: "0.1"
subpath: images/molecule-ubuntu2404
dockerfile: Dockerfile
job_image: ubuntu:24.04@sha256:9c7f200c07e3d4a03e7249d2c16bf66a51120fb876aa2242cf31451412543289
- name: molecule-ubuntu2604
version: 0.1.5
base: "0.1"
subpath: images/molecule-ubuntu2604
dockerfile: Dockerfile
job_image: ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db
- name: ci
version: 0.2.38
base: "0.2"
subpath: ""
dockerfile: images/ci/Dockerfile
job_image: ubuntu:26.04@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db
@@ -98,18 +96,7 @@ jobs:
env:
DEBIAN_FRONTEND: noninteractive
IMAGE_PATH: mortis/${{ matrix.name }}
IMAGE_VERSION: ${{ matrix.version }}
steps:
# The version becomes an image tag. OCI tags cannot contain '+' (semver build
# metadata), so only MAJOR.MINOR.PATCH[-prerelease] is accepted. Refuse before
# anything is installed or built. Only bash builtins are used.
- name: Validate the image version
run: |
if ! [[ "$IMAGE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
echo "::error::Image version '$IMAGE_VERSION' is not MAJOR.MINOR.PATCH[-prerelease]; refusing to build or push."
exit 1
fi
# One step, in this order, so the filesystem the build starts from is the pristine
# base image. Kaniko unpacks the base image into the job container's own root
# filesystem and snapshots from there, so anything installed in the job container
@@ -132,16 +119,24 @@ jobs:
# Its CA bundle (layers[1]) and executor (layers[9], both 0-based) are fetched by content digest and
# verified with sha256sum.
#
# The version: python3 runs scripts/next_image_version.py from this commit's source
# archive, without the registry credential in its environment, and writes
# "<version> <checksum>" to /kaniko/image-version, or nothing when the inputs are unchanged.
#
# The credential: the org push token, checked by one write probe before the build.
# Credentials reach commands only through the environment and curl's stdin
# config, never the argument list or the log. Writes /kaniko/.docker/config.json.
- name: Prepare kaniko and check the registry credential
- name: Choose the version, prepare kaniko and check the registry credential
env:
KANIKO_CA_LAYER_SHA256: 5ecab5922e6a5124fab96e8cb404b8cf93e8a96716af4fbbea2a9221b1216f86
KANIKO_EXECUTOR_LAYER_SHA256: 49c71aa9e7197af5dcf12811395f182f831c7e714ba94241908c955dd1649ca7
PAT_USER: ${{ secrets.PACKAGE_PUSH_USER }}
PAT_TOKEN: ${{ secrets.PACKAGE_PUSH_TOKEN }}
JOB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SERVER_URL: ${{ github.server_url }}
REPO: ${{ github.repository }}
SHA: ${{ github.sha }}
IMAGE_NAME: ${{ matrix.name }}
run: |
set +x
set -eu
@@ -161,7 +156,22 @@ jobs:
dpkg-query -W -f='${Package}:${Architecture} ${Version}\n' | LC_ALL=C sort > /kaniko/pkgv.before
apt-get update
apt-get install -y --no-install-recommends ca-certificates curl
apt-get install -y --no-install-recommends ca-certificates curl python3
set -o pipefail
mkdir -p /tmp/src
printf 'header = "Authorization: token %s"\n' "$JOB_TOKEN" \
| curl -fsSL -K - "${SERVER_URL}/api/v1/repos/${REPO}/archive/${SHA}.tar.gz" \
| tar -xz -C /tmp/src --strip-components=1
# -B: no bytecode left behind to break the pristine-filesystem check below.
env -u PAT_USER -u PAT_TOKEN -u JOB_TOKEN python3 -B -E -s \
/tmp/src/scripts/next_image_version.py /tmp/src "$IMAGE_NAME" "$registry" > /kaniko/image-version
if [ -s /kaniko/image-version ]; then
read -r IMAGE_VERSION _ < /kaniko/image-version
echo "Inputs of ${IMAGE_PATH} changed: publishing ${IMAGE_VERSION}."
else
echo "Inputs of ${IMAGE_PATH} are unchanged since its newest version: nothing to publish."
fi
fetch_layer() {
token="$(curl -fsS 'https://ghcr.io/token?scope=repository:osscontainertools/kaniko:pull' \
@@ -208,22 +218,20 @@ jobs:
write_config "$PAT_USER" "$PAT_TOKEN"
echo "Registry credential accepted: PACKAGE_PUSH_USER / PACKAGE_PUSH_TOKEN"
# Gitea cannot make a tag immutable, so look the version tag up first: when it
# exists the build must not move it (the build step reads this marker).
accept='application/vnd.oci.image.index.v1+json'
accept="$accept, application/vnd.oci.image.manifest.v1+json"
accept="$accept, application/vnd.docker.distribution.manifest.v2+json"
code="$(printf 'user = "%s:%s"\n' "$cred_user" "$cred_token" \
| curl -sS -o /dev/null -w '%{http_code}' -I -K - -H "Accept: $accept" \
"https://${registry}/v2/${IMAGE_PATH}/manifests/${IMAGE_VERSION}" || true)"
case "$code" in
200) touch /kaniko/version-published; echo "Version tag ${IMAGE_VERSION} is already published; it will not be moved." ;;
404) echo "Version tag ${IMAGE_VERSION} is not published yet." ;;
*)
echo "::error::Unexpected HTTP status $code looking up the tag ${IMAGE_VERSION}; refusing to guess whether it is published."
# Gitea cannot make a tag immutable, so check with the push credential that the
# chosen version is not published: an existing tag is never moved.
if [ -s /kaniko/image-version ]; then
accept='application/vnd.oci.image.index.v1+json'
accept="$accept, application/vnd.oci.image.manifest.v1+json"
accept="$accept, application/vnd.docker.distribution.manifest.v2+json"
code="$(printf 'user = "%s:%s"\n' "$cred_user" "$cred_token" \
| curl -sS -o /dev/null -w '%{http_code}' -I -K - -H "Accept: $accept" \
"https://${registry}/v2/${IMAGE_PATH}/manifests/${IMAGE_VERSION}" || true)"
if [ "$code" != "404" ]; then
echo "::error::Looking up ${IMAGE_PATH}:${IMAGE_VERSION} gave HTTP $code, not 404; refusing to move or guess about a published tag."
exit 1
;;
esac
fi
fi
# Back to the pristine base image (see above): purge exactly what the install
# added, then compare packages (names and versions) and files with the record.
@@ -266,21 +274,28 @@ jobs:
registry="${SERVER_URL#https://}"
image="${registry}/${IMAGE_PATH}"
# /kaniko is removed when the build finishes, so read the marker now. A published
# version is neither moved nor rebuilt: an image whose inputs changed needs a new
# version (Lint enforces it), and a rebuild of unchanged inputs would only give the
# same tag a second digest.
if [ -e /kaniko/version-published ]; then
echo "${image}:${IMAGE_VERSION} is already published; nothing to build."
# /kaniko is removed when the build finishes, so read the chosen version now.
IMAGE_VERSION=""
if [ -s /kaniko/image-version ]; then
read -r IMAGE_VERSION INPUTS_SHA256 < /kaniko/image-version
fi
if [ -z "$IMAGE_VERSION" ]; then
echo "${image}: inputs unchanged; nothing to build."
if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then
echo "${IMAGE_PATH}:${IMAGE_VERSION} is already published; skipped." >> "$GITHUB_STEP_SUMMARY" || true
echo "${IMAGE_PATH}: inputs unchanged; skipped." >> "$GITHUB_STEP_SUMMARY" || true
fi
exit 0
fi
# OCI tags cannot contain '+', and the checksum becomes a label value.
if ! [[ "$IMAGE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ && "$INPUTS_SHA256" =~ ^[0-9a-f]{64}$ ]]; then
echo "::error::next_image_version.py printed '${IMAGE_VERSION} ${INPUTS_SHA256}', not '<MAJOR.MINOR.PATCH> <sha256>'."
exit 1
fi
dests=(--destination "${image}:${IMAGE_VERSION}" --destination "${image}:latest")
# Labels only the build knows (the static ones are in the Dockerfile). The package page of
# the registry lists them next to the Dockerfile's.
labels=(--label "org.opencontainers.image.version=${IMAGE_VERSION}"
# the registry lists them next to the Dockerfile's; the next build compares the checksum.
labels=(--label "net.rkdr.mortis.inputs-sha256=${INPUTS_SHA256}"
--label "org.opencontainers.image.version=${IMAGE_VERSION}"
--label "org.opencontainers.image.revision=${SHA}"
--label "org.opencontainers.image.created=$(date -u +%Y-%m-%dT%H:%M:%SZ)")
+1 -8
View File
@@ -76,8 +76,7 @@ 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 pins (scripts/check_image_versions.py): 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
@@ -85,12 +84,6 @@ jobs:
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
# A pull request from a renovate/ branch may only move version, tag, digest and pin
# lines (scripts/check_bot_pr_diff.py), so the bot's automerge cannot change workflow
# logic or reach the org secrets. The branch name is attacker-controlled: this only
+15 -10
View File
@@ -13,8 +13,14 @@ name: Renovate
# RENOVATE_GITHUB_TOKEN_WARN=false below: the token check runs before package rules apply.
#
# Dry run: Actions > Renovate > Run workflow, dry_run=true (the default for a manual run), then
# read the debug log. The schedule runs live.
# read the debug log. The schedule runs live, and so does a successful Images run's completion, so
# the pin pull request for a new image version opens within minutes of its push. Gitea starts a
# workflow_run only for a run a person triggered, and its event carries no input or credential.
on: # yamllint disable-line rule:truthy
# Images runs only on main (push, dispatch), and this job reads nothing from its run but the conclusion.
workflow_run: # zizmor: ignore[dangerous-triggers]
workflows: [Images]
types: [completed]
schedule:
# Daily, off the hour so it avoids typical molecule and image runs.
- cron: "17 3 * * *"
@@ -39,12 +45,14 @@ concurrency:
jobs:
renovate:
# Only in this repository (a copy elsewhere has no such secret).
if: github.repository == 'mortis/kamino' || github.repository == 'Mortis/Kamino'
# Only in this repository (a copy elsewhere has no such secret), and not after a failed Images run.
if: >-
(github.repository == 'mortis/kamino' || github.repository == 'Mortis/Kamino') &&
(github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success')
runs-on: kamino-docker
timeout-minutes: 30
# Docker Hub image, pinned by digest. The -full flavour ships python3 for the
# postUpgradeTasks command. Hand-bumped: renovate.json
# Docker Hub image, pinned by digest. The -full flavour ships python3 for the report check
# below and pip-compile for lock refreshes. Hand-bumped: renovate.json
# disables updates for this file. The image sets RENOVATE_BINARY_SOURCE=global, so pip-compile
# runs on the image's own python (3.14.8 in 44.161.0) and ignores the Python that Renovate
# reads from the lock header: that python's minor version must equal .python-version, or a lock
@@ -66,17 +74,14 @@ jobs:
# No GitHub token exists, and the hooks go through git-tags (see the header). Without this
# Renovate marks every github-tags dependency as skipped before the package rule applies.
RENOVATE_GITHUB_TOKEN_WARN: "false"
# postUpgradeTasks may run exactly this one command (anchored, no wildcard); the JSON
# string holds a regex, hence the doubled backslash.
RENOVATE_ALLOWED_COMMANDS: '["^python3 scripts/bump_image_versions\\.py origin/main$"]'
# Renovate exits 0 when a repository run fails (e.g. the clone): with this it exits with
# an error-specific code instead (7 for an external host error such as a failed clone).
RENOVATE_EXIT_CODE_FOR_ERRORS: "true"
# The JSON report is checked after the run (see below).
RENOVATE_REPORT_TYPE: file
LOG_LEVEL: ${{ github.event_name == 'workflow_dispatch' && 'debug' || 'info' }}
# Fail safe: only the schedule is live. A manual dispatch is a dry run unless the input is
# exactly the string "false" (an empty input from an API or CLI dispatch stays a dry run).
# Fail safe: only the schedule and workflow_run are live. A manual dispatch is a dry run unless
# the input is exactly the string "false" (an empty input from an API or CLI dispatch stays one).
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run != 'false' && 'true' || 'false' }}
run: |
if [ -z "$RENOVATE_TOKEN" ]; then
+2 -2
View File
@@ -20,8 +20,8 @@ existing content is brought in line by separate issues.
*Reason:* every script here is code someone has to review and maintain.
*Held by:* review.
2. **One job per file, readable in one sitting.**
*Counter-example:* `scripts/check_image_versions.py` holds two checks, `pins` and `bump`, in over 800
lines.
*Counter-example:* `scripts/check_image_versions.py` holds a YAML reader and four checks (pins, job
containers, labels, the Python pin) in over 700 lines.
*Does not forbid:* helpers in the file that serve its one job, or a long file that is still one job;
do not split a file only for its length.
*Reason:* a reviewer has to hold the whole file in mind to judge a change to it.
+1 -1
View File
@@ -89,7 +89,7 @@ trailers, are in [ai-assistance.md](ai-assistance.md).
The rules for these live next to the files they govern: [scripts/AGENTS.md](../../scripts/AGENTS.md)
(scripts, their tests, tool pins and their lock, hook SHA pins),
[images/AGENTS.md](../../images/AGENTS.md) (image inputs, version bumps, pin pull requests, the layer
[images/AGENTS.md](../../images/AGENTS.md) (image inputs, versions, pin pull requests, the layer
limit), [.gitea/workflows/AGENTS.md](../../.gitea/workflows/AGENTS.md) (workflows, secrets, the
bot-diff check `scripts/check_bot_pr_diff.py`) and [docs/adr/AGENTS.md](../adr/AGENTS.md) (decision
records).
+3 -3
View File
@@ -77,9 +77,9 @@ real consumers.
`.gitea/workflows/image.yml` builds it with kaniko (repository root as build context, because the pin
files are copied in). The workflow runs on pushes to `main` that touch `images/**`, `requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml`,
`.pre-commit-config.yaml` or the workflow itself, never on a pull request, and builds an image only when its
`version:` in the workflow's matrix is not yet published. A change to the image's inputs therefore needs a new
`version:` (Lint checks it, and Renovate's bump step does it for dependency updates), and the merge builds
the image. Each pushed layer stays below 100 MB (Cloudflare's request limit), which is why the Go toolchains
inputs differ from those of its newest published version (`scripts/next_image_version.py` compares a checksum
label). It then publishes the next patch of the matrix's `base:`, and Renovate opens the pull request that
moves the pins to it. Each pushed layer stays below 100 MB (Cloudflare's request limit), which is why the Go toolchains
and the unused Go binaries are deleted from the hook cache, and why the build prints the compressed size of each layer
directory.
+2 -2
View File
@@ -67,8 +67,8 @@ systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`)
`.gitea/workflows/image.yml` builds it with kaniko. The workflow runs on pushes to `main` that touch `images/**`,
`requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml`, `.pre-commit-config.yaml` or the workflow itself, never on a pull request, and builds an
image only when its `version:` in the workflow's matrix is not yet published. A change under
`images/molecule-ubuntu2404/` therefore needs a new `version:` (Lint checks it) and the merge builds the image. The
image only when its inputs differ from those of its newest published version. A change under
`images/molecule-ubuntu2404/` therefore needs no version edit: the merge publishes the next patch of the matrix's `base:`. The
Ubuntu release is fixed by the name: a new Ubuntu release is a new image (`molecule-ubuntuNNNN`), and the roles
are tested on every release the hosts run or are moving to.
+2 -2
View File
@@ -66,8 +66,8 @@ systemd, packages, the `dbus` and `ssh` units, the Python bindings, `NET_ADMIN`)
`.gitea/workflows/image.yml` builds it with kaniko. The workflow runs on pushes to `main` that touch `images/**`,
`requirements-dev.txt`, `requirements-dev.lock`, `requirements.yml`, `.pre-commit-config.yaml` or the workflow itself, never on a pull request, and builds an
image only when its `version:` in the workflow's matrix is not yet published. A change under
`images/molecule-ubuntu2604/` therefore needs a new `version:` (Lint checks it) and the merge builds the image. The
image only when its inputs differ from those of its newest published version. A change under
`images/molecule-ubuntu2604/` therefore needs no version edit: the merge publishes the next patch of the matrix's `base:`. The
Ubuntu release is fixed by the name: a new Ubuntu release is a new image (`molecule-ubuntuNNNN`), and the roles
are tested on every release the hosts run or are moving to.
+26 -24
View File
@@ -8,27 +8,30 @@ change before it merges (`images/` and `.gitea/` are under `CODEOWNERS`); aspira
nothing checks it. "Until X (#N) lands" names a change that is planned and its backlog issue.
`image.yml` builds each image with kaniko on push to `main`, never on a pull request, and pushes
it to this repository's organisation in the Gitea registry as `<version>` and `latest`.
it to this repository's organisation in the Gitea registry as `<version>` and `latest`. CI assigns
`<version>`: the next patch of the matrix entry's `base:` when the image's inputs changed.
## Versions and pins
- **A published version is never moved and never rebuilt.** The build looks the version up in
the registry first and ends without building when it exists; there is no `sha-*` tag, so one
digest belongs to exactly one version. *Why:* a pin names exactly what a reviewer saw.
*Held:* control: the tag lookup in `image.yml`'s "Prepare kaniko and check the registry
credential" step.
- **A pull request that changes an image input (`requirements-dev.txt`, `requirements-dev.lock`,
`requirements.yml`, `.pre-commit-config.yaml`, `images/**`) raises that image's `version:` (a
PATCH bump) in the `image.yml` build matrix** (`python3 scripts/bump_image_versions.py` makes
the edit). Until #165 assigns versions in CI. *Why:* a published version is never rebuilt, so
a changed input needs a new version. *Held:* control: the Lint check's "Check image versions
were bumped" step.
- **After the merge builds the image, a second pull request moves the
- **A published version is never moved and never rebuilt.** The build publishes only a version
the registry does not have, and one whose inputs match the newest version's is not built;
there is no `sha-*` tag, so one digest belongs to exactly one version. *Why:* a pin names
exactly what a reviewer saw. *Held:* control: `scripts/next_image_version.py` and the tag
lookup in `image.yml`'s prepare step.
- **A pull request that changes an image input needs no version edit.** On `main`,
`scripts/next_image_version.py` compares a checksum of the image's inputs (its build context,
or the files its Dockerfile copies from the repository root) with the
`net.rkdr.mortis.inputs-sha256` label of the newest published `<base>.N`, and the build
publishes `<base>.N+1` when they differ. Edit `base:` by hand only for a minor or major.
*Why:* a version a person must remember to raise is a version someone forgets. *Held:*
control: the Images workflow assigns it (`next_image_version.py`, with its tests).
- **After the build pushes a new version, a second pull request moves the
`image:<version>@sha256:<digest>` pins in `lint.yml`, `build.yml`, `molecule.yml` and
`gitea-release-key.yml` to the digest the build printed.** It touches no `image.yml` trigger
path, so it rebuilds nothing. Renovate opens it for these images; a new image's first pin is a
hand-made pull request, and a major version is moved by hand. *Why:* consumers run exactly
the digest a reviewer saw. *Held:* review.
`gitea-release-key.yml` to it.** Renovate opens it within minutes: the Images run's successful
completion starts a live Renovate run (`workflow_run` in `renovate.yml`). It changes no image
input, so it publishes nothing. A new image's first pin is a hand-made pull request, and a
major version is moved by hand. *Why:* consumers run exactly the digest a reviewer saw.
*Held:* review.
- **Image-input bumps are no Collection release:** these files are in `galaxy.yml`
`build_ignore`, and their bumps need no changelog fragment and no new `galaxy.yml` version.
*Why:* they change neither the Collection nor what a consumer installs. *Held:* control for
@@ -45,10 +48,9 @@ it to this repository's organisation in the Gitea registry as `<version>` and `l
costs runner time and proves nothing. *Held:* aspirational.
- **Each matrix entry's `job_image: ubuntu:<release>@sha256:...` has the same release as the
`FROM ubuntu:` of its Dockerfile.** Moving an image to a new release is one edit: the `FROM`,
the `job_image` tag and digest, and the version bump. Digest drift within a release is
tolerated. A `job_image`-only bump is not an image input: no version bump, nothing rebuilt; the
post-merge Images run builds nothing past its prepare step for a published version, so that is
its only exercise.
and the `job_image` tag and digest. Digest drift within a release is tolerated. A
`job_image`-only bump is not an image input: the post-merge Images run publishes nothing, and
its prepare step is that bump's only exercise.
*Why:* kaniko runs inside the job container and unpacks the image it builds over it. *Held:*
control: `check_image_versions.py pins` in the Lint check.
- **kaniko (the osscontainertools fork) is pinned by layer digests in `image.yml` and bumped by
@@ -73,10 +75,10 @@ it to this repository's organisation in the Gitea registry as `<version>` and `l
## Metadata
- **Each Dockerfile carries the same label block** (`org.opencontainers.image.*` plus
`net.rkdr.mortis.purpose`, `contents` and `usage`); the build adds `version`, `revision` and
`created`. The readme-style text lives in `docs/images/<name>.md`, which the `documentation`
`net.rkdr.mortis.purpose`, `contents` and `usage`); the build adds `version`, `revision`,
`created` and `net.rkdr.mortis.inputs-sha256`. The readme-style text lives in `docs/images/<name>.md`, which the `documentation`
label links to. *Why:* Gitea's package page shows the labels and links but renders no README.
Editing that doc is not an image input and needs no new version; editing a label is and does.
Editing that doc is not an image input; editing a label is, and publishes a new version.
*Held:* control: `check_image_versions.py pins` fails when a label or the doc is missing.
## Image-smoke scenarios
+1 -2
View File
@@ -53,8 +53,7 @@ FROM os AS build
# The Python of /opt/venv: the minor version of .python-version (check_image_versions.py pins fails when
# an ARG PYTHON_VERSION line of this file, or the header of requirements-dev.lock, differs from it). The
# interpreters below and the python<MINOR> links of the final stage are derived from it. Moving it is one
# pull request: both ARG lines, .python-version, the lock (scripts/lock-requirements.sh) and the image
# version bump.
# pull request: both ARG lines, .python-version and the lock (scripts/lock-requirements.sh).
ARG PYTHON_VERSION=3.14
ENV PIP_DISABLE_PIP_VERSION_CHECK=1 \
+4 -13
View File
@@ -1,6 +1,6 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"description": "Run by .gitea/workflows/renovate.yml on this repository's own runner. Policy: automerge minor and patch, majors by hand. Every bot pull request must pass scripts/check_bot_pr_diff.py (lint workflow), which allows only version, tag, digest and pin lines. The top-level postUpgradeTasks runs scripts/bump_image_versions.py on every branch, lock refreshes included, which carry no package a packageRule could match (allowed by RENOVATE_ALLOWED_COMMANDS of .gitea/workflows/renovate.yml, where Renovate runs).",
"description": "Run by .gitea/workflows/renovate.yml on this repository's own runner. Policy: automerge minor and patch, majors by hand. Every bot pull request must pass scripts/check_bot_pr_diff.py (lint workflow), which allows only version, tag, digest and pin lines. Image versions are assigned by the Images workflow when an image's inputs change, so a bot pull request needs no version edit.",
"extends": [
"config:recommended",
":enablePreCommit"
@@ -22,15 +22,6 @@
"prHourlyLimit": 5,
"minimumReleaseAge": "3 days",
"minimumReleaseAgeBehaviour": "timestamp-optional",
"postUpgradeTasks": {
"commands": [
"python3 scripts/bump_image_versions.py origin/main"
],
"fileFilters": [
".gitea/workflows/image.yml"
],
"executionMode": "branch"
},
"timezone": "UTC",
"ansible-galaxy": {
"managerFilePatterns": [
@@ -62,7 +53,7 @@
"customManagers": [
{
"customType": "regex",
"description": "The uv pin that installs the build-stage Python interpreters of the ci image (images/ci/Dockerfile). It is an image input: the version bump comes from scripts/bump_image_versions.py via the top-level postUpgradeTasks.",
"description": "The uv pin that installs the build-stage Python interpreters of the ci image (images/ci/Dockerfile). It is an image input: the merge publishes a new ci version.",
"managerFilePatterns": [
"/^images/ci/Dockerfile$/"
],
@@ -99,7 +90,7 @@
],
"packageRules": [
{
"description": "Dockerfile base-image tag and digest bumps (images/*/Dockerfile) MAY automerge. Kamino is the untrusted side and the bump pull request's own CI exercises the new image before the merge. Placed first so the major-version rule below still turns automerge off. The image version bump in image.yml comes from scripts/bump_image_versions.py via the top-level postUpgradeTasks.",
"description": "Dockerfile base-image tag and digest bumps (images/*/Dockerfile) MAY automerge. Kamino is the untrusted side and the bump pull request's own CI exercises the new image before the merge. Placed first so the major-version rule below still turns automerge off. The merge publishes a new image version.",
"matchManagers": [
"dockerfile"
],
@@ -169,7 +160,7 @@
"automerge": false
},
{
"description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): moves the image:<version>@sha256:<digest> pins of lint.yml, build.yml, molecule.yml and gitea-release-key.yml to the newest published version and its digest, and automerges (PR 2 of the update loop). The pull request's own Lint and Build run in the new image before the merge, scripts/check_bot_pr_diff.py allows only these pin lines, and scripts/check_image_versions.py pins fails a pin that is newer than the matrix. The registry lists tags and digests anonymously, so no hostRules are needed. A major version stays manual (rule above).",
"description": "Pin follow-up for our own images (git.rkdr.net/mortis/*): moves the image:<version>@sha256:<digest> pins of lint.yml, build.yml, molecule.yml and gitea-release-key.yml to the newest published version and its digest, and automerges. The Images workflow's completion starts a Renovate run, so this pull request opens minutes after a new version is pushed. The pull request's own Lint and Build run in the new image before the merge, and scripts/check_bot_pr_diff.py allows only these pin lines. The registry lists tags and digests anonymously, so no hostRules are needed. A major version stays manual (rule above).",
"matchPackageNames": [
"git.rkdr.net/mortis/**"
],
+2 -2
View File
@@ -36,6 +36,6 @@ rules for scripts (prefer a standard tool, comment length) are in
*Why:* a tag can be moved; a commit SHA cannot. *Held:* review (`.pre-commit-config.yaml` is
under `CODEOWNERS`).
A pin file is also an input of the `ci` image: [images/AGENTS.md](../images/AGENTS.md) has the
version bump it needs. Whether a workflow runs a script from `main`'s copy or from the pull
A pin file is also an input of the `ci` image: [images/AGENTS.md](../images/AGENTS.md) has what
the merge publishes. Whether a workflow runs a script from `main`'s copy or from the pull
request's is a rule of [.gitea/workflows/AGENTS.md](../.gitea/workflows/AGENTS.md) ("Judge scripts").
-226
View File
@@ -1,226 +0,0 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Bump the PATCH version of every image whose inputs changed.
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 (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 runs as a Renovate `postUpgradeTasks` command: renovate.json sets it at the top level
(so it runs on every branch, a lock refresh with no package included), with executionMode branch and fileFilters limited to
.gitea/workflows/image.yml,
allowed by RENOVATE_ALLOWED_COMMANDS of .gitea/workflows/renovate.yml. It is a no-op when no image
input changed, 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"
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>.*)$"
)
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 _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
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)
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 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)
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 = read_text(path)
head_matrix = civ.matrix_of(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"
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())
)
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))
+8 -17
View File
@@ -16,8 +16,9 @@ When <head-ref> starts with `renovate/`, the diff of <base-ref>...HEAD may only
* .pre-commit-config.yaml: `rev:` lines (a tag, or a commit SHA with its `# frozen: <tag>` comment);
* images/<name>/Dockerfile: the tag and digest of FROM lines (the image name stays), and
the `uv==<version>` token of a line that holds one;
* .gitea/workflows/image.yml: the matrix `version:` lines, and the tag and digest of the
job containers' `job_image: ubuntu:...@sha256:...` lines (the name stays);
* .gitea/workflows/image.yml: the tag and digest of the job containers'
`job_image: ubuntu:...@sha256:...` lines (the name stays); CI assigns the image versions
and a human sets the matrix `base:`, so neither is the bot's to change;
* .gitea/workflows/{lint,build,molecule,gitea-release-key}.yml: the version and digest of a
`git.rkdr.net/mortis/<name>:<version>@sha256:<digest>` pin (the name stays), including
the MOLECULE_IMAGE value.
@@ -153,8 +154,6 @@ def reduce_dockerfile(line):
def reduce_image_yml(line):
if VERSION_LINE.match(line):
return "version"
m = UBUNTU_LINE.match(line)
return m[1] if m else None
@@ -191,7 +190,7 @@ def file_problem(path, removed, added):
removed,
added,
reduce_image_yml,
"a matrix `version:` or a `job_image:` ubuntu pin",
"a `job_image:` ubuntu pin",
)
if path in CONSUMERS:
return same_shape(
@@ -243,19 +242,11 @@ def parse_patch(text):
return [line for unused, line in removed], [line for unused, line in added]
def version_problem(removed, added):
"""A reason when the matrix `version:` lines were moved, lowered or swapped, else None.
Both lists are (line number, line); the changed lines must sit at the same line numbers."""
def moved_problem(removed, added):
"""A reason when a changed line changes position, else None; both lists are (line number, line).
A `job_image:` pin moved to another matrix entry would change which job runs on it."""
if [n for n, unused in removed] != [n for n, unused in added]:
return "moves or deletes a line (the changed lines must stay where they are)"
for (unused, old), (unused, new) in zip(removed, added):
old_m, new_m = VERSION_LINE.match(old), VERSION_LINE.match(new)
if (
old_m
and new_m
and civ.parse_version(new_m["v"]) <= civ.parse_version(old_m["v"])
):
return f"does not raise a version ({old_m['v']} -> {new_m['v']})"
return None
@@ -285,7 +276,7 @@ def check(entries, patch_of):
path, [line for unused, line in removed], [line for unused, line in added]
)
if not reason and path == civ.MATRIX_FILE:
reason = version_problem(removed, added)
reason = moved_problem(removed, added)
if reason:
problems.append(f"{path}: {reason}")
return problems
+31 -151
View File
@@ -1,22 +1,17 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Keep image versions and image pins honest.
"""Keep image pins honest.
python3 scripts/check_image_versions.py pins
python3 scripts/check_image_versions.py bump <base-ref>
The matrix of .gitea/workflows/image.yml is the registry of images: name, version,
build context (subpath), Dockerfile and job container (job_image). 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 <version>@<new digest> pin
would pair a tag with a digest it does not point to.
The matrix of .gitea/workflows/image.yml is the registry of images: name, base (the
MAJOR.MINOR that CI publishes the next <base>.N patch under), build context (subpath),
Dockerfile and job container (job_image).
pins No file under .gitea/workflows may mention `git.rkdr.net/defame1297/`: an image
namespace this repository's CI must not use.
Every `git.rkdr.net/mortis/<name>:<version>@sha256:<digest>` 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).
workflows must name an image of the matrix, with a well-formed digest.
Every matrix entry names its job container (`job_image: ubuntu:<release>@sha256:...`), and
that release must equal the release of the `FROM ubuntu:` lines of its Dockerfile: kaniko
runs inside the job container and unpacks the image over it.
@@ -24,24 +19,14 @@ pins No file under .gitea/workflows may mention `git.rkdr.net/defame1297/`: an
links to docs/images/<name>.md, which must exist.
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 <base-ref>...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:
* <base-ref> 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.
verified offline; only the shape of the pin is checked.
* Of the consumer files, only lint.yml is required (it runs this check); build.yml,
molecule.yml and gitea-release-key.yml are skipped when absent, and the success line
lists the files that were actually checked, so a consumer that vanished is visible.
* The matrix is read by a small block-style reader (the Renovate image has no PyYAML), not
* The matrix is read by a small block-style reader (its importers run where there is 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
@@ -115,6 +100,7 @@ _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_]*)?$")
BASE_RE = re.compile(rf"{_NUM}\.{_NUM}")
def _scalar(raw, where):
@@ -145,11 +131,11 @@ def _scalar(raw, where):
def matrix_of(text): # noqa: C901, PLR0912, PLR0915 hand-written block-YAML reader; #96 may replace it
"""Return {name: {version, subpath, dockerfile[, job_image]}} from the text of image.yml.
"""Return {name: {base, subpath, dockerfile[, job_image]}} 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`, `dockerfile` and `job_image`, and fails closed (one-line error) on
A purpose-built block-style reader, not a YAML parser: its importers run where there is
no PyYAML. It reads the single `include:` list and its entries' `name`, `base`
(MAJOR.MINOR), `subpath`, `dockerfile` and `job_image`, 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)]
@@ -212,16 +198,22 @@ def matrix_of(text): # noqa: C901, PLR0912, PLR0915 hand-written block-YAML re
matrix = {}
for n, entry in enumerate(entries, 1):
keys = entry["keys"]
for required in ("name", "version", "dockerfile"):
for required in ("name", "base", "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, base and dockerfile are required)"
)
# A `version` key fails closed: a reader would otherwise take it for the published version.
if "version" in keys:
raise CheckError(
f"{MATRIX_FILE} line {keys['version'][1]}: matrix.include entry {n} has the "
"key 'version' is not allowed; CI assigns the version, write base: \"MAJOR.MINOR\" instead"
)
values = {
k: _scalar(v[0], f"{MATRIX_FILE} line {v[1]}")
for k, v in keys.items()
if k in ("name", "version", "dockerfile", "subpath", "job_image")
if k in ("name", "base", "dockerfile", "subpath", "job_image")
}
name = values["name"]
if not name or (
@@ -234,8 +226,8 @@ def matrix_of(text): # noqa: C901, PLR0912, PLR0915 hand-written block-YAML re
raise CheckError(
f"{MATRIX_FILE}: duplicate image name '{name}' in matrix.include"
)
# A YAML number (0.1) would silently become a float; versions must be written as strings.
for key in ("version", "dockerfile"):
# A YAML number (0.1) would silently become a float; base must be written as a string.
for key in ("base", "dockerfile"):
raw = (keys[key][0] or "").strip()
if not values[key] or (
raw[:1] not in "\"'" and _NUMBER_RE.match(values[key])
@@ -244,8 +236,12 @@ def matrix_of(text): # noqa: C901, PLR0912, PLR0915 hand-written block-YAML re
f"{MATRIX_FILE}: image '{name}': {key} must be a string "
f"(quote it in the YAML), got {values[key]!r}"
)
if not BASE_RE.fullmatch(values["base"]):
raise CheckError(
f"{MATRIX_FILE}: image '{name}': base must be MAJOR.MINOR, got {values['base']!r}"
)
matrix[name] = {
"version": values["version"],
"base": values["base"],
"subpath": values.get("subpath", ""),
"dockerfile": values["dockerfile"],
}
@@ -381,20 +377,10 @@ def check_pins(matrix, consumer_texts):
f"{fname}: '{mention.group(0)}' is not a <name>:<version>@sha256:<64 hex> pin"
)
for m in PIN_RE.finditer(text):
name, version = m["name"], m["version"]
if name not in matrix:
if m["name"] not in matrix:
errors.append(
f"{fname}: image '{name}' is not in the matrix of {MATRIX_FILE}"
f"{fname}: image '{m['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
@@ -628,20 +614,6 @@ def check_image_metadata(matrix, read_file, size_of):
return 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 hits:
result[name] = sorted(hits)
return result
def check_foreign_images(workflow_texts):
"""Errors for each workflow file that mentions the denied image namespace, comments included."""
return [
@@ -652,28 +624,6 @@ def check_foreign_images(workflow_texts):
]
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(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:
@@ -691,58 +641,6 @@ def git(*args, raw=False):
) from exc
def changed_paths(base_ref, target="HEAD"):
"""(merge-base, changed paths) between base_ref and target; target None means the working tree."""
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
# 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:
image_yml = pathlib.Path(MATRIX_FILE).read_text()
@@ -787,22 +685,6 @@ def run(argv):
)
errors += check_foreign_images({str(f): f.read_text() for f in workflows})
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, changed = changed_paths(argv[2])
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, ""
@@ -815,10 +697,8 @@ def main(argv):
errors, note = run(argv)
except CheckError as exc:
errors = [str(exc)]
except UnicodeDecodeError as exc: # before ValueError, which it subclasses
except UnicodeDecodeError as exc:
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:
+1 -2
View File
@@ -12,8 +12,7 @@
# pip and pip-tools are installed, at the pinned versions below, into a throwaway virtualenv, never
# into the project's .venv. pip is pinned too: pip-tools breaks on newer pip releases (7.5.2 on pip 26). Commit
# the lock with requirements-dev.txt; pip refuses an install of the two when they disagree
# (`pip install --require-hashes -r requirements-dev.lock -r requirements-dev.txt`). An image input
# changed, so the image version needs its bump as usual (python3 scripts/bump_image_versions.py).
# (`pip install --require-hashes -r requirements-dev.lock -r requirements-dev.txt`).
# The pins are not hash-checked themselves: they come from PyPI over TLS, like the pip that
# created the throwaway venv.
#
+136
View File
@@ -0,0 +1,136 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Choose the version an image build publishes, or none.
python3 scripts/next_image_version.py <source-dir> <image-name> <registry-host>
Prints "<version> <checksum>" when the image's inputs differ from the newest published
<base>.N (its input-checksum label), and nothing when they match.
"""
import hashlib
import json
import os
import pathlib
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
import check_image_versions as civ
def input_checksum(root, entry):
"""sha256 over the path, executable bit and content of every input file of the image."""
root = pathlib.Path(root)
context = root / entry["subpath"] if entry["subpath"] else root
dockerfile = (context / entry["dockerfile"]).read_text(encoding="utf-8")
dirs, files = civ.inputs_of(entry, dockerfile)
paths = sorted(
p.relative_to(root).as_posix()
for p in root.rglob("*")
if (p.is_file() or p.is_symlink()) and ".git" not in p.relative_to(root).parts
)
digest = hashlib.sha256()
for path in civ.touched(paths, dirs, files):
full = root / path
if full.is_symlink():
kind, body = "l", os.readlink(full).encode()
else:
kind, body = ("x" if os.access(full, os.X_OK) else "f"), full.read_bytes()
digest.update(f"{path}\0{kind}\0{hashlib.sha256(body).hexdigest()}\n".encode())
return digest.hexdigest()
def next_version(base, tags, checksum, label_of):
"""The next <base>.N, or None when the newest one was built from these inputs."""
patches = [
int(m[1])
for t in tags
if (m := re.fullmatch(re.escape(base) + r"\.(0|[1-9][0-9]*)", t))
]
if not patches:
return f"{base}.0"
newest = max(patches)
if label_of(f"{base}.{newest}") == checksum:
return None
return f"{base}.{newest + 1}"
LABEL = "net.rkdr.mortis.inputs-sha256"
MANIFEST_TYPES = (
"application/vnd.oci.image.manifest.v1+json",
"application/vnd.docker.distribution.manifest.v2+json",
)
class Registry:
"""Anonymous reads of one image in an OCI registry: the images are public."""
def __init__(self, host, image):
self.host, self.image, self.token = host, image, None
def _get(self, path, accept="application/json"):
url = f"https://{self.host}/v2/{self.image}/{path}"
headers = {"Accept": accept}
if self.token:
headers["Authorization"] = f"Bearer {self.token}"
try:
with urllib.request.urlopen(
urllib.request.Request(url, headers=headers), timeout=30
) as resp:
return json.load(resp), resp.headers
except urllib.error.HTTPError as exc:
if exc.code != 401 or self.token:
raise
challenge = dict(
re.findall(r'(\w+)="([^"]*)"', exc.headers.get("WWW-Authenticate", ""))
)
query = urllib.parse.urlencode(
{
"service": challenge.get("service", ""),
"scope": f"repository:{self.image}:pull",
}
)
with urllib.request.urlopen(
f"{challenge['realm']}?{query}", timeout=30
) as resp:
self.token = json.load(resp)["token"]
return self._get(path, accept)
def tags(self):
tags, path = [], "tags/list"
while path:
body, headers = self._get(path)
tags += body.get("tags") or []
link = re.search(r"<[^>]*/tags/list(\?[^>]*)>", headers.get("Link", ""))
path = f"tags/list{link[1]}" if link else None
return tags
def label(self, tag):
manifest = self._get(f"manifests/{tag}", ", ".join(MANIFEST_TYPES))[0]
if manifest.get("mediaType") not in MANIFEST_TYPES:
raise ValueError(
f"{self.image}:{tag} is not a single-platform image manifest"
)
config = self._get(f"blobs/{manifest['config']['digest']}")[0]
return (config.get("config", {}).get("Labels") or {}).get(LABEL)
def main(argv):
if len(argv) != 4:
sys.stderr.write(__doc__)
return 2
root, name, host = pathlib.Path(argv[1]), argv[2], argv[3]
entry = civ.matrix_of((root / civ.MATRIX_FILE).read_text(encoding="utf-8"))[name]
checksum = input_checksum(root, entry)
registry = Registry(host, f"mortis/{name}")
version = next_version(entry["base"], registry.tags(), checksum, registry.label)
if version:
print(version, checksum)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+1 -1
View File
@@ -97,9 +97,9 @@ IGNORED = (
".gitea/workflows/image.yml",
".gitea/workflows/renovate.yml",
".gitea/workflows/gitea-release-key.yml",
"scripts/bump_image_versions.py",
"scripts/check_bot_pr_diff.py",
"scripts/check_image_versions.py",
"scripts/next_image_version.py",
"scripts/check_tarball.py",
"scripts/check_gitea_release_key.py",
"scripts/ansible-lint.sh",
-299
View File
@@ -1,299 +0,0 @@
# 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 shutil
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
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"})
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()
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, _unused = 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, _unused, err = self.bump(ref)
self.assertEqual(code, 1)
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, _unused, 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)
if __name__ == "__main__":
unittest.main()
+20 -36
View File
@@ -23,7 +23,7 @@ FILES = {
"images/molecule-ubuntu2404/Dockerfile": f"FROM ubuntu:24.04@{D1}\n",
".gitea/workflows/image.yml": (
f"jobs:\n image:\n matrix:\n include:\n - name: ci\n"
f" version: 0.2.0\n job_image: ubuntu:24.04@{D1}\n"
f' base: "0.2"\n job_image: ubuntu:24.04@{D1}\n'
" container:\n image: ${{ matrix.job_image }}\n"
" steps:\n - run: echo ok\n"
),
@@ -121,11 +121,6 @@ class RuleTest(unittest.TestCase):
"RUN pip install uv==0.13.5 \\",
"RUN pip install uv==0.14.0 \\",
),
(
".gitea/workflows/image.yml",
" version: 0.2.0",
" version: 0.2.1",
),
(
".gitea/workflows/image.yml",
f" job_image: ubuntu:24.04@{D1}",
@@ -239,7 +234,7 @@ class RuleTest(unittest.TestCase):
line = f" job_image: ubuntu:24.04@{D1}"
for old, new in (
(line, ""),
(" version: 0.2.0", f" version: 0.2.0\n{line}"),
(' base: "0.2"', f' base: "0.2"\n{line}'),
(" steps:", f" steps:\n{line}"),
):
self.assertIsNotNone(self.problem(path, old, new), (old, new))
@@ -301,25 +296,19 @@ class RuleTest(unittest.TestCase):
for path, old, new in cases:
self.assertIsNotNone(self.problem(path, old, new), (path, old, new))
def test_version_lines_stay_in_place_and_rise(self):
v = " version: {}"
self.assertIsNone(
cbd.version_problem([(5, v.format("0.2.0"))], [(5, v.format("0.2.1"))])
)
self.assertIsNotNone(
cbd.version_problem([(5, v.format("0.2.0"))], [(9, v.format("0.2.1"))])
)
self.assertIsNotNone(
cbd.version_problem([(5, v.format("0.2.1"))], [(5, v.format("0.2.0"))])
)
self.assertIsNotNone(
cbd.version_problem([(5, v.format("0.2.0"))], [(5, v.format("0.2.0"))])
)
swapped = cbd.version_problem(
[(5, v.format("0.1.0")), (9, v.format("0.2.0"))],
[(5, v.format("0.2.0")), (9, v.format("0.1.0"))],
)
self.assertIsNotNone(swapped)
def test_matrix_version_and_base_lines_are_refused(self):
# CI assigns image versions and a human edits `base:`; the bot changes neither.
path = ".gitea/workflows/image.yml"
for old, new in (
(" version: 0.2.0", " version: 0.2.1"),
(' base: "0.2"', ' base: "0.3"'),
):
self.assertIsNotNone(self.problem(path, old, new), (old, new))
def test_changed_lines_stay_in_place(self):
line = f" job_image: ubuntu:24.04@{D1}"
self.assertIsNone(cbd.moved_problem([(7, line)], [(7, line)]))
self.assertIsNotNone(cbd.moved_problem([(7, line)], [(3, line)]))
def test_unequal_line_counts_are_refused(self):
self.assertIsNotNone(
@@ -471,23 +460,18 @@ class RepoTest(unittest.TestCase):
)
self.assertEqual(proc.returncode, 0, proc.stderr)
def test_lowering_a_matrix_version_fails_and_raising_it_passes(self):
self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.1.9")
self.commit("lower")
def test_a_matrix_base_change_is_refused(self):
self.edit(".gitea/workflows/image.yml", 'base: "0.2"', 'base: "0.3"')
self.commit("base")
code, _unused, err = self.gate()
self.assertEqual(code, 1, err)
self.assertIn("version", err)
run(self.repo, "git", "checkout", "-q", "main")
run(self.repo, "git", "checkout", "-q", "-b", "renovate/ok")
self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.2.1")
self.commit("raise")
self.assertEqual(self.gate(head="renovate/ok")[0], 0)
self.assertIn(".gitea/workflows/image.yml", err)
def test_a_realistic_bot_pr_passes(self):
self.edit("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0")
self.edit(".pre-commit-config.yaml", "v1.0.0", "v1.1.0")
self.edit("images/ci/Dockerfile", "uv==0.13.5", "uv==0.14.0")
self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.2.1")
self.edit(".gitea/workflows/image.yml", D1, D2)
self.edit(".gitea/workflows/molecule.yml", D1, D2)
self.commit("bot")
code, out, err = self.gate()
+69 -214
View File
@@ -23,14 +23,14 @@ jobs:
matrix:
include:
- name: mol
version: {mol}
base: "{mol}"
subpath: images/mol
dockerfile: Dockerfile
job_image: """
+ JOB
+ """
- name: ci
version: {ci}
base: "{ci}"
subpath: ""
dockerfile: images/ci/Dockerfile
job_image: """
@@ -126,7 +126,7 @@ class PureTest(unittest.TestCase):
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"):
def matrix(self, mol="0.1", ci="0.2"):
return civ.matrix_of(IMAGE_YML.format(mol=mol, ci=ci))
def test_images_of_the_denied_namespace_are_refused(self):
@@ -153,15 +153,13 @@ class PureTest(unittest.TestCase):
"must not use or name",
)
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_pins_of_a_matrix_image_pass_whatever_their_version(self):
for version in ("0.1.0", "0.2.7", "0.3.0"):
pin = f"image: git.rkdr.net/mortis/ci:{version}@{DIGEST}\n"
self.assertEqual(civ.check_pins(self.matrix(), {"lint.yml": pin}), [])
def test_pin_ahead_of_matrix_unknown_image_and_malformed(self):
def test_unknown_image_and_malformed_pins(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
)
@@ -260,8 +258,8 @@ class PureTest(unittest.TestCase):
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)
unknown = f"x: (git.rkdr.net/mortis/zzz:0.1.0@{DIGEST}), z\n"
self.assertEqual(len(civ.check_pins(m, {"f": unknown})), 1)
self.assertEqual(
len(
civ.check_pins(
@@ -278,26 +276,32 @@ class PureTest(unittest.TestCase):
+ body
)
entry = " - name: a\n version: '0.1.0'\n dockerfile: D\n"
entry = (
" - name: a\n base: '0.1'\n dockerfile: D\n"
)
cases = {
"": "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",
" - name: 1\n base: '0.1'\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.replace("'0.1'", "0.1"): "base must be a string",
entry + entry: "duplicate image name 'a'",
entry + " version: '0.2.0'\n": "duplicate key 'version'",
entry + " base: '0.2'\n": "duplicate key 'base'",
entry.replace("base: '0.1'", "base: *anchor"): "cannot read the value",
entry.replace(
"version: '0.1.0'", "version: *anchor"
): "cannot read the value",
entry.replace(
"version: '0.1.0'", 'version: "0\\x2e1.0"'
"base: '0.1'", 'base: "0\\x2e1"'
): "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'",
" - name: a\n dockerfile: D\n": "lacks the key 'base'",
entry.replace("'0.1'", "'0.2.3'"): "base must be MAJOR.MINOR",
entry.replace("'0.1'", "'v1.0'"): "base must be MAJOR.MINOR",
entry.replace("'0.1'", "'01.2'"): "base must be MAJOR.MINOR",
entry.replace("'0.1'", "'1.02'"): "base must be MAJOR.MINOR",
entry.replace("'0.1'", "''"): "base must be a string",
entry + " version: '0.1.0'\n": "key 'version' is not allowed",
}
for body, text in cases.items():
with self.assertRaises(civ.CheckError, msg=body) as ctx:
@@ -312,13 +316,13 @@ class PureTest(unittest.TestCase):
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 = IMAGE_YML.format(mol="0.1", ci="0.2")
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 base: "0.2"\n',
" # the ci image\n - base: '0.2' # minor of the next build\n"
" name: ci\n",
)
self.assertEqual(civ.matrix_of(text)["ci"]["version"], "0.2.0")
self.assertEqual(civ.matrix_of(text)["ci"]["base"], "0.2")
self.assertEqual(civ.matrix_of(text)["mol"]["subpath"], "images/mol")
def test_matrix_reader_agrees_with_pyyaml_on_the_real_file(self):
@@ -328,35 +332,26 @@ class PureTest(unittest.TestCase):
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"],
"job_image": e["job_image"],
}
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")),
{
def oracle(text):
return {
e["name"]: {
"version": e["version"],
"base": e["base"],
"subpath": e.get("subpath") or "",
"dockerfile": e["dockerfile"],
"job_image": e["job_image"],
}
for e in yaml.safe_load(IMAGE_YML.format(mol="0.1.0", ci="0.2.0"))[
"jobs"
]["image"]["strategy"]["matrix"]["include"]
},
)
for e in yaml.safe_load(text)["jobs"]["image"]["strategy"]["matrix"][
"include"
]
}
self.assertEqual(civ.matrix_of(real), oracle(real))
fixture = IMAGE_YML.format(mol="0.1", ci="0.2")
self.assertEqual(civ.matrix_of(fixture), oracle(fixture))
def test_job_image_must_match_the_dockerfile_release(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
text = IMAGE_YML.format(mol="0.1", ci="0.2")
matrix = civ.matrix_of(text)
files = {
"images/mol/Dockerfile": f"FROM {JOB}\n",
@@ -394,7 +389,7 @@ class PureTest(unittest.TestCase):
)
def test_job_image_shape_and_missing_key(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
text = IMAGE_YML.format(mol="0.1", ci="0.2")
for bad in (
text.replace(f"job_image: {JOB}", "job_image: ubuntu:latest", 1),
text.replace(f" job_image: {JOB}\n", "", 1),
@@ -434,7 +429,7 @@ class PureTest(unittest.TestCase):
)
def test_container_line_must_sit_under_container(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
text = IMAGE_YML.format(mol="0.1", ci="0.2")
lookalike = text.replace(
" container:\n image: ${{ matrix.job_image }}\n",
" container:\n image: ubuntu:24.04\n steps:\n - run: |\n"
@@ -447,14 +442,14 @@ class PureTest(unittest.TestCase):
self.assertIn("the job container must be", errors[0])
def test_quoted_job_image_is_refused(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0").replace(
text = IMAGE_YML.format(mol="0.1", ci="0.2").replace(
f"job_image: {JOB}", f'job_image: "{JOB}"', 1
)
with self.assertRaises(civ.CheckError):
civ.matrix_of(text)
def test_image_metadata_labels_and_documentation(self):
text = IMAGE_YML.format(mol="0.1.0", ci="0.2.0")
text = IMAGE_YML.format(mol="0.1", ci="0.2")
matrix = civ.matrix_of(text)
files = {
"images/mol/Dockerfile": labelled("mol"),
@@ -528,45 +523,10 @@ class PureTest(unittest.TestCase):
[],
)
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
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
def test_script_does_not_import_yaml(self):
# Its importers run in job containers whose python3 has no PyYAML.
source = (SCRIPTS / "check_image_versions.py").read_text()
self.assertNotRegex(source, r"(?m)^\s*(import|from)\s+yaml\b")
class PythonPinTest(unittest.TestCase):
@@ -669,9 +629,7 @@ class GitTest(unittest.TestCase):
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(".gitea/workflows/image.yml", IMAGE_YML.format(mol="0.1", ci="0.2"))
self.write(
"images/ci/Dockerfile",
labelled(
@@ -700,20 +658,10 @@ class GitTest(unittest.TestCase):
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):
def script(self, *args):
proc = subprocess.run(
[sys.executable, str(SCRIPTS / "check_image_versions.py"), *args],
cwd=cwd or self.repo,
cwd=self.repo,
capture_output=True,
text=True,
check=False,
@@ -729,101 +677,48 @@ class GitTest(unittest.TestCase):
def test_pins_cli_refuses_the_denied_namespace_in_any_workflow(self):
self.write(".gitea/workflows/lint.yml", "name: Lint\n")
self.assertEqual(self.bump_args("pins")[0], 0)
self.assertEqual(self.script("pins")[0], 0)
self.write(
".gitea/workflows/other.yaml",
"container: git.rkdr.net/defame1297/runner:1\n",
)
code, err = self.bump_args("pins")
code, err = self.script("pins")
self.assertEqual(code, 1)
self.assertIn("other.yaml: mentions git.rkdr.net/defame1297/", 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_bump_mode_is_gone(self):
self.write(".gitea/workflows/lint.yml", "name: Lint\n")
self.assertEqual(self.script("bump", "main")[0], 2)
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_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):
def test_bad_base_in_matrix_is_one_line(self):
self.write(
".gitea/workflows/image.yml", IMAGE_YML.format(mol="latest", ci="0.2.0")
".gitea/workflows/image.yml", IMAGE_YML.format(mol="latest", ci="0.2")
)
self.commit("bad version")
self.assert_clean_failure(self.bump(), "'latest' is not MAJOR.MINOR.PATCH")
self.assert_clean_failure(self.script("pins"), "base must be MAJOR.MINOR")
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"
IMAGE_YML.replace(' base: "{mol}"\n', "").format(
mol="", ci="0.2"
),
)
self.commit("no version")
self.assert_clean_failure(self.bump(), "lacks the key")
self.assert_clean_failure(self.script("pins"), "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")
self.assert_clean_failure(
self.script("pins"), "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")
self.assert_clean_failure(self.script("pins"), "cannot read a file")
def test_empty_image_yml_says_so(self):
self.write(".gitea/workflows/image.yml", "")
self.commit("empty matrix")
self.assert_clean_failure(
self.bump(), "no jobs.image.strategy.matrix.include list"
self.script("pins"), "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")
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"],
@@ -849,46 +744,6 @@ class GitTest(unittest.TestCase):
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()
+96
View File
@@ -0,0 +1,96 @@
# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run with: python3 -m unittest discover -s tests/scripts"""
import pathlib
import sys
import tempfile
import unittest
SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts"
sys.path.insert(0, str(SCRIPTS))
import next_image_version as niv
def no_label(tag):
raise AssertionError(f"no label lookup expected, got {tag}")
class NextVersion(unittest.TestCase):
def test_first_version_of_a_base_is_patch_zero(self):
self.assertEqual(
niv.next_version("0.3", ["0.2.38", "latest"], "c1", no_label), "0.3.0"
)
def test_changed_inputs_raise_the_numerically_newest_patch(self):
seen = []
def label_of(tag):
seen.append(tag)
return "old"
tags = ["0.2.9", "0.2.10", "0.20.99", "1.2.11", "0.2.10-rc1", "latest"]
self.assertEqual(niv.next_version("0.2", tags, "new", label_of), "0.2.11")
self.assertEqual(seen, ["0.2.10"])
def test_unchanged_inputs_publish_nothing(self):
self.assertIsNone(
niv.next_version("0.1", ["0.1.4"], "same", lambda tag: "same")
)
def test_an_unlabelled_newest_version_counts_as_changed(self):
self.assertEqual(
niv.next_version("0.1", ["0.1.4"], "c", lambda tag: None), "0.1.5"
)
CI = {"subpath": "", "dockerfile": "images/ci/Dockerfile"}
MOL = {"subpath": "images/mol", "dockerfile": "Dockerfile"}
class InputChecksum(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = pathlib.Path(tmp.name)
self.write("images/ci/Dockerfile", "FROM ubuntu:26.04\nCOPY pins.txt ./\n")
self.write("images/mol/Dockerfile", "FROM ubuntu:24.04\n")
self.write("pins.txt", "a==1\n")
self.write("README.md", "readme\n")
def write(self, path, text):
target = self.root / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text, encoding="utf-8")
def checksum(self, entry):
return niv.input_checksum(self.root, entry)
def test_a_copied_file_is_an_input_and_an_unrelated_file_is_not(self):
before = self.checksum(CI)
self.write("README.md", "changed\n")
self.assertEqual(self.checksum(CI), before)
self.write("pins.txt", "a==2\n")
self.assertNotEqual(self.checksum(CI), before)
def test_the_build_context_of_a_subpath_image_is_its_input(self):
before = self.checksum(MOL)
self.write("pins.txt", "a==2\n")
self.assertEqual(self.checksum(MOL), before)
self.write("images/mol/files/new.conf", "x\n")
self.assertNotEqual(self.checksum(MOL), before)
def test_a_mode_change_is_an_input_change(self):
before = self.checksum(CI)
(self.root / "pins.txt").chmod(0o755)
self.assertNotEqual(self.checksum(CI), before)
def test_a_renamed_input_is_an_input_change(self):
self.write("images/mol/a.conf", "x\n")
before = self.checksum(MOL)
(self.root / "images/mol/a.conf").rename(self.root / "images/mol/b.conf")
self.assertNotEqual(self.checksum(MOL), before)
if __name__ == "__main__":
unittest.main()