• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 os.path
10import sys
11
12# Disable lint check for finding modules:
13# pylint: disable=F0401
14
15def _GetDirAbove(dirname):
16  """Returns the directory "above" this file containing |dirname| (which must
17  also be "above" this file)."""
18  path = os.path.abspath(__file__)
19  while True:
20    path, tail = os.path.split(path)
21    assert tail
22    if tail == dirname:
23      return path
24
25try:
26  imp.find_module("jinja2")
27except ImportError:
28  sys.path.append(os.path.join(_GetDirAbove("mojo"), "third_party"))
29import jinja2
30
31
32def ApplyTemplate(mojo_generator, path_to_template, params, **kwargs):
33  loader = jinja2.ModuleLoader(os.path.join(
34      mojo_generator.bytecode_path, "%s.zip" % mojo_generator.GetTemplatePrefix(
35      )))
36  final_kwargs = dict(mojo_generator.GetJinjaParameters())
37  final_kwargs.update(kwargs)
38  jinja_env = jinja2.Environment(loader=loader,
39                                 keep_trailing_newline=True,
40                                 **final_kwargs)
41  jinja_env.globals.update(mojo_generator.GetGlobals())
42  jinja_env.filters.update(mojo_generator.GetFilters())
43  template = jinja_env.get_template(path_to_template)
44  return template.render(params)
45
46
47def UseJinja(path_to_template, **kwargs):
48  def RealDecorator(generator):
49    def GeneratorInternal(*args, **kwargs2):
50      parameters = generator(*args, **kwargs2)
51      return ApplyTemplate(args[0], path_to_template, parameters, **kwargs)
52    GeneratorInternal.func_name = generator.func_name
53    return GeneratorInternal
54  return RealDecorator
55
56
57def PrecompileTemplates(generator_modules, output_dir):
58  for module in generator_modules.values():
59    generator = module.Generator(None)
60    jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader([os.path.join(
61        os.path.dirname(module.__file__), generator.GetTemplatePrefix())]))
62    jinja_env.filters.update(generator.GetFilters())
63    jinja_env.compile_templates(
64        os.path.join(output_dir, "%s.zip" % generator.GetTemplatePrefix()),
65        extensions=["tmpl"],
66        zip="stored",
67        py_compile=True,
68        ignore_errors=False)
69