#!/usr/bin/env python3
from os import listdir, mkdir, path
from sys import exit
from time import gmtime, strftime
from argparse import ArgumentParser
from configparser import ConfigParser
def handle_args():
parser = ArgumentParser()
parser.add_argument('config', help='location of strike.ini file (or a directory containing it)')
# does it make any sense to override the config file? probably not for cases involving multiple templates or excludes. but for simple ones i could see it
# parser.add_argument('--input', '-i', help='input directory (overrides config file)', default='')
# parser.add_argument('--output', '-o', help='output directory (overrides config file)', default='')
# parser.add_argument('--template', '-t', help='template to use (overrides config file)', default='')
return parser.parse_args()
def read_config(location):
parser = ConfigParser()
if path.isdir(location):
location = location + '/strike.ini'
if not path.exists(location):
raise FileNotFoundError(f'Config file not found at {location}.')
location = parser.read(location)
basedir = path.dirname(path.abspath(location[0]))
return basedir, parser
def handle_file(location):
meta_dict = dict(
title = '.'.join(path.basename(location).split('.')[:-1]),
date = strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(path.getmtime(location)))
)
with open(location, 'r') as fin:
file_contents = fin.read()
contents = handle_frontmatter(file_contents, meta_dict)
return contents, meta_dict
def handle_frontmatter(file_contents, meta_dict):
delim = '---\n'
if not file_contents.startswith(delim):
return file_contents
parts = file_contents.split(delim, maxsplit=2)
meta_lines = parts[1].splitlines()
meta = dict(
(x.strip(), y.strip())
for x, y in (kvp.split('=') for kvp in meta_lines)
)
meta_dict.update(meta)
return parts[2]
def apply_template(content, metadata, template="{content}"):
return template.format(
content = content,
meta = metadata
)
def main():
args = handle_args()
basedir, config = read_config(args.config)
input_dir = path.join(basedir, config['Input']['directory'])
exclusions = config['Input']['excludes'].splitlines()
default_template = path.join(basedir, config['Templates']['default'])
output_dir = path.join(basedir, config['Output']['directory'])
try: mkdir(output_dir)
except FileExistsError: pass
with open(default_template) as t:
template = t.read()
for file in listdir(input_dir):
if file in exclusions:
continue
file_contents, metadata = handle_file(path.join(input_dir, file))
output = apply_template(file_contents, metadata, template)
with open(path.join(output_dir, file), 'w') as fout:
fout.write(output)
if __name__ == '__main__':
exit(main())