Compare commits

..

3 Commits

Author SHA1 Message Date
4d00d6ccde dep_freshness: upstream: allowlist predicate for forks; Google API clients judged inside their generation
Some checks are pending
dependency freshness / dependencies on newest stable (push) Waiting to run
file length / file-length (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
palette drift / palette (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 20:32:34 +02:00
94f6873148 dep_freshness: a commit pin is current at any branch head, not only the default one
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 20:25:56 +02:00
930888bc15 dep_freshness: gitcommit ecosystem, no-stable fallback, JitPack repo; report unknowns beside stale
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-12 20:21:34 +02:00
26 changed files with 1042 additions and 114 deletions

View File

@ -18,13 +18,27 @@ CARGO: Final = "cargo"
GOMOD: Final = "gomod"
GITTAG: Final = "gittag"
MAVEN: Final = "maven"
# A JitPack artifact pinned to a commit hash instead of a tag. "Newest" is
# the source repository's default-branch HEAD: a hash pin has no release to
# wait for, so the only reading of "current" it admits is "at HEAD".
GITCOMMIT: Final = "gitcommit"
TOOLCHAIN: Final = "toolchain"
# The constraint a workflow parser writes for a version MATRIX. Standing
# decision (kuhy, 2026-08-28): one toolchain version per repo, always newest,
# so a matrix is a finding to delete rather than a range to satisfy.
MATRIX: Final = "matrix"
ECOSYSTEMS: Final = (PUB, PYPI, NPM, CARGO, GOMOD, GITTAG, MAVEN, TOOLCHAIN)
ECOSYSTEMS: Final = (
PUB,
PYPI,
NPM,
CARGO,
GOMOD,
GITTAG,
MAVEN,
GITCOMMIT,
TOOLCHAIN,
)
# --- Registry endpoints -----------------------------------------------------
@ -34,19 +48,25 @@ NPM_API: Final = "https://registry.npmjs.org/{name}"
CRATES_API: Final = "https://crates.io/api/v1/crates/{name}"
GOPROXY_API: Final = "https://proxy.golang.org/{name}/@latest"
FLUTTER_RELEASES: Final = (
"https://storage.googleapis.com/flutter_infra_release/releases/"
"releases_linux.json"
"https://storage.googleapis.com/flutter_infra_release/releases/releases_linux.json"
)
NODE_RELEASES: Final = "https://nodejs.org/dist/index.json"
GRADLE_RELEASES: Final = "https://services.gradle.org/versions/current"
# Asked in order; a 404 moves on. Google first because AndroidX and the
# Android Gradle plugin exist nowhere else, and Central answers 404 fast.
# JitPack last: it serves tag metadata for `com.github.*` artifacts that
# were never published anywhere else (PhotoView, DirectionalViewPager, ...).
MAVEN_REPOS: Final = (
"https://dl.google.com/dl/android/maven2/",
"https://repo1.maven.org/maven2/",
"https://plugins.gradle.org/m2/",
"https://jitpack.io/",
)
UTILS_TAG_REMOTE: Final = "https://github.com/kuhyx/utils"
# JitPack coordinates: `com.github.<owner>:<repo>` or
# `com.github.<owner>.<repo>:<module>`; the GitHub repo is what "HEAD" means.
JITPACK_GROUP_PREFIX: Final = "com.github."
GITHUB_REMOTE: Final = "https://github.com/{repo}"
# pnpm 11 quarantines packages younger than this before it will install them,
# to blunt the window in which a compromised publish is live. The gate matches
@ -67,7 +87,7 @@ CACHE_PATH_ENV: Final = "DEP_FRESHNESS_CACHE"
DEFAULT_CACHE_DIR: Final = "~/.cache/dep-freshness"
CACHE_FILE: Final = "registry.json"
TTL_SECONDS: Final = 6 * 3600
TTL_GITTAG_SECONDS: Final = 24 * 3600
TTL_GITTAG_SECONDS: Final = 24 * 3600 # also gitcommit: both cost a subprocess
HTTP_TIMEOUT: Final = 10.0
PROBE_TIMEOUT: Final = 2.0
MAX_WORKERS: Final = 8
@ -101,28 +121,66 @@ REQUIREMENTS_PATTERN: Final = r"^requirements.*\.txt$"
# repo being checked. Without it `--all` walks utils' own manifests and fails
# the consuming repo for staleness in a directory that repo does not own --
# which is exactly how punchme's first green local run turned red in CI.
EXCLUDED_DIRS: Final = frozenset({
".git", "node_modules", "build", "dist", ".dart_tool", ".venv", "venv",
"__pycache__", "target", "vendor", ".gradle", "ios", "macos", "windows",
".mypy_cache", ".pytest_cache", ".ruff_cache", "coverage", "htmlcov",
".idea", ".vscode", "Pods", ".fvm", ".utils",
})
EXCLUDED_DIRS: Final = frozenset(
{
".git",
"node_modules",
"build",
"dist",
".dart_tool",
".venv",
"venv",
"__pycache__",
"target",
"vendor",
".gradle",
"ios",
"macos",
"windows",
".mypy_cache",
".pytest_cache",
".ruff_cache",
"coverage",
"htmlcov",
".idea",
".vscode",
"Pods",
".fvm",
".utils",
}
)
# --- Constraint policy ------------------------------------------------------
# Q13: these resolve from the Flutter/Dart SDK or are lint packages coupled to
# it, so a caret range is allowed. An exact pin is still checked for staleness.
PUB_CARET_ALLOWED: Final = frozenset({
"flutter", "flutter_test", "flutter_localizations", "flutter_driver",
"flutter_web_plugins", "integration_test", "sky_engine",
"flutter_lints", "very_good_analysis", "lints",
})
PUB_CARET_ALLOWED: Final = frozenset(
{
"flutter",
"flutter_test",
"flutter_localizations",
"flutter_driver",
"flutter_web_plugins",
"integration_test",
"sky_engine",
"flutter_lints",
"very_good_analysis",
"lints",
}
)
# Packages that ship with the Flutter SDK: no registry version exists.
PUB_SDK_PACKAGES: Final = frozenset({
"flutter", "flutter_test", "flutter_localizations", "flutter_driver",
"flutter_web_plugins", "integration_test", "sky_engine",
})
PUB_SDK_PACKAGES: Final = frozenset(
{
"flutter",
"flutter_test",
"flutter_localizations",
"flutter_driver",
"flutter_web_plugins",
"integration_test",
"sky_engine",
}
)
# `dependency_overrides` is an unpinned dependency wearing a disguise.
PUB_OVERRIDE_KEY: Final = "dependency_overrides"
@ -137,3 +195,9 @@ ALLOWLIST_FILE: Final = "dependency-freshness.allowlist.yaml"
SHARED_ALLOWLIST_ENV: Final = "DEP_FRESHNESS_SHARED_ALLOWLIST"
ALLOWLIST_MAX_DAYS: Final = 90
TRANSITIVE_PREFIX: Final = "transitive:"
# A fork's predicate: the entry holds only while the upstream repository's own
# copy of the same manifest pins the same version, and dies the day upstream
# bumps. TachiyomiSY cannot take moko-resources 0.27.0 (a 300-file accessor
# rewrite that breaks every future upstream string) before jobobby04 does.
UPSTREAM_PREFIX: Final = "upstream:"
GITHUB_RAW: Final = "https://raw.githubusercontent.com/{repo}/HEAD/{path}"

View File

@ -6,6 +6,9 @@ Two entry classes, and the distinction is the whole point:
re-evaluated every run and the entry clears itself when upstream moves. It
never expires on a calendar, because a date nobody can act on turns the gate
red for a reason no commit can fix.
* `blocked_by: upstream:<owner>/<repo>` is the fork's predicate: it holds
while that repository's copy of the same manifest pins the same version
(`upstream.py`), and dies the day upstream bumps.
* anything else is **discretionary**: it needs `expires`, capped at 90 days,
and fails once past.
@ -15,13 +18,12 @@ allowlist that rots silently is a suppression, not an exception.
from __future__ import annotations
import os
from datetime import date, datetime
from pathlib import Path
import yaml
import os
from dep_freshness._tables import (
ALLOWLIST_FILE,
ALLOWLIST_MAX_DAYS,
@ -79,17 +81,19 @@ def _entry(raw: object, source: Path, position: int) -> Exception_:
expires=(str(raw["expires"]).strip() if raw.get("expires") else None),
source=source,
)
if entry.transitive:
if entry.predicate:
if entry.expires:
raise AllowlistError(
f"{where}: a transitive: entry must NOT set expires -- it clears "
f"{where}: a predicate entry must NOT set expires -- it clears "
"itself when the blocker lifts, and a date nobody can act on "
"only turns the gate red for no actionable reason"
)
if not entry.blocker or not all(entry.blocker):
if entry.transitive and (not entry.blocker or not all(entry.blocker)):
raise AllowlistError(
f"{where}: blocked_by must read transitive:<package>@<version>"
)
if entry.upstream and len((entry.upstream_repo or "").split("/")) != 2:
raise AllowlistError(f"{where}: blocked_by must read upstream:<owner>/<repo>")
return entry
if not entry.expires:
raise AllowlistError(f"{where}: a discretionary entry requires expires")
@ -98,7 +102,7 @@ def _entry(raw: object, source: Path, position: int) -> Exception_:
def check_expiry(entry: Exception_, today: date | None = None) -> None:
"""Raise if a discretionary entry is past due or reaches too far out."""
if entry.transitive or not entry.expires:
if entry.predicate or not entry.expires:
return
now = today or date.today()
when = _parse_date(entry.expires, f"{entry.source}: {entry.package}")

View File

@ -8,17 +8,18 @@ user, because `--no-verify` is banned.
from __future__ import annotations
from dataclasses import dataclass
import json
import os
from pathlib import Path
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
from dep_freshness._tables import (
CACHE_FILE,
CACHE_PATH_ENV,
DEFAULT_CACHE_DIR,
GITCOMMIT,
GITTAG,
TTL_GITTAG_SECONDS,
TTL_SECONDS,
@ -32,8 +33,8 @@ def cache_dir() -> Path:
def ttl_for(ecosystem: str) -> int:
"""Git tags move rarely and cost a subprocess, so they cache longer."""
return TTL_GITTAG_SECONDS if ecosystem == GITTAG else TTL_SECONDS
"""Git refs move rarely and cost a subprocess, so they cache longer."""
return TTL_GITTAG_SECONDS if ecosystem in (GITTAG, GITCOMMIT) else TTL_SECONDS
@dataclass

View File

@ -15,9 +15,9 @@ banned here, so a hook that hard-fails offline would leave no way to commit.
from __future__ import annotations
import argparse
from pathlib import Path
import subprocess
import sys
from pathlib import Path
from dep_freshness import report
from dep_freshness._tables import NPM
@ -27,7 +27,9 @@ from dep_freshness.evaluate import judge
from dep_freshness.models import Finding, Severity
from dep_freshness.quarantine import installable_latest
from dep_freshness.registries import http
from dep_freshness.registries.http import Offline
from dep_freshness.resolve import Answer, Resolver
from dep_freshness.upstream import still_pins
def repo_root(start: Path) -> Path:
@ -45,8 +47,9 @@ def repo_root(start: Path) -> Path:
def _excuse(
findings: list[Finding], entries, shared: Path | None = None,
whole_repo: bool = True,
) -> tuple[list[Finding], list]:
whole_repo: bool = True, root: Path | None = None,
degraded: list[str] | None = None,
) -> tuple[list[Finding], list, dict[str, bool]]:
"""Split findings into (still failing, excused), and flag dead entries.
A `transitive:` entry clears itself the moment its dependency is no longer
@ -68,6 +71,7 @@ def _excuse(
"""
by_label = {f"{e.ecosystem}:{e.package}": e for e in entries}
used: set[str] = set()
blocking: dict[str, bool] = {}
failing: list[Finding] = []
excused: list[Finding] = []
for finding in findings:
@ -76,9 +80,18 @@ def _excuse(
used.add(finding.label) # the entry applies here, even if it
# does not excuse this particular pin -- that is a stale pin to
# fix, not allowlist rot to delete.
blocking[finding.label] = True
if entry is None or not _covers(entry, finding):
failing.append(finding)
continue
if entry.upstream and not _upstream_holds(entry, finding, root, degraded):
blocking[finding.label] = False
failing.append(Finding(
finding.dep, finding.severity, finding.latest,
f"{entry.upstream_repo} no longer pins {entry.pinned}: drop the "
"allowlist entry and take the bump",
))
continue
excused.append(Finding(
finding.dep, finding.severity, finding.latest, finding.detail,
excused=entry.reason,
@ -89,7 +102,17 @@ def _excuse(
and f"{e.ecosystem}:{e.package}" not in used
and (shared is None or e.source != shared)
]
return failing, dead
return failing, dead, blocking
def _upstream_holds(entry, finding: Finding, root, degraded) -> bool:
"""Offline, an `upstream:` entry is trusted and the run is marked degraded."""
try:
return still_pins(entry, finding, root or Path.cwd())
except Offline as exc:
if degraded is not None:
degraded.append(f"{entry.blocked_by} unverified: {exc}")
return True
def _covers(entry, finding: Finding) -> bool:
@ -187,13 +210,11 @@ def main(argv: list[str] | None = None) -> int:
resolver = Resolver(refresh=args.refresh)
findings = collect(_targets(args, root), resolver)
shared = shared_path()
failing, dead = _excuse(
failing, dead, still_blocking = _excuse(
findings, entries,
shared=None if root == shared.parent else shared,
whole_repo=args.all,
whole_repo=args.all, root=root, degraded=resolver.degraded,
)
still_blocking = {f.label: True for f in findings}
report.exceptions_block(entries, still_blocking)
unknown = [f for f in failing if f.severity is Severity.UNKNOWN]
@ -213,10 +234,13 @@ def main(argv: list[str] | None = None) -> int:
print(report.as_json(failing, entries, code))
return code
# Both sections print when both apply: an undeterminable package hidden
# behind a stale one only surfaces after the bump, as a fresh red run.
if unknown or resolver.degraded:
report.degraded(resolver.degraded or [f.label for f in unknown])
if real:
report.violations(real, root)
return 1
if unknown or resolver.degraded:
report.degraded(resolver.degraded or [f.label for f in unknown])
return 3 if args.strict else 0
return 0

View File

@ -15,11 +15,53 @@ purpose:
from __future__ import annotations
from dep_freshness._tables import MATRIX, TOOLCHAIN
from dep_freshness._tables import GITCOMMIT, MATRIX, TOOLCHAIN
from dep_freshness.constraints import lower_bound, satisfies
from dep_freshness.models import Dep, Finding, Severity
from dep_freshness.resolve import Answer
from dep_freshness.versions import behind
from dep_freshness.versions import behind, google_api_key
# What JitPack accepts as a version, and what a bump pastes into the catalog.
_SHORT_SHA = 10
def _commit(dep: Dep, heads: str) -> Finding | None:
"""A hash pin is current while SOME branch head still starts with it.
`heads` is the registry's space-joined list, default branch first; the
default head is what a stale finding proposes.
"""
short = heads.split()[0][:_SHORT_SHA]
if not dep.pinned:
return Finding(dep, Severity.UNPINNED, short, detail=f"pin a commit ({short})")
pin = dep.pinned.lower()
if any(head.lower().startswith(pin) for head in heads.split()):
return None
return Finding(
dep,
Severity.STALE,
short,
detail="no branch of the source repository points at this commit any "
"more; a commit pin has no release to wait for",
)
def _generation(dep: Dep, pin, latest: str) -> Finding | None:
"""A Google API client is judged inside its own generation only."""
gen, rank = pin
for candidate in latest.split():
key = google_api_key(candidate)
if key is None or key[0] != gen:
continue
if key[1] > rank:
return Finding(dep, Severity.STALE, candidate)
return None
return Finding(
dep,
Severity.UNKNOWN,
None,
detail=f"the registry has no {gen} generation of this client any more",
)
def _toolchain(dep: Dep, latest: str) -> Finding | None:
@ -86,6 +128,11 @@ def judge(dep: Dep, answer: Answer) -> Finding | None:
if dep.ecosystem == TOOLCHAIN:
return _toolchain(dep, latest)
if dep.ecosystem == GITCOMMIT:
return _commit(dep, latest)
pin = google_api_key(dep.pinned or "")
if pin is not None:
return _generation(dep, pin, latest)
if dep.peer:
# A peerDependency declares what a CONSUMER may bring, so exact-pinning

View File

@ -76,11 +76,32 @@ class Exception_:
@property
def transitive(self) -> bool:
"""True when this is a predicate entry that never expires on a date."""
"""True when a named transitive dependency is what holds the pin."""
from dep_freshness._tables import TRANSITIVE_PREFIX
return self.blocked_by.startswith(TRANSITIVE_PREFIX)
@property
def upstream(self) -> bool:
"""True when the fork's upstream still pinning this version holds it."""
from dep_freshness._tables import UPSTREAM_PREFIX
return self.blocked_by.startswith(UPSTREAM_PREFIX)
@property
def predicate(self) -> bool:
"""True for either self-clearing class; False means a calendar expiry."""
return self.transitive or self.upstream
@property
def upstream_repo(self) -> str | None:
"""`owner/repo` of the upstream an `upstream:` entry names."""
from dep_freshness._tables import UPSTREAM_PREFIX
if not self.upstream:
return None
return self.blocked_by[len(UPSTREAM_PREFIX):].strip()
@property
def blocker(self) -> tuple[str, str] | None:
"""`(package, version)` this entry claims is holding the pin back."""

View File

@ -33,7 +33,7 @@ from typing import Any
import tomllib
from dep_freshness._tables import MAVEN, TOOLCHAIN
from dep_freshness._tables import GITCOMMIT, JITPACK_GROUP_PREFIX, MAVEN, TOOLCHAIN
from dep_freshness.models import Dep
from dep_freshness.parsers._lines import index
from dep_freshness.versions import exact_pin
@ -43,6 +43,15 @@ WRAPPER_NAME = "gradle-wrapper.properties"
_DISTRIBUTION = re.compile(
r"gradle-(?P<version>\d+(?:\.\d+)*(?:-[0-9A-Za-z.-]+?)?)-(?:bin|all)\.zip"
)
# JitPack accepts any commit as a version; 7 to 40 hex digits and nothing
# else is one. `1.0.0` never matches (dots), and a tag like `v2.3.0` has a
# letter outside a-f.
_COMMIT = re.compile(r"^[0-9a-f]{7,40}$")
def _commit_pin(name: str, version: str) -> bool:
"""True for `com.github.*` at a commit hash: a gitcommit dep, not maven."""
return name.startswith(JITPACK_GROUP_PREFIX) and bool(_COMMIT.match(version))
def _rich(value: Any) -> str:
@ -104,14 +113,17 @@ def parse_catalog(path: Path) -> list[Dep]:
continue # BOM-managed, or a dangling ref the build itself rejects
if plugin:
name = f"{name}:{name}.gradle.plugin"
ecosystem, pinned = MAVEN, exact_pin(version)
if _commit_pin(name, version):
ecosystem, pinned = GITCOMMIT, version.strip()
deps.append(
Dep(
ecosystem=MAVEN,
ecosystem=ecosystem,
name=name,
constraint=version,
path=path,
line=line,
pinned=exact_pin(version),
pinned=pinned,
)
)
return deps

View File

@ -0,0 +1,38 @@
"""`git ls-remote` as the one subprocess the registries share.
Deliberately not the GitHub REST API: that allows 60 unauthenticated requests
an hour, which ~20 consuming manifests would exhaust on a single `--all` run.
`ls-remote` is unmetered and answers tags and HEAD alike.
"""
from __future__ import annotations
import subprocess
from dep_freshness.registries.http import Offline, host_reachable
def ls_remote(remote: str, *args: str) -> list[str]:
"""Every `<sha>\\t<ref>` line `git ls-remote` prints for `remote`.
`--options` go before the URL and ref patterns (`HEAD`) after it: git
reads the first positional as the repository, so `ls-remote HEAD <url>`
fails with "'HEAD' does not appear to be a git repository".
"""
if not host_reachable(remote):
raise Offline(remote)
options = [a for a in args if a.startswith("-")]
patterns = [a for a in args if not a.startswith("-")]
try:
result = subprocess.run(
["git", "ls-remote", *options, remote, *patterns],
capture_output=True,
text=True,
timeout=20,
check=False,
)
except (OSError, subprocess.SubprocessError) as exc:
raise Offline(f"{remote}: {exc}") from exc
if result.returncode != 0:
raise Offline(f"{remote}: git ls-remote exit {result.returncode}")
return [line.strip() for line in result.stdout.splitlines() if line.strip()]

View File

@ -8,7 +8,7 @@ from __future__ import annotations
from dep_freshness._tables import CRATES_API
from dep_freshness.registries.http import get_json
from dep_freshness.versions import newest_stable
from dep_freshness.versions import reference
def latest(name: str) -> str | None:
@ -19,7 +19,5 @@ def latest(name: str) -> str | None:
stable = crate.get("max_stable_version")
if stable:
return str(stable)
live = [
v.get("num") for v in payload.get("versions") or [] if not v.get("yanked")
]
return newest_stable(live)
live = [v.get("num") for v in payload.get("versions") or [] if not v.get("yanked")]
return reference(live)

View File

@ -0,0 +1,63 @@
"""JitPack artifacts pinned to a commit: "newest" is the default branch's HEAD.
Seven of TachiyomiSY's dependencies are `com.github.<owner>:<repo>` at a
short hash. No registry lists a "latest" for those, and a hash is not a
version, so the gate's question becomes the only one a commit pin admits:
is the pinned commit still what the source repository's default branch
points at? (kuhy, 2026-09-12: chosen over never-expiring allowlist entries.)
The answer is every branch head's full sha, default branch first; `evaluate`
compares by prefix so a 7-, 10- or 40-character pin all work, and reports
the default head's first ten characters, which is what JitPack accepts as
a version.
"""
from __future__ import annotations
from dep_freshness._tables import GITHUB_REMOTE, JITPACK_GROUP_PREFIX
from dep_freshness.registries._git import ls_remote
def source_repo(name: str) -> str | None:
"""`owner/repo` behind a JitPack coordinate, or None for anything else.
`com.github.mihonapp:image-decoder` -> `mihonapp/image-decoder`;
`com.github.arkon.FlexibleAdapter:flexible-adapter` -> `arkon/FlexibleAdapter`
(a multi-module build names the repo in the group, the module after the
colon).
"""
group, sep, artifact = name.partition(":")
if not sep or not artifact or not group.startswith(JITPACK_GROUP_PREFIX):
return None
parts = group[len(JITPACK_GROUP_PREFIX) :].split(".")
if not parts[0]:
return None
repo = parts[1] if len(parts) > 1 and parts[1] else artifact
return f"{parts[0]}/{repo}"
def latest(name: str) -> str | None:
"""Every branch head of the source repo, default branch first, space-joined.
A pin is current when it is SOME branch's head, not only the default one:
Mihon pins `deadlock-fix` of sqldelight-androidx-driver and Tachiyomi
pins `fix-build2` of FlexibleAdapter, both side branches whose heads are
exactly the pinned commits. Comparing those against `master` alone
called two current pins stale. None when `name` is not a JitPack pin.
"""
repo = source_repo(name)
if repo is None:
return None
default: str | None = None
heads: list[str] = []
# No `--heads`: that filter drops the symbolic HEAD line, which is the
# only way to learn WHICH head is the default branch's.
for line in ls_remote(GITHUB_REMOTE.format(repo=repo)):
sha, _, ref = line.partition("\t")
sha, ref = sha.strip(), ref.strip()
if ref == "HEAD":
default = sha
elif ref.startswith("refs/heads/"):
heads.append(sha)
ordered = ([default] if default else []) + [h for h in heads if h != default]
return " ".join(ordered) or None

View File

@ -1,18 +1,15 @@
"""Shared libraries consumed by git tag out of `kuhyx/utils`.
"Newest" here is the newest tag matching `<package>-vX.Y.Z`, not a registry
answer. Deliberately `git ls-remote` rather than the GitHub REST API: that API
allows 60 unauthenticated requests an hour, which ~20 consuming manifests would
exhaust on a single `--all` run.
answer. The transport is `git ls-remote` (see `_git.py`), never the REST API.
"""
from __future__ import annotations
import re
import subprocess
from dep_freshness._tables import UTILS_TAG_REMOTE
from dep_freshness.registries.http import Offline, host_reachable
from dep_freshness.registries._git import ls_remote
from dep_freshness.versions import newest_stable
_TAG = re.compile(r"refs/tags/(?P<name>[A-Za-z0-9_.-]+)-v(?P<version>[0-9][^\s]*)$")
@ -20,23 +17,9 @@ _TAG = re.compile(r"refs/tags/(?P<name>[A-Za-z0-9_.-]+)-v(?P<version>[0-9][^\s]*
def latest(package: str, remote: str = UTILS_TAG_REMOTE) -> str | None:
"""Highest semver tag prefixed with `<package>-v`, or None if there is none."""
if not host_reachable(remote):
raise Offline(remote)
try:
result = subprocess.run(
["git", "ls-remote", "--tags", "--refs", remote],
capture_output=True,
text=True,
timeout=20,
check=False,
)
except (OSError, subprocess.SubprocessError) as exc:
raise Offline(f"{remote}: {exc}") from exc
if result.returncode != 0:
raise Offline(f"{remote}: git ls-remote exit {result.returncode}")
found = []
for line in result.stdout.splitlines():
match = _TAG.search(line.strip())
for line in ls_remote(remote, "--tags", "--refs"):
match = _TAG.search(line)
if match and match.group("name") == package:
found.append(match.group("version"))
return newest_stable(found)

View File

@ -1,14 +1,21 @@
"""Maven repositories: newest stable of `group:artifact`, from maven-metadata.
Three repositories, asked in order until one knows the artifact: Google
Four repositories, asked in order until one knows the artifact: Google
Maven (every `androidx.*` and `com.android.*` artifact lives ONLY there),
Maven Central, and the Gradle plugin portal (plugin marker artifacts
`<id>:<id>.gradle.plugin`). A 404 means "not here", not "not anywhere", so
it moves on; anything else surfaces as `Offline` from the HTTP layer.
Maven Central, the Gradle plugin portal (plugin marker artifacts
`<id>:<id>.gradle.plugin`) and JitPack (tag metadata for `com.github.*`
artifacts published nowhere else). A 404 means "not here", not "not
anywhere", so it moves on; anything else surfaces as `Offline` from the HTTP
layer.
`<latest>` and `<release>` in the metadata are not trusted: AndroidX writes
`1.2.0-alpha03` into `<latest>` routinely. The full `<versions>` list goes
through `newest_stable` like every other ecosystem.
through `newest_stable` like every other ecosystem. Only when NO repository
has a stable release at all does the newest pre-release become the reference
(`versions.reference`), which is how `androidx.biometric:biometric-ktx`,
alpha-only since 2021, gets a checkable answer. Google's API clients
(`v3-rev20260901-2.0.0`) are neither: for those the answer is the newest
revision of every generation, and the judge picks the pin's own.
"""
from __future__ import annotations
@ -17,7 +24,7 @@ from xml.etree import ElementTree
from dep_freshness._tables import MAVEN_REPOS
from dep_freshness.registries.http import get_text
from dep_freshness.versions import newest_stable
from dep_freshness.versions import newest_per_generation, newest_stable, reference
def metadata_url(repo: str, name: str) -> str | None:
@ -42,6 +49,7 @@ def versions_in(xml: str) -> list[str]:
def latest(name: str) -> str | None:
seen: list[str] = []
for repo in MAVEN_REPOS:
url = metadata_url(repo, name)
if url is None:
@ -49,7 +57,9 @@ def latest(name: str) -> str | None:
body = get_text(url)
if body is None:
continue
stable = newest_stable(versions_in(body))
versions = versions_in(body)
stable = newest_stable(versions)
if stable is not None:
return stable
return None
seen.extend(versions)
return reference(seen) or newest_per_generation(seen)

View File

@ -9,7 +9,7 @@ from __future__ import annotations
from dep_freshness._tables import NPM_ACCEPT, NPM_API
from dep_freshness.registries.http import get_json
from dep_freshness.versions import is_prerelease, newest_stable
from dep_freshness.versions import is_prerelease, reference
def latest(name: str) -> str | None:
@ -20,4 +20,4 @@ def latest(name: str) -> str | None:
tag = (payload.get("dist-tags") or {}).get("latest")
if tag and not is_prerelease(str(tag)):
return str(tag)
return newest_stable((payload.get("versions") or {}).keys())
return reference((payload.get("versions") or {}).keys())

View File

@ -4,7 +4,7 @@ from __future__ import annotations
from dep_freshness._tables import PUB_API
from dep_freshness.registries.http import get_json
from dep_freshness.versions import newest_stable
from dep_freshness.versions import newest_stable, reference
def latest(name: str) -> str | None:
@ -20,4 +20,4 @@ def latest(name: str) -> str | None:
if candidate and newest_stable([candidate]):
return candidate
versions = [v.get("version") for v in payload.get("versions") or []]
return newest_stable(versions)
return reference(versions)

View File

@ -10,7 +10,7 @@ from __future__ import annotations
from dep_freshness._tables import PYPI_ACCEPT, PYPI_API
from dep_freshness.registries.http import get_json
from dep_freshness.versions import newest_stable
from dep_freshness.versions import reference
_SUFFIXES = (".tar.gz", ".zip", ".whl", ".tar.bz2", ".egg")
@ -44,5 +44,5 @@ def latest(name: str) -> str | None:
if found:
live.add(found)
if live:
return newest_stable(live)
return newest_stable(versions)
return reference(live)
return reference(versions)

View File

@ -7,13 +7,14 @@ allowlist is that every not-latest pin stays visible.
from __future__ import annotations
from datetime import date, datetime
import json
from pathlib import Path
import sys
from datetime import date, datetime
from pathlib import Path
from dep_freshness.models import Exception_, Finding, Severity
def _err(stream):
"""Resolve stderr at call time.
@ -58,7 +59,7 @@ def exceptions_block(
print(f"\n⚠️ DEPENDENCY EXCEPTION IN USE — {len(entries)} active", file=stream)
for entry in entries:
print(f" {entry.package} {entry.pinned} ({entry.ecosystem})", file=stream)
if entry.transitive:
if entry.predicate:
state = "still blocking" if still_blocking.get(
f"{entry.ecosystem}:{entry.package}", True) else "CLEARED"
print(f" blocked_by: {entry.blocked_by} [{state}]", file=stream)
@ -76,7 +77,7 @@ def machine_lines(entries: list[Exception_]) -> list[str]:
head = (f"[DEP-EXCEPTION] {entry.ecosystem}:{entry.package} {entry.pinned}")
if entry.latest_known:
head += f" < {entry.latest_known}"
if entry.transitive:
if entry.predicate:
out.append(f"{head} blocked_by={entry.blocked_by} [still blocking]")
else:
left = _days_left(entry.expires or "")
@ -107,7 +108,7 @@ def violations(findings: list[Finding], root: Path, stream=None) -> None:
)
if finding.detail:
print(f" {finding.detail}", file=stream)
print("", file=stream)
print(file=stream)
print(
"Bump them to latest stable, or record an exception in "
"dependency-freshness.allowlist.yaml with reason + blocked_by.",

View File

@ -12,6 +12,7 @@ from dataclasses import dataclass
from dep_freshness._tables import (
CARGO,
GITCOMMIT,
GITTAG,
GOMOD,
MAVEN,
@ -23,7 +24,16 @@ from dep_freshness._tables import (
)
from dep_freshness.cache import Cache
from dep_freshness.models import Dep
from dep_freshness.registries import cargo, gittag, gomod, maven, npmjs, pub, pypi
from dep_freshness.registries import (
cargo,
gitcommit,
gittag,
gomod,
maven,
npmjs,
pub,
pypi,
)
from dep_freshness.registries import toolchain as tc
from dep_freshness.registries.http import Offline
@ -35,6 +45,7 @@ _LOOKUP = {
GOMOD: gomod.latest,
GITTAG: gittag.latest,
MAVEN: maven.latest,
GITCOMMIT: gitcommit.latest,
}
@ -43,8 +54,8 @@ class Answer:
"""Latest stable for one package, and how confident we are in it."""
version: str | None
stale_cache_days: float | None = None # served from an expired entry
unavailable: bool = False # no network and no cache at all
stale_cache_days: float | None = None # served from an expired entry
unavailable: bool = False # no network and no cache at all
def _toolchain_latest(name: str) -> str | None:

View File

@ -111,3 +111,23 @@ def _offline(_ecosystem, _name):
def test_the_cache_directory_is_honoured(cache_dir):
assert os.environ["DEP_FRESHNESS_CACHE"] == str(cache_dir)
def test_an_undeterminable_package_is_reported_beside_a_stale_one(
repo, run, capsys, monkeypatch
):
"""Hidden behind the stale finding it only surfaced after the bump, as a
fresh red run nobody could have planned for."""
from dep_freshness.registries.http import Offline
def fetch(ecosystem, package):
if package == "http":
return "1.7.0"
raise Offline(package)
monkeypatch.setattr("dep_freshness.resolve._fetch", fetch)
write(repo, "pubspec.yaml", STALE_PUBSPEC)
assert run("--all", "--strict") == 1
err = capsys.readouterr().err
assert "pub:http" in err
assert "DEGRADED" in err

View File

@ -0,0 +1,184 @@
"""JitPack commit pins: "newest" is the source repo's default-branch HEAD.
The fail-green case here is a hash the version parser cannot read: `behind`
returns False for unparseable input, so without its own ecosystem a moved
default branch would pass silently. Every path below is pinned down.
"""
from __future__ import annotations
import subprocess
from pathlib import Path
import pytest
from dep_freshness.cache import ttl_for
from dep_freshness.evaluate import judge
from dep_freshness.models import Dep, Severity
from dep_freshness.parsers import gradle
from dep_freshness.registries import _git, gitcommit
from dep_freshness.registries.http import Offline
from dep_freshness.resolve import _LOOKUP, Answer
from dep_freshness.tests.conftest import write
HEAD = "844a07002c3d2f2b68a6b26a25e8e401777c73e7"
SIDE = "c80135339b6f4c2d8e1a7b3f9d0e5c6a2b4d8f10"
@pytest.fixture
def ls_remote(monkeypatch):
monkeypatch.setattr(_git, "host_reachable", lambda _url: True)
calls: list[list[str]] = []
def install(stdout="", returncode=0, error=None):
def fake_run(args, **_kwargs):
calls.append(args)
if error:
raise error
return subprocess.CompletedProcess(args, returncode, stdout, "")
monkeypatch.setattr(subprocess, "run", fake_run)
return calls
return install
@pytest.mark.parametrize(
"name,expected",
[
("com.github.mihonapp:image-decoder", "mihonapp/image-decoder"),
("com.github.arkon.FlexibleAdapter:flexible-adapter", "arkon/FlexibleAdapter"),
("com.github.zhanghai.quickjs-java:quickjs-android", "zhanghai/quickjs-java"),
("com.github.owner.repo.deeper:module", "owner/repo"),
("com.github.owner.:module", "owner/module"),
("io.coil-kt:coil", None),
("com.github.:module", None),
("com.github.owner", None),
("com.github.owner:", None),
],
)
def test_the_github_repo_behind_a_jitpack_coordinate(name, expected):
assert gitcommit.source_repo(name) == expected
def test_latest_lists_every_branch_head_default_first(ls_remote):
calls = ls_remote(
f"{SIDE}\trefs/heads/fix-build2\n{HEAD}\tHEAD\n{HEAD}\trefs/heads/master\n"
f"{SIDE}\trefs/pull/1/head\n"
)
assert (
gitcommit.latest("com.github.arkon.FlexibleAdapter:flexible-adapter")
== f"{HEAD} {SIDE}"
)
assert calls[-1] == ["git", "ls-remote", "https://github.com/arkon/FlexibleAdapter"]
def test_a_repo_with_no_default_head_still_lists_its_branches(ls_remote):
ls_remote(f"{SIDE}\trefs/heads/dev\n")
assert gitcommit.latest("com.github.mihonapp:image-decoder") == SIDE
def test_no_head_line_means_no_answer(ls_remote):
ls_remote("\n \nabc\trefs/tags/v1\n")
assert gitcommit.latest("com.github.mihonapp:image-decoder") is None
def test_a_non_jitpack_coordinate_never_touches_git(ls_remote):
calls = ls_remote(f"{HEAD}\tHEAD\n")
assert gitcommit.latest("io.coil-kt:coil") is None
assert calls == []
def test_ls_remote_failures_degrade_to_offline(ls_remote, monkeypatch):
ls_remote(returncode=128)
with pytest.raises(Offline):
gitcommit.latest("com.github.mihon:unifile")
ls_remote(error=OSError("no git"))
with pytest.raises(Offline):
gitcommit.latest("com.github.mihon:unifile")
monkeypatch.setattr(_git, "host_reachable", lambda _url: False)
with pytest.raises(Offline):
gitcommit.latest("com.github.mihon:unifile")
CATALOG = """\
[versions]
unifile = "08f224c8f9"
photoView = "2.3.0"
tagged = "abc1234"
[libraries]
unifile = { module = "com.github.mihon:unifile", version.ref = "unifile" }
photoView = { module = "com.github.chrisbanes:PhotoView", version.ref = "photoView" }
inline = "com.github.mihonapp:image-decoder:e03b81e18a"
central = { module = "io.coil-kt:coil", version = "deadbeef" }
short = { module = "com.github.o:r", version = "abc12" }
tagged = { module = "org.example:lib", version.ref = "tagged" }
"""
def test_the_catalog_parser_tells_commit_pins_from_versions(tmp_path):
deps = {
d.name: d
for d in gradle.parse_catalog(write(tmp_path, "libs.versions.toml", CATALOG))
}
assert (
deps["com.github.mihon:unifile"].ecosystem,
deps["com.github.mihon:unifile"].pinned,
) == (
"gitcommit",
"08f224c8f9",
)
assert deps["com.github.mihonapp:image-decoder"].ecosystem == "gitcommit"
assert deps["com.github.chrisbanes:PhotoView"].ecosystem == "maven"
assert deps["com.github.chrisbanes:PhotoView"].pinned == "2.3.0"
# A hash-shaped version outside com.github.* is still a Maven version
# (an unpinned one, since it is not exact), and six hex digits is too few.
assert deps["io.coil-kt:coil"].ecosystem == "maven"
assert deps["io.coil-kt:coil"].pinned is None
assert deps["com.github.o:r"].ecosystem == "maven"
assert deps["org.example:lib"].ecosystem == "maven"
def dep(pinned: str | None = "844a07002c") -> Dep:
return Dep(
ecosystem="gitcommit",
name="com.github.arkon.FlexibleAdapter:flexible-adapter",
constraint=pinned or "",
path=Path("libs.versions.toml"),
line=1,
pinned=pinned,
)
def test_a_pin_at_any_branch_head_passes_whatever_its_length_or_case():
assert judge(dep("844a07002c"), Answer(HEAD)) is None
assert judge(dep("844A070"), Answer(HEAD)) is None
assert judge(dep(HEAD), Answer(HEAD)) is None
# fix-build2's head, not master's: still current.
assert judge(dep("c8013533"), Answer(f"{HEAD} {SIDE}")) is None
def test_a_pin_on_no_branch_head_is_stale_and_proposes_the_default_head():
finding = judge(dep("0123abc"), Answer(f"{HEAD} {SIDE}"))
assert finding.severity is Severity.STALE
assert finding.latest == "844a07002c"
assert "no branch" in finding.detail
def test_a_missing_pin_is_reported_unpinned_with_head_to_use():
finding = judge(dep(None), Answer(HEAD))
assert finding.severity is Severity.UNPINNED
assert "844a07002c" in finding.detail
def test_no_head_at_all_is_unknown_not_a_pass():
assert judge(dep(), Answer(None)).severity is Severity.UNKNOWN
def test_commit_answers_cache_as_long_as_tags():
assert ttl_for("gitcommit") == ttl_for("gittag") > ttl_for("maven")
def test_the_resolver_routes_gitcommit_to_the_git_registry():
assert _LOOKUP["gitcommit"] is gitcommit.latest

View File

@ -0,0 +1,74 @@
"""Google API clients: `v3-rev20260901-2.0.0` is ordered inside its generation.
The fail-green case: read loosely, every `v3-rev...` is "3", and a 2019 pin
compares equal to a 2026 revision. The fail-red case: `v2-...-2.0.0` read as
newer than `v3-...-1.25.0` because 2.0.0 > 1.25.0.
"""
from __future__ import annotations
from pathlib import Path
from dep_freshness.evaluate import judge
from dep_freshness.models import Dep, Severity
from dep_freshness.registries import maven
from dep_freshness.resolve import Answer
from dep_freshness.tests.test_gradle_registry import CENTRAL, metadata
from dep_freshness.versions import exact_pin, google_api_key, newest_per_generation
V3_OLD = "v3-rev197-1.25.0"
V3_NEW = "v3-rev20260901-2.0.0"
V2 = "v2-rev20220709-2.0.0"
def test_the_key_is_generation_then_library_then_revision():
assert google_api_key(V3_NEW)[0] == "v3"
assert google_api_key(V3_NEW)[1] > google_api_key(V3_OLD)[1]
assert google_api_key("v3-rev20260901-1.9.0")[1] < google_api_key(V3_OLD)[1]
assert google_api_key("2.0.0") is None
assert google_api_key("v3-rev197") is None
def test_newest_per_generation_keeps_every_generation():
assert (
newest_per_generation([V3_OLD, V2, V3_NEW, "junk", None, ""])
== f"{V2} {V3_NEW}"
)
assert newest_per_generation(["1.0.0"]) is None
# An older revision met AFTER the newest must not displace it.
assert newest_per_generation([V3_NEW, V3_OLD]) == V3_NEW
def test_the_pin_keeps_its_generation_prefix():
assert exact_pin(V3_OLD) == V3_OLD
def test_the_registry_answers_per_generation_when_nothing_else_parses(monkeypatch):
name = "com.google.apis:google-api-services-drive"
table = {maven.metadata_url(CENTRAL, name): metadata(V3_OLD, V2, V3_NEW)}
monkeypatch.setattr(maven, "get_text", lambda url, *a, **k: table.get(url))
assert maven.latest(name) == f"{V2} {V3_NEW}"
def dep(pinned: str = V3_OLD) -> Dep:
return Dep(
ecosystem="maven",
name="com.google.apis:google-api-services-drive",
constraint=pinned,
path=Path("libs.versions.toml"),
line=1,
pinned=pinned,
)
def test_a_pin_is_judged_inside_its_own_generation_only():
finding = judge(dep(), Answer(f"{V2} {V3_NEW}"))
assert finding.severity is Severity.STALE
assert finding.latest == V3_NEW
assert judge(dep(V3_NEW), Answer(f"{V2} {V3_NEW}")) is None
def test_a_generation_the_registry_dropped_is_unknown_not_a_pass():
finding = judge(dep(), Answer(V2))
assert finding.severity is Severity.UNKNOWN
assert "v3 generation" in finding.detail

View File

@ -1,4 +1,4 @@
"""Maven metadata across three repositories, and the Gradle release feed."""
"""Maven metadata across four repositories, and the Gradle release feed."""
from __future__ import annotations
@ -13,7 +13,7 @@ from dep_freshness.registries.http import Offline
from dep_freshness.resolve import _toolchain_latest
from dep_freshness.tests.conftest import write
GOOGLE, CENTRAL, PORTAL = maven.MAVEN_REPOS
GOOGLE, CENTRAL, PORTAL, JITPACK = maven.MAVEN_REPOS
def metadata(*versions: str, latest: str | None = None) -> str:
@ -68,6 +68,31 @@ def test_a_repo_with_only_prereleases_does_not_stop_the_search(repos):
assert maven.latest("g:a") == "0.9.0"
def test_jitpack_is_asked_last_and_reads_tag_metadata(repos):
"""PhotoView was never published anywhere but JitPack; `v`-tags and bare
tags both appear and the newest wins."""
name = "com.github.chrisbanes:PhotoView"
repos[maven.metadata_url(JITPACK, name)] = metadata("v1.3.1", "2.2.0", "2.3.0")
assert maven.latest(name) == "2.3.0"
def test_a_project_named_tag_is_read_as_its_version(repos):
"""`java-nat-sort` is tagged `natural-comparator-1.1`, not `1.1`."""
name = "com.github.gpanther:java-nat-sort"
repos[maven.metadata_url(JITPACK, name)] = metadata("natural-comparator-1.1")
assert maven.latest(name) == "natural-comparator-1.1"
def test_a_package_with_no_stable_anywhere_falls_back_to_newest_prerelease(repos):
"""biometric-ktx has been alpha-only since 2021: the newest alpha is the
reference, and a stable release in ANY repo would still win over it."""
name = "androidx.biometric:biometric-ktx"
repos[maven.metadata_url(GOOGLE, name)] = metadata(
"1.2.0-alpha05", "1.4.0-alpha02", "1.3.0-alpha01"
)
assert maven.latest(name) == "1.4.0-alpha02"
def test_unknown_everywhere_or_malformed_name_is_none(repos):
assert maven.latest("g:nowhere") is None
assert maven.latest("bare") is None

View File

@ -6,7 +6,7 @@ import subprocess
import pytest
from dep_freshness.registries import gittag
from dep_freshness.registries import _git, gittag
from dep_freshness.registries import toolchain as tc
from dep_freshness.registries.http import Offline
@ -75,7 +75,7 @@ LS_REMOTE = (
@pytest.fixture
def ls_remote(monkeypatch):
monkeypatch.setattr(gittag, "host_reachable", lambda _url: True)
monkeypatch.setattr(_git, "host_reachable", lambda _url: True)
def install(stdout="", returncode=0, error=None):
def fake_run(*_args, **_kwargs):
@ -114,6 +114,6 @@ def test_a_missing_git_binary_degrades_to_offline(ls_remote):
def test_an_unreachable_remote_degrades_to_offline(monkeypatch):
monkeypatch.setattr(gittag, "host_reachable", lambda _url: False)
monkeypatch.setattr(_git, "host_reachable", lambda _url: False)
with pytest.raises(Offline):
gittag.latest("crdt_sync_dart")

View File

@ -0,0 +1,160 @@
"""The `upstream:` predicate: an entry holds while the fork's upstream agrees.
The rot case is the one that matters: the day upstream bumps, the entry must
die loudly rather than keep excusing a pin nobody is waiting on any more.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from dep_freshness import upstream
from dep_freshness.allowlist import AllowlistError, load
from dep_freshness.models import Dep, Exception_, Finding, Severity
from dep_freshness.registries.http import Offline
from dep_freshness.report import exceptions_block, machine_lines
from dep_freshness.tests.conftest import ALLOWLIST, STALE_PUBSPEC, write
UPSTREAM_ENTRY = """\
exceptions:
- ecosystem: pub
package: http
pinned: "1.5.0"
reason: "the project we fork from is still on 1.5.0"
blocked_by: "upstream:someone/demo"
"""
def entry(**kwargs) -> Exception_:
base = {
"ecosystem": "pub",
"package": "http",
"pinned": "1.5.0",
"reason": "r",
"blocked_by": "upstream:someone/demo",
}
return Exception_(**{**base, **kwargs})
def finding(root: Path, path: str = "pubspec.yaml") -> Finding:
dep = Dep(
ecosystem="pub",
name="http",
constraint="1.5.0",
path=root / path,
line=5,
pinned="1.5.0",
)
return Finding(dep, Severity.STALE, "1.6.0")
@pytest.fixture
def raw(monkeypatch):
"""Canned bodies per raw.githubusercontent URL; anything else is a 404."""
table: dict[str, str] = {}
monkeypatch.setattr(upstream, "get_text", lambda url, *a, **k: table.get(url))
return table
URL = "https://raw.githubusercontent.com/someone/demo/HEAD/pubspec.yaml"
def test_the_upstream_manifest_is_fetched_at_the_same_relative_path(raw, tmp_path):
raw[URL] = STALE_PUBSPEC
assert upstream.upstream_pin(entry(), finding(tmp_path), tmp_path) == "1.5.0"
assert upstream.still_pins(entry(), finding(tmp_path), tmp_path)
def test_upstream_having_moved_on_clears_the_entry(raw, tmp_path):
raw[URL] = STALE_PUBSPEC.replace("1.5.0", "1.6.0")
assert not upstream.still_pins(entry(), finding(tmp_path), tmp_path)
def test_no_upstream_manifest_or_no_such_package_is_no_pin(raw, tmp_path):
assert upstream.upstream_pin(entry(), finding(tmp_path), tmp_path) is None
raw[URL] = "name: demo\ndependencies:\n other: 1.0.0\n"
assert upstream.upstream_pin(entry(), finding(tmp_path), tmp_path) is None
def test_a_manifest_outside_the_repo_is_no_pin(raw, tmp_path):
outside = finding(tmp_path.parent, "elsewhere/pubspec.yaml")
assert upstream.upstream_pin(entry(), outside, tmp_path / "repo") is None
def test_offline_propagates_from_the_transport(monkeypatch, tmp_path):
def down(*_a, **_k):
raise Offline("down")
monkeypatch.setattr(upstream, "get_text", down)
with pytest.raises(Offline):
upstream.still_pins(entry(), finding(tmp_path), tmp_path)
def test_an_upstream_entry_parses_and_may_not_carry_an_expiry(tmp_path):
write(tmp_path, ALLOWLIST, UPSTREAM_ENTRY)
parsed = load(tmp_path)[0]
assert parsed.upstream and parsed.predicate and not parsed.transitive
assert parsed.upstream_repo == "someone/demo"
assert parsed.blocker is None
write(tmp_path, ALLOWLIST, UPSTREAM_ENTRY + ' expires: "2099-01-01"\n')
with pytest.raises(AllowlistError, match="must NOT set expires"):
load(tmp_path)
def test_an_upstream_entry_must_name_owner_slash_repo(tmp_path):
write(tmp_path, ALLOWLIST, UPSTREAM_ENTRY.replace("someone/demo", "demo"))
with pytest.raises(AllowlistError, match="upstream:<owner>/<repo>"):
load(tmp_path)
def test_the_report_treats_it_as_a_predicate(capsys):
exceptions_block([entry()], {"pub:http": False})
assert "CLEARED" in capsys.readouterr().err
assert "[still blocking]" in machine_lines([entry()])[0]
def test_end_to_end_the_entry_excuses_while_upstream_agrees(repo, run, raw):
raw[URL] = STALE_PUBSPEC
write(repo, "pubspec.yaml", STALE_PUBSPEC)
write(repo, ALLOWLIST, UPSTREAM_ENTRY)
assert run("--all", "--strict") == 0
def test_end_to_end_upstream_moving_on_fails_the_pin(repo, run, raw, capsys):
raw[URL] = STALE_PUBSPEC.replace("1.5.0", "1.6.0")
write(repo, "pubspec.yaml", STALE_PUBSPEC)
write(repo, ALLOWLIST, UPSTREAM_ENTRY)
assert run("--all", "--strict") == 1
err = capsys.readouterr().err
assert "no longer pins 1.5.0" in err
assert "CLEARED" in err
def test_end_to_end_offline_trusts_the_entry_but_degrades(
repo, run, monkeypatch, capsys
):
def down(*_a, **_k):
raise Offline("down")
monkeypatch.setattr(upstream, "get_text", down)
write(repo, "pubspec.yaml", STALE_PUBSPEC)
write(repo, ALLOWLIST, UPSTREAM_ENTRY)
assert run("--all") == 0
assert "upstream:someone/demo unverified" in capsys.readouterr().err
assert run("--all", "--strict") == 3
def test_a_transitive_entry_has_no_upstream_repo():
assert entry(blocked_by="transitive:x@1.0.0").upstream_repo is None
def test_offline_without_a_degraded_list_still_trusts_the_entry(monkeypatch, tmp_path):
from dep_freshness.check import _upstream_holds
def down(*_a, **_k):
raise Offline("down")
monkeypatch.setattr(upstream, "get_text", down)
assert _upstream_holds(entry(), finding(tmp_path), tmp_path, None)

View File

@ -4,7 +4,14 @@ from __future__ import annotations
import pytest
from dep_freshness.versions import behind, exact_pin, is_prerelease, newest_stable
from dep_freshness.versions import (
behind,
exact_pin,
is_prerelease,
newest_stable,
reference,
split_tag_prefix,
)
@pytest.mark.parametrize("raw", [
@ -58,3 +65,49 @@ def test_behind_never_fires_on_unparseable_input():
"""An unpinned constraint is UNPINNED, never dressed up as staleness."""
assert not behind("^1.6.0", "1.7.0")
assert not behind("1.6.0", "latest")
@pytest.mark.parametrize("raw,expected", [
("natural-comparator-1.1", ("natural-comparator-", "1.1")),
("release-v2.0", ("release-", "v2.0")),
("2.3.0-rc1", ("", "2.3.0-rc1")),
("v1.0.0", ("", "v1.0.0")),
("alpha", ("", "alpha")),
])
def test_a_project_named_tag_splits_into_prefix_and_version(raw, expected):
"""JitPack serves java-nat-sort only as `natural-comparator-1.1`."""
assert split_tag_prefix(raw) == expected
def test_a_project_named_tag_is_a_stable_version_with_its_prefix_kept():
assert not is_prerelease("natural-comparator-1.1")
assert is_prerelease("natural-comparator-1.2-rc1")
assert newest_stable(["natural-comparator-1.1", "natural-comparator-1.0"]) == (
"natural-comparator-1.1"
)
assert behind("natural-comparator-1.0", "natural-comparator-1.1")
assert exact_pin("natural-comparator-1.1") == "natural-comparator-1.1"
assert exact_pin("version-v1.2") == "version-1.2"
def test_reference_is_newest_stable_when_one_exists():
assert reference(["1.0.0", "2.0.0-alpha01"]) == "1.0.0"
def test_reference_falls_back_to_newest_prerelease_only_when_nothing_is_stable():
"""androidx.biometric:biometric-ktx: alpha-only since 2021."""
assert reference(["1.2.0-alpha05", "1.4.0-alpha02", "1.3.0-alpha01"]) == "1.4.0-alpha02"
assert reference(iter(["1.4.0-alpha02", "junk"])) == "1.4.0-alpha02"
assert reference([]) is None
assert reference(["junk", ""]) is None
def test_an_api_generation_is_not_a_project_name():
"""Google's `v3-rev197-1.25.0`: splitting on `v3-rev197-` compared the
Drive v3 client against a v2 artifact and called v2 newer."""
assert split_tag_prefix("v3-rev197-1.25.0") == ("", "v3-rev197-1.25.0")
assert is_prerelease("v3-rev197-1.25.0")
assert newest_stable(["v3-rev197-1.25.0", "v2-rev20220709-2.0.0"]) is None
# ... and the no-stable fallback must not pick one up either: loosely
# parsed, every v3 revision is "3" and the 2019 pin reads as current.
assert reference(["v3-rev197-1.25.0", "v3-rev20250723-2.0.0"]) is None

48
dep_freshness/upstream.py Normal file
View File

@ -0,0 +1,48 @@
"""The `upstream:` predicate: does the fork's upstream still pin this version?
A fork cannot always take a release before the project it tracks does --
moko-resources 0.27.0 rewrites every string accessor across 300 files of
TachiyomiSY and would break each future upstream commit that adds a string.
"Wait for upstream" is the honest reason, and it is checkable: fetch the
upstream repository's copy of the SAME manifest, parse it with the same
parser, and compare the pin. Equal means the entry holds; different means
upstream moved and the entry is dead, which exits 2 like every other rotten
allowlist entry.
"""
from __future__ import annotations
import tempfile
from pathlib import Path
from dep_freshness._tables import GITHUB_RAW
from dep_freshness.discover import parse_manifest
from dep_freshness.models import Exception_, Finding
from dep_freshness.registries.http import get_text
def upstream_pin(entry: Exception_, finding: Finding, root: Path) -> str | None:
"""What `entry.upstream_repo` pins for this package in the same manifest.
None when upstream has no such manifest or does not declare the package;
`Offline` propagates from the transport so the caller can degrade.
"""
try:
relative = finding.dep.path.resolve().relative_to(root.resolve())
except ValueError:
return None
body = get_text(GITHUB_RAW.format(repo=entry.upstream_repo, path=relative.as_posix()))
if body is None:
return None
with tempfile.TemporaryDirectory() as scratch:
copy = Path(scratch) / finding.dep.path.name
copy.write_text(body, encoding="utf-8")
for dep in parse_manifest(copy):
if dep.ecosystem == finding.dep.ecosystem and dep.name == finding.dep.name:
return dep.pinned or dep.constraint
return None
def still_pins(entry: Exception_, finding: Finding, root: Path) -> bool:
"""True while upstream pins exactly the version the entry excuses."""
return upstream_pin(entry, finding, root) == entry.pinned

View File

@ -3,7 +3,8 @@
The dangerous bug class here fails *green*: npm publishes pre-releases to
`dist-tags.latest` and crates.io's `max_version` includes them, so an adapter
that trusts either reports "up to date" while the pin is behind. Every
"latest" that leaves this package goes through `newest_stable`.
"latest" that leaves this package goes through `newest_stable` or, for a
package that has never shipped a stable release, `reference`.
"""
from __future__ import annotations
@ -19,15 +20,38 @@ _SEMVER = re.compile(
r"(?:-(?P<pre>[0-9A-Za-z.-]+))?"
r"(?:\+(?P<build>[0-9A-Za-z.-]+))?$"
)
# A tag that carries its project name: JitPack serves `java-nat-sort` only as
# `natural-comparator-1.1`. Only a digit-free name that STARTS with a letter
# and is followed by the version counts: `2.3.0-rc1` is untouched and stays a
# pre-release, and Google's `v3-rev197-1.25.0` API clients are NOT split,
# because `v3-` is an API generation, not a project name, and reading it as
# one proposed a `v2-...-2.0.0` artifact as "newer".
_TAG_PREFIX = re.compile(r"^(?P<prefix>[A-Za-z][A-Za-z_.-]*?-)(?=v?\d)")
def parse(raw: str) -> Version | None:
"""A comparable version, or None when the string is not one."""
text = raw.strip().lstrip("v")
def split_tag_prefix(raw: str) -> tuple[str, str]:
"""`("natural-comparator-", "1.1")`; an unprefixed version keeps `("", ...)`."""
text = raw.strip()
match = _TAG_PREFIX.match(text)
if not match:
return ("", text)
return (match.group("prefix"), text[match.end() :])
def parse(raw: str, strict: bool = False) -> Version | None:
"""A comparable version, or None when the string is not one.
`strict` refuses the semver-core fallback: `v3-rev197-1.25.0` reads as
`3` loosely, which is enough to order it but says nothing about what it
is, and the pre-release fallback below must not build on that.
"""
tail = split_tag_prefix(raw)[1]
try:
return Version(text)
return Version(tail.lstrip("v"))
except InvalidVersion:
match = _SEMVER.match(raw.strip())
if strict:
return None
match = _SEMVER.match(tail)
if not match:
return None
# `core` is `\d+(\.\d+){0,2}`, which Version always accepts.
@ -41,26 +65,84 @@ def is_prerelease(raw: str) -> bool:
silently normalises some semver pre-release tags (`-alpha` survives, but
an unknown suffix can be dropped) and a dropped suffix reads as stable.
"""
if "-" in raw.split("+", 1)[0].lstrip("v"):
tail = split_tag_prefix(raw)[1]
if "-" in tail.split("+", 1)[0].lstrip("v"):
return True
version = parse(raw)
return bool(version and (version.is_prerelease or version.is_devrelease))
def newest_stable(candidates) -> str | None:
"""The highest non-pre-release version in `candidates`, or None."""
def _canonical(raw: str) -> str:
if GOOGLE_API.match(raw.strip()):
return raw.strip() # the leading `v` is the API generation, not noise
prefix, tail = split_tag_prefix(raw)
return prefix + tail.lstrip("v")
def _newest(candidates, prereleases: bool) -> str | None:
best: tuple[Version, str] | None = None
for raw in candidates:
if not raw or is_prerelease(raw):
if not raw or (not prereleases and is_prerelease(raw)):
continue
version = parse(raw)
version = parse(raw, strict=prereleases)
if version is None:
continue
if best is None or version > best[0]:
best = (version, str(raw).strip().lstrip("v"))
best = (version, _canonical(str(raw)))
return best[1] if best else None
def newest_stable(candidates) -> str | None:
"""The highest non-pre-release version in `candidates`, or None."""
return _newest(candidates, prereleases=False)
def reference(candidates) -> str | None:
"""Newest stable, or newest pre-release when no stable was EVER shipped.
`androidx.biometric:biometric-ktx` has been alpha-only since 2021; holding
such a package to "newest stable" is a question with no answer, and an
allowlist entry for it would need renewing every 90 days forever. The
fallback is a predicate: the day a stable release appears, it wins.
Only pre-releases PEP 440 can read qualify. Google's Drive client ships
`v3-rev197-1.25.0`-style versions that are not pre-releases at all; the
loose parser orders them by API generation, and a fallback built on that
once declared a 2019 pin current against every newer revision.
"""
candidates = list(candidates)
return newest_stable(candidates) or _newest(candidates, prereleases=True)
# Google's API clients: `v3-rev20260901-2.0.0` is generation v3 of the API,
# revision 20260901 of the discovery document, built on library 2.0.0. No
# ordering across generations exists (v2 and v3 are different APIs), so the
# registry answers with the newest revision of EVERY generation and the
# judge picks the pin's own.
GOOGLE_API = re.compile(r"^(?P<gen>v\d+)-rev(?P<rev>\d+)-(?P<lib>\d+(?:\.\d+)*)$")
def google_api_key(raw: str) -> tuple[str, tuple[Version, int]] | None:
"""`("v3", (Version("2.0.0"), 20260901))` for a Google API client version."""
match = GOOGLE_API.match(raw.strip())
if not match:
return None
return (match.group("gen"), (Version(match.group("lib")), int(match.group("rev"))))
def newest_per_generation(candidates) -> str | None:
"""Space-joined newest Google API client per generation, or None."""
best: dict[str, tuple[tuple[Version, int], str]] = {}
for raw in candidates:
key = google_api_key(raw or "")
if key is None:
continue
gen, rank = key
if gen not in best or rank > best[gen][0]:
best[gen] = (rank, raw.strip())
return " ".join(best[gen][1] for gen in sorted(best)) or None
def behind(pinned: str, latest: str) -> bool:
"""True when `pinned` is strictly older than `latest`.
@ -76,8 +158,13 @@ def behind(pinned: str, latest: str) -> bool:
# Any number of numeric release components, not three: PyPI stub packages
# date-stamp a fourth (`types-requests==2.33.0.20260712`), and capping at
# three reported an exact pin as unpinned against itself.
EXACT = re.compile(r"^\s*(?:==\s*)?v?\d+(?:\.\d+)*(?:[-+][0-9A-Za-z.-]+)?\s*$")
# three reported an exact pin as unpinned against itself. A project-name
# prefix (`natural-comparator-1.1`) is part of the pin, since it is what the
# registry's version list spells.
EXACT = re.compile(
r"^\s*(?:==\s*)?(?:[A-Za-z][A-Za-z_.-]*?-(?=v?\d))?"
r"v?\d+(?:\.\d+)*(?:[-+][0-9A-Za-z.-]+)?\s*$"
)
def exact_pin(constraint: str) -> str | None:
@ -92,4 +179,4 @@ def exact_pin(constraint: str) -> str | None:
text = str(constraint).strip()
if not EXACT.match(text):
return None
return text.lstrip("=").strip().lstrip("v")
return _canonical(text.lstrip("=").strip())