Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Python script to compile .shtml files with server side includes down to flat HTML suitable for hosting on S3 or where SSIs aren't supported.
#! /usr/bin/env python
import os
import re
import shutil
from os.path import splitext
SOURCE = os.getcwd() + "/www/"
TARGET = os.getcwd() + "/compiled/"
if not os.path.exists(TARGET):
regex = re.compile(r'<!--#include virtual="([^"]*)" -->')
file_contents = lambda filename: open(filename).read()
match_ssi = lambda match: ssi(file_contents('%s%s' % (SOURCE,
ssi = lambda txt: regex.sub(match_ssi, txt)
def get_extension(filename):
>>> get_extension("index.shtml")
>>> get_extension("noextension")
return splitext(filename)[1].lower()[1:]
def change_extension(filename, new_extension):
>>> change_extension("index.shtml", "html")
>>> change_extension("something.jpg", "png")
>>> change_extension("noextension", "txt")
return "%s.%s" % (splitext(filename)[0].lower()[:], new_extension)
def process_file(filename):
print "Processing %s" % filename
return ssi(file_contents(filename))
print "Compiling site."
print "Source: %s" % SOURCE
print "Target: %s" % TARGET
for root, dirs, files in os.walk(SOURCE):
for filename in files:
name = os.path.join(root, filename)
relative_path = name.replace(SOURCE, "")
new_filename = os.path.join(TARGET, relative_path)
new_path = os.path.dirname(new_filename)
if not os.path.exists(new_path):
print "Writing %s" % new_filename
extension = get_extension(name)
if extension in ["shtml", ]:
# we need to do some processing on this extension type
new_content = process_file(name)
new_filename = change_extension(new_filename, "html")
f = open(new_filename, 'w')
# otherwise we just do a straight copy
shutil.copy(name, new_filename)

This comment has been minimized.

Copy link

@lewiscollard lewiscollard commented May 22, 2014

You just saved me writing this! Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.