15 """Simple Mako renderer.
17 Just a wrapper around the mako rendering library.
27 from typing
import List
29 from mako
import exceptions
30 from mako.lookup
import TemplateLookup
31 from mako.runtime
import Context
32 from mako.template
import Template
35 PROJECT_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"..",
38 sys.path.append(os.path.join(PROJECT_ROOT,
'tools',
'buildgen',
'plugins'))
41 def out(msg: str) ->
None:
42 print(msg, file=sys.stderr)
46 out(
'mako-renderer.py [-o out] [-m cache] [-P preprocessed_input] [-d dict] [-d dict...]'
47 ' [-t template] [-w preprocessed_output]')
51 """Render the mako template with given context.
53 Prints an error template to indicate where and what in the template caused
57 template.render_context(context)
59 out(exceptions.text_error_template().
render())
63 def main(argv: List[str]) ->
None:
65 module_directory =
None
66 preprocessed_output =
None
71 got_preprocessed_input =
False
75 opts, args = getopt.getopt(argv,
'hM:m:o:t:P:')
76 except getopt.GetoptError:
83 out(
'Displaying showhelp')
88 out(
'Got more than one output')
94 if module_directory
is not None:
95 out(
'Got more than one cache directory')
98 module_directory = arg
100 if output_merged
is not None:
101 out(
'Got more than one output merged path')
106 assert not got_preprocessed_input
107 assert json_dict == {}
108 with open(arg,
'rb')
as dict_file:
109 dictionary = pickle.load(dict_file)
110 got_preprocessed_input =
True
116 srcs = list(yaml.load_all(f.read(), Loader=yaml.FullLoader))
118 if isinstance(src, str):
119 assert len(srcs) == 1
120 template = Template(src,
122 module_directory=module_directory,
123 lookup=TemplateLookup(directories=[
'.']))
124 with open(output_name,
'w')
as output_file:
131 if not os.path.exists(output_name):
133 elif os.path.isfile(output_name):
134 os.unlink(output_name)
136 shutil.rmtree(output_name, ignore_errors=
True)
140 for el
in dictionary[src[
'foreach']]:
142 args = dict(dictionary)
143 args[
'selected'] = el
144 if not eval(src[
'cond'], {}, args):
151 args = dict(dictionary)
152 args[
'selected'] = item
153 item_output_name = os.path.join(
155 Template(src[
'output_name']).
render(**args))
156 if not os.path.exists(os.path.dirname(item_output_name)):
157 os.makedirs(os.path.dirname(item_output_name))
161 module_directory=module_directory,
162 lookup=TemplateLookup(directories=[
'.']))
163 with open(item_output_name,
'w')
as output_file:
166 if not got_input
and not preprocessed_output:
167 out(
'Got nothing to do')
171 if __name__ ==
'__main__':