1
Fork 0
mkdocs-site/hooks/redirects.py

34 lines
994 B
Python

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)