#! /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 + '\n' + 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 + '
\n' + evald_text + '
\n' except Exception as e: print("Error processing line {}:\n {}\nError: {}".format(i, line, e)) return None else: # just include the line! try: result = result + line.decode("utf-8") except Exception as e: print("Error processing line {}:\n {}\nError: {}".format(i, line, e)) return None return result if __name__ == "__main__": if len(sys.argv) != 2: print("Usage: {} ".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) 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)