|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import re |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +from extract_snippet import extract_symbol_source, SymbolType |
| 7 | + |
| 8 | + |
| 9 | +ROOT = Path(__file__).resolve().parents[1] |
| 10 | +DOCS_DIR = ROOT / "docs" |
| 11 | +OUTPUT_DIR = ROOT / "docs_generated" |
| 12 | + |
| 13 | + |
| 14 | +BLOCK_RE = re.compile( |
| 15 | + r"::: py-symbol\s+" |
| 16 | + r"path:\s*(?P<path>.+?)\s+" |
| 17 | + r"symbol:\s*(?P<symbol>.+?)\s+" |
| 18 | + r"type:\s*(?P<type>function|class)\s*" |
| 19 | + r":::", |
| 20 | + re.DOTALL, |
| 21 | +) |
| 22 | + |
| 23 | + |
| 24 | +def replace_block(md_text: str) -> str: |
| 25 | + def _repl(match: re.Match) -> str: |
| 26 | + path_str = match.group("path").strip() |
| 27 | + symbol = match.group("symbol").strip() |
| 28 | + symbol_type_str = match.group("type").strip() |
| 29 | + symbol_type: SymbolType = symbol_type_str # type: ignore[assignment] |
| 30 | + |
| 31 | + py_path = ROOT / path_str |
| 32 | + code = extract_symbol_source(py_path, symbol, symbol_type) |
| 33 | + |
| 34 | + return f"```python\n{code}\n```" |
| 35 | + |
| 36 | + return BLOCK_RE.sub(_repl, md_text) |
| 37 | + |
| 38 | + |
| 39 | +def clean_output_dir() -> None: |
| 40 | + if not OUTPUT_DIR.exists(): |
| 41 | + return |
| 42 | + for p in sorted(OUTPUT_DIR.rglob("*"), reverse=True): |
| 43 | + if p.is_file(): |
| 44 | + p.unlink() |
| 45 | + elif p.is_dir(): |
| 46 | + p.rmdir() |
| 47 | + |
| 48 | + |
| 49 | +def main() -> None: |
| 50 | + clean_output_dir() |
| 51 | + OUTPUT_DIR.mkdir(parents=True, exist_ok=True) |
| 52 | + |
| 53 | + for md_path in DOCS_DIR.rglob("*.md"): |
| 54 | + rel = md_path.relative_to(DOCS_DIR) |
| 55 | + out_path = OUTPUT_DIR / rel |
| 56 | + out_path.parent.mkdir(parents=True, exist_ok=True) |
| 57 | + |
| 58 | + text = md_path.read_text(encoding="utf-8") |
| 59 | + new_text = replace_block(text) |
| 60 | + out_path.write_text(new_text, encoding="utf-8") |
| 61 | + print(f"processed {rel}") |
| 62 | + |
| 63 | + print(f"All markdown files expanded into {OUTPUT_DIR}") |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + main() |
| 68 | + |
0 commit comments