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
70
|
#!/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']
try: exclusions = config['Input']['excludes'].splitlines()
except KeyError: exclusions = {}
default_template = basedir/config['Templates']['default']
template = default_template.read_text()
output_dir = basedir/config['Output']['directory']
for path, _, files in os.walk(input_dir):
loc = os.path.relpath(path, input_dir)
(output_dir/loc).mkdir(parents=True, exist_ok=True)
for file in files:
if file in exclusions:
continue
contents, meta = handle_file(input_dir/loc/file)
output = apply_template(contents, meta, template)
(output_dir/loc/file).write_text(output)
if __name__ == '__main__':
import sys
sys.exit(main())
|