# Make Site # author: Jonathan Bernard # # Stupid-simple static site generator. Operates on the current working # directory. Outputs rendered HTML to a directory named 'rendered'. # # 1. Reads in an HTML template from a file 'template.html'. # 3. Walks the 'content' directory looking for files. # # a. For all files with the '.md' extension: # i. splits out optional front-matter (JSON), # ii. compiles the rest into HTML fragments, # iii. stuffs the fragments into the template, and # iv. writes an HTML file at the same relative path in the 'rendered' # directory with the same filename (extension changed to .html). # # b. For all other files, copies them verbatim into the same relative path # in the 'rendered' directory. import json, nre, os, osproc from strutils import endsWith, rfind # Read in the template let htmlTemplate = readFile("template.html") let contentKey = re"<%CONTENT%>" let mdExtRe = re"md$" let tempFile = "temp.make_site.md" # Make our output directory if necessary. if not dirExists("rendered"): createDir("rendered") # Walk the directory looking for .md files. for file in walkDirRec("content", {pcFile, pcDir, pcLinkToFile}): #echo "Considering " & file let dir = file[8..file.rfind('/')] let filename = file[(file.rfind('/') + 1)..^1] # Create output subdir if necessary if not existsDir("rendered/" & dir): createDir("rendered/" & dir) if filename.endsWith(".md"): echo "> Rendering " & dir & filename var renderedTemplate = htmlTemplate var mdDoc: string let outputFile = "rendered/" & dir & filename.replace(mdExtRe, "html") # Split out front-matter let docSplit = file.readFile.split(re"\+\+\+", 2) # Parse the front-matter (if there is any) if docSplit.len > 1: let metadata = json.parseJson(docSplit[0]) mdDoc = docSplit[1] for key, value in metadata: let replKey = re("<%" & key & "%>") renderedTemplate = htmlTemplate.replace(replKey, value.getStr) else: mdDoc = docSplit[0] # Compile the file into an HTML fragment writeFile(tempFile, mdDoc) let htmlDoc = execProcess("markdown " & tempFile) renderedTemplate = renderedTemplate.replace(contentKey, htmlDoc) writeFile(outputFile, renderedTemplate) else: echo "> Copying " & dir & filename copyFile(file, "rendered/" & dir & filename); removeFile(tempFile)