above_the_waters/generate.py

84 lines
2.0 KiB
Python

import html
import sys
import urllib.parse
template = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>__title__</title>
<style>
html { background-color: #eee; }
body {
margin: 1em auto;
max-width: 40em;
padding: 1em; padding-top: 0.2em; padding-bottom: 0.2em;
text-align: justify; font-size: 14pt;
background-color: #fff;
}
h1, h2, h3 { font-weight: bold; }
h1, h2, h3, h4, h5, h6 { text-align: left; }
em { font-style: italic; }
@media print {
body { max-width: none; padding: 0; }
}
</style>
</head>
<body>
<h1>__scene__</h1>
__description__
__choices__
</body>
</html>"""
def generate_html(name, scene, description, choices):
# HTML escape the plain text fields
name = html.escape(name)
scene = html.escape(scene)
# Create a list of paragraphs from the description array
description = ['<p>%s</p>' % html.escape(paragraph) for paragraph in description]
description = '\n'.join(description)
# Generate a list of links from choices array
choices = ['<li><a href="%s.html">%s</a></li>' % (urllib.parse.quote(target), text) for target, text in choices]
choices = '\n'.join(choices)
choices = '<ul>\n%s\n</ul>' % choices
title = '%s - %s' % (name, scene)
return template.replace('__title__', title).replace('__scene__', scene).replace('__description__', description).replace('__choices__', choices)
def parse_file(contents):
lines = contents.replace('\r\n', '\n').split('\n')
scene = lines[0]
description = []
choices = []
for line in lines[1:]:
if line[0:1] == '>':
# Choice
target, _, text = line[1:].strip().partition(' ')
choices.append((target, text))
else:
description.append(line)
description = '\n'.join(description).split('\n\n')
while '' in description:
description.remove('')
return scene, description, choices
def main():
name = sys.argv[1]
with open(sys.argv[2], 'r') as f:
contents = f.read()
scene, description, choices = parse_file(contents)
print(generate_html(name, scene, description, choices))
if __name__ == '__main__':
main()