64 lines
1.8 KiB
Python
64 lines
1.8 KiB
Python
from mkdocs.utils import meta, write_file, clean_directory
|
|
from mkdocs.structure.files import File, Files
|
|
import tempfile
|
|
import os
|
|
|
|
TAGS_TEMP_DIR = tempfile.mkdtemp()
|
|
|
|
def on_post_build(*args, **kwargs):
|
|
clean_directory(TAGS_TEMP_DIR)
|
|
|
|
on_build_error = on_pre_build = on_post_build
|
|
|
|
def on_files(files: Files, config):
|
|
tags = set()
|
|
|
|
env = config["theme"].get_env()
|
|
|
|
template = env.get_template("tag-template.md")
|
|
list_template = env.get_template("tag-list-template.md")
|
|
|
|
for file in files.documentation_pages():
|
|
with open(file.abs_src_path) as f:
|
|
_, metadata = meta.get_data(f.read())
|
|
tags.update(metadata.get("tags", []))
|
|
|
|
for tag in tags:
|
|
if found_tag_page := files.get_file_from_path(f"tags/{tag}.md"):
|
|
with open(found_tag_page.abs_src_path) as f:
|
|
content, _ = meta.get_data(f.read())
|
|
|
|
files.remove(found_tag_page)
|
|
else:
|
|
content = ""
|
|
|
|
filename = f"tags/{tag}.md"
|
|
|
|
write_file(template.render(tag=tag, content=content).encode(), os.path.join(TAGS_TEMP_DIR, filename))
|
|
|
|
files.append(File(
|
|
path=filename,
|
|
src_dir=TAGS_TEMP_DIR,
|
|
dest_dir=config["site_dir"],
|
|
use_directory_urls=True
|
|
))
|
|
|
|
if found_index_page := files.get_file_from_path("tags/index.md"):
|
|
with open(found_index_page.abs_src_path) as f:
|
|
content, _ = meta.get_data(f.read())
|
|
|
|
files.remove(found_index_page)
|
|
else:
|
|
content = ""
|
|
|
|
write_file(list_template.render(content=content).encode(), os.path.join(TAGS_TEMP_DIR, "tags", "index.md"))
|
|
|
|
files.append(File(
|
|
path="tags/index.md",
|
|
src_dir=TAGS_TEMP_DIR,
|
|
dest_dir=config["site_dir"],
|
|
use_directory_urls=True
|
|
))
|
|
|
|
return files
|