|
| 1 | +"""Topic enumeration and fuzzy search. |
| 2 | +
|
| 3 | +Scans a template directory once and caches the result, |
| 4 | +keyed on the directory path plus its mtime so the cache |
| 5 | +self-invalidates when templates regenerate. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import difflib |
| 11 | +import logging |
| 12 | +import threading |
| 13 | +from pathlib import Path |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | +_TYPE_DIRS = ( |
| 18 | + "concepts", |
| 19 | + "tasks", |
| 20 | + "references", |
| 21 | + "quickstarts", |
| 22 | + "comparisons", |
| 23 | + "tips", |
| 24 | + "troubleshooting", |
| 25 | + "warnings", |
| 26 | + "errors", |
| 27 | + "faqs", |
| 28 | + "notes", |
| 29 | +) |
| 30 | + |
| 31 | +_INDEX_CACHE: dict[tuple[str, float], dict[str, list[str]]] = {} |
| 32 | +_INDEX_LOCK = threading.Lock() |
| 33 | + |
| 34 | + |
| 35 | +def invalidate_index_cache() -> None: |
| 36 | + """Clear the topic index cache.""" |
| 37 | + with _INDEX_LOCK: |
| 38 | + _INDEX_CACHE.clear() |
| 39 | + |
| 40 | + |
| 41 | +def build_index(generated_dir: Path) -> dict[str, list[str]]: |
| 42 | + """Return ``{type: [slug, ...]}`` for a template tree. |
| 43 | +
|
| 44 | + Cached keyed on the directory path and its current |
| 45 | + mtime — touching the directory invalidates the cache |
| 46 | + automatically. |
| 47 | +
|
| 48 | + Args: |
| 49 | + generated_dir: Path to the template directory. |
| 50 | +
|
| 51 | + Returns: |
| 52 | + Dict mapping type name (``concepts``, ``tasks``, |
| 53 | + …) to a sorted list of slugs (filename stems). |
| 54 | + """ |
| 55 | + gen = Path(generated_dir) |
| 56 | + try: |
| 57 | + mtime = gen.stat().st_mtime |
| 58 | + except OSError: |
| 59 | + return {} |
| 60 | + |
| 61 | + cache_key = (str(gen.resolve()), mtime) |
| 62 | + with _INDEX_LOCK: |
| 63 | + hit = _INDEX_CACHE.get(cache_key) |
| 64 | + if hit is not None: |
| 65 | + return hit |
| 66 | + |
| 67 | + index: dict[str, list[str]] = {} |
| 68 | + for type_name in _TYPE_DIRS: |
| 69 | + subdir = gen / type_name |
| 70 | + if not subdir.is_dir(): |
| 71 | + continue |
| 72 | + slugs = sorted(p.stem for p in subdir.glob("*.md") if p.is_file()) |
| 73 | + if slugs: |
| 74 | + index[type_name] = slugs |
| 75 | + |
| 76 | + _INDEX_CACHE[cache_key] = index |
| 77 | + return index |
| 78 | + |
| 79 | + |
| 80 | +def list_topics( |
| 81 | + generated_dir: Path, |
| 82 | + type: str | None = None, |
| 83 | + limit: int | None = None, |
| 84 | +) -> list[str]: |
| 85 | + """Enumerate topic slugs. |
| 86 | +
|
| 87 | + Args: |
| 88 | + generated_dir: Template directory. |
| 89 | + type: Optional type filter (e.g. ``"concepts"``). |
| 90 | + ``None`` returns all types flattened. |
| 91 | + limit: Optional cap on returned items. |
| 92 | +
|
| 93 | + Returns: |
| 94 | + Sorted list of slugs. |
| 95 | + """ |
| 96 | + index = build_index(generated_dir) |
| 97 | + if type is not None: |
| 98 | + result = list(index.get(type, [])) |
| 99 | + else: |
| 100 | + result = sorted({s for slugs in index.values() for s in slugs}) |
| 101 | + if limit is not None: |
| 102 | + result = result[:limit] |
| 103 | + return result |
| 104 | + |
| 105 | + |
| 106 | +def search( |
| 107 | + generated_dir: Path, |
| 108 | + query: str, |
| 109 | + limit: int = 10, |
| 110 | +) -> list[tuple[str, float]]: |
| 111 | + """Fuzzy-search topic slugs. |
| 112 | +
|
| 113 | + Uses ``difflib.SequenceMatcher`` against slug strings, |
| 114 | + plus a substring bonus so exact substrings outrank |
| 115 | + pure fuzzy matches. |
| 116 | +
|
| 117 | + Args: |
| 118 | + generated_dir: Template directory. |
| 119 | + query: Search text. |
| 120 | + limit: Maximum results to return. |
| 121 | +
|
| 122 | + Returns: |
| 123 | + List of ``(slug, score)`` tuples, best first. |
| 124 | + Scores range (0, 2]; 1.0 means perfect fuzzy |
| 125 | + match, values > 1 indicate substring hits. |
| 126 | + """ |
| 127 | + if not query: |
| 128 | + return [] |
| 129 | + |
| 130 | + query_l = query.lower().strip() |
| 131 | + slugs: set[str] = set() |
| 132 | + for bucket in build_index(generated_dir).values(): |
| 133 | + slugs.update(bucket) |
| 134 | + |
| 135 | + scored: list[tuple[str, float]] = [] |
| 136 | + for slug in slugs: |
| 137 | + ratio = difflib.SequenceMatcher(None, query_l, slug).ratio() |
| 138 | + if query_l in slug: |
| 139 | + ratio += 1.0 |
| 140 | + if ratio >= 0.4: |
| 141 | + scored.append((slug, ratio)) |
| 142 | + |
| 143 | + scored.sort(key=lambda x: (-x[1], x[0])) |
| 144 | + return scored[:limit] |
| 145 | + |
| 146 | + |
| 147 | +def suggest( |
| 148 | + generated_dir: Path, |
| 149 | + topic: str, |
| 150 | + limit: int = 5, |
| 151 | +) -> list[str]: |
| 152 | + """Return fuzzy-match slugs for a missing topic. |
| 153 | +
|
| 154 | + Thin wrapper around :func:`search` that drops scores. |
| 155 | +
|
| 156 | + Args: |
| 157 | + generated_dir: Template directory. |
| 158 | + topic: The (likely misspelled) topic the caller |
| 159 | + looked up. |
| 160 | + limit: Maximum suggestions. |
| 161 | +
|
| 162 | + Returns: |
| 163 | + List of slugs ranked by similarity. |
| 164 | + """ |
| 165 | + return [slug for slug, _ in search(generated_dir, topic, limit=limit)] |
0 commit comments