| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Inline build-time generated content into existing docs pages. |
| 4 | |
| 5 | Source pages mark where generated content goes with a snippet-style marker, |
| 6 | `--8<-- "gen:<key>"`, so the insertion point is explicit and readable. The |
| 7 | substitution happens here (at gen-files time, before mkdocs-gen-files shadows |
| 8 | the page), not via pymdownx.snippets, so the content can be generated at build |
| 9 | time without living in a real file on disk. |
| 10 | |
| 11 | The `gen:` prefix keeps these markers distinct from real pymdownx.snippets |
| 12 | includes, and `fill_markers` fails loudly if a marker is missing or left behind |
| 13 | (pymdownx.snippets would otherwise silently drop an unsubstituted marker). |
| 14 | """ |
| 15 | |
| 16 | from pathlib import Path |
| 17 | |
| 18 | import mkdocs_gen_files |
| 19 | import regex as re |
| 20 | |
| 21 | DOCS_DIR = Path(__file__).parent.parent.parent |
| 22 | |
| 23 | _MARKER = '--8<-- "gen:{key}"' |
| 24 | _ANY_MARKER = re.compile(r'--8<-- "gen:[^"]*"') |
| 25 | |
| 26 | |
| 27 | def fill_markers(doc_path: str, blocks: dict[str, str]) -> None: |
| 28 | """Replace `--8<-- "gen:<key>"` markers in a docs page with generated content. |
| 29 | |
| 30 | Args: |
| 31 | doc_path: Docs-relative path of the source page to fill. |
| 32 | blocks: Mapping of marker key to the markdown to insert in its place. |
| 33 | |
| 34 | Raises: |
| 35 | FileNotFoundError: If the source page does not exist. |
| 36 | ValueError: If an expected marker is missing, or any `gen:` marker is |
| 37 | left unsubstituted after filling. |
| 38 | |
| 39 | """ |
| 40 | source = DOCS_DIR / doc_path |
| 41 | if not source.exists(): |
| 42 | raise FileNotFoundError(f"Cannot fill markers in missing page: {doc_path}") |
| 43 | |
| 44 | text = source.read_text() |
| 45 | for key, content in blocks.items(): |
| 46 | marker = _MARKER.format(key=key) |
| 47 | if marker not in text: |
| 48 | raise ValueError(f"{doc_path}: missing marker {marker}") |
| 49 | text = text.replace(marker, content) |
| 50 | |
| 51 | if leftover := _ANY_MARKER.search(text): |
| 52 | raise ValueError(f"{doc_path}: unsubstituted marker {leftover.group()}") |
| 53 | |
| 54 | with mkdocs_gen_files.open(doc_path, "w") as f: |
| 55 | f.write(text) |
| 56 | # Keep the edit button pointing at the real source page |
| 57 | mkdocs_gen_files.set_edit_path(doc_path, doc_path) |