52 lines
1.8 KiB
Nim
52 lines
1.8 KiB
Nim
|
# Make Site
|
||
|
# author: Jonathan Bernard <jonathan@jdbernard.com>
|
||
|
#
|
||
|
# Stupid-simple static site generator. Operates on the current working
|
||
|
# directory. Outputs rendered HTML to a directory named 'rendered'. Reads in an
|
||
|
# HTML template from a file 'template.html'. Walks the current working directory
|
||
|
# looking for files with the '.rst' extension, splits out optional front-matter
|
||
|
# (JSON), compiles the rest into HTML fragments, stuffs the fragments into the
|
||
|
# template and write an HTML file at the same relative path in the 'rendered'
|
||
|
# directory with the same filename (extension changed to .html).
|
||
|
|
||
|
import os, nre, json, strtabs
|
||
|
import packages/docutils/rstgen
|
||
|
from strutils import endsWith, rfind
|
||
|
|
||
|
# Read in the template
|
||
|
let htmlTemplate = readFile("template.html")
|
||
|
let contentKey = re"<%CONTENT%>"
|
||
|
let rstExtRe = re"rst$"
|
||
|
|
||
|
# Make our output directory if necessary.
|
||
|
if not dirExists("rendered"): createDir("rendered")
|
||
|
|
||
|
# Walk the directory looking for .rst files.
|
||
|
for file in walkDirRec("."):
|
||
|
if not file.endsWith(".rst"): continue
|
||
|
|
||
|
var renderedTemplate = htmlTemplate
|
||
|
var rstDoc: string
|
||
|
let outputFile = "rendered/" & file.replace(rstExtRe, "html")
|
||
|
let outputDir = "rendered/" & file[0..file.rfind('/')]
|
||
|
|
||
|
if not existsDir(outputDir): createDir(outputDir)
|
||
|
|
||
|
# 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])
|
||
|
rstDoc = docSplit[1]
|
||
|
for key, value in metadata:
|
||
|
let replKey = re("<%" & key & "%>")
|
||
|
renderedTemplate = htmlTemplate.replace(replKey, value.getStr)
|
||
|
else: rstDoc = docSplit[0]
|
||
|
|
||
|
# Compile the file into an HTML fragment
|
||
|
let htmlDoc = rstToHtml(rstDoc, {}, newStringTable())
|
||
|
renderedTemplate = renderedTemplate.replace(contentKey, htmlDoc)
|
||
|
|
||
|
writeFile(outputFile, renderedTemplate)
|