|
| 1 | +import os |
| 2 | +import re |
| 3 | +import pathlib |
| 4 | +import textwrap |
| 5 | +from typing import Iterator, List, Tuple |
| 6 | + |
| 7 | +# ---------------------------- |
| 8 | +# Configuration |
| 9 | +# ---------------------------- |
| 10 | +BASE_DIR = pathlib.Path(__file__).resolve().parent.parent |
| 11 | +DOCS_DIR = BASE_DIR / "docs" |
| 12 | + |
| 13 | +# Regex to match triple-backticked code blocks: |
| 14 | +# - PYTHON_ONLY matches blocks explicitly labeled as Python (python|py|python3|pycon|ipython) |
| 15 | +# - ANY_LABEL_OR_UNLABELED matches python-labeled OR unlabeled blocks |
| 16 | +PYTHON_CODE_BLOCK_PATTERN = re.compile( |
| 17 | + r"```\s*(?:python|py|python3|pycon|ipython)(?:[^\n]*)?\s*\n(.*?)```", |
| 18 | + re.DOTALL, |
| 19 | +) |
| 20 | +ANY_CODE_BLOCK_PATTERN = re.compile( |
| 21 | + r"```(?:\s*(?:python|py|python3|pycon|ipython)(?:[^\n]*)?)?\s*\n(.*?)```", |
| 22 | + re.DOTALL, |
| 23 | +) |
| 24 | + |
| 25 | +# Directories to skip when walking the docs tree (common build outputs) |
| 26 | +SKIP_DIRS = {"_build", ".git", ".venv", "build", "site", "dist", "node_modules"} |
| 27 | + |
| 28 | + |
| 29 | +def _extract_code_blocks_from_markdown( |
| 30 | + markdown_text: str, only_python: bool = True |
| 31 | +) -> List[str]: |
| 32 | + """Extract triple-backtick code blocks from a markdown string and fix indentation. |
| 33 | +
|
| 34 | + If only_python is True, only code blocks explicitly labeled as Python are captured. |
| 35 | + Otherwise, unlabeled code blocks are captured as well. |
| 36 | + """ |
| 37 | + pattern = ( |
| 38 | + PYTHON_CODE_BLOCK_PATTERN if only_python else ANY_CODE_BLOCK_PATTERN |
| 39 | + ) |
| 40 | + code_blocks = pattern.findall(markdown_text or "") |
| 41 | + |
| 42 | + fixed_blocks: List[str] = [] |
| 43 | + for code in code_blocks: |
| 44 | + dedented_code = textwrap.dedent(code) |
| 45 | + fixed_blocks.append(dedented_code) |
| 46 | + |
| 47 | + return fixed_blocks |
| 48 | + |
| 49 | + |
| 50 | +def _iter_markdown_files(root: pathlib.Path) -> Iterator[pathlib.Path]: |
| 51 | + """Yield markdown files (.md, .mdx) under root, skipping common build dirs.""" |
| 52 | + if not root.exists(): |
| 53 | + return |
| 54 | + |
| 55 | + for dirpath, dirnames, filenames in os.walk(root): |
| 56 | + # In-place prune dirs to skip |
| 57 | + dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS] |
| 58 | + |
| 59 | + for filename in filenames: |
| 60 | + if filename.lower().endswith((".md", ".mdx")): |
| 61 | + yield pathlib.Path(dirpath) / filename |
| 62 | + |
| 63 | + |
| 64 | +def gather_markdown_snippets(only_python: bool = True) -> List[Tuple[str, str]]: |
| 65 | + """Gather all triple-backtick code snippets from markdown docs in `docs/`. |
| 66 | +
|
| 67 | + For each markdown file, concatenate all discovered code blocks into a single |
| 68 | + Python snippet. Returns a list of (file_identifier, concatenated_code) tuples. |
| 69 | + The identifier is the path to the markdown file relative to the repo root. |
| 70 | +
|
| 71 | + Parameters |
| 72 | + ---------- |
| 73 | + only_python: bool |
| 74 | + If True (default), only capture code fences labeled as Python. If False, |
| 75 | + also capture unlabeled fences. |
| 76 | + """ |
| 77 | + print("Gathering markdown snippets from docs/ ...") |
| 78 | + |
| 79 | + snippets: List[Tuple[str, str]] = [] |
| 80 | + |
| 81 | + if not DOCS_DIR.exists(): |
| 82 | + print(f"docs/ directory not found at {DOCS_DIR}") |
| 83 | + return snippets |
| 84 | + |
| 85 | + files = list(_iter_markdown_files(DOCS_DIR)) |
| 86 | + print(f"Found {len(files)} markdown files to process") |
| 87 | + |
| 88 | + for index, md_path in enumerate(sorted(files)): |
| 89 | + rel_path = md_path.relative_to(BASE_DIR) |
| 90 | + print(f"[{index + 1}/{len(files)}] Processing: {rel_path}") |
| 91 | + try: |
| 92 | + text = md_path.read_text(encoding="utf-8") |
| 93 | + except Exception as exc: |
| 94 | + print( |
| 95 | + f" -> Failed to read {rel_path}: {type(exc).__name__}: {exc}" |
| 96 | + ) |
| 97 | + # Treat read errors as test cases too for visibility |
| 98 | + snippets.append( |
| 99 | + ( |
| 100 | + f"{rel_path} (read error)", |
| 101 | + f"# read error\nraise IOError({repr(str(exc))})", |
| 102 | + ) |
| 103 | + ) |
| 104 | + continue |
| 105 | + |
| 106 | + code_blocks = _extract_code_blocks_from_markdown( |
| 107 | + text, only_python=only_python |
| 108 | + ) |
| 109 | + print(f" -> Found {len(code_blocks)} code blocks") |
| 110 | + |
| 111 | + if code_blocks: |
| 112 | + # Concatenate all blocks with spacing to avoid accidental token pasting |
| 113 | + concatenated = ( |
| 114 | + "\n\n".join(block.strip("\n") for block in code_blocks) + "\n" |
| 115 | + ) |
| 116 | + identifier = f"{rel_path}" |
| 117 | + snippets.append((identifier, concatenated)) |
| 118 | + print(f" -> Added concatenated snippet for: {identifier}") |
| 119 | + |
| 120 | + print(f"Finished gathering snippets. Total: {len(snippets)} snippets") |
| 121 | + return snippets |
| 122 | + |
| 123 | + |
| 124 | +__all__ = [ |
| 125 | + "gather_markdown_snippets", |
| 126 | +] |
0 commit comments