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 third_party/WebKit/Source/build/scripts/template_expander.py. 6 7import os.path 8import sys 9 10_current_dir = os.path.dirname(os.path.realpath(__file__)) 11# jinja2 is in chromium's third_party directory 12# Insert at front to override system libraries, and after path[0] == script dir 13sys.path.insert( 14 1, os.path.join(_current_dir, *([os.pardir] * 7 + ['third_party']))) 15import jinja2 16 17 18def ApplyTemplate(mojo_generator, path_to_template, params, **kwargs): 19 loader = jinja2.ModuleLoader(os.path.join( 20 mojo_generator.bytecode_path, "%s.zip" % mojo_generator.GetTemplatePrefix( 21 ))) 22 final_kwargs = dict(mojo_generator.GetJinjaParameters()) 23 final_kwargs.update(kwargs) 24 jinja_env = jinja2.Environment(loader=loader, 25 keep_trailing_newline=True, 26 **final_kwargs) 27 jinja_env.globals.update(mojo_generator.GetGlobals()) 28 jinja_env.filters.update(mojo_generator.GetFilters()) 29 template = jinja_env.get_template(path_to_template) 30 return template.render(params) 31 32 33def UseJinja(path_to_template, **kwargs): 34 def RealDecorator(generator): 35 def GeneratorInternal(*args, **kwargs2): 36 parameters = generator(*args, **kwargs2) 37 return ApplyTemplate(args[0], path_to_template, parameters, **kwargs) 38 GeneratorInternal.func_name = generator.func_name 39 return GeneratorInternal 40 return RealDecorator 41 42 43def PrecompileTemplates(generator_modules, output_dir): 44 for module in generator_modules.values(): 45 generator = module.Generator(None) 46 jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader([os.path.join( 47 os.path.dirname(module.__file__), generator.GetTemplatePrefix())])) 48 jinja_env.filters.update(generator.GetFilters()) 49 jinja_env.compile_templates( 50 os.path.join(output_dir, "%s.zip" % generator.GetTemplatePrefix()), 51 extensions=["tmpl"], 52 zip="stored", 53 py_compile=True, 54 ignore_errors=False) 55