Update mojo sdk to rev 59145288bae55b0fce4276b017df6a1117bcf00f
[chromium-blink-merge.git] / mojo / public / tools / bindings / pylib / mojom / generate / template_expander.py
blob94db92e40fb2aca4b5b19124b4765a60490a05f9
1 # Copyright 2013 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
5 # Based on:
6 # http://src.chromium.org/viewvc/blink/trunk/Source/build/scripts/template_expander.py
8 import imp
9 import inspect
10 import os.path
11 import sys
13 # Disable lint check for finding modules:
14 # pylint: disable=F0401
16 def _GetDirAbove(dirname):
17 """Returns the directory "above" this file containing |dirname| (which must
18 also be "above" this file)."""
19 path = os.path.abspath(__file__)
20 while True:
21 path, tail = os.path.split(path)
22 assert tail
23 if tail == dirname:
24 return path
26 try:
27 imp.find_module("jinja2")
28 except ImportError:
29 sys.path.append(os.path.join(_GetDirAbove("public"), "public/third_party"))
30 import jinja2
33 def ApplyTemplate(mojo_generator, base_dir, path_to_template, params,
34 filters=None, **kwargs):
35 template_directory, template_name = os.path.split(path_to_template)
36 path_to_templates = os.path.join(base_dir, template_directory)
37 loader = jinja2.FileSystemLoader([path_to_templates])
38 final_kwargs = dict(mojo_generator.GetJinjaParameters())
39 final_kwargs.update(kwargs)
40 jinja_env = jinja2.Environment(loader=loader, keep_trailing_newline=True,
41 **final_kwargs)
42 jinja_env.globals.update(mojo_generator.GetGlobals())
43 if filters:
44 jinja_env.filters.update(filters)
45 template = jinja_env.get_template(template_name)
46 return template.render(params)
49 def UseJinja(path_to_template, **kwargs):
50 # Get the directory of our caller's file.
51 base_dir = os.path.dirname(inspect.getfile(sys._getframe(1)))
52 def RealDecorator(generator):
53 def GeneratorInternal(*args, **kwargs2):
54 parameters = generator(*args, **kwargs2)
55 return ApplyTemplate(args[0], base_dir, path_to_template, parameters,
56 **kwargs)
57 GeneratorInternal.func_name = generator.func_name
58 return GeneratorInternal
59 return RealDecorator