docs site: rewrite directory-style links to their landing pages
A MkDocs hook turns links like [incidents/](incidents/) — which Gitea renders as a directory listing but a static site would resolve against the page URL — into links to the generated landing page for that directory.
This commit is contained in:
1 parent
2d3291d493
commit
387269e245
3 files changed
+44
No files matched your search
@@ -34,6 +34,7 @@ tar cf - \
|
||||
--exclude='.site-build' \
|
||||
--exclude='.venv-docs' \
|
||||
--exclude='*.sh' \
|
||||
--exclude='*.py' \
|
||||
--exclude='publishing/webhook-receiver.py' \
|
||||
--exclude='publishing/webhook-receiver.service' \
|
||||
--exclude='mkdocs.yml' \
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"""MkDocs hook: make directory-style links work on a static site.
|
||||
|
||||
The documents sometimes link to a directory the way Gitea renders it, e.g.
|
||||
infrastructure.md contains [`incidents/`](incidents/). On a static site with
|
||||
directory URLs, that href resolves relative to the *page* (giving
|
||||
/infrastructure/incidents/ and a 404). This hook rewrites such links to the
|
||||
generated landing page for that directory (build.sh creates
|
||||
<dir>/index.md for documented directories that lack one). It never edits the
|
||||
documents themselves.
|
||||
"""
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
|
||||
from mkdocs.utils import get_relative_url
|
||||
|
||||
_HREF = re.compile(r'(href=)("([^"]+)/")')
|
||||
|
||||
|
||||
def on_page_content(html, page, config, files):
|
||||
index_urls = {}
|
||||
for f in files:
|
||||
src = f.src_path
|
||||
if src.endswith("/index.md"):
|
||||
index_urls[posixpath.dirname(src)] = f.url
|
||||
|
||||
page_dir = posixpath.dirname(page.file.src_path)
|
||||
|
||||
def fix(match):
|
||||
href = match.group(3)
|
||||
if href.startswith(("http://", "https://", "/", "#")):
|
||||
return match.group(0)
|
||||
target = posixpath.normpath(posixpath.join(page_dir, href))
|
||||
if target in (".", "..") or target not in index_urls:
|
||||
return match.group(0)
|
||||
return f'{match.group(1)}"{get_relative_url(index_urls[target], page.file.url)}"'
|
||||
|
||||
return _HREF.sub(fix, html)
|
||||
Reference in new issue
Block a user