from __future__ import annotations from dataclasses import dataclass from .document_tree import DocumentEntry @dataclass(frozen=True) class SearchMatch: entry: DocumentEntry snippet: str class SearchIndex: def __init__(self, entries: list[DocumentEntry] | None = None) -> None: self._records: list[tuple[DocumentEntry, str]] = [] if entries: self.rebuild(entries) def rebuild(self, entries: list[DocumentEntry]) -> None: self._records = [(entry, self._haystack(entry)) for entry in entries] def matches_entry(self, entry: DocumentEntry, query: str) -> bool: normalized = query.strip().casefold() if not normalized: return True for indexed_entry, haystack in self._records: if indexed_entry.path == entry.path: return normalized in haystack.casefold() return normalized in self._haystack(entry).casefold() def search(self, query: str, limit: int = 80) -> list[SearchMatch]: normalized = query.strip().casefold() if not normalized: return [] matches: list[SearchMatch] = [] for entry, haystack in self._records: index = haystack.casefold().find(normalized) if index < 0: continue matches.append(SearchMatch(entry=entry, snippet=_snippet(haystack, index, len(normalized)))) if len(matches) >= limit: break return matches def _haystack(self, entry: DocumentEntry) -> str: return f"{entry.title}\n{entry.relative_path}\n{_read_text(entry)}" def matches_entry(entry: DocumentEntry, query: str) -> bool: normalized = query.strip().casefold() if not normalized: return True haystack = f"{entry.title}\n{entry.relative_path}\n{_read_text(entry)}".casefold() return normalized in haystack def search_entries(entries: list[DocumentEntry], query: str, limit: int = 80) -> list[SearchMatch]: normalized = query.strip().casefold() if not normalized: return [] matches: list[SearchMatch] = [] for entry in entries: text = _read_text(entry) haystack = f"{entry.title}\n{entry.relative_path}\n{text}" index = haystack.casefold().find(normalized) if index < 0: continue matches.append(SearchMatch(entry=entry, snippet=_snippet(haystack, index, len(normalized)))) if len(matches) >= limit: break return matches def _read_text(entry: DocumentEntry) -> str: try: return entry.path.read_text(encoding="utf-8") except OSError: return "" def _snippet(text: str, index: int, length: int) -> str: start = max(0, index - 42) end = min(len(text), index + length + 86) snippet = text[start:end].replace("\r", " ").replace("\n", " ") snippet = " ".join(snippet.split()) if start > 0: snippet = "..." + snippet if end < len(text): snippet += "..." return snippet