From 7e3060cc02aacecd13ba220cf69d1b8ae2517e09 Mon Sep 17 00:00:00 2001 From: neodarz Date: Sun, 26 May 2019 15:46:29 +0200 Subject: Move generate_index to external file --- generators/generators.py | 64 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) (limited to 'generators/generators.py') diff --git a/generators/generators.py b/generators/generators.py index 1792fa57..06a34743 100644 --- a/generators/generators.py +++ b/generators/generators.py @@ -8,6 +8,9 @@ import re import bs4 import dateutil +import io +import subprocess + from config.config import * @@ -284,3 +287,64 @@ def generate_notes_list(): with open("build/notes/index.html", 'w', encoding='utf-8') as indexmd: for line in lines: indexmd.write(re.sub(r'{% generate notes_list here %}', div_notes_list, line)) + + +def generate_index(feed): + """Generate index.html from index.md and a TOC.""" + + sys.stderr.write("generating index.html\n") + + # generate TOC + tocbuff = io.StringIO() + tocbuff.write('
') + year = 10000 # will be larger than the latest year for quite a while + # recall that entries are in reverse chronological order + table_opened = False + for entry in feed.entries: + date = entry.updated_datetime + if date.year < year: + # close the previous table if there is one + if table_opened: + tocbuff.write(u'\n') + # write a new

tag with the smaller year + year = date.year + tocbuff.write(u'\n

.:{0}:.

\n\n'.format(year)) + tocbuff.write(u'\n') + table_opened = True + + # write a new table row entry in Markdown, in the format: + # + # + # + # + # + monthday = date.strftime("%b %d") + tocbuff.write(u'' + '\n' % + (date.isoformat(), monthday, entry.title_text, entry.relpath)) + if table_opened: + tocbuff.write(u'
[Blah blah](/blog/2015-05-04-blah-blah.html)
[%s](%s)
\n') + tocbuff.write('
') + + # create tempfile with index.md and the TOC concatenated, and generate index.html from that + # pylint: disable=invalid-name + fd, tmppath = tempfile.mkstemp() + os.close(fd) + with open(tmppath, 'w', encoding='utf-8') as tmpfile: + if os.path.exists(INDEXMD): + with open(INDEXMD, 'r', encoding='utf-8') as indexmd: + tmpfile.write(u"%s\n\n
\n\n" % indexmd.read()) + tmpfile.write("%s\n" % tocbuff.getvalue()) + tocbuff.close() + + pandoc_args = [ + "pandoc", tmppath, + "--template", HTMLTEMPLATE, + "--highlight-style=pygments", + "-o", INDEXHTML, + ] + try: + subprocess.check_call(pandoc_args) + except subprocess.CalledProcessError: + sys.stderr.write("error: failed to generate index.html\n") + os.remove(tmppath) -- cgit v1.2.1