feat(ci): pin hook revisions by SHA and install dev tools from a hashed lock
Refs #113. - .pre-commit-config.yaml: every hook repo is pinned by commit SHA with the release in a `# frozen:` comment, so a moved tag cannot change the code a hook environment is built from. - requirements-dev.lock: hashed lock of requirements-dev.txt, installed with `pip install --require-hashes` by scripts/dev-setup.sh, the ci image and the fallback install of the Lint and Build workflows. - scripts/lock-requirements.sh regenerates the lock; scripts/check_requirements_lock.py (offline, a pre-commit hook) fails when it drifts from the direct pins. - check_bot_pr_diff.py accepts a `rev:` line with a `# frozen:` comment and nothing else. - ci image 0.2.16 -> 0.2.17 (image inputs changed).
This commit is contained in:
1 parent
212dd7aea8
commit
1184938f1e
21 files changed
+1648
-36
No files matched your search
@@ -9,7 +9,7 @@ When <head-ref> starts with `renovate/`, the diff of <base-ref>...HEAD may only
|
||||
* requirements-dev.txt: pinned `name==version` lines, the same packages before and after;
|
||||
* requirements.yml and extensions/molecule/requirements.yml: `version:` lines (the collection
|
||||
names, and every other line, stay);
|
||||
* .pre-commit-config.yaml: `rev:` lines;
|
||||
* .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
|
||||
@@ -49,7 +49,9 @@ PREFIX = "renovate/"
|
||||
TAG = r"[A-Za-z0-9._-]+"
|
||||
PIN = re.compile(rf"(git\.rkdr\.net/mortis/[a-z0-9._-]+):{TAG}@sha256:[0-9a-f]{{64}}")
|
||||
REQ_LINE = re.compile(r"^([A-Za-z0-9][A-Za-z0-9._-]*)==[0-9][0-9A-Za-z.+!_-]*$")
|
||||
REV_LINE = re.compile(r"^\s*rev:\s*\S+\s*$")
|
||||
# A hook `rev:` is a tag or a commit SHA; a SHA carries its release in a `# frozen: <tag>` comment.
|
||||
# Nothing else may trail it, so the comment cannot hide a second instruction.
|
||||
REV_LINE = re.compile(r"^\s*rev:\s*\S+(?:\s+#\s*frozen:\s*\S+)?\s*$")
|
||||
VERSION_LINE = re.compile(
|
||||
r"""^\s*(?:-\s*)?version:\s*["']?(?P<v>[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?)["']?\s*(?:#.*)?$"""
|
||||
)
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
# SPDX-FileCopyrightText: Defame1297 and contributors
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Check that requirements-dev.lock is the hashed lock of requirements-dev.txt, offline.
|
||||
|
||||
python3 scripts/check_requirements_lock.py [<requirements-dev.txt> <requirements-dev.lock>]
|
||||
|
||||
requirements-dev.txt holds the direct pins (`name==version`, bumped by Renovate); the lock lists
|
||||
every package, direct and transitive, with the sha256 of each release file, and is what `pip
|
||||
install --require-hashes` installs (scripts/dev-setup.sh, images/ci, the fallback install of the
|
||||
Lint and Build workflows). The lock is made by scripts/lock-requirements.sh, which needs the
|
||||
network; this check needs none. It fails when
|
||||
|
||||
* a direct pin of the txt file is missing from the lock, or is there at another version;
|
||||
* a lock entry has no `--hash=sha256:` line, or its version is not an exact `==` pin;
|
||||
* the lock carries a line that is neither an entry, a hash, nor a comment (a URL, an
|
||||
`-e` editable, an index option: none of these can be verified by a hash).
|
||||
|
||||
It does not prove that the hashes are genuine (only the lock script, against PyPI, does), it
|
||||
proves the file cannot drift from the pins or smuggle in an unhashed install.
|
||||
|
||||
Exit codes: 0 ok, 1 a finding (one `::error::` line each), 2 bad usage.
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
|
||||
DEFAULT_TXT = "requirements-dev.txt"
|
||||
DEFAULT_LOCK = "requirements-dev.lock"
|
||||
NAME = r"[A-Za-z0-9][A-Za-z0-9._-]*"
|
||||
PIN = re.compile(
|
||||
rf"^(?P<name>{NAME})==(?P<version>[0-9][0-9A-Za-z.+!_-]*)\s*(?:;[^#\\]*)?(?:\\)?\s*$"
|
||||
)
|
||||
HASH = re.compile(r"^\s+--hash=sha256:[0-9a-f]{64}(?:\s+\\)?\s*$")
|
||||
USAGE = "usage: check_requirements_lock.py [<requirements-dev.txt> <requirements-dev.lock>]\n"
|
||||
|
||||
|
||||
def canonical(name):
|
||||
"""PEP 503 name, so `Ruamel.Yaml` and `ruamel-yaml` are one package."""
|
||||
return re.sub(r"[-_.]+", "-", name).lower()
|
||||
|
||||
|
||||
def read_pins(text):
|
||||
"""{canonical name: version} of the `name==version` lines of requirements-dev.txt."""
|
||||
pins = {}
|
||||
for line in text.splitlines():
|
||||
stripped = line.split("#", 1)[0].strip()
|
||||
if not stripped:
|
||||
continue
|
||||
m = PIN.match(stripped)
|
||||
if m:
|
||||
pins[canonical(m["name"])] = m["version"]
|
||||
return pins
|
||||
|
||||
|
||||
def read_lock(text):
|
||||
"""({canonical name: version}, [finding]) of the lock file."""
|
||||
entries, findings = {}, []
|
||||
current = None
|
||||
hashes = {}
|
||||
for number, line in enumerate(text.splitlines(), 1):
|
||||
if not line.strip() or line.lstrip().startswith("#"):
|
||||
continue
|
||||
if HASH.match(line):
|
||||
if current is None:
|
||||
findings.append(f"line {number}: a hash with no package before it")
|
||||
else:
|
||||
hashes[current] += 1
|
||||
continue
|
||||
m = PIN.match(line)
|
||||
if m and not line[0].isspace():
|
||||
current = canonical(m["name"])
|
||||
if current in entries:
|
||||
findings.append(f"line {number}: {current} is listed twice")
|
||||
entries[current] = m["version"]
|
||||
hashes.setdefault(current, 0)
|
||||
continue
|
||||
findings.append(
|
||||
f"line {number}: not a `name==version` entry, a sha256 hash or a comment: {line.strip()[:60]}"
|
||||
)
|
||||
for name, count in hashes.items():
|
||||
if count == 0:
|
||||
findings.append(f"{name}=={entries[name]} has no --hash=sha256 line")
|
||||
return entries, findings
|
||||
|
||||
|
||||
def check(txt, lock):
|
||||
pins = read_pins(txt)
|
||||
entries, findings = read_lock(lock)
|
||||
for name, version in sorted(pins.items()):
|
||||
if name not in entries:
|
||||
findings.append(
|
||||
f"{name}=={version} is pinned in requirements-dev.txt but missing from the lock"
|
||||
)
|
||||
elif entries[name] != version:
|
||||
findings.append(
|
||||
f"{name} is {version} in requirements-dev.txt but {entries[name]} in the lock"
|
||||
)
|
||||
if findings:
|
||||
findings.append("regenerate the lock with scripts/lock-requirements.sh")
|
||||
return findings
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) not in (1, 3):
|
||||
sys.stderr.write(USAGE)
|
||||
return 2
|
||||
txt_path, lock_path = (
|
||||
(argv[1], argv[2]) if len(argv) == 3 else (DEFAULT_TXT, DEFAULT_LOCK)
|
||||
)
|
||||
try:
|
||||
with (
|
||||
open(txt_path, encoding="utf-8") as f,
|
||||
open(lock_path, encoding="utf-8") as g,
|
||||
):
|
||||
findings = check(f.read(), g.read())
|
||||
except OSError as exc:
|
||||
print(f"::error::{exc}")
|
||||
return 1
|
||||
for finding in findings:
|
||||
print(f"::error::{lock_path}: {finding}")
|
||||
return 1 if findings else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
# Sets up a local checkout for development: a virtualenv with the pinned tools
|
||||
# (requirements-dev.txt, the versions CI runs), the pinned collections the roles call
|
||||
# (requirements-dev.lock, the hashed lock of requirements-dev.txt: the versions CI runs), the pinned collections the roles call
|
||||
# (requirements.yml) and git hooks that find the tools.
|
||||
#
|
||||
# scripts/dev-setup.sh # KAMINO_PYTHON=python3.13 scripts/dev-setup.sh to pick one
|
||||
@@ -21,7 +21,7 @@
|
||||
# of requirements.yml into .ansible/collections of this clone: scripts/ansible-lint.sh (the
|
||||
# ansible-lint hook) resolves modules from there, so local lint sees the collection versions CI
|
||||
# does (the ci image bakes requirements.yml) and not the control host's ~/.ansible. It is
|
||||
# idempotent; run it again after changing requirements-dev.txt, requirements.yml or the hook types.
|
||||
# idempotent; run it again after changing requirements-dev.txt or its lock, requirements.yml or the hook types.
|
||||
set -euo pipefail
|
||||
|
||||
# ansible-core 2.22 (requirements-dev.txt) needs Python 3.13+. Renovate raises that pin, so
|
||||
@@ -120,7 +120,7 @@ if [ -x .venv/bin/python ] && ! .venv/bin/python -c "$py_ok" 2>/dev/null; then
|
||||
rm -rf "$root/.venv"
|
||||
fi
|
||||
[ -x .venv/bin/python ] || "$python" -m venv .venv
|
||||
.venv/bin/pip install --quiet --disable-pip-version-check -r requirements-dev.txt
|
||||
.venv/bin/pip install --quiet --disable-pip-version-check --require-hashes -r requirements-dev.lock
|
||||
.venv/bin/pre-commit install --install-hooks
|
||||
|
||||
# The collections of requirements.yml, exactly as pinned, into this clone (.ansible/ is ignored by
|
||||
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env bash
|
||||
# SPDX-FileCopyrightText: Defame1297 and contributors
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Regenerate requirements-dev.lock, the hashed lock of requirements-dev.txt (#113).
|
||||
#
|
||||
# scripts/lock-requirements.sh
|
||||
#
|
||||
# Needs the network (PyPI) and Python 3.13+ (ansible-core 2.22; KAMINO_PYTHON overrides python3).
|
||||
# pip-tools is installed, at the pinned version below, into a throwaway virtualenv, never into
|
||||
# the project's .venv. Run it in the same pull request as any change to requirements-dev.txt,
|
||||
# then commit both files: scripts/check_requirements_lock.py (a pre-commit hook and the Lint job)
|
||||
# fails when they disagree. An image input changed, so the image version needs its bump as usual
|
||||
# (python3 scripts/bump_image_versions.py).
|
||||
set -euo pipefail
|
||||
|
||||
pip_tools_version="7.5.2"
|
||||
python="${KAMINO_PYTHON:-python3}"
|
||||
if ! "$python" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 13) else 1)' 2>/dev/null; then
|
||||
echo "error: $python is missing or older than 3.13; set KAMINO_PYTHON=/path/to/python3.13" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
root="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/.." && pwd)"
|
||||
tmp="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
|
||||
"$python" -m venv "$tmp/venv"
|
||||
"$tmp/venv/bin/pip" install --quiet --disable-pip-version-check "pip-tools==${pip_tools_version}"
|
||||
cd "$root"
|
||||
# --allow-unsafe: setuptools is a dependency of a tool here, and pip refuses an unpinned
|
||||
# requirement in a file that carries hashes.
|
||||
"$tmp/venv/bin/pip-compile" --quiet --generate-hashes --strip-extras --allow-unsafe --newline lf \
|
||||
--output-file requirements-dev.lock requirements-dev.txt
|
||||
python3 scripts/check_requirements_lock.py
|
||||
echo "requirements-dev.lock regenerated; commit it with requirements-dev.txt."
|
||||
@@ -66,6 +66,7 @@ IGNORED = (
|
||||
".ansible-lint",
|
||||
".pre-commit-config.yaml",
|
||||
"requirements-dev.txt",
|
||||
"requirements-dev.lock",
|
||||
"ruff.toml",
|
||||
"apm.yml",
|
||||
"apm.lock.yaml",
|
||||
|
||||
Reference in new issue
Block a user