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"link-tree.html": "link-tree.html", 19"404.html": "404.html" 20} 21 22def WipeFinalDir(): 23if not PathExists(BUILD_DIRECTORY): 24CreateDirectory(BUILD_DIRECTORY) 25for item in ListDirectory(BUILD_DIRECTORY): 26path = BUILD_DIRECTORY + "/" + item 27if IsFile(path): 28DeleteFile(path) 29continue 30DeleteDirectory(path) 31 32def PostSortHelper(Post): 33return datetime.strptime(Post["date"], "%Y %b %d") 34 35def GetBlogList(): 36PostSlugs = ListDirectory("blog-posts") 37Posts = [] 38for slug in PostSlugs: 39with open("blog-posts/" + slug, encoding="utf-8") as MDFile: 40PostHTML = RenderMarkdown(MDFile.read()) 41Item = PostHTML.metadata 42Item["content"] = PostHTML 43Item["pathname"] = slug.replace(".md", ".html") 44Posts.append(Item) 45PostsByDate = sorted(Posts, key=PostSortHelper, reverse=True) 46return PostsByDate 47 48PostList = GetBlogList() 49 50def RenderPosts(): 51for post in ListDirectory("blog-posts"): 52path = "blog-posts/" + post 53RenderedHTML: str 54with open(path, "r", encoding="utf-8") as PostContent: 55PostHTML = RenderMarkdown(PostContent.read()) 56Title = PostHTML.metadata["title"] 57PostDate = PostHTML.metadata["date"] 58RenderedHTML = RenderTemplate("blog-post.html", Title=Title, PostDate=PostDate, Content=PostHTML) 59with open(BUILD_DIRECTORY + "/blog/" + post.replace(".md", ".html"), "w", encoding="utf-8") as PostLocation: 60PostLocation.write(RenderedHTML) 61 62def RenderPage(PageInput: str, ContentDest: str, **kwargs): 63with open(BUILD_DIRECTORY + "/" + ContentDest, "w", encoding="utf-8") as DestLocation: 64DestLocation.write(RenderTemplate(PageInput, **kwargs)) 65 66if __name__ == "__main__": 67print("Wiping directory") 68WipeFinalDir() 69print("Creating blog holder") 70CreateDirectory(BUILD_DIRECTORY + "/blog") 71print("Rendering posts") 72RenderPosts() 73print("Copying static directory") 74CopyDirectory("static", BUILD_DIRECTORY) 75 76print("Building pages") 77for file, path in PAGES.items(): 78RenderPage(file, path, PostList=PostList) 79 80pass