Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions scripts/sync_from_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,8 +429,13 @@ def load_existing_search_index(
return {}
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (ValueError, OSError):
return {}
if not isinstance(data, list):
raise ValueError("expected a JSON array")
except (ValueError, OSError) as exc:
raise SystemExit(
f"Cannot parse existing search index {path}: {exc}. "
"Refusing to overwrite it."
) from exc
return {e["slug"]: e for e in data if isinstance(e, dict) and e.get("slug")}


Expand Down
92 changes: 92 additions & 0 deletions tests/test_sync_from_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from __future__ import annotations

import json
import sys
from pathlib import Path

import pytest
Expand Down Expand Up @@ -63,6 +64,17 @@ def _entry(**overrides) -> dict:
</body></html>
"""

INDEX_WITH_SEARCH = """<!doctype html>
<html><body>
<script id="registry-data" type="application/json">
[]
</script>
<script id="search-index" type="application/json">
[]
</script>
</body></html>
"""


@pytest.fixture
def catalog(tmp_path: Path):
Expand All @@ -84,6 +96,86 @@ def _embedded(root: Path) -> list[dict]:
return json.loads(html[start:end])


def test_corrupt_search_index_fails_loudly(catalog, monkeypatch):
root = catalog([_entry()])
(root / "docs" / "index.html").write_text(INDEX_WITH_SEARCH, encoding="utf-8")
search_path = root / "docs" / "search-index.json"
corrupt = "[{\"slug\": \"sample-tools\",\n"
search_path.write_text(corrupt, encoding="utf-8")
monkeypatch.setattr(sync, "REPO_ROOT", root)
monkeypatch.setattr(sync, "REGISTRY_PATH", root / "registry.json")
monkeypatch.setattr(sys, "argv", ["sync_from_registry.py"])

with pytest.raises(SystemExit) as excinfo:
sync.main()

assert excinfo.value.code != 0
error = str(excinfo.value)
assert "Cannot parse existing search index" in error
assert "docs/search-index.json" in error
assert search_path.read_text(encoding="utf-8") == corrupt


def test_search_arrays_survive_sync(catalog):
root = catalog([_entry(description="Updated description")])
(root / "docs" / "index.html").write_text(INDEX_WITH_SEARCH, encoding="utf-8")
existing = [{
"name": "Sample Tools",
"slug": "sample-tools",
"skills": ["Preserved Skill"],
"rules": ["Preserved Rule"],
"mcpTools": ["preserved_tool"],
}]
(root / "docs" / "search-index.json").write_text(
json.dumps(existing), encoding="utf-8"
)

sync.sync_all(root=root)

result = json.loads((root / "docs" / "search-index.json").read_text())
assert result[0]["description"] == "Updated description"
assert result[0]["skills"] == ["Preserved Skill"]
assert result[0]["rules"] == ["Preserved Rule"]
assert result[0]["mcpTools"] == ["preserved_tool"]


def test_new_search_entry_gets_empty_arrays(catalog):
root = catalog([
_entry(),
_entry(name="Other", repo="TMHSDigital/Other", slug="other"),
])
(root / "docs" / "index.html").write_text(INDEX_WITH_SEARCH, encoding="utf-8")
(root / "docs" / "search-index.json").write_text(json.dumps([{
"name": "Sample Tools",
"slug": "sample-tools",
"skills": ["Existing Skill"],
"rules": [],
"mcpTools": [],
}]), encoding="utf-8")

sync.sync_all(root=root)

result = json.loads((root / "docs" / "search-index.json").read_text())
other = next(entry for entry in result if entry["slug"] == "other")
assert other["skills"] == []
assert other["rules"] == []
assert other["mcpTools"] == []


def test_removed_search_entry_is_not_kept(catalog):
root = catalog([_entry()])
(root / "docs" / "index.html").write_text(INDEX_WITH_SEARCH, encoding="utf-8")
(root / "docs" / "search-index.json").write_text(json.dumps([
{"name": "Sample Tools", "slug": "sample-tools", "skills": [], "rules": [], "mcpTools": []},
{"name": "Removed", "slug": "removed", "skills": ["Stale"], "rules": [], "mcpTools": []},
]), encoding="utf-8")

sync.sync_all(root=root)

result = json.loads((root / "docs" / "search-index.json").read_text())
assert [entry["slug"] for entry in result] == ["sample-tools"]


def test_write_then_check_is_clean(catalog):
root = catalog([_entry()])
assert sync.sync_all(root=root, check=False) is True
Expand Down
Loading