#!/usr/bin/env python3 import os from time import gmtime, strftime from argparse import ArgumentParser from configparser import ConfigParser from pathlib import Path def handle_args(): parser = ArgumentParser() parser.add_argument('config', help='location of strike.ini file (or a directory containing it)') return parser.parse_args() def read_config(location): location = Path(location) config = ConfigParser() if location.is_dir(): location = location/'strike.ini' if not location.exists(): raise FileNotFoundError(f'Config file not found at {location}.') config.read(location) return location.resolve().parent, config def handle_file(file): meta = dict( title = file.stem, date = strftime('%a, %d %b %Y %H:%M:%S GMT', gmtime(file.stat().st_mtime)) ) contents = file.read_text() delim = '---\n' if contents.startswith(delim): parts = contents.split(delim, maxsplit=2) meta.update(dict((key.strip(), value.strip()) for key, value in (line.split('=') for line in parts[1].splitlines()) )) contents = parts[2] return contents, meta def apply_template(content, meta, template="{content}"): return template.format( content = content, meta = meta ) def main(): args = handle_args() basedir, config = read_config(args.config) input_dir = basedir/config['Input']['directory'] exclusions = config['Input']['excludes'].splitlines() default_template = basedir/config['Templates']['default'] template = default_template.read_text() output_dir = basedir/config['Output']['directory'] output_dir.mkdir(parents=True, exist_ok=True) for file in os.listdir(input_dir): if (input_dir/file).is_dir(): continue if file in exclusions: continue contents, meta = handle_file(input_dir/file) output = apply_template(contents, meta, template) (output_dir/file).write_text(output) if __name__ == '__main__': import sys sys.exit(main())