#!/usr/bin/env python3 """ Convert RFC822 headers into an ABlog post directive. """ import sys import os import email import pathlib import datetime import logging import argparse from dateutil import parser prog = os.path.basename(sys.argv[0]) doc = __doc__.strip() logger = logging.getLogger(prog) TEMPLATE_DEFAULT = pathlib.Path(__file__).parents[1] / "post.rst.in" arg_parser = argparse.ArgumentParser( prog=prog, description=doc) arg_parser.add_argument( "--template-file", type=argparse.FileType("r"), help=f"The reStructuredText template for a post directive " f"(default: {TEMPLATE_DEFAULT})") arg_parser.add_argument( "properties_file", nargs="?", type=argparse.FileType("r"), default=sys.stdin, help="The RFC822 properties file to convert (default: stdin)") arg_parser.add_argument( "rst_path", metavar="rst_file", type=pathlib.Path, help="The reStructuredText file to add the post directive to") def main( properties_file=arg_parser.get_default("properties_file"), rst_path=arg_parser.get_default("rst_path"), template_file=arg_parser.get_default("template_file"), ): properties_parsed = email.message_from_file(properties_file) properties = dict(properties_parsed) properties["now"] = datetime.datetime.now() properties["subject"] = ( properties["subject"].split("\n ") if properties["subject"].strip() else [] ) properties["keywords"] = properties["tags"] = "" if properties["subject"]: properties["keywords"] = "\n :keywords: {}".format( ", ".join(properties["subject"]), ) properties["tags"] = "\n :tags: {}".format( ", ".join(properties["subject"]), ) for property_name, property_value in list(properties.items()): if not (property_name.endswith("_date") or property_name.endswith("Date")): continue if property_value.lower().strip() == "none": property_value = None else: try: property_value = parser.parse(property_value) except parser.ParserError: property_value = parser.parse(property_value.rsplit(" ", 1)[0]) properties[property_name] = property_value properties["title_underline"] = "#" * len(properties["title"]) properties["description_underline"] = "*" * len(properties["description"]) body = "" if rst_path.exists(): with rst_path.open() as rst_file: body = rst_file.read() properties["body"] = body if template_file is None: template_file = TEMPLATE_DEFAULT.open() template = template_file.read() directive = template.format(**properties) with rst_path.open(mode="w") as rst_file: rst_file.write(directive) main.__doc__ = __doc__ if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) args = arg_parser.parse_args() main(**vars(args))