139 lines
4.2 KiB
Python
139 lines
4.2 KiB
Python
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
|
|
from .document_tree import DocumentEntry
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class SearchMatch:
|
|
entry: DocumentEntry
|
|
snippet: str
|
|
match_count: int = 0
|
|
match_kind: str = "正文"
|
|
|
|
|
|
class SearchIndex:
|
|
def __init__(self, entries: list[DocumentEntry] | None = None) -> None:
|
|
self._records: list[tuple[DocumentEntry, str, str, str]] = []
|
|
if entries:
|
|
self.rebuild(entries)
|
|
|
|
def rebuild(self, entries: list[DocumentEntry]) -> None:
|
|
self._records = [(entry, entry.title, entry.relative_path, _read_text(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, title, relative_path, body in self._records:
|
|
if indexed_entry.path == entry.path:
|
|
haystack = self._haystack(title, relative_path, body)
|
|
return normalized in haystack.casefold()
|
|
return normalized in self._haystack(entry.title, entry.relative_path, _read_text(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, title, relative_path, body in self._records:
|
|
result = _match_details(title, relative_path, body, normalized)
|
|
if result is None:
|
|
continue
|
|
|
|
snippet, match_count, match_kind = result
|
|
matches.append(
|
|
SearchMatch(
|
|
entry=entry,
|
|
snippet=snippet,
|
|
match_count=match_count,
|
|
match_kind=match_kind,
|
|
)
|
|
)
|
|
if len(matches) >= limit:
|
|
break
|
|
return matches
|
|
|
|
def _haystack(self, title: str, relative_path: str, body: str) -> str:
|
|
return f"{title}\n{relative_path}\n{body}"
|
|
|
|
|
|
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)
|
|
result = _match_details(entry.title, entry.relative_path, text, normalized)
|
|
if result is None:
|
|
continue
|
|
|
|
snippet, match_count, match_kind = result
|
|
matches.append(
|
|
SearchMatch(
|
|
entry=entry,
|
|
snippet=snippet,
|
|
match_count=match_count,
|
|
match_kind=match_kind,
|
|
)
|
|
)
|
|
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
|
|
|
|
|
|
def _match_details(title: str, relative_path: str, body: str, normalized_query: str) -> tuple[str, int, str] | None:
|
|
fields = (
|
|
("标题", title),
|
|
("路径", relative_path),
|
|
("正文", body),
|
|
)
|
|
total = sum(_count_matches(text, normalized_query) for _, text in fields)
|
|
if total <= 0:
|
|
return None
|
|
|
|
for kind, text in fields:
|
|
index = text.casefold().find(normalized_query)
|
|
if index >= 0:
|
|
return _snippet(text, index, len(normalized_query)), total, kind
|
|
|
|
return None
|
|
|
|
|
|
def _count_matches(text: str, normalized_query: str) -> int:
|
|
if not normalized_query:
|
|
return 0
|
|
return text.casefold().count(normalized_query)
|