Compare commits

...

2 Commits

Author SHA1 Message Date
2e1f3da6cf Point a pubspec finding at the dependency, not the config block of the same name
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
Every Flutter app here declares `flutter_launcher_icons` twice: as a dev
dependency, and as a TOP-LEVEL configuration block for the same tool. The line
lookup broke ties by indentation alone, so the top-level block won and the
gate told you to fix a line that carries no version at all -- lyricanki
reported `pubspec.yaml:64` while the caret being complained about is at 48.

The pubspec parser now says which top-level keys may hold a version, and a key
found outside them is only a fallback. `environment` is in that list on
purpose: without it the `sdk:` inside a `flutter: {sdk: flutter}` block would
outrank the SDK constraint it is meant to find.

Only the pubspec parser passes the hint. JSON and TOML indent their section
headers differently, so they keep the old behaviour unchanged.

310 tests, 100% branch coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 14:33:11 +02:00
49ce0b250c Put the hook in the last repo: local block, not at end of file
Most of these configs interleave local and remote hook repos -- diet-guard,
screen-locker and wake-alarm carry nine `- repo:` blocks each. Appending at
end of file lands the hook under whichever block happens to be last, and a
local hook definition handed to a remote repo fails with an error naming an
unknown id rather than the real problem. diet-guard's last block happens to be
`local`, so this would have worked by luck there and broken elsewhere.

A config with no local block now refuses rather than guessing.

308 tests, 100% branch coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CRykabMwPgDzFHcARoqpaK
2026-08-28 14:21:31 +02:00
5 changed files with 169 additions and 17 deletions

View File

@ -49,10 +49,32 @@ def _needs_hook(repo: Path) -> bool:
return f"id: {HOOK_ID}" not in target.read_text(encoding="utf-8") return f"id: {HOOK_ID}" not in target.read_text(encoding="utf-8")
def _write_hook(repo: Path) -> None: LOCAL_REPO = " - repo: local"
"""Append the hook block to the repo's `local` hooks list.
Appending rather than parsing-and-re-emitting is deliberate: every one of
def _local_block_end(lines: list[str]) -> int:
"""Index just past the LAST `- repo: local` block, or -1 if there is none.
Appending at end-of-file is wrong whenever a config interleaves local and
remote hook repos, which most of these do -- diet-guard, screen-locker and
wake-alarm each carry nine `- repo:` blocks. A block appended under
`- repo: https://github.com/...` would be handed to that remote repo's
hook definitions and fail with an unhelpful error about an unknown id.
"""
starts = [n for n, line in enumerate(lines) if line.rstrip() == LOCAL_REPO]
if not starts:
return -1
after = [
n for n in range(starts[-1] + 1, len(lines))
if lines[n].startswith(" - repo:")
]
return after[0] if after else len(lines)
def _write_hook(repo: Path) -> None:
"""Insert the hook into the repo's LAST `local` hooks list.
Inserting rather than parsing-and-re-emitting is deliberate: every one of
these configs carries comments explaining why a hook exists, and a YAML these configs carries comments explaining why a hook exists, and a YAML
round-trip through the standard library drops all of them. round-trip through the standard library drops all of them.
""" """
@ -60,8 +82,19 @@ def _write_hook(repo: Path) -> None:
body = target.read_text(encoding="utf-8") if target.is_file() else EMPTY_PRECOMMIT body = target.read_text(encoding="utf-8") if target.is_file() else EMPTY_PRECOMMIT
if not body.endswith("\n"): if not body.endswith("\n"):
body += "\n" body += "\n"
# `body` was just made to end in a newline, so the split always leaves a
# trailing empty element; dropping it keeps the join below symmetric.
lines = body.split("\n")[:-1]
cut = _local_block_end(lines)
if cut < 0:
raise ValueError(
f"{target} has no `{LOCAL_REPO}` block to add the hook to; "
"add one by hand, then re-run"
)
block = _template("precommit-hook.yaml").rstrip("\n").split("\n")
lines[cut:cut] = ["", *block]
target.parent.mkdir(parents=True, exist_ok=True) target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(f"{body}\n{_template('precommit-hook.yaml')}", encoding="utf-8") target.write_text("\n".join(lines) + "\n", encoding="utf-8")
def plan(repo: Path) -> list[str]: def plan(repo: Path) -> list[str]:

View File

@ -4,36 +4,52 @@
without a line makes the fix a search, so the key is located textually after without a line makes the fix a search, so the key is located textually after
the fact; a miss degrades to line 0 rather than failing. the fact; a miss degrades to line 0 rather than failing.
Ties are broken by *indentation*, not by order: a pubspec that declares Two tie-breaks, in order:
`path: ^1.9.1` as a dependency also has a nested `path:` inside a git block six
spaces in, and first-match would point the fix at the wrong line. 1. **Inside a declared section beats outside it.** A Flutter app declares
`flutter_launcher_icons` twice: once as a dev dependency and once as a
TOP-LEVEL configuration block for the same tool. Indentation alone points
the fix at the config block, which has no version on it at all.
2. **Then least indented.** A pubspec that declares `path: ^1.9.1` as a
dependency also has a nested `path:` inside a git block six spaces in, and
first-match would point the fix at the wrong line.
""" """
from __future__ import annotations from __future__ import annotations
from pathlib import Path
import re import re
from pathlib import Path
_KEY = re.compile(r'^(?P<indent>\s*)-?\s*["\']?(?P<key>[A-Za-z0-9_.@/-]+)["\']?\s*[:=]') _KEY = re.compile(r'^(?P<indent>\s*)-?\s*["\']?(?P<key>[A-Za-z0-9_.@/-]+)["\']?\s*[:=]')
def index(path: Path) -> dict[str, int]: def index(path: Path, sections: tuple[str, ...] = ()) -> dict[str, int]:
"""Map `key` -> the 1-based line where it appears least-indented.""" """Map `key` -> the 1-based line where it is most likely declared.
best: dict[str, tuple[int, int]] = {}
`sections` names the top-level keys that actually hold dependencies
(`dependencies`, `dev_dependencies`, ...). Anything found outside them is
kept only as a fallback, so a config block sharing a package's name never
wins over the declaration that carries the version.
"""
best: dict[str, tuple[int, int, int]] = {}
try: try:
text = path.read_text(encoding="utf-8", errors="replace") text = path.read_text(encoding="utf-8", errors="replace")
except OSError: except OSError:
return {} return {}
inside = not sections # with no sections declared, everything counts
for number, line in enumerate(text.splitlines(), start=1): for number, line in enumerate(text.splitlines(), start=1):
match = _KEY.match(line) match = _KEY.match(line)
if not match: if not match:
continue continue
key = match.group("key") key = match.group("key")
depth = len(match.group("indent").expandtabs(4)) depth = len(match.group("indent").expandtabs(4))
if key not in best or depth < best[key][0]: if depth == 0 and sections:
best[key] = (depth, number) inside = key in sections
return {key: number for key, (_, number) in best.items()} score = (0 if inside else 1, depth, number)
if key not in best or score < best[key]:
best[key] = score
return {key: number for key, (_, _, number) in best.items()}
def find(path: Path, name: str) -> int: def find(path: Path, name: str, sections: tuple[str, ...] = ()) -> int:
return index(path).get(name, 0) return index(path, sections).get(name, 0)

View File

@ -26,6 +26,14 @@ from dep_freshness.parsers._lines import index
from dep_freshness.versions import exact_pin from dep_freshness.versions import exact_pin
_SECTIONS = (("dependencies", False), ("dev_dependencies", True)) _SECTIONS = (("dependencies", False), ("dev_dependencies", True))
# Where a version may legitimately be declared. Everything else at top level is
# configuration -- and a Flutter app has a `flutter_launcher_icons:` config
# block sharing its name with the dev dependency, which without this hint wins
# the line lookup by being less indented and sends the fix to a line that
# carries no version at all.
_LINE_SECTIONS = (
"environment", "dependencies", "dev_dependencies", PUB_OVERRIDE_KEY,
)
def _load(path: Path) -> dict: def _load(path: Path) -> dict:
@ -61,7 +69,7 @@ def parse(path: Path) -> list[Dep]:
data = _load(path) data = _load(path)
if not data: if not data:
return [] return []
lines = index(path) lines = index(path, _LINE_SECTIONS)
locks = locked_versions(path.with_name("pubspec.lock")) locks = locked_versions(path.with_name("pubspec.lock"))
deps: list[Dep] = [] deps: list[Dep] = []

View File

@ -180,3 +180,52 @@ def test_the_module_entrypoint_runs_the_cli(repo, monkeypatch):
with pytest.raises(SystemExit) as exit_info: with pytest.raises(SystemExit) as exit_info:
runpy.run_module("dep_freshness.install_main", run_name="__main__") runpy.run_module("dep_freshness.install_main", run_name="__main__")
assert exit_info.value.code == 0 assert exit_info.value.code == 0
def test_the_hook_lands_in_the_last_local_block_not_at_end_of_file(repo):
"""Most of these configs interleave local and remote hook repos.
diet-guard, screen-locker and wake-alarm carry nine `- repo:` blocks each,
and a hook appended under a remote one is handed to that repo's hook
definitions -- which fails with an error naming an unknown id rather than
the real problem.
"""
write(
repo,
".pre-commit-config.yaml",
"""\
repos:
- repo: local
hooks:
- id: file-length-cap
entry: bash scripts/check_file_length.sh
language: system
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.16.0
hooks:
- id: ruff
""",
)
installer.install(repo)
lines = (repo / ".pre-commit-config.yaml").read_text(encoding="utf-8").split("\n")
hook = lines.index(" - id: dependency-freshness")
remote = lines.index(" - repo: https://github.com/astral-sh/ruff-pre-commit")
assert hook < remote, "the hook must sit inside the local block"
assert lines[-2] == " - id: ruff", "the remote block keeps its own hooks"
def test_a_config_with_no_local_block_refuses_rather_than_guessing(repo):
write(
repo,
".pre-commit-config.yaml",
"""\
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.16.0
hooks:
- id: ruff
""",
)
with pytest.raises(ValueError, match="no ` - repo: local` block"):
installer.install(repo)

View File

@ -94,3 +94,49 @@ def test_line_index_of_an_unreadable_file_is_empty(tmp_path):
from dep_freshness.parsers._lines import find, index from dep_freshness.parsers._lines import find, index
assert index(tmp_path / "nope") == {} assert index(tmp_path / "nope") == {}
assert find(tmp_path / "nope", "x") == 0 assert find(tmp_path / "nope", "x") == 0
def test_a_config_block_never_wins_the_line_over_the_dependency(tmp_path):
"""Every Flutter app here declares `flutter_launcher_icons` twice.
Once as a dev dependency, and once as a TOP-LEVEL configuration block for
the same tool. Least-indented wins sends the fix to the config block --
lyricanki reported `pubspec.yaml:64`, the config key, while the version
being complained about lives at line 48.
"""
body = """\
name: demo
environment:
sdk: ^3.12.2
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_launcher_icons: ^0.14.4
flutter_launcher_icons:
android: true
image_path: "assets/icon/icon.png"
"""
deps = {
d.name: d
for d in pubspec.parse(write(tmp_path, "pubspec.yaml", body))
}
assert deps["flutter_launcher_icons"].line == 8
def test_the_sdk_line_is_the_environment_one_not_a_plugin_block(tmp_path):
"""`flutter: {sdk: flutter}` also declares an `sdk:` key, deeper in."""
body = """\
name: demo
environment:
sdk: ^3.12.2
dependencies:
flutter:
sdk: flutter
"""
deps = {
d.name: d
for d in pubspec.parse(write(tmp_path, "pubspec.yaml", body))
}
assert deps["dart"].line == 3