|
| 1 | +""" |
| 2 | +Rewrite links to docs. |
| 3 | +
|
| 4 | +This hook is used to rewrite links within the documentation. Due to the way |
| 5 | +Markdown files are collected across the repository (specifically, within `docs/` |
| 6 | +and outside of `docs/`), links that cross this boundary don't already work |
| 7 | +correctly. |
| 8 | +
|
| 9 | +This hook is used to rewrite links dynamically. |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import re |
| 15 | +from typing import TYPE_CHECKING |
| 16 | + |
| 17 | +import mkdocs.plugins |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from mkdocs.config.defaults import MkDocsConfig |
| 21 | + from mkdocs.structure.files import Files |
| 22 | + from mkdocs.structure.pages import Page |
| 23 | + |
| 24 | + |
| 25 | +@mkdocs.plugins.event_priority(-50) |
| 26 | +def on_page_markdown( |
| 27 | + markdown: str, |
| 28 | + page: Page, # noqa: ARG001 |
| 29 | + config: MkDocsConfig, # noqa: ARG001 |
| 30 | + files: Files, # noqa: ARG001 |
| 31 | +) -> str | None: |
| 32 | + """ |
| 33 | + Rewrite links to docs. |
| 34 | +
|
| 35 | + Performs a simple regex substitution on the Markdown content. Specifically, |
| 36 | + any link to a file within `docs/{path}` is rewritten to just `/{path}`, and |
| 37 | + any links containing `../docs/..` are rewritten to just `../..`. |
| 38 | +
|
| 39 | + This is clearly fragile, but until a better solution is needed, this should |
| 40 | + be sufficient. |
| 41 | + """ |
| 42 | + # Find all links that start with `docs/` and rewrite them. |
| 43 | + markdown = re.sub( |
| 44 | + r"\]\((?P<link>docs/[^)]+)\)", |
| 45 | + lambda match: f"]({match.group('link')[5:]})", |
| 46 | + markdown, |
| 47 | + count=0, |
| 48 | + flags=re.MULTILINE, |
| 49 | + ) |
| 50 | + |
| 51 | + # Find links that have an embedded `/docs/` and rewrite them. |
| 52 | + return re.sub( |
| 53 | + r"\]\((?P<link>[^)]+/docs/[^)]+)\)", |
| 54 | + lambda match: f"]({match.group('link').replace('/docs/', '/')})", |
| 55 | + markdown, |
| 56 | + count=0, |
| 57 | + flags=re.MULTILINE, |
| 58 | + ) |
0 commit comments