import glob
import json
import sys
toc = []
inpatt = sys.argv[1] if len(sys.argv) > 1 else 'toc-*.json'
outpath = sys.argv[2] if len(sys.argv) > 2 else 'toc.json'
outpath_html = outpath + '.html'
for path in glob.glob(inpatt):
local_toc = json.load(open(path, 'r'))
toc.extend(local_toc)
toc = sorted(toc, key=lambda e: e['page'])
print(toc)
with open(outpath, 'w') as out:
json.dump(toc, out, ensure_ascii=False)
print('Wrote {}'.format(outpath))
######
# Templates for generated html
global_template = """
"""
index_letter_template = """
{letter}
"""
toc_row_template = """
"""
######
# Constructing the index
toc_html = ""
for r in toc:
toc_html += toc_row_template.format(level=r['level'], label=r['label'], pagenumber=r['page'])
body = global_template.format(toc=toc_html)
#######
# Write to an html file
with open("header.html", "r", encoding="utf-8") as input_file:
h = input_file.read()
# Insert id in header based on filename
h = h.replace("{{ id }}", "toc")
with open("footer.html", "r", encoding="utf-8") as input_file:
f = input_file.read()
with open(outpath_html, "w", encoding="utf-8") as o:
o.write('{header} {body} {footer}'.format(header=h, body=body, footer=f))
print('Wrote {}'.format(outpath_html))