A tiny, local-first CLI that finds the files your AI coding agent actually needs — and packs them into a focused context.
| 1 | """Ignore rules: built-in defaults plus optional .gitignore support.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import fnmatch |
| 6 | import re |
| 7 | from dataclasses import dataclass, field |
| 8 | from pathlib import Path, PurePosixPath |
| 9 | |
| 10 | |
| 11 | # Directories / patterns that are almost never useful agent context. |
| 12 | BUILTIN_IGNORE_PATTERNS: tuple[str, ...] = ( |
| 13 | ".git/", |
| 14 | ".hg/", |
| 15 | ".svn/", |
| 16 | ".bzr/", |
| 17 | "node_modules/", |
| 18 | ".next/", |
| 19 | ".nuxt/", |
| 20 | ".output/", |
| 21 | "dist/", |
| 22 | "build/", |
| 23 | "out/", |
| 24 | "coverage/", |
| 25 | ".cache/", |
| 26 | ".parcel-cache/", |
| 27 | ".turbo/", |
| 28 | ".vercel/", |
| 29 | ".svelte-kit/", |
| 30 | "venv/", |
| 31 | ".venv/", |
| 32 | "ENV/", |
| 33 | "env/", |
| 34 | "__pycache__/", |
| 35 | ".pytest_cache/", |
| 36 | ".mypy_cache/", |
| 37 | ".ruff_cache/", |
| 38 | ".tox/", |
| 39 | "htmlcov/", |
| 40 | "target/", |
| 41 | "vendor/", |
| 42 | "Pods/", |
| 43 | ".gradle/", |
| 44 | ".idea/", |
| 45 | ".vscode/", |
| 46 | "*.min.js", |
| 47 | "*.min.css", |
| 48 | "*.map", |
| 49 | "*.pyc", |
| 50 | "*.pyo", |
| 51 | "*.class", |
| 52 | "*.o", |
| 53 | "*.a", |
| 54 | "*.lib", |
| 55 | "*.dylib", |
| 56 | "*.so", |
| 57 | "*.dll", |
| 58 | "*.exe", |
| 59 | "package-lock.json", |
| 60 | "yarn.lock", |
| 61 | "pnpm-lock.yaml", |
| 62 | "Cargo.lock", |
| 63 | "poetry.lock", |
| 64 | "Pipfile.lock", |
| 65 | "composer.lock", |
| 66 | "Gemfile.lock", |
| 67 | "bun.lockb", |
| 68 | ) |
| 69 | |
| 70 | |
| 71 | @dataclass |
| 72 | class IgnoreRule: |
| 73 | """A single ignore (or negation) rule.""" |
| 74 | |
| 75 | pattern: str |
| 76 | negated: bool = False |
| 77 | directory_only: bool = False |
| 78 | anchored: bool = False |
| 79 | |
| 80 | |
| 81 | @dataclass |
| 82 | class IgnoreMatcher: |
| 83 | """Match relative paths against built-in, gitignore, and custom rules.""" |
| 84 | |
| 85 | rules: list[IgnoreRule] = field(default_factory=list) |
| 86 | include_globs: list[str] = field(default_factory=list) |
| 87 | exclude_globs: list[str] = field(default_factory=list) |
| 88 | |
| 89 | @classmethod |
| 90 | def create( |
| 91 | cls, |
| 92 | root: Path, |
| 93 | *, |
| 94 | include: list[str] | None = None, |
| 95 | exclude: list[str] | None = None, |
| 96 | use_gitignore: bool = True, |
| 97 | use_builtins: bool = True, |
| 98 | ) -> IgnoreMatcher: |
| 99 | matcher = cls( |
| 100 | include_globs=list(include or []), |
| 101 | exclude_globs=list(exclude or []), |
| 102 | ) |
| 103 | if use_builtins: |
| 104 | for pattern in BUILTIN_IGNORE_PATTERNS: |
| 105 | matcher.rules.append(_parse_pattern(pattern)) |
| 106 | if use_gitignore: |
| 107 | gitignore = root / ".gitignore" |
| 108 | if gitignore.is_file(): |
| 109 | matcher._load_gitignore(gitignore) |
| 110 | return matcher |
| 111 | |
| 112 | def _load_gitignore(self, path: Path) -> None: |
| 113 | try: |
| 114 | text = path.read_text(encoding="utf-8", errors="replace") |
| 115 | except OSError: |
| 116 | return |
| 117 | for raw in text.splitlines(): |
| 118 | line = raw.strip() |
| 119 | if not line or line.startswith("#"): |
| 120 | continue |
| 121 | self.rules.append(_parse_pattern(line)) |
| 122 | |
| 123 | def is_ignored(self, rel_path: str, *, is_dir: bool = False) -> bool: |
| 124 | """Return True if the relative path should be excluded. |
| 125 | |
| 126 | ``rel_path`` must use forward slashes and must not start with ``./``. |
| 127 | """ |
| 128 | rel = rel_path.replace("\\", "/").lstrip("./") |
| 129 | if not rel: |
| 130 | return False |
| 131 | |
| 132 | for glob in self.exclude_globs: |
| 133 | if _path_matches_glob(rel, glob, is_dir=is_dir): |
| 134 | return True |
| 135 | |
| 136 | if self.include_globs and not _include_allows(rel, self.include_globs, is_dir=is_dir): |
| 137 | return True |
| 138 | |
| 139 | ignored = False |
| 140 | for rule in self.rules: |
| 141 | if _rule_applies(rel, rule, is_dir=is_dir): |
| 142 | ignored = not rule.negated |
| 143 | return ignored |
| 144 | |
| 145 | def should_skip_dir(self, rel_path: str) -> bool: |
| 146 | """Early-out for directory walking.""" |
| 147 | return self.is_ignored(rel_path, is_dir=True) |
| 148 | |
| 149 | |
| 150 | def _include_allows(rel: str, include_globs: list[str], *, is_dir: bool) -> bool: |
| 151 | if any(_path_matches_glob(rel, g, is_dir=is_dir) for g in include_globs): |
| 152 | return True |
| 153 | if not is_dir: |
| 154 | return False |
| 155 | # Allow walking ancestors of include globs. |
| 156 | prefix = rel.rstrip("/") + "/" |
| 157 | for g in include_globs: |
| 158 | g_norm = g.replace("\\", "/").lstrip("./") |
| 159 | if "**" in g_norm: |
| 160 | return True |
| 161 | base = g_norm.rstrip("*").rstrip("/") |
| 162 | if g_norm.startswith(prefix) or prefix.startswith(base + "/") or prefix == base + "/": |
| 163 | return True |
| 164 | return False |
| 165 | |
| 166 | |
| 167 | def _rule_applies(rel: str, rule: IgnoreRule, *, is_dir: bool) -> bool: |
| 168 | if _matches_rule(rel, rule, is_dir=is_dir): |
| 169 | return True |
| 170 | # Directory patterns also ignore everything underneath. |
| 171 | parts = PurePosixPath(rel).parts |
| 172 | for i in range(len(parts)): |
| 173 | parent = "/".join(parts[: i + 1]) |
| 174 | if _matches_rule(parent, rule, is_dir=True): |
| 175 | return True |
| 176 | return False |
| 177 | |
| 178 | |
| 179 | def _parse_pattern(raw: str) -> IgnoreRule: |
| 180 | pattern = raw.strip() |
| 181 | negated = False |
| 182 | if pattern.startswith("!"): |
| 183 | negated = True |
| 184 | pattern = pattern[1:] |
| 185 | |
| 186 | directory_only = pattern.endswith("/") |
| 187 | if directory_only: |
| 188 | pattern = pattern.rstrip("/") |
| 189 | |
| 190 | anchored = pattern.startswith("/") |
| 191 | if anchored: |
| 192 | pattern = pattern[1:] |
| 193 | |
| 194 | return IgnoreRule( |
| 195 | pattern=pattern, |
| 196 | negated=negated, |
| 197 | directory_only=directory_only, |
| 198 | anchored=anchored, |
| 199 | ) |
| 200 | |
| 201 | |
| 202 | def _matches_rule(rel: str, rule: IgnoreRule, *, is_dir: bool) -> bool: |
| 203 | pattern = rule.pattern |
| 204 | if not pattern: |
| 205 | return False |
| 206 | |
| 207 | # Anchored: match from repo root. |
| 208 | if rule.anchored: |
| 209 | return _fnmatch_path(rel, pattern) or ( |
| 210 | is_dir and _fnmatch_path(rel.rstrip("/") + "/", pattern + "/") |
| 211 | ) |
| 212 | |
| 213 | # Unanchored: match against basename or any path suffix. |
| 214 | name = PurePosixPath(rel).name |
| 215 | if _fnmatch_path(name, pattern): |
| 216 | return True |
| 217 | if _fnmatch_path(rel, pattern): |
| 218 | return True |
| 219 | # Match `**/pattern` semantics for unanchored globs. |
| 220 | if "/" not in pattern and fnmatch.fnmatch(name, pattern): |
| 221 | return True |
| 222 | parts = PurePosixPath(rel).parts |
| 223 | for i in range(len(parts)): |
| 224 | suffix = "/".join(parts[i:]) |
| 225 | if _fnmatch_path(suffix, pattern): |
| 226 | return True |
| 227 | return False |
| 228 | |
| 229 | |
| 230 | def _fnmatch_path(path: str, pattern: str) -> bool: |
| 231 | """fnmatch with limited ``**`` support.""" |
| 232 | path = path.replace("\\", "/") |
| 233 | pattern = pattern.replace("\\", "/") |
| 234 | if "**" not in pattern: |
| 235 | return fnmatch.fnmatch(path, pattern) |
| 236 | |
| 237 | # Convert ** glob to regex. |
| 238 | regex_parts: list[str] = [] |
| 239 | i = 0 |
| 240 | while i < len(pattern): |
| 241 | if pattern.startswith("**/", i): |
| 242 | regex_parts.append("(?:.*/)?") |
| 243 | i += 3 |
| 244 | elif pattern.startswith("**", i): |
| 245 | regex_parts.append(".*") |
| 246 | i += 2 |
| 247 | else: |
| 248 | ch = pattern[i] |
| 249 | if ch == "*": |
| 250 | regex_parts.append("[^/]*") |
| 251 | elif ch == "?": |
| 252 | regex_parts.append("[^/]") |
| 253 | else: |
| 254 | regex_parts.append(re.escape(ch)) |
| 255 | i += 1 |
| 256 | try: |
| 257 | return re.fullmatch("".join(regex_parts), path) is not None |
| 258 | except re.error: |
| 259 | return fnmatch.fnmatch(path, pattern) |
| 260 | |
| 261 | |
| 262 | def _path_matches_glob(rel: str, glob: str, *, is_dir: bool = False) -> bool: |
| 263 | g = glob.replace("\\", "/").lstrip("./") |
| 264 | if g.endswith("/"): |
| 265 | g = g.rstrip("/") |
| 266 | if is_dir and (_fnmatch_path(rel, g) or rel.startswith(g + "/")): |
| 267 | return True |
| 268 | return rel == g or rel.startswith(g + "/") |
| 269 | if _fnmatch_path(rel, g): |
| 270 | return True |
| 271 | # Prefix directory match for patterns like src/** |
| 272 | if g.endswith("/**"): |
| 273 | prefix = g[:-3].rstrip("/") |
| 274 | if not prefix: |
| 275 | return True |
| 276 | return rel == prefix or rel.startswith(prefix + "/") |
| 277 | return False |