about summary refs log tree commit diff
path: root/strike.py
blob: 194c52d76ee724bdbd8cdd8c57f646cb8b2170ae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python3
from os import listdir, mkdir, path
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)')
    return parser.parse_args()

def read_config(location):
    config = ConfigParser()
    if path.isdir(location):
        location = location + '/strike.ini'
    if not path.exists(location):
        raise FileNotFoundError(f'Config file not found at {location}.')
    config.read(location)
    return path.dirname(path.abspath(location)), config

def handle_file(location):
    meta = 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:
        contents = fin.read()
    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, 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__':
    import sys
    sys.exit(main())