|
| 1 | +"""Search in the generated ACLib module catalog (``_codelib/catalog/catalog.json``). |
| 2 | +
|
| 3 | +The catalog is read from the local repository (path from the wizard configuration) or from |
| 4 | +GitHub raw. Only a fixed host and validated repository names are used. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import json |
| 10 | +import re |
| 11 | +import urllib.error |
| 12 | +import urllib.request |
| 13 | +from pathlib import Path |
| 14 | +from typing import Any |
| 15 | + |
| 16 | +CATALOG_RELATIVE_PATH = "_codelib/catalog/catalog.json" |
| 17 | +GITHUB_RAW_URL = ( |
| 18 | + "https://raw.githubusercontent.com/{owner}/{repo}/{branch}/" + CATALOG_RELATIVE_PATH |
| 19 | +) |
| 20 | +DEFAULT_GITHUB = {"owner": "AccessCodeLib", "repo": "AccessCodeLib", "branch": "master"} |
| 21 | +HTTP_TIMEOUT_SECONDS = 30 |
| 22 | +MAX_MEMBERS_SHOWN = 8 |
| 23 | +_NAME_WEIGHT = 5 |
| 24 | +_DESCRIPTION_WEIGHT = 3 |
| 25 | +_MEMBER_WEIGHT = 1 |
| 26 | + |
| 27 | + |
| 28 | +class CatalogError(Exception): |
| 29 | + """The catalog could not be loaded or parsed.""" |
| 30 | + |
| 31 | + |
| 32 | +def github_location(config: dict[str, Any], repo: str | None) -> dict[str, str]: |
| 33 | + """Return ``{owner, repo, branch}``: from ``repo`` ('owner/name[@branch]') or the config.""" |
| 34 | + if repo: |
| 35 | + name, _, branch = repo.partition("@") |
| 36 | + owner, _, repo_name = name.partition("/") |
| 37 | + return {"owner": owner, "repo": repo_name, "branch": branch or "master"} |
| 38 | + github = config.get("github") |
| 39 | + if isinstance(github, dict) and all(github.get(k) for k in ("owner", "repo", "branch")): |
| 40 | + return {k: str(github[k]) for k in ("owner", "repo", "branch")} |
| 41 | + return dict(DEFAULT_GITHUB) |
| 42 | + |
| 43 | + |
| 44 | +def catalog_origin(config: dict[str, Any], source: str, repo: str | None) -> str: |
| 45 | + """Return the local catalog file path or the GitHub raw URL for the effective source.""" |
| 46 | + local = str(config.get("localRepositoryPath") or "").strip() |
| 47 | + use_local = not repo and (source == "local" or (source == "config" and local)) |
| 48 | + if use_local: |
| 49 | + if not local: |
| 50 | + raise CatalogError("No local repository configured in the ACLib Import Wizard.") |
| 51 | + return str(Path(local) / CATALOG_RELATIVE_PATH) |
| 52 | + location = github_location(config, repo) |
| 53 | + return GITHUB_RAW_URL.format(**location) |
| 54 | + |
| 55 | + |
| 56 | +def load_catalog(origin: str) -> dict[str, Any]: |
| 57 | + """Load and parse the catalog from a file path or an https URL.""" |
| 58 | + try: |
| 59 | + if origin.startswith("https://raw.githubusercontent.com/"): |
| 60 | + with urllib.request.urlopen(origin, timeout=HTTP_TIMEOUT_SECONDS) as response: # noqa: S310 |
| 61 | + raw = response.read() |
| 62 | + else: |
| 63 | + raw = Path(origin).read_bytes() |
| 64 | + data = json.loads(raw.decode("utf-8-sig")) |
| 65 | + except urllib.error.HTTPError as exc: |
| 66 | + raise CatalogError(f"Catalog not found ({exc.code}): {origin}") from None |
| 67 | + except (OSError, urllib.error.URLError, ValueError) as exc: |
| 68 | + raise CatalogError(f"Catalog could not be read ({exc}): {origin}") from None |
| 69 | + if not isinstance(data, dict) or not isinstance(data.get("modules"), list): |
| 70 | + raise CatalogError(f"Catalog has an unexpected format: {origin}") |
| 71 | + return data |
| 72 | + |
| 73 | + |
| 74 | +def _terms(query: str) -> list[str]: |
| 75 | + seen: dict[str, None] = {} |
| 76 | + for term in re.split(r"[\s,;]+", query.lower().strip()): |
| 77 | + if term: |
| 78 | + seen[term] = None |
| 79 | + return list(seen) |
| 80 | + |
| 81 | + |
| 82 | +def _hit(term: str, text: str) -> bool: |
| 83 | + """True if ``term`` starts a word in ``text`` (so 'filter' finds 'filters', not 'prefilter').""" |
| 84 | + return re.search(r"(?<![a-z0-9])" + re.escape(term), text) is not None |
| 85 | + |
| 86 | + |
| 87 | +def _score(module: dict[str, Any], terms: list[str]) -> tuple[int, int] | None: |
| 88 | + """Return ``(matched terms, weighted score)`` if at least one term matches, else ``None``.""" |
| 89 | + name = f"{module.get('path') or ''} {module.get('name') or ''}".lower() |
| 90 | + description = str(module.get("description") or "").lower() |
| 91 | + members = " ".join(str(m) for m in module.get("publicMembers") or []).lower() |
| 92 | + matched = score = 0 |
| 93 | + for term in terms: |
| 94 | + points = ( |
| 95 | + _NAME_WEIGHT * _hit(term, name) |
| 96 | + + _DESCRIPTION_WEIGHT * _hit(term, description) |
| 97 | + + _MEMBER_WEIGHT * _hit(term, members) |
| 98 | + ) |
| 99 | + if points: |
| 100 | + matched += 1 |
| 101 | + score += points |
| 102 | + return (matched, score) if matched else None |
| 103 | + |
| 104 | + |
| 105 | +def _entry(module: dict[str, Any], terms: list[str]) -> dict[str, Any]: |
| 106 | + members = [str(m) for m in module.get("publicMembers") or []] |
| 107 | + matching = [m for m in members if any(_hit(t, m.lower()) for t in terms)] |
| 108 | + shown = (matching or members)[:MAX_MEMBERS_SHOWN] |
| 109 | + entry: dict[str, Any] = { |
| 110 | + "path": module.get("path"), |
| 111 | + "kind": module.get("kind"), |
| 112 | + "description": module.get("description"), |
| 113 | + "descriptionSource": module.get("descriptionSource"), |
| 114 | + } |
| 115 | + for key in ("predeclaredId",): |
| 116 | + if module.get(key): |
| 117 | + entry[key] = True |
| 118 | + for key in ("uses", "replaces", "sameObjectName", "tests", "examples"): |
| 119 | + if module.get(key): |
| 120 | + entry[key] = module[key] |
| 121 | + entry["publicMembers"] = shown |
| 122 | + if len(matching or members) > len(shown): |
| 123 | + entry["publicMembersTruncated"] = True |
| 124 | + return entry |
| 125 | + |
| 126 | + |
| 127 | +def overview(catalog: dict[str, Any]) -> list[str]: |
| 128 | + """Return one compact ``path - description`` line per module.""" |
| 129 | + return [ |
| 130 | + f"{m.get('path')} - {m.get('description') or ''}".rstrip(" -") |
| 131 | + for m in catalog["modules"] |
| 132 | + if isinstance(m, dict) |
| 133 | + ] |
| 134 | + |
| 135 | + |
| 136 | +def search_modules( |
| 137 | + catalog: dict[str, Any], query: str, limit: int, want_overview: bool = False |
| 138 | +) -> dict[str, Any]: |
| 139 | + """Return the best matches for ``query`` (OR over the words, ranked by matched words). |
| 140 | +
|
| 141 | + Without any match, or with ``want_overview``, a compact list of all modules is returned |
| 142 | + instead, so that the caller can choose by meaning. |
| 143 | + """ |
| 144 | + terms = _terms(query) |
| 145 | + if not terms: |
| 146 | + raise ValueError("query must contain at least one word") |
| 147 | + scored = [] |
| 148 | + for module in catalog["modules"]: |
| 149 | + if isinstance(module, dict): |
| 150 | + score = _score(module, terms) |
| 151 | + if score is not None: |
| 152 | + scored.append((score, str(module.get("path")), module)) |
| 153 | + scored.sort(key=lambda item: (-item[0][0], -item[0][1], item[1])) |
| 154 | + result: dict[str, Any] = { |
| 155 | + "total": len(scored), |
| 156 | + "shown": min(limit, len(scored)), |
| 157 | + "modules": [_entry(m, terms) for _, _, m in scored[:limit]], |
| 158 | + } |
| 159 | + if want_overview or not scored: |
| 160 | + result["overview"] = overview(catalog) |
| 161 | + if not scored: |
| 162 | + result["note"] = "No module matched; choose from the overview by meaning." |
| 163 | + return result |
0 commit comments