Compare commits

..

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

5 changed files with 16 additions and 168 deletions

View File

@ -49,32 +49,10 @@ def _needs_hook(repo: Path) -> bool:
return f"id: {HOOK_ID}" not in target.read_text(encoding="utf-8")
LOCAL_REPO = " - repo: local"
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.
"""Append the hook block to the repo's `local` hooks list.
Inserting rather than parsing-and-re-emitting is deliberate: every one of
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.
"""
@ -82,19 +60,8 @@ def _write_hook(repo: Path) -> None:
body = target.read_text(encoding="utf-8") if target.is_file() else EMPTY_PRECOMMIT
if not body.endswith("\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.write_text("\n".join(lines) + "\n", encoding="utf-8")
target.write_text(f"{body}\n{_template('precommit-hook.yaml')}", encoding="utf-8")
def plan(repo: Path) -> list[str]:

View File

@ -4,52 +4,36 @@
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.
Two tie-breaks, in order:
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.
Ties are broken by *indentation*, not by order: 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
import re
from pathlib import Path
import re
_KEY = re.compile(r'^(?P<indent>\s*)-?\s*["\']?(?P<key>[A-Za-z0-9_.@/-]+)["\']?\s*[:=]')
def index(path: Path, sections: tuple[str, ...] = ()) -> dict[str, int]:
"""Map `key` -> the 1-based line where it is most likely declared.
`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]] = {}
def index(path: Path) -> dict[str, int]:
"""Map `key` -> the 1-based line where it appears least-indented."""
best: dict[str, tuple[int, int]] = {}
try:
text = path.read_text(encoding="utf-8", errors="replace")
except OSError:
return {}
inside = not sections # with no sections declared, everything counts
for number, line in enumerate(text.splitlines(), start=1):
match = _KEY.match(line)
if not match:
continue
key = match.group("key")
depth = len(match.group("indent").expandtabs(4))
if depth == 0 and sections:
inside = key in sections
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()}
if key not in best or depth < best[key][0]:
best[key] = (depth, number)
return {key: number for key, (_, number) in best.items()}
def find(path: Path, name: str, sections: tuple[str, ...] = ()) -> int:
return index(path, sections).get(name, 0)
def find(path: Path, name: str) -> int:
return index(path).get(name, 0)

View File

@ -26,14 +26,6 @@ from dep_freshness.parsers._lines import index
from dep_freshness.versions import exact_pin
_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:
@ -69,7 +61,7 @@ def parse(path: Path) -> list[Dep]:
data = _load(path)
if not data:
return []
lines = index(path, _LINE_SECTIONS)
lines = index(path)
locks = locked_versions(path.with_name("pubspec.lock"))
deps: list[Dep] = []

View File

@ -180,52 +180,3 @@ def test_the_module_entrypoint_runs_the_cli(repo, monkeypatch):
with pytest.raises(SystemExit) as exit_info:
runpy.run_module("dep_freshness.install_main", run_name="__main__")
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,49 +94,3 @@ def test_line_index_of_an_unreadable_file_is_empty(tmp_path):
from dep_freshness.parsers._lines import find, index
assert index(tmp_path / "nope") == {}
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