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. 4 5# Based on: 6# http://src.chromium.org/viewvc/blink/trunk/Source/build/scripts/template_expander.py 7 8import imp 9import inspect 10import os.path 11import sys 12 13# Disable lint check for finding modules: 14# pylint: disable=F0401 15 16def _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 25 26try: 27 imp.find_module("jinja2") 28except ImportError: 29 sys.path.append(os.path.join(_GetDirAbove("mojo"), "third_party")) 30import jinja2 31 32 33def ApplyTemplate(base_dir, path_to_template, params, filters=None, **kwargs): 34 template_directory, template_name = os.path.split(path_to_template) 35 path_to_templates = os.path.join(base_dir, template_directory) 36 loader = jinja2.FileSystemLoader([path_to_templates]) 37 jinja_env = jinja2.Environment(loader=loader, keep_trailing_newline=True, 38 **kwargs) 39 if filters: 40 jinja_env.filters.update(filters) 41 template = jinja_env.get_template(template_name) 42 return template.render(params) 43 44 45def UseJinja(path_to_template, **kwargs): 46 # Get the directory of our caller's file. 47 base_dir = os.path.dirname(inspect.getfile(sys._getframe(1))) 48 def RealDecorator(generator): 49 def GeneratorInternal(*args, **kwargs2): 50 parameters = generator(*args, **kwargs2) 51 return ApplyTemplate(base_dir, path_to_template, parameters, **kwargs) 52 GeneratorInternal.func_name = generator.func_name 53 return GeneratorInternal 54 return RealDecorator 55