zettel/hugo2zettel

71 lines
2.1 KiB
Python

#!/usr/bin/python3
import argparse
import html
import yaml
import psycopg
ap = argparse.ArgumentParser()
ap.add_argument("--author",default="hjp")
ap.add_argument("file")
args = ap.parse_args()
if args.file.endswith(".md"):
file_type = "markdown"
elif args.file.endswith(".html"):
file_type = "html"
else:
file_type = "plain"
with open(args.file) as fh:
section = None
frontmatter = ""
body = ""
for ln in fh:
if section is None and ln == "---\n":
section = "frontmatter"
elif section == "frontmatter" and ln == "---\n":
section = "body"
elif section == "frontmatter":
frontmatter += ln
elif section == "body":
body += ln
else:
raise RuntimeError("oops")
frontmatter = yaml.safe_load(frontmatter)
# We don't have a dedicated title. Just prepend it to the body
if file_type == "html":
body = "<h1>" + html.escape(frontmatter["title"]) + "</h1>" + "\n" \
+ body
else:
body = frontmatter["title"] + "\n" \
+ "=" * len(frontmatter["title"]) + "\n" \
+ "\n" \
+ body
ts = frontmatter.get("lastmod") or frontmatter.get("date")
conn = psycopg.connect(dbname="zettel")
csr = conn.cursor(row_factory=psycopg.rows.namedtuple_row)
csr.execute("select * from role where name = %s", (args.author,))
author_id = csr.fetchone().id
csr.execute(
"""
insert into post(text, ts, content_type, author) values(%s, %s, %s, %s)
returning id
""",
(body, ts, "text/" + file_type, author_id,))
post_id = csr.fetchone().id
for tag in frontmatter["tags"]:
csr.execute("select * from tag where lower(name) = lower(%s)",
(tag,)) # XXX - use citext?
r = csr.fetchone()
if not r:
csr.execute("insert into tag(name) values(%s) returning id",
(tag,))
r = csr.fetchone()
tag_id = r.id
csr.execute("insert into tag_post(tag, post) values(%s, %s)",
(tag_id, post_id,))
conn.commit()