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).
126 lines
4.5 KiB
Python
126 lines
4.5 KiB
Python
# 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))
|