|
| 1 | +"""MkDocs hook writing `llms.txt`, `llms-full.txt` and each page's Markdown beside its HTML in the built site.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from pathlib import Path |
| 6 | +from typing import Iterable, Iterator |
| 7 | + |
| 8 | +from mkdocs.config.defaults import MkDocsConfig |
| 9 | +from mkdocs.structure.files import Files |
| 10 | +from mkdocs.structure.nav import Navigation, Section |
| 11 | +from mkdocs.structure.pages import Page |
| 12 | + |
| 13 | +_nav: Navigation |
| 14 | +_files: Files |
| 15 | + |
| 16 | + |
| 17 | +def on_nav(nav: Navigation, config: MkDocsConfig, files: Files) -> Navigation: |
| 18 | + global _nav, _files |
| 19 | + _nav, _files = nav, files |
| 20 | + |
| 21 | + return nav |
| 22 | + |
| 23 | + |
| 24 | +def on_post_build(config: MkDocsConfig) -> None: |
| 25 | + site = Path(config.site_dir) |
| 26 | + in_nav = {page.file.src_uri for page in _nav.pages} |
| 27 | + outside_nav = [file for file in _files.documentation_pages() if file.src_uri not in in_nav] |
| 28 | + ordered = [page.file for page in _nav.pages] + outside_nav |
| 29 | + |
| 30 | + for file in ordered: |
| 31 | + (site / file.src_uri).write_text(Path(file.abs_src_path).read_text(encoding="utf-8"), encoding="utf-8") |
| 32 | + |
| 33 | + index = [f"# {config.site_name}", "", f"> {config.site_description}", "", *_index_lines(_nav.items)] |
| 34 | + |
| 35 | + if outside_nav: |
| 36 | + index += ["", "## Other pages", ""] |
| 37 | + index += [f"- [{file.name}]({file.src_uri})" for file in outside_nav] |
| 38 | + |
| 39 | + (site / "llms.txt").write_text("\n".join(index) + "\n", encoding="utf-8") |
| 40 | + (site / "llms-full.txt").write_text( |
| 41 | + "\n\n".join(Path(file.abs_src_path).read_text(encoding="utf-8").strip() for file in ordered) + "\n", |
| 42 | + encoding="utf-8", |
| 43 | + ) |
| 44 | + |
| 45 | + |
| 46 | +def _index_lines(items: Iterable[object], depth: int = 0) -> Iterator[str]: |
| 47 | + indent = " " * max(depth - 1, 0) |
| 48 | + |
| 49 | + for item in items: |
| 50 | + if isinstance(item, Section): |
| 51 | + yield from ["", f"## {item.title}", ""] if depth == 0 else [f"{indent}- {item.title}"] |
| 52 | + yield from _index_lines(item.children, depth + 1) |
| 53 | + elif isinstance(item, Page): |
| 54 | + yield f"{indent}- [{item.title}]({item.file.src_uri})" |
0 commit comments