1#!/usr/bin/env python 2# 3# Copyright 2014 The Chromium Authors. All rights reserved. 4# Use of this source code is governed by a BSD-style license that can be 5# found in the LICENSE file. 6 7"""Renders one or more template files using the Jinja template engine.""" 8 9import codecs 10import optparse 11import os 12import sys 13 14from util import build_utils 15 16sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir)) 17from pylib.constants import host_paths 18 19# Import jinja2 from third_party/jinja2 20sys.path.append(os.path.join(host_paths.DIR_SOURCE_ROOT, 'third_party')) 21import jinja2 # pylint: disable=F0401 22 23 24class RecordingFileSystemLoader(jinja2.FileSystemLoader): 25 '''A FileSystemLoader that stores a list of loaded templates.''' 26 def __init__(self, searchpath): 27 jinja2.FileSystemLoader.__init__(self, searchpath) 28 self.loaded_templates = set() 29 30 def get_source(self, environment, template): 31 contents, filename, uptodate = jinja2.FileSystemLoader.get_source( 32 self, environment, template) 33 self.loaded_templates.add(os.path.relpath(filename)) 34 return contents, filename, uptodate 35 36 def get_loaded_templates(self): 37 return list(self.loaded_templates) 38 39 40def ProcessFile(env, input_filename, loader_base_dir, output_filename, 41 variables): 42 input_rel_path = os.path.relpath(input_filename, loader_base_dir) 43 template = env.get_template(input_rel_path) 44 output = template.render(variables) 45 with codecs.open(output_filename, 'w', 'utf-8') as output_file: 46 output_file.write(output) 47 48 49def ProcessFiles(env, input_filenames, loader_base_dir, inputs_base_dir, 50 outputs_zip, variables): 51 with build_utils.TempDir() as temp_dir: 52 for input_filename in input_filenames: 53 relpath = os.path.relpath(os.path.abspath(input_filename), 54 os.path.abspath(inputs_base_dir)) 55 if relpath.startswith(os.pardir): 56 raise Exception('input file %s is not contained in inputs base dir %s' 57 % (input_filename, inputs_base_dir)) 58 59 output_filename = os.path.join(temp_dir, relpath) 60 parent_dir = os.path.dirname(output_filename) 61 build_utils.MakeDirectory(parent_dir) 62 ProcessFile(env, input_filename, loader_base_dir, output_filename, 63 variables) 64 65 build_utils.ZipDir(outputs_zip, temp_dir) 66 67 68def main(): 69 parser = optparse.OptionParser() 70 build_utils.AddDepfileOption(parser) 71 parser.add_option('--inputs', help='The template files to process.') 72 parser.add_option('--output', help='The output file to generate. Valid ' 73 'only if there is a single input.') 74 parser.add_option('--outputs-zip', help='A zip file containing the processed ' 75 'templates. Required if there are multiple inputs.') 76 parser.add_option('--inputs-base-dir', help='A common ancestor directory of ' 77 'the inputs. Each output\'s path in the output zip will ' 78 'match the relative path from INPUTS_BASE_DIR to the ' 79 'input. Required if --output-zip is given.') 80 parser.add_option('--loader-base-dir', help='Base path used by the template ' 81 'loader. Must be a common ancestor directory of ' 82 'the inputs. Defaults to DIR_SOURCE_ROOT.', 83 default=host_paths.DIR_SOURCE_ROOT) 84 parser.add_option('--variables', help='Variables to be made available in the ' 85 'template processing environment, as a GYP list (e.g. ' 86 '--variables "channel=beta mstone=39")', default='') 87 options, args = parser.parse_args() 88 89 build_utils.CheckOptions(options, parser, required=['inputs']) 90 inputs = build_utils.ParseGypList(options.inputs) 91 92 if (options.output is None) == (options.outputs_zip is None): 93 parser.error('Exactly one of --output and --output-zip must be given') 94 if options.output and len(inputs) != 1: 95 parser.error('--output cannot be used with multiple inputs') 96 if options.outputs_zip and not options.inputs_base_dir: 97 parser.error('--inputs-base-dir must be given when --output-zip is used') 98 if args: 99 parser.error('No positional arguments should be given.') 100 101 variables = {} 102 for v in build_utils.ParseGypList(options.variables): 103 if '=' not in v: 104 parser.error('--variables argument must contain "=": ' + v) 105 name, _, value = v.partition('=') 106 variables[name] = value 107 108 loader = RecordingFileSystemLoader(options.loader_base_dir) 109 env = jinja2.Environment(loader=loader, undefined=jinja2.StrictUndefined, 110 line_comment_prefix='##') 111 if options.output: 112 ProcessFile(env, inputs[0], options.loader_base_dir, options.output, 113 variables) 114 else: 115 ProcessFiles(env, inputs, options.loader_base_dir, options.inputs_base_dir, 116 options.outputs_zip, variables) 117 118 if options.depfile: 119 deps = loader.get_loaded_templates() + build_utils.GetPythonDependencies() 120 build_utils.WriteDepfile(options.depfile, deps) 121 122 123if __name__ == '__main__': 124 main() 125