Files
computer-playbook/utils/cache/gitignore.py
T
kevinveenbirkenbachandClaude Opus 4.7 16e292e805 chore(ruff): enable RUF/SIM/C4/PERF/RET/PIE rule families — 364 → 0
Extends ``[tool.ruff.lint].select`` with six additional rule families:
``RUF`` (ruff-specific), ``SIM`` (flake8-simplify), ``C4``
(flake8-comprehensions), ``PERF`` (perflint), ``RET`` (flake8-return),
``PIE`` (flake8-pie). Adds ``RUF001/002/003`` to ``ignore`` because
those exist for homoglyph-attack detection, not English typography —
the project uses em/en-dashes and ``ℹ`` as a UI-hint glyph in CLI help
output deliberately.

Auto-fixed (~225, mechanical & behavior-preserving)
====================================================
- RUF005:  ``a + [b]``     → ``[*a, b]``
- C408:    ``dict(k=v)``   → ``{"k": v}``
- C420:    ``dict.fromkeys(seq)`` shape simplifications
- SIM103/SIM110/SIM118:    truthy-return / dict-key / dict-method
                           idiom simplifications
- RET504/RET505:           drop unneeded final assigns / ``else`` after
                           ``return``
- PIE810:                  combine ``str.startswith(a) or .startswith(b)``
                           into one call with a tuple
- RUF010:                  ``f"{str(x)}"`` → ``f"{x\!s}"``
- RUF100:                  removed unused ``# noqa`` directives that
                           became stale (mostly old ``# noqa: E402``
                           markers that ruff's smart E402 implementation
                           no longer flags after ``sys.path`` shims)
- RUF015 / RUF013 / RUF022 / RUF046 / RUF059: misc small wins
- I001:                    re-sorted import blocks where the new
                           imports above shifted them

Hand-fixed (~140, scripted where mechanical)
============================================
PERF401 (42): scripted AST rewrite of
  ``for x in iter: target.append(expr)`` (with optional ``if`` guard)
  →  ``target.extend(expr for x in iter [if cond])``.
  ``list.extend(genexp)`` consumes the generator immediately, so the
  rewrite is semantically equivalent to the original eager loop.

SIM117 (41): scripted AST combiner for nested ``with`` blocks where
  the inner is the only statement of the outer (38 sites). The remaining
  3 multi-line ``patch.object(...)`` chains were combined by hand using
  the parenthesised ``with (\\n A,\\n B,\\n):`` form.

SIM102 (14): scripted AST combiner for nested ``if`` (10 sites). The
  remaining 4 carry an inline ``# noqa: SIM102`` with rationale —
  combining would either change semantics (the outer body has siblings
  beyond the inner ``if``, e.g. ``cli/encrypt/inventory/__main__.py``
  where ``encrypted_value = …`` runs regardless of ``ask_confirmation``)
  or hurt readability (long literal whitelists).

RUF012 (9): annotated mutable class attributes with ``ClassVar[…]``
  and added ``from typing import ClassVar``.

SIM105 (6): ``try/except: pass`` → ``with contextlib.suppress(…):``
  with the necessary ``import contextlib`` added. Verified on
  ``utils/templating.py`` (3 occurrences in a ``finally`` block) —
  cleanup behaviour is identical.

SIM115 (4): wrapped ``tempfile.NamedTemporaryFile(..., delete=False)``
  call patterns in a ``with`` block; ``delete=False`` keeps the file
  on disk after the block, so callers' ``return f.name`` still works.

PERF402, PERF403, B007, SIM108, SIM103: 5 misc fixes (loop→list-copy,
  loop→dict-comprehension, unused-loop-var rename, ternary, return
  expression).

Verification
============
- ``ruff check .`` → All checks passed
- ``ruff format --check .`` → 894 files already formatted
- 1621 unit tests → all pass
- Integration suite: 44 baseline failures, 1 skipped (unchanged)
- Sample-audited PERF401 rewrites in ``resolver.py``, ``inventory.py``,
  ``cache/files.py``, ``ressources/__main__.py``; SIM117 in
  ``test_main.py``; SIM105 in ``utils/templating.py``; SIM102 noqa
  rationales in ``cli/encrypt/inventory/__main__.py``.

182 files changed, +993 / −960. With this and the prior strict-rule
commit the branch satisfies 11 ruff rule families end-to-end.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 17:23:32 +02:00

106 lines
3.9 KiB
Python

"""Gitignore-aware path matching for project-tree scans.
SPOT for the fnmatch-based ``.gitignore``-style filter used by lint and
integration tests that need to walk the repository without spawning
``git``. Covers the shapes the repo's ``.gitignore`` actually uses
(basename patterns, path-qualified patterns, trailing-slash-as-directory)
and intentionally omits negation (``!``) and ``**`` globstar — adding
either would require a real pathspec implementation.
Public API:
* :func:`load_gitignore_patterns` — read non-empty, non-comment,
non-negated lines from ``<root>/.gitignore``. Cached process-wide.
* :func:`is_path_gitignored` — pure matcher: does a repo-relative
POSIX-style path match any of the supplied patterns?
The combined "yield project files filtered through ``.gitignore``"
helper lives in :mod:`utils.cache.files` (``iter_non_ignored_files``)
because it composes the cached project walk with this matcher.
"""
from __future__ import annotations
import fnmatch
from collections.abc import Iterable
from functools import lru_cache
from pathlib import Path
from . import PROJECT_ROOT
@lru_cache(maxsize=4)
def load_gitignore_patterns(root: str | None = None) -> tuple[str, ...]:
"""Load non-comment, non-blank, non-negated patterns from ``<root>/.gitignore``.
Returns a tuple (immutable, hashable for ``lru_cache``). Pass ``root``
as a string so the cache key is plainly hashable; defaults to
:data:`PROJECT_ROOT` when omitted.
Negation (``!``) and ``**`` globstar are intentionally not supported —
the repo's ``.gitignore`` does not use them, and supporting either
would require a real pathspec implementation. If a future
``.gitignore`` adds them, extend this helper rather than duplicating
the logic in callers.
"""
base = Path(root) if root else PROJECT_ROOT
gitignore = base / ".gitignore"
if not gitignore.is_file():
return ()
patterns: list[str] = []
for raw in gitignore.read_text(encoding="utf-8").splitlines():
line = raw.strip()
if not line or line.startswith(("#", "!")):
continue
patterns.append(line)
return tuple(patterns)
def is_path_gitignored(rel_path: str, patterns: Iterable[str]) -> bool:
"""Return True iff ``rel_path`` (POSIX-style, repo-root-relative) is
matched by any of ``patterns``.
Supports the shapes the repo's ``.gitignore`` actually uses:
* Bare-basename patterns (no slash): match any path component via
``fnmatch``.
* Path-qualified patterns (with slash): match from the repo root via
``fnmatch``, plus ``prefix/*`` shorthand and bare-prefix directory
matching.
* Trailing ``/`` (directory-only): treated as the stripped pattern
because we only test against file paths.
Behaviour intentionally diverges from real git ``pathspec``: ``*``
here matches across ``/`` (``fnmatch`` semantics). If you need full
fidelity, use a dedicated pathspec library.
"""
parts = rel_path.split("/")
for raw in patterns:
pattern = raw.lstrip("/").rstrip("/")
if not pattern:
continue
if "/" in pattern:
if fnmatch.fnmatch(rel_path, pattern):
return True
if pattern.endswith("/*"):
prefix = pattern[:-2]
if rel_path.startswith(prefix + "/"):
return True
if rel_path.startswith(pattern + "/"):
return True
else:
for part in parts:
if fnmatch.fnmatch(part, pattern):
return True
return False
def _reset() -> None:
"""Test-only helper: clear the cached gitignore patterns.
Named ``_reset`` for parity with the per-domain reset helpers in
sibling modules; ``utils.cache._reset_cache_for_tests`` orchestrates
calls to all of them.
"""
load_gitignore_patterns.cache_clear()