1
Fork 0

Write nginx-compatible map file for redirects

This commit is contained in:
Jake Howard 2023-09-12 22:42:33 +01:00
parent 8038bb819d
commit d2777ba027
Signed by: jake
GPG key ID: 57AFB45680EDD477
3 changed files with 40 additions and 0 deletions

View file

@ -1 +1,6 @@
---
redirects:
- /sibling
---
# Sibling # Sibling

34
hooks/redirects.py Normal file
View file

@ -0,0 +1,34 @@
from mkdocs.structure.pages import Page
from mkdocs.structure.files import Files
from mkdocs.exceptions import PluginError
import os
from mkdocs.utils import write_file
REDIRECTS = dict()
def on_pre_build(config):
REDIRECTS.clear()
def on_page_markdown(markdown, page: Page, config, files: Files):
if not (redirects := page.meta.get("redirects")):
return
for redirect in redirects:
if files.get_file_from_path(redirect):
raise PluginError(f"Cannnot redirect to {page.url}, source {redirect} already exists")
if redirect in REDIRECTS:
raise PluginError(f"Redirect from {redirect} already exists: {REDIRECTS[redirect]}")
REDIRECTS[redirect] = f"/{page.url}"
def on_post_build(config):
redirect_file = os.path.join(config["site_dir"], ".config", "redirects.txt")
redirects = "\n".join(
f"{src}\t{dest};"
for src, dest in REDIRECTS.items()
)
write_file(redirects.encode(), redirect_file)

View file

@ -14,6 +14,7 @@ hooks:
- hooks/images.py - hooks/images.py
- hooks/page-render.py - hooks/page-render.py
- hooks/static.py - hooks/static.py
- hooks/redirects.py
markdown_extensions: markdown_extensions:
- attr_list - attr_list