Skip to content
This repository was archived by the owner on Nov 23, 2026. It is now read-only.

Commit 2b03156

Browse files
committed
Write the llms files with a script instead of a MkDocs hook
1 parent 5030aa6 commit 2b03156

5 files changed

Lines changed: 101 additions & 59 deletions

File tree

‎Makefile‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ help:
1313
@echo 'make convert Convert the user guide into ./docs'
1414
@echo 'make convert PAGE=<page> Convert one page, such as models/model'
1515
@echo 'make verify Compare ./docs with the RST source'
16-
@echo 'make build Build the site into ./site, failing on warnings'
16+
@echo 'make build Build the site and its llms files into ./site, failing on warnings'
1717
@echo 'make serve Preview the site at http://127.0.0.1:8000'
1818

1919
install: $(MKDOCS)
@@ -31,6 +31,7 @@ verify:
3131

3232
build: $(MKDOCS)
3333
$(MKDOCS) build --strict
34+
$(VENV)/bin/python admin/llms.py
3435

3536
serve: $(MKDOCS)
3637
$(MKDOCS) serve

‎admin/how_to_build_docs.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ make build
2727
```
2828

2929
This runs `mkdocs build --strict`, which fails on a broken link or a nav entry without a page.
30+
It then runs `admin/llms.py`, which writes `llms.txt`, `llms-full.txt` and a Markdown copy of
31+
each page beside its HTML in `site/`.
32+
The script reads only the nav and the Markdown, so it does not depend on MkDocs.
3033

3134
## See the Docs
3235

@@ -40,6 +43,7 @@ Without `make`, run the same steps by hand:
4043
python3 -m venv venv
4144
venv/bin/pip install -r requirements.txt
4245
venv/bin/mkdocs build --strict
46+
venv/bin/python admin/llms.py
4347
venv/bin/mkdocs serve
4448
```
4549

‎admin/llms.py‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
"""Writes 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+
import re
6+
import sys
7+
from pathlib import Path
8+
9+
import yaml
10+
11+
12+
class Loader(yaml.SafeLoader):
13+
pass
14+
15+
16+
Loader.add_multi_constructor("!", lambda loader, suffix, node: None)
17+
18+
19+
def load(path: Path) -> dict:
20+
return yaml.load(path.read_text(encoding="utf-8"), Loader=Loader) or {}
21+
22+
23+
def title_of(markdown: Path) -> str:
24+
fenced = False
25+
26+
for line in markdown.read_text(encoding="utf-8").splitlines():
27+
if line.startswith("```"):
28+
fenced = not fenced
29+
elif not fenced and (match := re.match(r"# (.+?)\s*#*\s*$", line)):
30+
return match.group(1)
31+
32+
return markdown.stem
33+
34+
35+
def index_lines(items: list, docs: Path, depth: int = 0) -> list[str]:
36+
indent = " " * max(depth - 1, 0)
37+
lines: list[str] = []
38+
39+
for item in items:
40+
title, target = next(iter(item.items())) if isinstance(item, dict) else (None, item)
41+
42+
if isinstance(target, list):
43+
lines += ["", f"## {title}", ""] if depth == 0 else [f"{indent}- {title}"]
44+
lines += index_lines(target, docs, depth + 1)
45+
elif isinstance(target, str) and target.endswith(".md"):
46+
lines.append(f"{indent}- [{title or title_of(docs / target)}]({target})")
47+
48+
return lines
49+
50+
51+
def nav_pages(items: list) -> list[str]:
52+
pages: list[str] = []
53+
54+
for item in items:
55+
target = next(iter(item.values())) if isinstance(item, dict) else item
56+
57+
if isinstance(target, list):
58+
pages += nav_pages(target)
59+
elif isinstance(target, str) and target.endswith(".md"):
60+
pages.append(target)
61+
62+
return pages
63+
64+
65+
def main(config_path: Path) -> None:
66+
config = load(config_path)
67+
base = config_path.parent
68+
nav = config.get("nav") or load(base / config["INHERIT"]).get("nav", [])
69+
docs = base / config.get("docs_dir", "docs")
70+
site = base / config.get("site_dir", "site")
71+
72+
in_nav = nav_pages(nav)
73+
outside_nav = sorted(
74+
path.relative_to(docs).as_posix() for path in docs.rglob("*.md") if path.relative_to(docs).as_posix() not in in_nav
75+
)
76+
pages = in_nav + outside_nav
77+
78+
for page in pages:
79+
(site / page).write_text((docs / page).read_text(encoding="utf-8"), encoding="utf-8")
80+
81+
index = [f"# {config['site_name']}", "", f"> {config['site_description']}", "", *index_lines(nav, docs)]
82+
83+
if outside_nav:
84+
index += ["", "## Other pages", ""]
85+
index += [f"- [{title_of(docs / page)}]({page})" for page in outside_nav]
86+
87+
(site / "llms.txt").write_text("\n".join(index) + "\n", encoding="utf-8")
88+
(site / "llms-full.txt").write_text(
89+
"\n\n".join((docs / page).read_text(encoding="utf-8").strip() for page in pages) + "\n",
90+
encoding="utf-8",
91+
)
92+
93+
94+
if __name__ == "__main__":
95+
main(Path(sys.argv[1] if len(sys.argv) > 1 else "mkdocs.yml"))

‎hooks/llms.py‎

Lines changed: 0 additions & 54 deletions
This file was deleted.

‎mkdocs.yml‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,8 @@ validation:
7272
anchors: warn
7373

7474
watch:
75-
- hooks
7675
- overrides
7776

78-
hooks:
79-
- hooks/llms.py
80-
8177
markdown_extensions:
8278
- admonition
8379
- pymdownx.superfences

0 commit comments

Comments
 (0)