diff --git a/documentation.py b/documentation.py index 670a89c..5737a19 100644 --- a/documentation.py +++ b/documentation.py @@ -9,7 +9,7 @@ import git # type: ignore from config import Config from git_utils import get_first_remote -from markdown_utils import rewrite_image_paths +from markdown_utils import rewrite_image_paths, rewrite_image_paths_for_website from project import Project @@ -175,6 +175,11 @@ class Docs: yaml_data["weight"] = project.index + 1 yaml_data["git_action"] = project.get_workflow_url_when_submitted() yaml_data["shuttle_id"] = self.config["id"] + yaml_data["user_docs"] = rewrite_image_paths_for_website( + yaml_data["user_docs"], + os.path.join(project.src_dir, "docs"), + project_image_dir, + ) doc = doc_template.format(**yaml_data) with open(os.path.join(project_dir, "_index.md"), "w") as pfh: diff --git a/markdown_utils.py b/markdown_utils.py index a9d9426..642f3ed 100644 --- a/markdown_utils.py +++ b/markdown_utils.py @@ -1,4 +1,5 @@ import os +import shutil from typing import Any, Dict import mistune @@ -42,3 +43,34 @@ class ImagePathRewriterRenderer(MarkdownRenderer): def rewrite_image_paths(source: str, prefix: str) -> str: markdown = mistune.create_markdown(renderer=ImagePathRewriterRenderer(prefix)) return markdown(source) + + +class WebsiteImagePathRewriterRenderer(MarkdownRenderer): + def __init__(self, source_dir: str, target_dir: str): + super().__init__() + self.source_dir = source_dir + self.target_dir = target_dir + + def image(self, token, state): + url = token["attrs"]["url"] + if ".." in url: + token["attrs"]["url"] = "" + elif "://" not in url and not url.startswith("/"): + filename = os.path.basename(url) + if url.startswith("/"): + url = "../" + url[1:] + shutil.copyfile( + os.path.join(self.source_dir, url), + os.path.join(self.target_dir, filename), + ) + token["attrs"]["url"] = f"images/{filename}" + return super().image(token, state) + + +def rewrite_image_paths_for_website( + source: str, source_dir: str, target_dir: str +) -> str: + markdown = mistune.create_markdown( + renderer=WebsiteImagePathRewriterRenderer(source_dir, target_dir) + ) + return markdown(source)