Skip to content

Commit 1695527

Browse files
committed
docs: fix links to docs/
Due to the processing that is done on files outside of `docs/`, links to file _inside_ the `docs/` directory do not work. This adds a hook to MkDocs which rewrites these links. Signed-off-by: JP-Ellis <josh@jpellis.me>
1 parent 0cf605e commit 1695527

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

docs/scripts/rewrite-docs-links.py

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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+
)

mkdocs.yml

+3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ repo_url: https://github.com/pact-foundation/pact-python
66

77
edit_uri: edit/develop/docs
88

9+
hooks:
10+
- docs/scripts/rewrite-docs.links.py
11+
912
plugins:
1013
- search
1114
- literate-nav:

0 commit comments

Comments
 (0)