utils/dep_freshness/constraints.py
Krzysztof kuhy Rudnicki 2a2f18ca56 Add the shared dependency-freshness gate
"Are we on the newest version?" was not mechanically answerable across these
repos: constraint styles had drifted per-ecosystem and a caret range is
"newest-compatible" by definition, which gives a checker nothing to compare.
This gate makes it answerable and then enforces the answer.

Checks two things at once -- that every dependency carries an exact pin, and
that the pin equals its registry's latest STABLE release -- across pub.dev,
PyPI, npm, crates.io, the Go proxy, kuhyx/utils git tags, and the Flutter /
Node / Python toolchains.

Three deliberate design points:

* Pre-releases are rejected per-ecosystem, because every ecosystem leaks them
  differently and each leak fails GREEN. npm lets a maintainer point
  `dist-tags.latest` at an rc; crates.io's `max_version` includes them; PyPI's
  legacy `info.version` includes yanked releases. Unit-tested with fixtures,
  since an end-to-end run cannot surface a wrong "up to date".

* Offline, the gate serves an expired cache entry and PASSES with a DEGRADED
  banner (exit 3 only under --strict, which is CI). `--no-verify` is banned
  here, so a hook that hard-failed offline would leave no way to commit at all.

* The allowlist has two entry classes. `blocked_by: transitive:<pkg>@<ver>` is
  a predicate that clears itself when upstream moves and must NOT carry a
  date; everything else is discretionary and requires `expires`, capped at 90
  days. Exact pins plus latest-everywhere is provably unsatisfiable when a
  dependency internally constrains a shared transitive, and expiring the
  predicate class on a calendar would turn the gate red for a reason no commit
  could fix. An entry with nothing left to excuse is itself an error.

One hook id, one shim, one shared implementation -- always delegating, so it
cannot fork the way the 250-line cap forked into four ids, two of which were
independent reimplementations.

256 tests, 100% branch coverage on every module of the gate. Also adds the
workflow that runs them, which incidentally gives md_naming's 71 tests their
first CI run.

Not yet installed in any repo: a repo that gets the gate before its deps are
bumped is instantly and permanently red, so the gate and the upgrade land
together, per repo.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 13:00:35 +02:00

85 lines
2.8 KiB
Python

"""Does a range constraint admit a given version?
Only used for the toolchain declarations, where a range is legitimate: an app
saying `sdk: ^3.12.2` is not stale just because Dart moved to 3.13.2 — that
constraint already permits it. The meaningful question there is whether the
range *excludes* the current toolchain, which is a real, actionable break.
Deliberately small: caret, tilde and the comparison operators cover every
constraint style present in these repos. Anything unrecognised returns True,
because a checker that guesses "violation" on syntax it does not understand
produces exactly the red-for-no-reason the gate must avoid.
"""
from __future__ import annotations
import re
from dep_freshness.versions import parse
_OP = re.compile(r"(>=|<=|==|!=|\^|~>|~|>|<)?\s*([0-9][0-9A-Za-z.\-+*]*)")
_ANY = frozenset({"", "any", "*", "latest"})
def _upper_for_caret(text: str) -> str:
"""Caret's exclusive upper bound: `^1.2.3` -> `2.0.0`, `^0.2.1` -> `0.3.0`.
Dart and npm agree on the 0.x special case, and it matters: `^0.2.1` must
not admit 0.3.0.
"""
parts = [int(p) for p in re.split(r"[.\-+]", text)[:3] if p.isdigit()]
while len(parts) < 3:
parts.append(0)
major, minor, _ = parts
if major > 0:
return f"{major + 1}.0.0"
if minor > 0:
return f"0.{minor + 1}.0"
return f"0.0.{parts[2] + 1}"
def _clause(operator: str | None, bound: str, version) -> bool:
other = parse(bound)
if other is None:
return True
if operator == "^":
upper = parse(_upper_for_caret(bound))
return version >= other and (upper is None or version < upper)
if operator in ("~", "~>"):
upper = parse(f"{other.major}.{other.minor + 1}.0")
return version >= other and (upper is None or version < upper)
if operator == ">=":
return version >= other
if operator == "<=":
return version <= other
if operator == ">":
return version > other
if operator == "<":
return version < other
if operator == "!=":
return version != other
return version == other # bare or `==`
def satisfies(constraint: str, candidate: str) -> bool:
"""True when `candidate` falls inside `constraint`."""
text = str(constraint or "").strip().strip('"').strip("'")
if text.lower() in _ANY:
return True
version = parse(candidate)
if version is None:
return True
clauses = [c for c in _OP.finditer(text)]
if not clauses:
return True
return all(_clause(m.group(1), m.group(2), version) for m in clauses)
def lower_bound(constraint: str) -> str | None:
"""The smallest version a constraint admits, when it states one."""
text = str(constraint or "").strip()
match = re.match(r"\s*(\^|~>|~|>=|==)?\s*([0-9][0-9A-Za-z.\-+]*)", text)
if not match:
return None
return match.group(2)