-
Notifications
You must be signed in to change notification settings - Fork 1
/
parse_template.py
executable file
·100 lines (80 loc) · 2.11 KB
/
parse_template.py
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python3
import os
import sys
import json
import argparse
from jinja2 import Environment, FileSystemLoader, select_autoescape
def parse_args():
parser = argparse.ArgumentParser(
prog='parse_template',
description='a jinja template parser',
add_help=False
)
parser.add_argument(
'-h', '--help',
action='help',
help='display help message',
)
parser.add_argument(
'-D', '--define',
action='append',
nargs=2,
type=str,
metavar=('key', 'value'),
help='define data with key-value pairs',
)
parser.add_argument(
'-o', '--output',
nargs='?',
type=str,
metavar='file',
help='output file or "-" for stdout',
)
parser.add_argument(
'docdir',
type=str,
metavar='docdir',
help='Full documentation directory path',
)
parser.add_argument(
'template',
type=str,
metavar='template',
help='template file path relative to docdir',
)
return parser.parse_args()
def parse_value(value):
try:
return json.loads(value)
except ValueError:
return value
def main():
args = parse_args()
doc_dir = args.docdir
template_path = args.template
output = args.output or os.path.join(doc_dir, template_path)
data = {k: parse_value(v) for k, v in args.define or []}
env = Environment(
loader=FileSystemLoader(doc_dir),
autoescape=False,
block_start_string='<!-- {%',
block_end_string='%} -->',
variable_start_string='<!-- {{',
variable_end_string='}} -->',
comment_start_string='<!-- {#',
comment_end_string='#} -->',
auto_reload=True,
trim_blocks=True,
lstrip_blocks=True
)
template = env.get_template(template_path)
if output == '-':
print(template.render(**data))
else:
fout = open(output, 'w')
try:
fout.write(template.render(**data))
finally:
fout.close()
if __name__ == '__main__':
main()