Files
chemenu/tools/lock_requirements.py
torbenandClaude Opus 5.5 37070ffae2
CI / verify (push) Successful in 8m47s
CI / pwsh (push) Successful in 3m13s
CI / python314 (push) Successful in 5m35s
Converters / converters (push) Successful in 9m49s
Release / converters (push) Successful in 26s
Release / release (push) Successful in 39s
Release / wiki-mirror (push) Skipped
tools, instructions: Abhängigkeiten festgeschrieben - Lock-Dateien mit Hashes und 7 Tagen Abkühlzeit, Preflight-Stempel über das Lock, pip-audit und frische Auflösung im Nightly; Python 3.13-3.14 als zugelassene Spanne, CI auf beiden Enden (#245); 11.0.0-beta.1
Files changed:
- .gitea/workflows/ci.yml
- .gitea/workflows/converters.yml
- .gitea/workflows/nightly.yml
- .gitea/workflows/release.yml
- .gitea/workflows/tracker-live.yml
- CHANGES.md
- INSTALL.md
- VERSION
- docs/dev/development.md
- docs/how-to/set-up-the-mcp-server.md
- instructions/dev/dependency-locks.md
- instructions/dev/publish-and-ci.md
- instructions/dev/stack-mode.md
- instructions/dev/tracker-testing.md
- instructions/mcp-read-server.md
- instructions/preflight.md
- tools/CONTRACT.md
- tools/README.md
- tools/chemenu/commands/dist_cmd.py
- tools/chemenu/commands/doctor.py
- tools/chemenu/install_doc.py
- tools/chemenu/prerequisites.py
- tools/chemenu/tests/test_dependency_locks.py
- tools/chemenu/tests/test_dist_cmd.py
- tools/chemenu/tests/test_doctor.py
- tools/chemenu/tests/test_install_doc.py
- tools/chemenu/tests/test_preflight.py
- tools/chemenu/tests/test_preflight_pwsh.py
- tools/lock_requirements.py
- tools/preflight.ps1
- tools/preflight.sh
- tools/prerequisites.txt
- tools/requirements-browser.lock
- tools/requirements-browser.txt
- tools/requirements-dev.lock
- tools/requirements-dev.txt
- tools/requirements-mcp.lock
- tools/requirements-mcp.txt
- tools/requirements.lock
- tools/requirements.txt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015uxGFdBAmyA23g1isCtGEY
2026-11-18 21:34:20 +01:00

159 lines
6.4 KiB
Python

"""Write the four lock files of tools/ from their source files - dev-only.
python3 tools/lock_requirements.py regenerate tools/*.lock
python3 tools/lock_requirements.py --out <dir> write them into <dir> instead
python3 tools/lock_requirements.py --exception <name>=<timestamp>
a security lift (see below)
Each `tools/requirements*.txt` names what the stack needs with lower bounds; its
`.lock` beside it names exact versions and SHA-256 hashes for everything that
resolves from it, transitive packages included. The preflight and CI install only
from the locks, with `pip install --require-hashes`. This script is the one way
a lock is written; the procedure around it - when to run it, the security lift,
how the result is checked - is instructions/dev/dependency-locks.md.
What every run does:
- resolves with `uv pip compile --universal --generate-hashes` (one file for
Linux, macOS and Windows), for the Python minimum in tools/prerequisites.txt;
- leaves out every file uploaded in the last COOLDOWN_DAYS days
(`--exclude-newer`): a compromised release is usually found and pulled within
hours to days, and a lock never takes one before that has had time to happen;
- resolves the locks in a chain, each constrained by the ones before it, so a
package that sits in two locks has the same version in both - all four end up
in one venv, and a later lock must not move a package an earlier one placed;
- carries every `--exclude-newer-package` exception from the current locks'
headers over while its timestamp is still inside the cooldown, and drops it
once the global cutoff has passed it. `--exception` adds a new one.
Needs `uv` on PATH (requirements-dev.lock carries it). An instance never runs
this: it ships no source of truth to resolve against, only the locks.
"""
from __future__ import annotations
import argparse
import re
import shutil
import subprocess
import sys
from datetime import datetime, timedelta, timezone
from pathlib import Path
TOOLS = Path(__file__).resolve().parent
ROOT = TOOLS.parent
COOLDOWN_DAYS = 7
# Source file -> lock file, in the order they are resolved: each one is
# constrained by every lock above it.
CHAIN = (
("requirements.txt", "requirements.lock"),
("requirements-mcp.txt", "requirements-mcp.lock"),
("requirements-browser.txt", "requirements-browser.lock"),
("requirements-dev.txt", "requirements-dev.lock"),
)
EXCEPTION_RE = re.compile(r"--exclude-newer-package[ =]([A-Za-z0-9._-]+)=(\S+)")
CUTOFF_RE = re.compile(r"--exclude-newer[ =](\S+)")
def timestamp(moment: datetime) -> str:
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def parse_timestamp(text: str) -> datetime:
return datetime.fromisoformat(text.replace("Z", "+00:00")).astimezone(timezone.utc)
def header(lock: Path) -> str:
"""The command uv wrote into the lock's head, or '' for a missing file."""
if not lock.is_file():
return ""
lines = []
for line in lock.read_text(encoding="utf-8").splitlines():
if not line.startswith("#"):
break
lines.append(line)
return "\n".join(lines)
def cutoff_of(lock: Path) -> datetime | None:
found = CUTOFF_RE.search(header(lock))
return parse_timestamp(found.group(1)) if found else None
def exceptions_of(lock: Path) -> dict[str, datetime]:
return {name: parse_timestamp(stamp) for name, stamp in EXCEPTION_RE.findall(header(lock))}
def python_minimum() -> str:
for line in (TOOLS / "prerequisites.txt").read_text(encoding="utf-8").splitlines():
fields = line.split("|")
if fields[:2] == ["tool", "python"]:
return fields[2]
raise SystemExit("lock_requirements: tools/prerequisites.txt has no python line")
def carried_exceptions(cutoff: datetime) -> dict[str, datetime]:
"""Exceptions in the current locks still younger than the cutoff - the ones
without which the next resolution would fail rather than lower the package."""
carried: dict[str, datetime] = {}
for _, lock in CHAIN:
for name, stamp in exceptions_of(TOOLS / lock).items():
if stamp > cutoff:
carried[name] = max(stamp, carried.get(name, stamp))
return carried
def relative(path: Path) -> str:
try:
return path.relative_to(ROOT).as_posix()
except ValueError:
return str(path)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n\n", 1)[0])
parser.add_argument("--out", type=Path, help="write the locks here instead of tools/")
parser.add_argument("--exception", action="append", default=[], metavar="NAME=TIMESTAMP",
help="exempt one package from the cooldown up to TIMESTAMP (a security lift)")
args = parser.parse_args(argv)
uv = shutil.which("uv")
if not uv:
print("lock_requirements: uv is not on PATH - install tools/requirements-dev.lock, "
"or put uv on PATH another way", file=sys.stderr)
return 1
cutoff = datetime.now(timezone.utc).replace(microsecond=0) - timedelta(days=COOLDOWN_DAYS)
exceptions = carried_exceptions(cutoff)
for entry in args.exception:
name, sep, stamp = entry.partition("=")
if not sep or not name:
parser.error(f"--exception wants NAME=TIMESTAMP, got {entry!r}")
exceptions[name.lower()] = parse_timestamp(stamp)
out = (args.out or TOOLS).resolve()
out.mkdir(parents=True, exist_ok=True)
done: list[Path] = []
for source, lock in CHAIN:
target = out / lock
command = [uv, "pip", "compile", relative(TOOLS / source)]
for previous in done:
command += ["-c", relative(previous)]
command += ["--universal", "--generate-hashes", "--python-version", python_minimum(),
"--exclude-newer", timestamp(cutoff)]
for name in sorted(exceptions):
command += ["--exclude-newer-package", f"{name}={timestamp(exceptions[name])}"]
command += ["--no-config", "--quiet", "-o", relative(target)]
result = subprocess.run(command, cwd=ROOT)
if result.returncode != 0:
print(f"lock_requirements: resolving {source} failed - see uv's message above", file=sys.stderr)
return result.returncode
done.append(target)
print(f"wrote {relative(target)}")
return 0
if __name__ == "__main__":
sys.exit(main())