84 lines
3.4 KiB
Python
84 lines
3.4 KiB
Python
"""Refresh the document index; validate metadata with --check."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import re
|
|
from datetime import date
|
|
from pathlib import Path
|
|
from urllib.parse import quote
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
INDEX = ROOT / "content-index.json"
|
|
|
|
|
|
def read(path):
|
|
return json.loads(path.read_text(encoding="utf-8"))
|
|
|
|
|
|
def documents():
|
|
return sorted((ROOT / "core-docs").rglob("*.md"))
|
|
|
|
|
|
def record(f, previous, origin):
|
|
path = f.relative_to(ROOT).as_posix()
|
|
raw = f.read_text(encoding="utf-8-sig")
|
|
heading = re.search(r"^#\s+(.+)$", raw, re.M)
|
|
title = heading[1].replace("**", "").strip() if heading else f.stem.replace("_", " ")
|
|
slug = re.sub(r"[^a-z0-9]+", "-", f.stem.lower()).strip("-")[:70].rstrip("-")
|
|
key = "web3-" + slug + "-" + hashlib.sha256(path.encode()).hexdigest()[:8]
|
|
item = dict(previous)
|
|
item.setdefault("content_id", key)
|
|
item.setdefault("description", title)
|
|
item.setdefault("topics", ["token-technology"])
|
|
item.setdefault("status", "draft")
|
|
item.setdefault("content_type", "guide")
|
|
item.update(title=title, path=path,
|
|
canonical_url=origin + "/src/branch/main/" + quote(path))
|
|
return item
|
|
|
|
|
|
def check(index, manifest, variables):
|
|
from jsonschema import Draft202012Validator, FormatChecker
|
|
|
|
for name, data in [("repository", manifest), ("repository-variables", variables), ("content-index", index)]:
|
|
schema = read(ROOT / "schemas" / (name + ".schema.json"))
|
|
Draft202012Validator(schema, format_checker=FormatChecker()).validate(data)
|
|
items = index["items"]
|
|
ids = {i["content_id"] for i in items}
|
|
if len(ids) != len(items) or any(set(i.get("related_content_ids", [])) - ids for i in items):
|
|
raise ValueError("Duplicate or unresolved content IDs")
|
|
version = (ROOT / "VERSION").read_text().strip()
|
|
if manifest["version"] != version or f"version: {version}" not in (ROOT / "CITATION.cff").read_text():
|
|
raise ValueError("Version mismatch")
|
|
if manifest["rights"] != variables["rights"]:
|
|
raise ValueError("Rights mismatch")
|
|
for path in [*manifest["entrypoints"].values(), *manifest["ai_retrieval"]["read_first"],
|
|
*manifest["ai_retrieval"]["retrieve_as_needed"], manifest["rights"]["license_file"]]:
|
|
if not (ROOT / path).exists():
|
|
raise ValueError(f"Missing repository reference: {path}")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--check", action="store_true")
|
|
args = parser.parse_args()
|
|
index = read(INDEX)
|
|
manifest = read(ROOT / "repository.json")
|
|
previous = {i["path"]: i for i in index["items"]}
|
|
items = [record(f, previous.get(f.relative_to(ROOT).as_posix(), {}), manifest["canonical_url"])
|
|
for f in documents()]
|
|
if args.check:
|
|
if index["items"] != items:
|
|
raise ValueError("Index is stale. Run python scripts/catalog.py and review the diff.")
|
|
check(index, manifest, read(ROOT / "repository-variables.json"))
|
|
print(f"Validated 3 schemas and {len(items)} indexed documents.")
|
|
elif items != index["items"]:
|
|
index.update(items=items, updated_at=date.today().isoformat())
|
|
tmp = INDEX.with_suffix(".json.tmp")
|
|
tmp.write_text(json.dumps(index, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
|
tmp.replace(INDEX)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|