mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-06 14:50:36 +08:00
docs: update documentation links and add CI workflow for building and checking the docs site
This commit is contained in:
238
docs/scripts/check_docs.py
Normal file
238
docs/scripts/check_docs.py
Normal file
@@ -0,0 +1,238 @@
|
||||
"""Locale parity, screenshot hashes, channel-schema drift, and built-site link checks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
CONTENT = ROOT / "docs" / "src" / "content" / "docs"
|
||||
PUBLIC = ROOT / "docs" / "public" / "screenshots" / "dev"
|
||||
MANIFEST = ROOT / "assets" / "figs" / "web-dev" / "manifest.json"
|
||||
DIST = ROOT / "docs" / "dist"
|
||||
CHANNELS = ROOT / "deeptutor" / "partners" / "channels"
|
||||
CHANNEL_SCHEMA = ROOT / "deeptutor" / "partners" / "config" / "schema.py"
|
||||
HREF = re.compile(r"""(?:href|src)=["']([^"']+)["']""")
|
||||
SKIP_CHANNEL_MODULES = {"base", "manager", "registry", "weixin_qr", "lark_http"}
|
||||
SHARED_SWITCHES = {"enabled", "send_progress", "send_tool_hints", "streaming", "allow_from"}
|
||||
|
||||
|
||||
def pages(base: Path) -> set[str]:
|
||||
found = set()
|
||||
for pattern in ("*.md", "*.mdx"):
|
||||
for path in base.rglob(pattern):
|
||||
rel = path.relative_to(base).as_posix()
|
||||
if rel.startswith("zh-cn/"):
|
||||
continue
|
||||
found.add(rel)
|
||||
return found
|
||||
|
||||
|
||||
def check_parity() -> list[str]:
|
||||
errors = []
|
||||
en = pages(CONTENT)
|
||||
zh = pages(CONTENT / "zh-cn")
|
||||
if en - zh:
|
||||
errors.append("only English: " + ", ".join(sorted(en - zh)))
|
||||
if zh - en:
|
||||
errors.append("only Chinese: " + ", ".join(sorted(zh - en)))
|
||||
for path in list(CONTENT.rglob("*.md")) + list(CONTENT.rglob("*.mdx")):
|
||||
rel = path.relative_to(CONTENT).as_posix()
|
||||
if rel in {"index.mdx", "zh-cn/index.mdx"}:
|
||||
continue
|
||||
text = path.read_text()
|
||||
if not text.startswith("---"):
|
||||
errors.append(f"{rel} is missing frontmatter")
|
||||
continue
|
||||
block = text.split("---", 2)[1]
|
||||
if "quadrant:" not in block and "template: splash" not in block:
|
||||
errors.append(f"{rel} is missing quadrant")
|
||||
return errors
|
||||
|
||||
|
||||
def check_screenshots() -> list[str]:
|
||||
errors = []
|
||||
manifest = json.loads(MANIFEST.read_text())
|
||||
for row in manifest["files"]:
|
||||
name = row["file"]
|
||||
copy = PUBLIC / name
|
||||
if not copy.exists():
|
||||
continue
|
||||
digest = hashlib.sha256(copy.read_bytes()).hexdigest()
|
||||
if digest != row["sha256"]:
|
||||
errors.append(f"{name} sha256 {digest} != manifest {row['sha256']}")
|
||||
referenced = set()
|
||||
for path in CONTENT.rglob("*"):
|
||||
if path.suffix not in {".md", ".mdx"}:
|
||||
continue
|
||||
referenced.update(re.findall(r"/screenshots/dev/([A-Za-z0-9_.-]+)", path.read_text()))
|
||||
for name in sorted(referenced):
|
||||
if not (PUBLIC / name).exists():
|
||||
errors.append(f"missing screenshot {name}")
|
||||
return errors
|
||||
|
||||
|
||||
def dest_exists(url: str) -> bool:
|
||||
path = url.split("#", 1)[0].split("?", 1)[0]
|
||||
if path in {"", "/"}:
|
||||
return (DIST / "index.html").exists()
|
||||
relative = path.lstrip("/")
|
||||
candidates = [
|
||||
DIST / relative,
|
||||
DIST / relative / "index.html",
|
||||
DIST / f"{relative}.html",
|
||||
]
|
||||
return any(item.exists() for item in candidates)
|
||||
|
||||
|
||||
def _class_fields(node: ast.ClassDef) -> list[str]:
|
||||
fields = []
|
||||
for stmt in node.body:
|
||||
if isinstance(stmt, ast.AnnAssign) and isinstance(stmt.target, ast.Name):
|
||||
name = stmt.target.id
|
||||
if not name.startswith("_"):
|
||||
fields.append(name)
|
||||
return fields
|
||||
|
||||
|
||||
def _class_index(paths: list[Path]) -> dict[str, tuple[list[str], list[str]]]:
|
||||
index: dict[str, tuple[list[str], list[str]]] = {}
|
||||
for path in paths:
|
||||
tree = ast.parse(path.read_text())
|
||||
for node in tree.body:
|
||||
if not isinstance(node, ast.ClassDef):
|
||||
continue
|
||||
bases = []
|
||||
for base in node.bases:
|
||||
if isinstance(base, ast.Name):
|
||||
bases.append(base.id)
|
||||
elif isinstance(base, ast.Attribute):
|
||||
bases.append(base.attr)
|
||||
index[node.name] = (bases, _class_fields(node))
|
||||
return index
|
||||
|
||||
|
||||
def _resolved_fields(index: dict[str, tuple[list[str], list[str]]], name: str, seen: set[str] | None = None) -> list[str]:
|
||||
seen = seen or set()
|
||||
if name in seen or name not in index:
|
||||
return []
|
||||
seen.add(name)
|
||||
bases, fields = index[name]
|
||||
resolved: list[str] = []
|
||||
for base in bases:
|
||||
resolved.extend(_resolved_fields(index, base, seen))
|
||||
resolved.extend(fields)
|
||||
return resolved
|
||||
|
||||
|
||||
def _channel_configs() -> dict[str, list[str]]:
|
||||
index = _class_index([CHANNEL_SCHEMA, *sorted(CHANNELS.glob("*.py"))])
|
||||
configs: dict[str, list[str]] = {}
|
||||
for path in sorted(CHANNELS.glob("*.py")):
|
||||
if path.stem in SKIP_CHANNEL_MODULES:
|
||||
continue
|
||||
tree = ast.parse(path.read_text())
|
||||
for node in tree.body:
|
||||
if not isinstance(node, ast.ClassDef) or not node.name.endswith("Channel"):
|
||||
continue
|
||||
key = None
|
||||
for stmt in node.body:
|
||||
if (
|
||||
isinstance(stmt, ast.Assign)
|
||||
and any(isinstance(target, ast.Name) and target.id == "name" for target in stmt.targets)
|
||||
and isinstance(stmt.value, ast.Constant)
|
||||
and isinstance(stmt.value.value, str)
|
||||
):
|
||||
key = stmt.value.value
|
||||
if not key:
|
||||
continue
|
||||
config_name = node.name.replace("Channel", "Config")
|
||||
fields = _resolved_fields(index, config_name)
|
||||
if fields:
|
||||
configs[key] = list(dict.fromkeys(fields))
|
||||
return configs
|
||||
|
||||
|
||||
def _mentioned_fields(text: str) -> set[str]:
|
||||
names = set(re.findall(r"`([a-z][a-z0-9_]*)`", text))
|
||||
for label in re.findall(r"\*\*([^*]+)\*\*", text):
|
||||
slug = re.sub(r"[^a-z0-9_]", "", label.strip().lower().replace(" ", "_").replace("-", "_"))
|
||||
if slug:
|
||||
names.add(slug)
|
||||
return names
|
||||
|
||||
|
||||
def _schema_sections(text: str) -> tuple[str, dict[str, str]]:
|
||||
parts = re.split(r'<a id="([^"]+)"></a>', text)
|
||||
sections: dict[str, str] = {}
|
||||
iterator = iter(parts[1:])
|
||||
for key, body in zip(iterator, iterator):
|
||||
sections[key] = body
|
||||
shared = ""
|
||||
match = re.search(r"## (?:Shared delivery switches|共享投递开关)(.*?)(?:\n## |\Z)", parts[0], re.S)
|
||||
if match:
|
||||
shared = match.group(1)
|
||||
return shared, sections
|
||||
|
||||
|
||||
def check_channel_schema() -> list[str]:
|
||||
"""The hand-written channel pages must name every config field the source declares."""
|
||||
errors = []
|
||||
configs = _channel_configs()
|
||||
if not configs:
|
||||
return ["channel schema source produced no configs"]
|
||||
pages = {
|
||||
"en": CONTENT / "channels" / "schema.md",
|
||||
"zh": CONTENT / "zh-cn" / "channels" / "schema.md",
|
||||
}
|
||||
for locale, path in pages.items():
|
||||
text = path.read_text()
|
||||
shared, sections = _schema_sections(text)
|
||||
shared_names = _mentioned_fields(shared)
|
||||
for key, fields in sorted(configs.items()):
|
||||
if f"`{key}`" not in text:
|
||||
errors.append(f"{locale} channel matrix is missing `{key}`")
|
||||
section = sections.get(key, "")
|
||||
if not section:
|
||||
errors.append(f"{locale} channel schema is missing the {key} field section")
|
||||
continue
|
||||
mentioned = _mentioned_fields(section) | (shared_names & SHARED_SWITCHES)
|
||||
missing = [field for field in fields if field not in mentioned]
|
||||
if missing:
|
||||
errors.append(f"{locale} {key} docs omit {', '.join(missing)}")
|
||||
return errors
|
||||
|
||||
|
||||
def check_links() -> list[str]:
|
||||
if not DIST.exists():
|
||||
return ["docs/dist is missing; run the docs build first"]
|
||||
errors = []
|
||||
for page in DIST.rglob("*.html"):
|
||||
for match in HREF.findall(page.read_text(errors="ignore")):
|
||||
if match.startswith(("http://", "https://", "mailto:", "data:", "#", "javascript:")):
|
||||
continue
|
||||
if not match.startswith("/"):
|
||||
continue
|
||||
if not dest_exists(match):
|
||||
errors.append(f"{page.relative_to(DIST)} -> {match}")
|
||||
return errors
|
||||
|
||||
|
||||
def main() -> int:
|
||||
mode = sys.argv[1] if len(sys.argv) > 1 else "source"
|
||||
errors = check_parity() + check_screenshots() + check_channel_schema()
|
||||
if mode == "dist":
|
||||
errors.extend(check_links())
|
||||
if errors:
|
||||
print("\n".join(errors))
|
||||
return 1
|
||||
print("docs checks passed")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
162
docs/scripts/generate_reference.py
Normal file
162
docs/scripts/generate_reference.py
Normal file
@@ -0,0 +1,162 @@
|
||||
"""Regenerate public reference pages from module manifests and the router index.
|
||||
|
||||
Run from the repository root:
|
||||
|
||||
python3 docs/scripts/generate_reference.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MANIFESTS = ROOT / "deeptutor" / "modules" / "manifests"
|
||||
ROUTER_INDEX = ROOT / "deeptutor" / "api" / "router_index.json"
|
||||
DOCS = ROOT / "docs" / "src" / "content" / "docs"
|
||||
MARKER = "<!-- generated-route-index -->"
|
||||
|
||||
EXTRA_MOUNTS = {
|
||||
"deeptutor.api.routers.modules:router": {
|
||||
"prefix": "/api/modules",
|
||||
"auth": "authenticated",
|
||||
"module": "server",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def load_mounts() -> dict[str, dict]:
|
||||
mounts = dict(EXTRA_MOUNTS)
|
||||
for path in sorted(MANIFESTS.glob("*.json")):
|
||||
data = json.loads(path.read_text())
|
||||
for route in data.get("routes", []):
|
||||
options = route.get("options") or {}
|
||||
mounts[route["reference"]] = {
|
||||
"prefix": options.get("prefix") or "",
|
||||
"auth": route.get("auth") or "",
|
||||
"module": data["id"],
|
||||
}
|
||||
return mounts
|
||||
|
||||
|
||||
def route_index(locale: str) -> str:
|
||||
index = json.loads(ROUTER_INDEX.read_text())
|
||||
mounts = load_mounts()
|
||||
groups: list[tuple[str, str, str, list[dict]]] = []
|
||||
missing = []
|
||||
for reference, patterns in index["routers"].items():
|
||||
mount = mounts.get(reference)
|
||||
if mount is None:
|
||||
missing.append(reference)
|
||||
continue
|
||||
groups.append((mount["module"], mount["prefix"], mount["auth"], reference, patterns))
|
||||
groups.sort(key=lambda row: (row[0], row[1], row[3]))
|
||||
|
||||
if locale == "zh":
|
||||
intro = (
|
||||
"## 路由索引\n\n"
|
||||
"下面的表由 `deeptutor/modules/manifests/*.json` 与 "
|
||||
"`deeptutor/api/router_index.json` 生成。路径是挂载前缀加上路由模板。"
|
||||
"字段和请求体以运行中的 `GET /openapi.json` 为准。\n"
|
||||
)
|
||||
columns = "| 方法 | 路径 |\n| --- | --- |"
|
||||
missing_label = "索引里有、清单未挂载"
|
||||
else:
|
||||
intro = (
|
||||
"## Route index\n\n"
|
||||
"Generated from `deeptutor/modules/manifests/*.json` and "
|
||||
"`deeptutor/api/router_index.json`. Each path is the mount prefix plus the route template. "
|
||||
"Request and response fields stay in the live `GET /openapi.json`.\n"
|
||||
)
|
||||
columns = "| Method | Path |\n| --- | --- |"
|
||||
missing_label = "Indexed but not mounted by a manifest"
|
||||
|
||||
lines = [MARKER, "", intro]
|
||||
current = None
|
||||
for module, prefix, auth, reference, patterns in groups:
|
||||
if module != current:
|
||||
current = module
|
||||
lines.append(f"### {module}\n")
|
||||
short = reference.rsplit(".", 1)[-1]
|
||||
lines.append(f"#### `{short}` — `{prefix or '/'}` · {auth}\n")
|
||||
lines.append(columns)
|
||||
for pattern in patterns:
|
||||
methods = ", ".join(pattern["methods"]) or "WS"
|
||||
path = f"{prefix}{pattern['path']}"
|
||||
lines.append(f"| `{methods}` | `{path}` |")
|
||||
lines.append("")
|
||||
if missing:
|
||||
lines.append(f"### {missing_label}\n")
|
||||
for reference in missing:
|
||||
lines.append(f"- `{reference}`")
|
||||
lines.append("")
|
||||
return "\n".join(lines).rstrip() + "\n"
|
||||
|
||||
|
||||
def capabilities(locale: str) -> str:
|
||||
rows = []
|
||||
for path in sorted(MANIFESTS.glob("*.json")):
|
||||
data = json.loads(path.read_text())
|
||||
for name, spec in (data.get("capabilities") or {}).items():
|
||||
manifest = spec.get("manifest") or {}
|
||||
stages = ", ".join(f"`{stage}`" for stage in manifest.get("stages") or [])
|
||||
aliases = ", ".join(f"`{alias}`" for alias in manifest.get("cli_aliases") or []) or "—"
|
||||
description = (manifest.get("description") or "").replace("|", "\\|")
|
||||
rows.append((spec.get("order", 0), data["id"], name, stages, aliases, description))
|
||||
rows.sort(key=lambda row: (row[1], row[0], row[2]))
|
||||
if locale == "zh":
|
||||
head = """---
|
||||
title: 能力
|
||||
description: 已注册能力的名称、阶段、所属模块和 CLI 别名。
|
||||
quadrant: reference
|
||||
---
|
||||
|
||||
名称、阶段和 CLI 别名来自 `deeptutor/modules/manifests/*.json` 里每个能力的 `manifest`。描述保持清单中的英文原文。
|
||||
|
||||
| 能力 | 模块 | 阶段 | CLI | 说明 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
"""
|
||||
else:
|
||||
head = """---
|
||||
title: Capabilities
|
||||
description: Registered capability names, stages, owning modules, and CLI aliases.
|
||||
quadrant: reference
|
||||
---
|
||||
|
||||
Names, stages, and CLI aliases come from each capability `manifest` in `deeptutor/modules/manifests/*.json`.
|
||||
|
||||
| Capability | Module | Stages | CLI | Description |
|
||||
| --- | --- | --- | --- | --- |
|
||||
"""
|
||||
body = "\n".join(
|
||||
f"| `{name}` | `{module}` | {stages or '—'} | {aliases} | {description} |"
|
||||
for _, module, name, stages, aliases, description in rows
|
||||
)
|
||||
return head + body + "\n"
|
||||
|
||||
|
||||
def write_capabilities() -> None:
|
||||
for locale, folder in (("en", DOCS), ("zh", DOCS / "zh-cn")):
|
||||
target = folder / "developers" / "reference" / "capabilities.md"
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(capabilities(locale))
|
||||
|
||||
|
||||
def append_routes() -> None:
|
||||
for locale, folder in (("en", DOCS), ("zh", DOCS / "zh-cn")):
|
||||
target = folder / "developers" / "reference" / "http-api.md"
|
||||
text = target.read_text()
|
||||
if MARKER in text:
|
||||
text = text.split(MARKER, 1)[0].rstrip() + "\n\n"
|
||||
else:
|
||||
text = text.rstrip() + "\n\n"
|
||||
target.write_text(text + route_index(locale))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
write_capabilities()
|
||||
append_routes()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user