about summary refs log tree commit diff
path: root/strike.py
blob: b417bf1e271d3e3b00a52563c9ab70b9970191a1 (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
#!/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):
    metadata = 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()
    return file_contents, metadata

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())