Files
cleveragents-core/docs/gen_ref_pages.py
T
2026-02-18 00:09:50 -05:00

86 lines
2.9 KiB
Python

"""Generate the code reference pages and navigation.
This script is executed by mkdocs-gen-files during the docs build.
It walks the `src/cleveragents` package tree and generates a `.md`
page for every public Python module. Each page contains an
mkdocstrings `::: module.path` directive so the API docs are
rendered from live docstrings.
A `SUMMARY.md` file is also written so that mkdocs-literate-nav can
build the Reference section of the sidebar automatically.
"""
from pathlib import Path
import mkdocs_gen_files
nav = mkdocs_gen_files.Nav()
SRC_DIR = Path("src")
PACKAGE = "cleveragents"
def _is_proper_package(py_file: Path) -> bool:
"""Return True only if every ancestor directory (up to SRC_DIR) has an __init__.py.
This filters out stray .py files that live in directories without
__init__.py (e.g. templates/renderer.py) which griffe cannot resolve.
"""
parent = py_file.parent
while parent != SRC_DIR:
if not (parent / "__init__.py").exists():
return False
parent = parent.parent
return True
# Walk every .py file under src/cleveragents
for path in sorted(SRC_DIR.rglob("*.py")):
# Only include modules that belong to proper Python packages
if not _is_proper_package(path):
continue
# Compute the dotted module path and the docs destination path
module_path = path.relative_to(SRC_DIR).with_suffix(
""
) # e.g. cleveragents/domain/models/core/plan
doc_path = path.relative_to(SRC_DIR).with_suffix(
".md"
) # e.g. cleveragents/domain/models/core/plan.md
full_doc_path = Path(
"reference", doc_path
) # e.g. reference/cleveragents/domain/models/core/plan.md
parts = tuple(module_path.parts)
# Skip __main__ — not useful API surface
if parts[-1] == "__main__":
continue
# For __init__.py files, use the package itself as the page
if parts[-1] == "__init__":
parts = parts[:-1]
doc_path = doc_path.with_name("index.md")
full_doc_path = full_doc_path.with_name("index.md")
# Build the nav entry
nav_parts = parts # e.g. ("cleveragents", "domain", "models", "core", "plan")
nav[nav_parts] = doc_path.as_posix()
# Write the stub .md page with the mkdocstrings directive
dotted = ".".join(parts) # e.g. "cleveragents.domain.models.core.plan"
with mkdocs_gen_files.open(full_doc_path, "w") as fd:
fd.write(f"# `{dotted}`\n\n")
fd.write(f"::: {dotted}\n")
# Tell mkdocs-gen-files where the edit link should point
mkdocs_gen_files.set_edit_path(full_doc_path, path.as_posix())
# Include manually-authored reference pages that live alongside the
# auto-generated API docs.
nav[("actors_schema",)] = "actors_schema.md"
# Write the literate-nav summary file for the Reference section
with mkdocs_gen_files.open("reference/SUMMARY.md", "w") as nav_file:
nav_file.writelines(nav.build_literate_nav())