Compare commits

..

No commits in common. "71a43d96583a5c4c34aeb6b0e0a2b92dd8e2697d" and "c4a5db8ebc85c8503fd028791e5f004beaf3e040" have entirely different histories.

22 changed files with 101 additions and 978 deletions

View File

@ -2,7 +2,7 @@ name: crdt_sync
description: >-
Shared CRDT merge scheme + GitHub-Contents-API sync transport for
cross-device apps. Pure Dart, no Flutter dependency.
version: 0.11.1
version: 0.11.0
publish_to: 'none'
environment:

View File

@ -4,7 +4,7 @@ description: >-
persisted per-install device id, and a one-call bootstrap. Removes the
~150 lines of firebase_backend.dart every consuming app was copying.
publish_to: 'none'
version: 0.3.1
version: 0.3.0
environment:
sdk: ^3.12.2
@ -13,7 +13,7 @@ dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.11.1
ref: crdt_sync_dart-v0.11.0
path: crdt_sync_dart
crypto: 3.0.7
flutter:

View File

@ -114,12 +114,5 @@ PUB_SDK_PACKAGES: Final = frozenset({
PUB_OVERRIDE_KEY: Final = "dependency_overrides"
ALLOWLIST_FILE: Final = "dependency-freshness.allowlist.yaml"
# A blocker like "typescript-eslint does not support TS 7" holds in EVERY repo
# that pins typescript, so a repo-only allowlist would mean hand-copying one
# entry into eight files that then all rot independently -- the four-way fork
# of the 250-line cap, in the mechanism built to avoid it. The shared file in
# ~/utils is inherited; a repo entry for the same package overrides it.
SHARED_ALLOWLIST_ENV: Final = "DEP_FRESHNESS_SHARED_ALLOWLIST"
ALLOWLIST_MAX_DAYS: Final = 90
TRANSITIVE_PREFIX: Final = "transitive:"

View File

@ -20,13 +20,7 @@ from pathlib import Path
import yaml
import os
from dep_freshness._tables import (
ALLOWLIST_FILE,
ALLOWLIST_MAX_DAYS,
SHARED_ALLOWLIST_ENV,
)
from dep_freshness._tables import ALLOWLIST_FILE, ALLOWLIST_MAX_DAYS
from dep_freshness.models import Exception_
REQUIRED = ("ecosystem", "package", "pinned", "reason", "blocked_by")
@ -40,18 +34,6 @@ def path_for(root: Path) -> Path:
return root / ALLOWLIST_FILE
def shared_path() -> Path:
"""The fleet-wide allowlist that every repo inherits.
Lives beside the gate it belongs to. Overridable so a test -- or a machine
that keeps utils somewhere else -- is not forced to touch the real one.
"""
override = os.environ.get(SHARED_ALLOWLIST_ENV)
if override:
return Path(override).expanduser()
return Path(__file__).resolve().parent.parent / ALLOWLIST_FILE
def _parse_date(raw: object, where: str) -> date:
if isinstance(raw, date) and not isinstance(raw, datetime):
return raw
@ -114,21 +96,8 @@ def check_expiry(entry: Exception_, today: date | None = None) -> None:
def load(root: Path) -> list[Exception_]:
"""Every exception in force for `root`: the shared set, then the repo's.
A repo entry for the same `ecosystem:package` replaces the shared one, so a
repo can always be stricter or state its own reason -- but nobody has to
copy a fleet-wide blocker into forty files to be able to commit.
"""
entries = {
f"{e.ecosystem}:{e.package}": e for e in _load_file(shared_path())
}
for entry in _load_file(path_for(root)):
entries[f"{entry.ecosystem}:{entry.package}"] = entry
return list(entries.values())
def _load_file(source: Path) -> list[Exception_]:
"""Every exception declared for `root`; [] when there is no allowlist."""
source = path_for(root)
if not source.is_file():
return []
try:

View File

@ -21,7 +21,7 @@ import sys
from dep_freshness import report
from dep_freshness._tables import NPM
from dep_freshness.allowlist import AllowlistError, load, shared_path
from dep_freshness.allowlist import AllowlistError, load
from dep_freshness.discover import find_manifests, is_manifest, parse_manifest
from dep_freshness.evaluate import judge
from dep_freshness.models import Finding, Severity
@ -43,28 +43,12 @@ def repo_root(start: Path) -> Path:
return Path(result.stdout.strip() or start)
def _excuse(
findings: list[Finding], entries, shared: Path | None = None,
whole_repo: bool = True,
) -> tuple[list[Finding], list]:
def _excuse(findings: list[Finding], entries) -> tuple[list[Finding], list]:
"""Split findings into (still failing, excused), and flag dead entries.
A `transitive:` entry clears itself the moment its dependency is no longer
stale — that is what makes it a predicate rather than a date. An entry with
nothing left to excuse is allowlist rot and exits 2.
Inherited entries are exempt from that rot check everywhere except the
repo that owns the shared file. A fleet-wide hold on `typescript`
legitimately excuses nothing in a Flutter app, and failing there would
make every repo without that dependency uncommittable.
`whole_repo` is False for a file-scoped run -- what pre-commit does, since
it passes only the staged manifests. Such a run has seen a SUBSET of the
repo by construction, so "no finding mentioned this package" carries no
information about whether the entry is still needed. Judging rot there
fails the commit over a manifest the commit never touched: staging two
pubspec.yaml files in utils reported the fleet-wide typescript hold as
dead, because no package.json was in scope to be found stale.
"""
by_label = {f"{e.ecosystem}:{e.package}": e for e in entries}
used: set[str] = set()
@ -80,12 +64,7 @@ def _excuse(
finding.dep, finding.severity, finding.latest, finding.detail,
excused=entry.reason,
))
dead = [
e for e in entries
if whole_repo
and f"{e.ecosystem}:{e.package}" not in used
and (shared is None or e.source != shared)
]
dead = [e for e in entries if f"{e.ecosystem}:{e.package}" not in used]
return failing, dead
@ -170,12 +149,7 @@ 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(
findings, entries,
shared=None if root == shared.parent else shared,
whole_repo=args.all,
)
failing, dead = _excuse(findings, entries)
still_blocking = {f.label: True for f in findings}
report.exceptions_block(entries, still_blocking)

View File

@ -1,113 +0,0 @@
"""Install the three gate pieces into a repo, from one set of templates.
The gate ships as three hand-replicated files per repo -- a delegate script, a
pre-commit hook entry and a CI workflow -- and hand-replication is exactly how
the 250-line cap ended up with four different hook ids, two of them
independent reimplementations rather than delegates. Sixteen more repos of
copy-paste would repeat that, so the copy is a script and the templates have
one home.
Idempotent by design: running it twice changes nothing the second time, and
`plan()` reports what a run WOULD do without touching the repo.
"""
from __future__ import annotations
from pathlib import Path
TEMPLATES = Path(__file__).resolve().parent / "templates"
DELEGATE = Path("scripts/check_dependency_freshness.sh")
WORKFLOW = Path(".github/workflows/dependency-freshness.yml")
PRECOMMIT = Path(".pre-commit-config.yaml")
HOOK_ID = "dependency-freshness"
EMPTY_PRECOMMIT = "repos:\n - repo: local\n hooks:\n"
def _template(name: str) -> str:
return (TEMPLATES / name).read_text(encoding="utf-8")
def _needs_delegate(repo: Path) -> bool:
target = repo / DELEGATE
return not target.is_file() or target.read_text(encoding="utf-8") != _template(
"delegate.sh"
)
def _needs_workflow(repo: Path) -> bool:
target = repo / WORKFLOW
return not target.is_file() or target.read_text(encoding="utf-8") != _template(
"workflow.yml"
)
def _needs_hook(repo: Path) -> bool:
target = repo / PRECOMMIT
if not target.is_file():
return True
return f"id: {HOOK_ID}" not in target.read_text(encoding="utf-8")
def _write_hook(repo: Path) -> None:
"""Append the hook block to the repo's `local` hooks list.
Appending rather than parsing-and-re-emitting is deliberate: every one of
these configs carries comments explaining why a hook exists, and a YAML
round-trip through the standard library drops all of them.
"""
target = repo / PRECOMMIT
body = target.read_text(encoding="utf-8") if target.is_file() else EMPTY_PRECOMMIT
if not body.endswith("\n"):
body += "\n"
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(f"{body}\n{_template('precommit-hook.yaml')}", encoding="utf-8")
def plan(repo: Path) -> list[str]:
"""Which pieces are missing or have drifted from the template."""
todo = []
if _needs_delegate(repo):
todo.append(str(DELEGATE))
if _needs_workflow(repo):
todo.append(str(WORKFLOW))
if _needs_hook(repo):
todo.append(f"{PRECOMMIT} ({HOOK_ID} hook)")
return todo
def install(repo: Path) -> list[str]:
"""Write every missing or drifted piece. Returns what changed."""
done = []
if _needs_delegate(repo):
target = repo / DELEGATE
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(_template("delegate.sh"), encoding="utf-8")
target.chmod(0o755)
done.append(str(DELEGATE))
if _needs_workflow(repo):
target = repo / WORKFLOW
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(_template("workflow.yml"), encoding="utf-8")
done.append(str(WORKFLOW))
if _needs_hook(repo):
_write_hook(repo)
done.append(f"{PRECOMMIT} ({HOOK_ID} hook)")
return done
def write_fvmrc(repo: Path, version: str) -> bool:
"""Pin the Flutter SDK. Returns True if the file changed.
Only for repos that actually hold a pubspec.yaml -- an .fvmrc in a Python
repo is a declaration about a toolchain nothing there builds with, and the
gate would then check a version that cannot go stale in any useful sense.
"""
if not any(repo.rglob("pubspec.yaml")):
return False
target = repo / ".fvmrc"
body = '{\n "flutter": "%s"\n}\n' % version
if target.is_file() and target.read_text(encoding="utf-8") == body:
return False
target.write_text(body, encoding="utf-8")
return True

View File

@ -1,57 +0,0 @@
"""Command line for `install`: which repo, check-only, and the SDK pin."""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
from dep_freshness.install import install, plan, write_fvmrc
from dep_freshness.registries.toolchain import flutter_latest
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Install the dependency-freshness gate into a repo."
)
parser.add_argument("repo", type=Path)
parser.add_argument(
"--check",
action="store_true",
help="report what would be written, change nothing",
)
parser.add_argument(
"--fvm", action="store_true", help="also pin the Flutter SDK in <repo>/.fvmrc"
)
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
repo = args.repo.resolve()
if args.check:
todo = plan(repo)
for piece in todo:
print(f"would write: {piece}")
if not todo:
print("gate already current")
return 0
for piece in install(repo):
print(f"wrote: {piece}")
if args.fvm:
version, _dart = flutter_latest()
if version is None:
# Guessing a version here would pin every repo to a number nobody
# chose, and the gate would then compare against it forever.
print(
"could not resolve latest stable Flutter; .fvmrc left alone",
file=sys.stderr,
)
return 1
if write_fvmrc(repo, version):
print(f"wrote: .fvmrc (flutter {version})")
return 0

View File

@ -1,10 +0,0 @@
"""`python3 -m dep_freshness.install_main` — the installer's entrypoint.
Three lines for the same reason as `__main__.py`: an `if __name__` guard
inside install_cli.py would be a branch no test can enter, and the honest way
to hold full coverage is to have no untestable branch rather than suppress one.
"""
from dep_freshness.install_cli import main
raise SystemExit(main())

View File

@ -17,14 +17,9 @@ from __future__ import annotations
from datetime import datetime, timedelta, timezone
from dep_freshness._tables import NPM_API, NPM_QUARANTINE_HOURS
from dep_freshness.cache import Cache
from dep_freshness.registries.http import Offline, get_json
from dep_freshness.versions import newest_stable, parse
# Its own cache namespace: the answer here is narrower than `npm/<name>` and
# the two must not overwrite each other.
CACHE_ECOSYSTEM = "npm-installable"
def cutoff(now: datetime | None = None) -> datetime:
"""Publishes at or after this instant are still quarantined."""
@ -40,10 +35,7 @@ def _parse(stamp: str) -> datetime | None:
def installable_latest(
name: str,
ceiling: str,
now: datetime | None = None,
cache: Cache | None = None,
name: str, ceiling: str, now: datetime | None = None
) -> str | None:
"""Newest stable release published before the quarantine cutoff.
@ -58,25 +50,11 @@ def installable_latest(
registry has no `time` map), which callers must treat as "no change" --
narrowing on a guess would hide a genuinely stale dependency.
"""
# Cached under the normal TTL. Without this every gate run in a JS-heavy
# repo re-downloads tens of full packuments, inside a pre-commit hook --
# the exact cost the 6h cache exists to prevent.
#
# The ceiling is part of the KEY, not applied afterwards: clamping a cached
# answer to the ceiling would return the ceiling itself, and the ceiling is
# frequently the very release the quarantine is excluding. `dist-tags.latest`
# is stable within a TTL, so hits still land across manifests.
store = cache if cache is not None else Cache()
key = f"{name}@{ceiling}"
entry = store.get(CACHE_ECOSYSTEM, key)
if entry is not None and entry.fresh(CACHE_ECOSYSTEM):
return entry.version
url = NPM_API.format(name=name.replace("/", "%2f"))
try:
payload = get_json(url)
except Offline:
return entry.version if entry is not None else None # stale beats none
return None
if not payload:
return None
times = payload.get("time")
@ -95,7 +73,4 @@ def installable_latest(
if top is not None and (here is None or here > top):
continue
old_enough.append(version)
answer = newest_stable(old_enough)
store.put(CACHE_ECOSYSTEM, key, answer)
store.save()
return answer
return newest_stable(old_enough)

View File

@ -1,34 +0,0 @@
#!/bin/bash
# ============================================================================
# Fail if any dependency in the commit is behind its ecosystem's newest stable.
#
# Thin delegate to the shared gate in ~/utils, which owns the registry
# adapters, the pre-release rules and the allowlist semantics. Copying that
# logic here is what lets one repo's idea of "current" drift from every other
# repo's -- so this script only locates the shared checker and forwards its
# arguments.
#
# Usage:
# scripts/check_dependency_freshness.sh <file> [<file> ...] # pre-commit
# scripts/check_dependency_freshness.sh --all --strict # CI
#
# Exit: 0 current | 1 behind | 2 allowlist wrong | 3 undeterminable (offline)
# ============================================================================
set -euo pipefail
readonly SHARED_GATE="${UTILS_ROOT:-$HOME/utils}/scripts/check_dependency_freshness.sh"
main() {
if [[ ! -x "$SHARED_GATE" ]]; then
echo "Error: shared dependency-freshness gate not found at $SHARED_GATE" >&2
echo " Clone github.com/kuhyx/utils to ~/utils, or set" >&2
echo " UTILS_ROOT to where it lives." >&2
exit 1
fi
exec bash "$SHARED_GATE" "$@"
}
main "$@"

View File

@ -1,20 +0,0 @@
# Every dependency on its ecosystem's newest STABLE release, exact-pinned
# so the question is mechanically answerable at all.
#
# `files:` is what keeps this cheap: a commit touching only source makes
# ZERO network requests, and manifest commits mostly hit a 6h disk cache.
#
# Runs WITHOUT --strict on purpose. Offline it degrades to the cached
# answer and passes with a loud banner; `--no-verify` is banned here, so
# a hook that hard-failed on a flaky connection would leave no way to
# commit at all. CI, always online, is the strict authority.
- id: dependency-freshness
name: dependencies on newest stable
entry: scripts/check_dependency_freshness.sh
language: system
pass_filenames: true
files: >-
(pubspec\.(yaml|lock)|pyproject\.toml|requirements.*\.txt|uv\.lock
|package\.json|package-lock\.json|pnpm-lock\.yaml
|Cargo\.(toml|lock)|go\.(mod|sum)
|\.fvmrc|\.nvmrc|\.python-version)$

View File

@ -1,57 +0,0 @@
name: dependency freshness
# Every dependency on its ecosystem's newest STABLE release, enforced on push
# as well as at commit time. The local pre-commit hook only sees the manifests
# in a commit and can be skipped entirely by a fresh clone that never ran
# `pre-commit install`; this runs `--all` over the whole repo.
#
# `--strict` is CI-only. Offline the gate degrades to its cached answer and
# passes, because `--no-verify` is banned locally and a hook that hard-failed
# on a flaky connection would leave no way to commit. A runner is always
# online, so here an undeterminable answer is a real failure.
#
# Expect this to go red for reasons this repo's commit did not cause: an
# upstream release overnight is enough. That is the chosen behaviour -- the
# alternative is a gate that only notices staleness when someone remembers to
# look.
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
jobs:
dependency-freshness:
name: dependencies on newest stable
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# The gate lives in the shared utils repo so every repo resolves the
# same "latest stable" the same way. Checking it out beats vendoring a
# copy, which is exactly how a gate and its survey start disagreeing.
- name: Check out the shared gate
uses: actions/checkout@v4
with:
repository: kuhyx/utils
path: .utils
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.13"
- name: Install the gate's two runtime dependencies
run: python -m pip install --upgrade pyyaml packaging
- name: Cache registry lookups
uses: actions/cache@v4
with:
path: ~/.cache/dep-freshness
key: dep-freshness-${{ hashFiles('**/pubspec.yaml', '**/pyproject.toml',
'**/requirements*.txt', '**/package.json', '**/Cargo.toml', '**/go.mod') }}
restore-keys: dep-freshness-
- name: Every dependency is on newest stable
run: bash .utils/scripts/check_dependency_freshness.sh --all --strict

View File

@ -46,35 +46,9 @@ def no_network(monkeypatch):
http.force_offline(False)
@pytest.fixture(autouse=True)
def no_shared_allowlist(tmp_path, monkeypatch) -> Path:
"""Point the fleet-wide allowlist at a path that does not exist.
AUTOUSE for the same reason as `cache_dir`: repos inherit the real
~/utils/dependency-freshness.allowlist.yaml, so without this every test
silently reads whatever is currently excused fleet-wide and starts
depending on it.
"""
# In its OWN directory, not tmp_path: the `repo` fixture is tmp_path, and
# the gate exempts inherited entries from the rot check everywhere except
# the repo that owns the shared file. Putting both in one directory makes
# every test look like it is running inside utils.
target = tmp_path / "shared" / "shared-allowlist.yaml"
target.parent.mkdir(parents=True, exist_ok=True)
monkeypatch.setenv("DEP_FRESHNESS_SHARED_ALLOWLIST", str(target))
return target
@pytest.fixture(autouse=True)
@pytest.fixture
def cache_dir(tmp_path, monkeypatch) -> Path:
"""Point the on-disk registry snapshot at a scratch directory.
AUTOUSE, and not negotiable: any code path that constructs a bare `Cache()`
writes to the real ~/.cache/dep-freshness/registry.json otherwise. That
already happened once -- a quarantine test seeded a fake answer for package
"x" into the live cache, and the next run of the same test read its own
pollution back and passed for the wrong reason.
"""
"""Point the on-disk registry snapshot at a scratch directory."""
target = tmp_path / "cache"
monkeypatch.setenv("DEP_FRESHNESS_CACHE", str(target))
return target
@ -85,49 +59,3 @@ def write(root: Path, relative: str, body: str) -> Path:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(body, encoding="utf-8")
return path
STALE_PUBSPEC = """\
name: demo
environment:
sdk: ^3.12.2
dependencies:
http: 1.5.0
"""
CURRENT_PUBSPEC = STALE_PUBSPEC.replace("1.5.0", "1.6.0")
ALLOWLIST = "dependency-freshness.allowlist.yaml"
@pytest.fixture
def canned(monkeypatch, cache_dir):
"""One registry answer for every package the end-to-end fixtures declare.
Deliberately NOT autouse: the resolver tests monkeypatch `_fetch`
themselves, and a fixture that quietly re-patched it for the whole suite
would make those tests pass against this table instead of their own.
`run` depends on it, so every end-to-end test still gets it.
"""
answers = {("pub", "http"): "1.6.0", ("toolchain", "dart"): "3.13.2"}
monkeypatch.setattr(
"dep_freshness.resolve._fetch",
lambda eco, name: answers.get((eco, name)),
)
return answers
@pytest.fixture
def run(repo, monkeypatch, canned):
"""Invoke the CLI inside the throwaway repo and return its exit code.
`check` is imported here rather than at module scope for the same reason
as in `no_network`: the sys.path insert above is what makes the package
importable, and a top-level import would run before it.
"""
from dep_freshness import check
assert canned, "the registry table must be patched before the CLI runs"
def invoke(*argv):
monkeypatch.chdir(repo)
return check.main(list(argv))
return invoke

View File

@ -152,46 +152,3 @@ def test_unreadable_yaml_is_an_error(tmp_path):
_allowlist(tmp_path, "exceptions: [\n")
with pytest.raises(AllowlistError, match="unreadable"):
load(tmp_path)
def test_the_shared_allowlist_is_inherited(tmp_path, no_shared_allowlist):
"""A fleet-wide blocker must not have to be copied into forty repos."""
no_shared_allowlist.write_text(TRANSITIVE, encoding="utf-8")
entries = load(tmp_path)
assert [(e.ecosystem, e.package) for e in entries] == [
("pub", "plugin_platform_interface")
]
def test_a_repo_entry_overrides_the_shared_one(tmp_path, no_shared_allowlist):
no_shared_allowlist.write_text(TRANSITIVE, encoding="utf-8")
_allowlist(tmp_path, TRANSITIVE.replace(
'reason: "firebase_core 4.2.0 constrains this below latest"',
'reason: "this repo has its own reason"'))
entries = load(tmp_path)
assert len(entries) == 1
assert entries[0].reason == "this repo has its own reason"
def test_shared_and_repo_entries_for_different_packages_both_apply(
tmp_path, no_shared_allowlist
):
no_shared_allowlist.write_text(TRANSITIVE, encoding="utf-8")
_allowlist(tmp_path, _discretionary(30))
assert {e.package for e in load(tmp_path)} == {
"plugin_platform_interface", "abandoned"
}
def test_a_malformed_shared_allowlist_is_an_error(tmp_path, no_shared_allowlist):
no_shared_allowlist.write_text("exceptions:\n - just-a-string\n",
encoding="utf-8")
with pytest.raises(AllowlistError, match="must be a mapping"):
load(tmp_path)
def test_the_shared_path_defaults_to_the_gate_repo(monkeypatch):
from dep_freshness.allowlist import shared_path
monkeypatch.delenv("DEP_FRESHNESS_SHARED_ALLOWLIST", raising=False)
assert shared_path().name == NAME
assert shared_path().parent.name == "utils"

View File

@ -7,6 +7,7 @@ this repo has shipped exactly that twice before (two fake file-length gates).
from __future__ import annotations
from datetime import date, timedelta
import os
import pytest
@ -14,12 +15,36 @@ import pytest
from dep_freshness import check
from dep_freshness.cache import Cache
from dep_freshness.registries import http
from dep_freshness.tests.conftest import (
ALLOWLIST,
CURRENT_PUBSPEC,
STALE_PUBSPEC,
write,
)
from dep_freshness.tests.conftest import write
STALE_PUBSPEC = """\
name: demo
environment:
sdk: ^3.12.2
dependencies:
http: 1.5.0
"""
CURRENT_PUBSPEC = STALE_PUBSPEC.replace("1.5.0", "1.6.0")
ALLOWLIST = "dependency-freshness.allowlist.yaml"
@pytest.fixture(autouse=True)
def canned(monkeypatch, cache_dir):
"""One registry answer for every package the fixtures declare."""
answers = {("pub", "http"): "1.6.0", ("toolchain", "dart"): "3.13.2"}
monkeypatch.setattr(
"dep_freshness.resolve._fetch",
lambda eco, name: answers.get((eco, name)),
)
return answers
@pytest.fixture
def run(repo, monkeypatch):
def invoke(*argv):
monkeypatch.chdir(repo)
return check.main(list(argv))
return invoke
def test_a_stale_pin_fails_and_names_the_package(repo, run, capsys):
@ -46,6 +71,56 @@ def test_a_non_manifest_path_is_ignored(repo, run):
assert run("lib/main.dart") == 0
def test_a_transitive_exception_excuses_the_finding(repo, run):
write(repo, "pubspec.yaml", STALE_PUBSPEC)
write(repo, ALLOWLIST, """\
exceptions:
- ecosystem: pub
package: http
pinned: "1.5.0"
reason: "something upstream holds it"
blocked_by: "transitive:some_pkg@1.0.0"
""")
assert run("--all") == 0
def test_an_exception_prints_loudly_even_on_success(repo, run, capsys):
test_a_transitive_exception_excuses_the_finding(repo, run)
err = capsys.readouterr().err
assert "DEPENDENCY EXCEPTION IN USE" in err
assert "still blocking" in err
def test_an_exception_with_nothing_left_to_excuse_is_an_error(repo, run, capsys):
write(repo, "pubspec.yaml", CURRENT_PUBSPEC)
write(repo, ALLOWLIST, """\
exceptions:
- ecosystem: pub
package: http
pinned: "1.5.0"
reason: "stale entry nobody removed"
blocked_by: "transitive:some_pkg@1.0.0"
""")
assert run("--all") == 2
assert "no longer stale" in capsys.readouterr().err
def test_an_expired_allowlist_exits_two(repo, run, capsys):
write(repo, "pubspec.yaml", STALE_PUBSPEC)
yesterday = (date.today() - timedelta(days=1)).isoformat()
write(repo, ALLOWLIST, f"""\
exceptions:
- ecosystem: pub
package: http
pinned: "1.5.0"
reason: "held"
blocked_by: "discretionary"
expires: "{yesterday}"
""")
assert run("--all") == 2
assert "Allowlist ERROR" in capsys.readouterr().err
def test_offline_with_a_cold_cache_passes_with_a_degraded_banner(
repo, run, capsys, monkeypatch
):

View File

@ -1,131 +0,0 @@
"""Allowlist behaviour, end to end: what an exception excuses, and when it rots.
Split out of test_check.py for the 250-line cap. The fixtures (`run`,
`canned`, `repo`, and the `no_shared_allowlist` redirect) live in conftest.py
so both files see one definition.
"""
from __future__ import annotations
from datetime import date, timedelta
from dep_freshness.tests.conftest import (
ALLOWLIST,
CURRENT_PUBSPEC,
STALE_PUBSPEC,
write,
)
SHARED = """\
exceptions:
- ecosystem: pub
package: some_other_package
pinned: "1.0.0"
reason: "a fleet-wide hold on something this repo does not use"
blocked_by: "transitive:whatever@1.0.0"
"""
def test_a_transitive_exception_excuses_the_finding(repo, run):
write(repo, "pubspec.yaml", STALE_PUBSPEC)
write(repo, ALLOWLIST, """\
exceptions:
- ecosystem: pub
package: http
pinned: "1.5.0"
reason: "something upstream holds it"
blocked_by: "transitive:some_pkg@1.0.0"
""")
assert run("--all") == 0
def test_an_exception_prints_loudly_even_on_success(repo, run, capsys):
test_a_transitive_exception_excuses_the_finding(repo, run)
err = capsys.readouterr().err
assert "DEPENDENCY EXCEPTION IN USE" in err
assert "still blocking" in err
def test_an_exception_with_nothing_left_to_excuse_is_an_error(repo, run, capsys):
write(repo, "pubspec.yaml", CURRENT_PUBSPEC)
write(repo, ALLOWLIST, """\
exceptions:
- ecosystem: pub
package: http
pinned: "1.5.0"
reason: "stale entry nobody removed"
blocked_by: "transitive:some_pkg@1.0.0"
""")
assert run("--all") == 2
assert "no longer stale" in capsys.readouterr().err
def test_a_file_scoped_run_never_judges_an_entry_dead(repo, run, capsys):
"""pre-commit passes staged files, so it only ever sees a subset.
The entry below excuses a dependency that lives in a manifest outside the
scoped path. `--all` would find it stale and mark the entry used; a scoped
run cannot, and must not conclude the entry is rot -- that failed a commit
in utils over the fleet-wide typescript hold when the staged files were
two pubspec.yaml.
"""
write(repo, "pubspec.yaml", STALE_PUBSPEC)
write(repo, "sub/pubspec.yaml", CURRENT_PUBSPEC)
write(repo, ALLOWLIST, """\
exceptions:
- ecosystem: pub
package: http
pinned: "1.5.0"
reason: "held by something upstream"
blocked_by: "transitive:some_pkg@1.0.0"
""")
assert run("sub/pubspec.yaml") == 0
assert "no longer stale" not in capsys.readouterr().err
# The same allowlist over the whole repo still excuses, not rots.
assert run("--all") == 0
def test_an_expired_allowlist_exits_two(repo, run, capsys):
write(repo, "pubspec.yaml", STALE_PUBSPEC)
yesterday = (date.today() - timedelta(days=1)).isoformat()
write(repo, ALLOWLIST, f"""\
exceptions:
- ecosystem: pub
package: http
pinned: "1.5.0"
reason: "held"
blocked_by: "discretionary"
expires: "{yesterday}"
""")
assert run("--all") == 2
assert "Allowlist ERROR" in capsys.readouterr().err
def test_an_inherited_entry_this_repo_does_not_need_is_not_rot(
repo, run, no_shared_allowlist
):
"""A fleet-wide hold on typescript excuses nothing in a Flutter app.
Treating that as a dead entry would make every repo without the dependency
uncommittable -- the shared allowlist would be unusable for the exact case
it exists for.
"""
no_shared_allowlist.write_text(SHARED, encoding="utf-8")
write(repo, "pubspec.yaml", CURRENT_PUBSPEC)
assert run("--all") == 0
def test_a_repo_local_entry_with_nothing_to_excuse_is_still_rot(
repo, run, no_shared_allowlist
):
no_shared_allowlist.write_text(SHARED, encoding="utf-8")
write(repo, "pubspec.yaml", CURRENT_PUBSPEC)
write(repo, ALLOWLIST, """\
exceptions:
- ecosystem: pub
package: http
pinned: "1.5.0"
reason: "this repo's own stale entry"
blocked_by: "transitive:x@1.0.0"
""")
assert run("--all") == 2

View File

@ -1,182 +0,0 @@
"""The gate installer: three pieces in, idempotent, and no comments lost.
The point of this module is that sixteen repos get byte-identical copies, so
the assertions compare against the templates rather than against a paraphrase
of them -- a test that spelled the expected content out by hand would let the
template and the installed file drift, which is the failure the installer
exists to prevent.
"""
from __future__ import annotations
import runpy
from pathlib import Path
import pytest
from dep_freshness import install as installer
from dep_freshness.install_cli import main
from dep_freshness.tests.conftest import write
TEMPLATES = Path(installer.__file__).resolve().parent / "templates"
def _template(name: str) -> str:
return (TEMPLATES / name).read_text(encoding="utf-8")
def test_a_bare_repo_gets_all_three_pieces(repo):
assert installer.install(repo) == [
"scripts/check_dependency_freshness.sh",
".github/workflows/dependency-freshness.yml",
".pre-commit-config.yaml (dependency-freshness hook)",
]
delegate = repo / "scripts/check_dependency_freshness.sh"
assert delegate.read_text(encoding="utf-8") == _template("delegate.sh")
assert delegate.stat().st_mode & 0o111, "the hook execs it; it must be +x"
assert (repo / ".github/workflows/dependency-freshness.yml").read_text(
encoding="utf-8"
) == _template("workflow.yml")
assert "id: dependency-freshness" in (repo / ".pre-commit-config.yaml").read_text(
encoding="utf-8"
)
def test_a_second_run_writes_nothing(repo):
installer.install(repo)
assert installer.install(repo) == []
assert installer.plan(repo) == []
def test_plan_names_what_is_missing_without_writing_it(repo):
assert installer.plan(repo) == [
"scripts/check_dependency_freshness.sh",
".github/workflows/dependency-freshness.yml",
".pre-commit-config.yaml (dependency-freshness hook)",
]
assert not (repo / "scripts").exists()
def test_a_drifted_copy_is_rewritten(repo):
installer.install(repo)
delegate = repo / "scripts/check_dependency_freshness.sh"
delegate.write_text("#!/bin/bash\necho lol\n", encoding="utf-8")
workflow = repo / ".github/workflows/dependency-freshness.yml"
workflow.write_text("name: something else\n", encoding="utf-8")
assert installer.install(repo) == [
"scripts/check_dependency_freshness.sh",
".github/workflows/dependency-freshness.yml",
]
assert delegate.read_text(encoding="utf-8") == _template("delegate.sh")
def test_an_existing_pre_commit_config_keeps_its_hooks_and_comments(repo):
"""Appending, not re-emitting: a YAML round-trip drops every comment.
Each of these configs explains why its hooks exist, and that prose is the
only record of it.
"""
write(
repo,
".pre-commit-config.yaml",
"""\
# The 250-line cap. A file that cannot be read in one piece forces re-reads.
repos:
- repo: local
hooks:
- id: file-length-cap
name: file length <= 250 lines
entry: bash scripts/check_file_length.sh
language: system
""",
)
installer.install(repo)
body = (repo / ".pre-commit-config.yaml").read_text(encoding="utf-8")
assert "# The 250-line cap." in body
assert "id: file-length-cap" in body
assert "id: dependency-freshness" in body
def test_a_config_that_already_has_the_hook_is_left_alone(repo):
write(
repo,
".pre-commit-config.yaml",
"""\
repos:
- repo: local
hooks:
- id: dependency-freshness
entry: scripts/check_dependency_freshness.sh
language: system
""",
)
before = (repo / ".pre-commit-config.yaml").read_text(encoding="utf-8")
installer.install(repo)
assert (repo / ".pre-commit-config.yaml").read_text(encoding="utf-8") == before
def test_a_config_without_a_trailing_newline_still_appends_cleanly(repo):
write(repo, ".pre-commit-config.yaml", "repos:\n - repo: local\n hooks:")
installer.install(repo)
body = (repo / ".pre-commit-config.yaml").read_text(encoding="utf-8")
assert body.startswith("repos:\n - repo: local\n hooks:\n\n #")
assert "id: dependency-freshness" in body
def test_fvmrc_is_only_for_repos_that_hold_a_pubspec(repo):
assert installer.write_fvmrc(repo, "3.47.2") is False
assert not (repo / ".fvmrc").exists()
write(repo, "app/pubspec.yaml", "name: demo\n")
assert installer.write_fvmrc(repo, "3.47.2") is True
assert (repo / ".fvmrc").read_text(
encoding="utf-8"
) == '{\n "flutter": "3.47.2"\n}\n'
assert installer.write_fvmrc(repo, "3.47.2") is False
def test_the_cli_installs_and_reports_each_piece(repo, capsys):
assert main([str(repo)]) == 0
out = capsys.readouterr().out
assert "wrote: scripts/check_dependency_freshness.sh" in out
assert "wrote: .github/workflows/dependency-freshness.yml" in out
def test_the_cli_check_mode_writes_nothing(repo, capsys):
assert main([str(repo), "--check"]) == 0
assert (
"would write: scripts/check_dependency_freshness.sh" in capsys.readouterr().out
)
assert not (repo / "scripts").exists()
main([str(repo)])
assert main([str(repo), "--check"]) == 0
assert "gate already current" in capsys.readouterr().out
def test_the_cli_pins_the_sdk_when_asked(repo, monkeypatch, capsys):
monkeypatch.setattr(
"dep_freshness.install_cli.flutter_latest", lambda: ("3.47.2", "3.13.2")
)
write(repo, "pubspec.yaml", "name: demo\n")
assert main([str(repo), "--fvm"]) == 0
assert "wrote: .fvmrc (flutter 3.47.2)" in capsys.readouterr().out
# Same version again: the pin is already right, so nothing is reported.
assert main([str(repo), "--fvm"]) == 0
assert ".fvmrc" not in capsys.readouterr().out
def test_an_unresolvable_sdk_leaves_the_pin_alone(repo, monkeypatch, capsys):
"""Offline, the alternative is pinning every repo to a guessed number."""
monkeypatch.setattr(
"dep_freshness.install_cli.flutter_latest", lambda: (None, None)
)
write(repo, "pubspec.yaml", "name: demo\n")
assert main([str(repo), "--fvm"]) == 1
assert "could not resolve latest stable Flutter" in capsys.readouterr().err
assert not (repo / ".fvmrc").exists()
def test_the_module_entrypoint_runs_the_cli(repo, monkeypatch):
monkeypatch.setattr("sys.argv", ["install_main", str(repo), "--check"])
with pytest.raises(SystemExit) as exit_info:
runpy.run_module("dep_freshness.install_main", run_name="__main__")
assert exit_info.value.code == 0

View File

@ -166,52 +166,3 @@ def test_a_repo_pinned_to_the_newest_installable_version_passes(
'{"dependencies": {"@testing-library/react": "16.3.2"}}')
monkeypatch.chdir(repo)
assert check.main(["--all"]) == 0
def test_the_answer_is_cached_so_a_second_run_makes_no_request(packument,
cache_dir):
"""A 7MB packument per npm finding, per run, inside a pre-commit hook is
exactly what the 6h cache exists to prevent."""
from dep_freshness.cache import Cache
store = Cache(cache_dir / "registry.json")
packument(PACKUMENT)
assert quarantine.installable_latest("x", "16.3.3", now=NOW,
cache=store) == "16.3.2"
packument(None) # any further fetch would now answer "no such package"
assert quarantine.installable_latest("x", "16.3.3", now=NOW,
cache=store) == "16.3.2"
def test_a_different_dist_tag_is_a_different_cache_entry(packument, cache_dir):
"""The ceiling is part of the key: clamping a cached answer to it would
return the ceiling, which is often the release being excluded."""
from dep_freshness.cache import Cache
store = Cache(cache_dir / "registry.json")
packument(PACKUMENT)
assert quarantine.installable_latest("x", "16.3.2", now=NOW,
cache=store) == "16.3.2"
assert store.get(quarantine.CACHE_ECOSYSTEM, "x@16.3.3") is None
def test_a_stale_cache_entry_is_served_when_the_registry_is_down(packument,
cache_dir):
from dep_freshness.cache import Cache
from dep_freshness.registries.http import Offline
store = Cache(cache_dir / "registry.json")
store.put(quarantine.CACHE_ECOSYSTEM, "x@16.3.3", "16.3.2")
store._data[f"{quarantine.CACHE_ECOSYSTEM}/x@16.3.3"]["fetched_at"] = 0.0
def down(*_a, **_k):
raise Offline("no network")
monkey = down
import dep_freshness.quarantine as q
original, q.get_json = q.get_json, monkey
try:
assert q.installable_latest("x", "16.3.3", cache=store) == "16.3.2"
finally:
q.get_json = original

View File

@ -1,11 +1,5 @@
# Dependencies deliberately held below latest stable, and why.
#
# THIS IS THE FLEET-WIDE FILE. Every repo inherits it; a repo's own
# dependency-freshness.allowlist.yaml adds to it, and an entry there for the
# same ecosystem:package overrides the one here. A blocker like "typescript-eslint
# does not support TS 7" holds in every repo that pins typescript, and copying
# it into eight of them would give eight entries that rot independently.
#
# Two entry classes, and the distinction is load-bearing:
#
# blocked_by: transitive:<pkg>@<ver>
@ -30,10 +24,6 @@ exceptions:
typescript-eslint 8.68.0 -- itself the latest release -- declares
`typescript: ">=4.8.4 <6.1.0"` and throws "typescript-eslint does not
support TS 7.0" when eslint loads its config. No 9.x exists. Taking TS 7
would mean dropping every type-aware lint rule from every repo that pins
it, so the compiler waits for the linter.
Held fleet-wide: this blocks ts_core, web_ui, konbini-67, iron-and-anvil,
awesome-mcp-explorer, europe-county-map and every other repo pinning
typescript, which is exactly why the entry lives here and not in eight
separate files.
would mean dropping every type-aware lint rule from ts_core and web_ui
until upstream catches up, so the compiler waits for the linter.
blocked_by: "transitive:typescript-eslint@8.68.0"

View File

@ -5,7 +5,7 @@ description: >-
helpers that were each reimplemented in three or more repos. Owns the tokens
-- consumers import them rather than transcribing the token table by hand.
publish_to: 'none'
version: 0.2.1
version: 0.2.0
environment:
sdk: ^3.12.2

View File

@ -1,85 +0,0 @@
#!/bin/bash
# ============================================================================
# Install the dependency-freshness gate's three pieces into a repo.
#
# The gate is a delegate script + a pre-commit hook entry + a CI workflow, and
# every repo needs all three. Copying them by hand across ~16 repos is what
# produced four different ids for the 250-line cap, two of them independent
# reimplementations, so the copy lives here and the templates have one home
# (utils/dep_freshness/templates/).
#
# Idempotent: a second run reports "already current" and writes nothing.
#
# NOTE: never install the gate ahead of the upgrade. A repo that gets the gate
# while its dependencies are still stale is instantly and permanently red --
# gate and upgrade belong in the same commit.
#
# Usage:
# scripts/install_dependency_freshness_gate.sh <repo> [--check] [--fvm]
#
# Options:
# --check report what a run would write, change nothing
# --fvm also pin the Flutter SDK in <repo>/.fvmrc (Dart repos only)
#
# Exit: 0 installed or already current | 1 bad usage / missing repo
# ============================================================================
set -euo pipefail
readonly UTILS_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
readonly SCRIPT_NAME="$(basename "$0")"
REPO=""
CHECK=""
FVM=""
usage() {
echo "Usage: $SCRIPT_NAME <repo> [--check] [--fvm]"
echo " --check report what would be written, change nothing"
echo " --fvm also write <repo>/.fvmrc pinning the Flutter SDK"
exit 0
}
validate_requirements() {
if [[ -z "$REPO" ]]; then
echo "Error: a repository path is required" >&2
exit 1
fi
if [[ ! -d "$REPO" ]]; then
echo "Error: no such directory: $REPO" >&2
exit 1
fi
}
main() {
validate_requirements
PYTHONPATH="$UTILS_ROOT${PYTHONPATH:+:$PYTHONPATH}" \
python3 -m dep_freshness.install_main "$REPO" $CHECK $FVM
}
while [[ $# -gt 0 ]]; do
case $1 in
--check)
CHECK="--check"
shift
;;
--fvm)
FVM="--fvm"
shift
;;
-h|--help)
usage
;;
-*)
echo "Unknown option: $1" >&2
exit 1
;;
*)
REPO="$1"
shift
;;
esac
done
main

View File

@ -5,7 +5,7 @@ description: >-
injected closures -- no keystore or platform plugin access lives in this
package itself.
publish_to: 'none'
version: 0.4.1
version: 0.4.0
environment:
sdk: ^3.12.2
@ -14,7 +14,7 @@ dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.11.1
ref: crdt_sync_dart-v0.11.0
path: crdt_sync_dart
flutter:
sdk: flutter