Files
unshackle/docs/hooks/download_fields.py
T

52 lines
2.2 KiB
Python

"""MkDocs hook that renders the POST /api/download request body table from the OpenAPI block in routes.py.
It reads routes.py with ast and never imports unshackle, because the docs build installs only the docs requirements.
"""
import ast
import json
from pathlib import Path
from typing import Any
import yaml
MARKER = "<!-- download-fields -->"
PAGE = "dev/rest-api/endpoints.md"
ROUTES = Path(__file__).parents[2] / "unshackle/core/api/routes.py"
def request_schema() -> dict[str, Any]:
"""The JSON schema of the POST /api/download request body, read from the docstring of ``download`` after its last
``---``, as aiohttp_swagger3 reads it."""
tree = ast.parse(ROUTES.read_text(encoding="utf-8"))
func = next(node for node in tree.body if isinstance(node, ast.AsyncFunctionDef) and node.name == "download")
spec = yaml.safe_load(str(ast.get_docstring(func)).rsplit("---", 1)[-1])
return spec["requestBody"]["content"]["application/json"]["schema"]
def type_text(schema: dict[str, Any]) -> str:
if "oneOf" in schema:
return " / ".join(type_text(option) for option in schema["oneOf"])
if "enum" in schema:
return ", ".join(f"`{value}`" for value in schema["enum"])
if schema["type"] == "array":
return type_text(schema["items"]) + "[]"
return schema["type"] + (f" ≥ {schema['minimum']}" if "minimum" in schema else "")
def render(schema: dict[str, Any]) -> str:
rows = ["| Field | Type | Default | Description |", "| --- | --- | --- | --- |"]
for name, field in schema["properties"].items():
default = "required" if name in schema.get("required", ()) else f"`{json.dumps(field.get('default'))}`"
description = " ".join(field.get("description", "").split()).replace("|", "\\|")
rows.append(f"| `{name}` | {type_text(field)} | {default} | {description} |")
return "\n".join(rows)
def on_page_markdown(markdown: str, page: Any, **kwargs: Any) -> str:
if MARKER not in markdown:
if page.file.src_uri == PAGE:
raise ValueError(f"{PAGE} has no {MARKER} marker for the download request table")
return markdown
return markdown.replace(MARKER, render(request_schema()))