-
Notifications
You must be signed in to change notification settings - Fork 0
/
render
executable file
·78 lines (60 loc) · 2.04 KB
/
render
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
71
72
73
74
75
76
77
78
#!venv/bin/python
import os
import shutil
import sys
import pystache
import yaml
TEMPLATE_DIR = 'templates'
OUT_DIR = 'out'
def get_theme(theme_path):
'''
Returns an object representation of the YAML file at theme_path, or None if
the file cannot be parsed/read.
'''
try:
with open(theme_path) as theme_file:
return yaml.safe_load(theme_file)
except:
return None
def render(template_path, theme, out_path):
'''
Renders template_path to out_path, using the theme configuration
object, and creating directories as necessary.
'''
with open(template_path, encoding='utf8') as template_file:
try:
rendered = pystache.Renderer(missing_tags='strict') \
.render(template_file.read(), theme)
except pystache.context.KeyNotFoundError as e:
raise KeyError(e.key)
# Need to ensure base directories exist
os.makedirs(os.path.dirname(out_path), exist_ok=True)
with open(out_path, 'w', encoding='utf8') as out:
out.write(rendered)
def main():
if len(sys.argv) != 2:
sys.exit('Usage: {} theme.yml'.format(sys.argv[0]))
theme_file = sys.argv[1]
theme = get_theme(theme_file)
if theme is None:
sys.exit('Could not read theme {}'.format(theme_file))
# Gather all template files
templates = set()
for dirpath, dirs, files in os.walk(TEMPLATE_DIR):
templates.update(map(lambda f: os.path.join(dirpath, f), files))
has_missing = False
for template_path in templates:
out_path = template_path.replace(TEMPLATE_DIR, OUT_DIR, 1)
try:
render(template_path, theme, out_path)
except KeyError as e:
has_missing = True
print('{}: missing tag {} (others may also be missing)'.format(
template_path, str(e)))
continue
# Copy permissions to keep scripts executable
shutil.copymode(template_path, out_path)
if has_missing:
sys.exit(1)
if __name__ == '__main__':
main()