summaryrefslogtreecommitdiff
path: root/generator/generate.py
blob: 494ad0c124fc636e3ea6cde2fe24e2397178df40 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#! /usr/bin/env python3

import sys
import os
import subprocess

def replace_references(lines, file_dir):
    result = ""
    for (i, line) in enumerate(lines):
        if line.startswith("#include "):
# include that file directly
            # find the file as a path relative to the file we opened..
            filepath = file_dir + line[len("#include "):].strip()
            try:
                f = open(filepath)
                content = f.read()
                result = result + content
            except Exception as err:
                print("Error reading file {}:{}".format(filepath, str(err)))
                return None
        elif line.startswith("#eval "):
# include results of system'ing that line
            try:
                command = line[6:].strip()
                eval_p = subprocess.Popen(['bash', '-c', command], stdout=subprocess.PIPE, stdin=subprocess.PIPE, cwd=file_dir)
                evald_text = eval_p.communicate()[0].decode('utf-8')
                if evald_text is None or len(evald_text.strip()) == 0:
                    raise Exception("Evaluating `{}` produced no output".format(command))
                result = result + '<pre>\n' + evald_text + '</pre>\n'
            except Exception as e:
                print("Error processing line {}:\n  {}\nError: {}".format(i, line, e))
                return None
        else:
# just include the line!
            result = result + line
    return result

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: {} <page_to_compile>".format(sys.argv[0]))

    md_source = sys.argv[1]
    ridx = md_source.rfind('.')
    if ridx >= len(md_source) - 5:
        page_path = md_source[:ridx]
    else:
        page_path = md_source
    page_path = page_path + ".html"
    page_cwd = './'
    if '/' in page_path:
        page_cwd = page_path[:(md_source.rfind('/') + 1)]
        page_path = page_path[(md_source.rfind('/') + 1):]

    headers_file = './headers.html'

    compiled_dest = './generated/{}{}'.format(page_cwd, page_path).replace('source/', '')
    dest_wd = compiled_dest[:compiled_dest.rfind('/') + 1]
    print("Source: {}\nPage path: {}\nDest file: {}".format(md_source, page_path, compiled_dest))
    try:
        md_file = open(md_source)
        lines = md_file.readlines()

        print("Compiling {}".format(md_source))

        markdown_blob = replace_references(lines, page_cwd)
        if markdown_blob == None:
            print("Error compiling {}".format(md_source))
            sys.exit(3)
        # now shove it all through pandoc
        pandoc_proc = subprocess.Popen(['pandoc', '--template=content_template.pandoc'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
        html = pandoc_proc.communicate(markdown_blob.encode('utf-8'))[0]
        try:
            if not os.path.isdir(dest_wd):
                os.makedirs(dest_wd)
            out_file = open(compiled_dest, 'w')
            out_file.write(html.decode('utf-8'))
            out_file.close()
        except IOError as ioerr:
            print("Unknown error writing result: " + str(ioerr))
            sys.exit(2)
    except IOError as ioerr:
        if ioerr.errno == 2:
            print("Source file '{}' does not exist".format(md_source))
        else:
            print("Unknown ioerr: " + str(ioerr))
        sys.exit(1)