videogen/scripts/gen_codemaps.py
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

178 lines
6.8 KiB
Python

#!/usr/bin/env python3
"""Generate `docs/CODEMAPS/**` navigational docs from the REAL code on disk.
Codemaps are per-area maps: for each module they list its one-line purpose (the
module docstring / Rust `//!` header) and its public surface (top-level
functions / classes / structs / enums). Generated from the actual source so they
never drift into fiction — re-run after changing code (the `/update-codemaps`
contract). Deterministic output (sorted); no network, no app import.
Run: ``python scripts/gen_codemaps.py`` (from the repo root). ``--check`` fails if
the committed docs are stale.
"""
from __future__ import annotations
import argparse
import ast
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "docs" / "CODEMAPS"
API = ROOT / "apps" / "api" / "app"
CRATES = ROOT / "apps" / "desktop" / "crates"
# --------------------------------------------------------------------------- #
# Extractors
# --------------------------------------------------------------------------- #
def _py_module(path: Path) -> tuple[str, list[str]]:
"""Return (one-line purpose, public symbols) for a Python module."""
try:
tree = ast.parse(path.read_text(encoding="utf-8"))
except (SyntaxError, UnicodeDecodeError):
return ("", [])
doc = (ast.get_docstring(tree) or "").strip().splitlines()
purpose = doc[0].strip() if doc else ""
syms: list[str] = []
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
if not node.name.startswith("_"):
kind = "class" if isinstance(node, ast.ClassDef) else "def"
syms.append(f"{kind} {node.name}")
return (purpose, syms)
_RS_DOC = re.compile(r"^\s*//!\s?(.*)$")
_RS_PUB = re.compile(r"^\s*pub\s+(?:async\s+)?(fn|struct|enum|trait)\s+([A-Za-z0-9_]+)")
def _rs_module(path: Path) -> tuple[str, list[str]]:
purpose = ""
syms: list[str] = []
for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
if not purpose:
m = _RS_DOC.match(line)
if m and m.group(1).strip():
purpose = m.group(1).strip()
pm = _RS_PUB.match(line)
if pm:
syms.append(f"{pm.group(1)} {pm.group(2)}")
return (purpose, syms)
# --------------------------------------------------------------------------- #
# Rendering
# --------------------------------------------------------------------------- #
def _render(title: str, rel_root: str, files: list[Path], extractor) -> str:
lines = [f"# CODEMAP — {title}", ""]
lines.append(f"> Generated from `{rel_root}` by `scripts/gen_codemaps.py`. "
"Do not edit by hand; re-run after code changes.")
lines.append("")
lines.append("| Module | Purpose | Public surface |")
lines.append("|---|---|---|")
for f in sorted(files):
purpose, syms = extractor(f)
rel = f.relative_to(ROOT).as_posix()
surface = ", ".join(f"`{s}`" for s in syms[:12]) or "—"
if len(syms) > 12:
surface += f", … (+{len(syms) - 12})"
lines.append(f"| `{rel}` | {purpose or '—'} | {surface} |")
lines.append("")
return "\n".join(lines)
def _py_files(d: Path) -> list[Path]:
return [p for p in d.glob("*.py") if p.name != "__init__.py"]
def _write(target: Path, content: str, check: bool, stale: list[str]) -> None:
target.parent.mkdir(parents=True, exist_ok=True)
if check:
if not target.exists() or target.read_text(encoding="utf-8") != content:
stale.append(target.relative_to(ROOT).as_posix())
return
target.write_text(content, encoding="utf-8")
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--check", action="store_true", help="fail if committed docs are stale")
args = ap.parse_args()
stale: list[str] = []
written: list[str] = []
# API domains.
domains_dir = API / "domains"
for d in sorted(p for p in domains_dir.iterdir() if p.is_dir()):
files = list(d.rglob("*.py"))
files = [f for f in files if f.name != "__init__.py"]
if not files:
continue
rel = f"apps/api/app/domains/{d.name}"
content = _render(f"apps/api · domain · {d.name}", rel, files, _py_module)
_write(OUT / "apps" / "api" / "domains" / f"{d.name}.md", content, args.check, stale)
written.append(f"domains/{d.name}")
# API services.
services_dir = API / "services"
if services_dir.is_dir():
for d in sorted(p for p in services_dir.iterdir() if p.is_dir()):
files = [f for f in d.rglob("*.py") if f.name != "__init__.py"]
if not files:
continue
rel = f"apps/api/app/services/{d.name}"
content = _render(f"apps/api · service · {d.name}", rel, files, _py_module)
_write(OUT / "apps" / "api" / "services" / f"{d.name}.md", content, args.check, stale)
written.append(f"services/{d.name}")
# API top-level areas.
for area in ("events", "telemetry", "workers", "models", "controllers"):
d = API / area
if not d.is_dir():
continue
files = [f for f in d.rglob("*.py") if f.name != "__init__.py"]
if not files:
continue
content = _render(f"apps/api · {area}", f"apps/api/app/{area}", files, _py_module)
_write(OUT / "apps" / "api" / f"{area}.md", content, args.check, stale)
written.append(area)
# Desktop crates.
if CRATES.is_dir():
for crate in sorted(p for p in CRATES.iterdir() if p.is_dir()):
libs = list(crate.rglob("*.rs"))
if not libs:
continue
content = _render(f"apps/desktop · crate · {crate.name}",
f"apps/desktop/crates/{crate.name}", libs, _rs_module)
_write(OUT / "apps" / "desktop" / f"{crate.name}.md", content, args.check, stale)
written.append(f"crate/{crate.name}")
# Root index.
idx = ["# CODEMAPS", "",
"> Auto-generated navigational maps of the ReelForge codebase "
"(`scripts/gen_codemaps.py`). Each map lists a module's purpose + public surface.",
"", f"**{len(written)} area maps** generated from live source.", ""]
for area in sorted(written):
idx.append(f"- `{area}`")
idx.append("")
_write(OUT / "README.md", "\n".join(idx), args.check, stale)
if args.check:
if stale:
print("Stale CODEMAPS (re-run scripts/gen_codemaps.py):", file=sys.stderr)
for s in stale:
print(f" {s}", file=sys.stderr)
return 1
print("CODEMAPS are current.")
return 0
print(f"Wrote {len(written) + 1} CODEMAP files under docs/CODEMAPS/")
return 0
if __name__ == "__main__":
raise SystemExit(main())