Skip to content

Instantly share code, notes, and snippets.

@maphew
Created September 14, 2021 23:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maphew/cb25a1f798b4b6a9d8441280c0b1fc31 to your computer and use it in GitHub Desktop.
Save maphew/cb25a1f798b4b6a9d8441280c0b1fc31 to your computer and use it in GitHub Desktop.
Generate a blog-style index page written in markdown
"""Generate a blog-style index page written in markdown.
A header line with link to page, followed by a few lines of the story.
"""
import os
from pathlib import Path
import dateutil.parser
from inspect import getsourcefile
here = os.path.dirname(os.path.abspath(getsourcefile(lambda:0)))
src = os.path.join(here, "blog")
page = "index-blog.md"
docs = Path(src).rglob("*.md")
def parse_endmatter(lines):
"""Look for yaml style metadata at end of file and attempt to parse it.
Only 'date' for now and ignoring any others.
"""
# date to use if no date is found
parsed_date = dateutil.parser.parse("1970")
for line in reversed(lines):
if line.startswith("---"):
break
# remove formatting with '*' or '_' from outer ends, also whitespace
line = line.strip().lstrip('*_').rstrip('*_')
if line.lower().startswith('date:'):
mydate = line.split('date:')[1]
# print(mydate)
parsed_date = dateutil.parser.parse(mydate)
return parsed_date
posts = {}
for f in docs:
if not f.name.startswith("index"):
doc = Path(f.resolve())
link_path = Path(f.resolve()).relative_to(src).as_posix()
text = []
with open(f.resolve(), encoding="utf8") as ff:
lines = ff.readlines()
doc_date = parse_endmatter(lines)
# convert header level 1 to level 2 and link to the page
title = lines[0].rstrip().lstrip("# ")
text.append(f"## [{title}]({link_path}) <sup>{doc_date.date()}</sup>\n\n")
# write blog intro
text.append(''.join(lines[2:6]).rstrip())
text.append(f" [(...)]({link_path})\n\n")
# text.append(f"_{doc_date.date()}_\n\n")
posts[link_path] = [doc_date, text]
with open(os.path.join(src,page), 'w') as out_file:
out_file.write("# Blog\n\n")
# Posts is dict of (relative file path): (date), (intro blurb text)
sorted_posts = sorted(posts.items(), key=lambda item:item[1], reverse=True)
for p in sorted_posts:
out_file.writelines(p[1][1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment