|
| 1 | +"""Shared source-file walking: pattern + .gitignore matching, reused by the |
| 2 | +indexer, the daemon's doctor file-walk, and ``ccc grep``. |
| 3 | +
|
| 4 | +The matcher (include/exclude globs + nested ``.gitignore`` awareness) is the |
| 5 | +single source of truth for "which files count as part of the project". The |
| 6 | +indexer feeds it to CocoIndex's incremental file source; the daemon and ``ccc |
| 7 | +grep`` drive a plain :func:`os.walk` over it via :func:`iter_included_files`. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import os |
| 13 | +from collections.abc import Iterable, Iterator |
| 14 | +from pathlib import Path, PurePath |
| 15 | + |
| 16 | +from cocoindex.resources.file import FilePathMatcher, PatternFilePathMatcher |
| 17 | +from pathspec import GitIgnoreSpec |
| 18 | + |
| 19 | +from .settings import load_gitignore_spec |
| 20 | + |
| 21 | + |
| 22 | +def _normalize_gitignore_lines(lines: Iterable[str], directory: PurePath) -> list[str]: |
| 23 | + """Normalize .gitignore lines to root-relative gitignore patterns.""" |
| 24 | + if directory in (PurePath("."), PurePath("")): |
| 25 | + prefix = "" |
| 26 | + else: |
| 27 | + prefix = f"{directory.as_posix().rstrip('/')}/" |
| 28 | + |
| 29 | + normalized: list[str] = [] |
| 30 | + for raw_line in lines: |
| 31 | + line = raw_line.rstrip("\n\r") |
| 32 | + if not line: |
| 33 | + continue |
| 34 | + stripped = line.lstrip() |
| 35 | + if not stripped or stripped.startswith("#"): |
| 36 | + continue |
| 37 | + if line.startswith("\\#") or line.startswith("\\!"): |
| 38 | + line = line[1:] |
| 39 | + negated = line.startswith("!") |
| 40 | + if negated: |
| 41 | + line = line[1:] |
| 42 | + body = line.strip() |
| 43 | + if not body: |
| 44 | + continue |
| 45 | + anchor = body.startswith("/") |
| 46 | + if anchor: |
| 47 | + body = body.lstrip("/") |
| 48 | + pattern = f"{prefix}{body}" if prefix else body |
| 49 | + else: |
| 50 | + contains_slash = "/" in body |
| 51 | + base = prefix |
| 52 | + if contains_slash: |
| 53 | + pattern = f"{base}{body}" |
| 54 | + else: |
| 55 | + if base: |
| 56 | + pattern = f"{base}**/{body}" |
| 57 | + else: |
| 58 | + pattern = f"**/{body}" |
| 59 | + if negated: |
| 60 | + pattern = f"!{pattern}" |
| 61 | + normalized.append(pattern) |
| 62 | + return normalized |
| 63 | + |
| 64 | + |
| 65 | +class GitignoreAwareMatcher(FilePathMatcher): |
| 66 | + """Wraps another matcher and applies .gitignore filtering.""" |
| 67 | + |
| 68 | + def __init__( |
| 69 | + self, |
| 70 | + delegate: FilePathMatcher, |
| 71 | + root_spec: GitIgnoreSpec | None, |
| 72 | + project_root: Path, |
| 73 | + ) -> None: |
| 74 | + self._delegate = delegate |
| 75 | + self._root = project_root |
| 76 | + self._spec_cache: dict[PurePath, GitIgnoreSpec | None] = {PurePath("."): root_spec} |
| 77 | + |
| 78 | + def _spec_for(self, directory: PurePath) -> GitIgnoreSpec | None: |
| 79 | + if directory in self._spec_cache: |
| 80 | + return self._spec_cache[directory] |
| 81 | + |
| 82 | + parent_dir = directory.parent if directory != PurePath(".") else PurePath(".") |
| 83 | + parent_spec = self._spec_for(parent_dir) |
| 84 | + spec = parent_spec |
| 85 | + |
| 86 | + gitignore_path = (self._root / directory) / ".gitignore" |
| 87 | + if gitignore_path.is_file(): |
| 88 | + try: |
| 89 | + lines = gitignore_path.read_text().splitlines() |
| 90 | + except (OSError, UnicodeDecodeError): |
| 91 | + lines = [] |
| 92 | + normalized = _normalize_gitignore_lines(lines, directory) |
| 93 | + if normalized: |
| 94 | + new_spec = GitIgnoreSpec.from_lines(normalized) |
| 95 | + spec = new_spec if spec is None else spec + new_spec |
| 96 | + |
| 97 | + self._spec_cache[directory] = spec |
| 98 | + return spec |
| 99 | + |
| 100 | + def _is_ignored(self, path: PurePath, is_dir: bool) -> bool: |
| 101 | + directory = path if is_dir else path.parent |
| 102 | + if directory == PurePath(""): |
| 103 | + directory = PurePath(".") |
| 104 | + spec = self._spec_for(directory) |
| 105 | + if spec is None: |
| 106 | + return False |
| 107 | + match_path = path.as_posix() |
| 108 | + if is_dir and not match_path.endswith("/"): |
| 109 | + match_path = f"{match_path}/" |
| 110 | + return spec.match_file(match_path) |
| 111 | + |
| 112 | + def is_dir_included(self, path: PurePath) -> bool: |
| 113 | + if self._is_ignored(path, True): |
| 114 | + return False |
| 115 | + return self._delegate.is_dir_included(path) |
| 116 | + |
| 117 | + def is_file_included(self, path: PurePath) -> bool: |
| 118 | + if self._is_ignored(path, False): |
| 119 | + return False |
| 120 | + return self._delegate.is_file_included(path) |
| 121 | + |
| 122 | + |
| 123 | +def find_git_root(start: Path) -> Path | None: |
| 124 | + """Walk up from ``start`` to the nearest directory holding a ``.git`` entry — a |
| 125 | + directory for a normal repo, or a *file* for a submodule or linked worktree. |
| 126 | + Returns that directory, or ``None`` if ``start`` is not inside a git repo. |
| 127 | +
|
| 128 | + Used to anchor ``.gitignore`` resolution at the real repo root when grepping a |
| 129 | + subdirectory that isn't inside an initialized cocoindex project.""" |
| 130 | + current = start.resolve() |
| 131 | + while True: |
| 132 | + if (current / ".git").exists(): |
| 133 | + return current |
| 134 | + if current.parent == current: |
| 135 | + return None |
| 136 | + current = current.parent |
| 137 | + |
| 138 | + |
| 139 | +def build_matcher( |
| 140 | + project_root: Path, |
| 141 | + included_patterns: list[str], |
| 142 | + excluded_patterns: list[str], |
| 143 | +) -> FilePathMatcher: |
| 144 | + """Build the project's file matcher: include/exclude globs plus nested |
| 145 | + ``.gitignore`` awareness anchored at ``project_root``.""" |
| 146 | + base_matcher = PatternFilePathMatcher( |
| 147 | + included_patterns=included_patterns, |
| 148 | + excluded_patterns=excluded_patterns, |
| 149 | + ) |
| 150 | + return GitignoreAwareMatcher(base_matcher, load_gitignore_spec(project_root), project_root) |
| 151 | + |
| 152 | + |
| 153 | +def iter_included_files( |
| 154 | + start: Path, |
| 155 | + base: Path, |
| 156 | + matcher: FilePathMatcher, |
| 157 | +) -> Iterator[tuple[Path, PurePath]]: |
| 158 | + """Walk ``start`` recursively, yielding ``(absolute_path, path_relative_to_base)`` |
| 159 | + for every file ``matcher`` includes, pruning excluded directories. |
| 160 | +
|
| 161 | + ``base`` anchors the relative paths the matcher sees (the project root, so |
| 162 | + its patterns line up); ``start`` is where traversal begins and may be a |
| 163 | + subdirectory of ``base``. Both must be absolute. Traversal is deterministic |
| 164 | + (directories and files are visited in sorted order). |
| 165 | + """ |
| 166 | + for dirpath_str, dirnames, filenames in os.walk(start): |
| 167 | + dirpath = Path(dirpath_str) |
| 168 | + rel_dir = PurePath(dirpath.relative_to(base)) |
| 169 | + if rel_dir != PurePath(".") and not matcher.is_dir_included(rel_dir): |
| 170 | + dirnames.clear() |
| 171 | + continue |
| 172 | + dirnames.sort() |
| 173 | + for fname in sorted(filenames): |
| 174 | + rel_path = rel_dir / fname if rel_dir != PurePath(".") else PurePath(fname) |
| 175 | + if matcher.is_file_included(rel_path): |
| 176 | + yield dirpath / fname, rel_path |
0 commit comments