build.py
Python script, ASCII text executable
1from Renderers import RenderTemplate, RenderMarkdown 2from sys import argv 3from shutil import rmtree as DeleteDirectory 4from os import mkdir as CreateDirectory, listdir as ListDirectory, unlink as DeleteFile 5from os.path import isfile as IsFile, exists as PathExists 6from distutils.dir_util import copy_tree as CopyDirectory 7from datetime import datetime 8 9GITHUB_BUILD_DIR = "docs" # Separate because this site is built with an action that won't work if they aren't 10LOCAL_BUILD_DIR = "build" 11 12BUILD_DIRECTORY = GITHUB_BUILD_DIR if len(argv) > 1 and argv[1] == "gh-pages-deploy" else LOCAL_BUILD_DIR 13 14PAGES = { 15"index.html": "index.html", 16"blog-list.html": "blog/index.html", 17"blog-feed.rss": "blog/feed.rss", 18"404.html": "404.html" 19} 20 21def WipeFinalDir(): 22if not PathExists(BUILD_DIRECTORY): 23CreateDirectory(BUILD_DIRECTORY) 24for item in ListDirectory(BUILD_DIRECTORY): 25path = BUILD_DIRECTORY + "/" + item 26if IsFile(path): 27DeleteFile(path) 28continue 29DeleteDirectory(path) 30 31def PostSortHelper(Post): 32return datetime.strptime(Post["date"], "%Y %b %d") 33 34def GetBlogList(): 35PostSlugs = ListDirectory("blog-posts") 36Posts = [] 37for slug in PostSlugs: 38with open("blog-posts/" + slug, encoding="utf-8") as MDFile: 39PostHTML = RenderMarkdown(MDFile.read()) 40Item = PostHTML.metadata 41Item["content"] = PostHTML 42Item["pathname"] = slug.replace(".md", ".html") 43Posts.append(Item) 44PostsByDate = sorted(Posts, key=PostSortHelper, reverse=True) 45return PostsByDate 46 47PostList = GetBlogList() 48 49def RenderPosts(): 50for post in ListDirectory("blog-posts"): 51path = "blog-posts/" + post 52RenderedHTML: str 53with open(path, "r", encoding="utf-8") as PostContent: 54PostHTML = RenderMarkdown(PostContent.read()) 55Title = PostHTML.metadata["title"] 56PostDate = PostHTML.metadata["date"] 57RenderedHTML = RenderTemplate("blog-post.html", Title=Title, PostDate=PostDate, Content=PostHTML) 58with open(BUILD_DIRECTORY + "/blog/" + post.replace(".md", ".html"), "w", encoding="utf-8") as PostLocation: 59PostLocation.write(RenderedHTML) 60 61def RenderPage(PageInput: str, ContentDest: str, **kwargs): 62with open(BUILD_DIRECTORY + "/" + ContentDest, "w", encoding="utf-8") as DestLocation: 63DestLocation.write(RenderTemplate(PageInput, **kwargs)) 64 65if __name__ == "__main__": 66print("Wiping directory") 67WipeFinalDir() 68print("Creating blog holder") 69CreateDirectory(BUILD_DIRECTORY + "/blog") 70print("Rendering posts") 71RenderPosts() 72print("Copying static directory") 73CopyDirectory("static", BUILD_DIRECTORY) 74 75print("Building pages") 76for file, path in PAGES.items(): 77RenderPage(file, path, PostList=PostList) 78 79pass