diff --git a/content/nested/sibling.md b/content/nested/sibling.md index 9933f1a..6230c80 100644 --- a/content/nested/sibling.md +++ b/content/nested/sibling.md @@ -1 +1,6 @@ +--- +redirects: + - /sibling +--- + # Sibling diff --git a/hooks/redirects.py b/hooks/redirects.py new file mode 100644 index 0000000..b660a8f --- /dev/null +++ b/hooks/redirects.py @@ -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) diff --git a/mkdocs.yml b/mkdocs.yml index 23e659b..991ca58 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -14,6 +14,7 @@ hooks: - hooks/images.py - hooks/page-render.py - hooks/static.py + - hooks/redirects.py markdown_extensions: - attr_list