• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# Copyright 2016 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6import os.path
7import sys
8import argparse
9import collections
10import functools
11import re
12import copy
13try:
14    import json
15except ImportError:
16    import simplejson as json
17
18import pdl
19
20try:
21    unicode
22except NameError:
23    # Define unicode for Py3
24    def unicode(s, *_):
25        return s
26
27# Path handling for libraries and templates
28# Paths have to be normalized because Jinja uses the exact template path to
29# determine the hash used in the cache filename, and we need a pre-caching step
30# to be concurrency-safe. Use absolute path because __file__ is absolute if
31# module is imported, and relative if executed directly.
32# If paths differ between pre-caching and individual file compilation, the cache
33# is regenerated, which causes a race condition and breaks concurrent build,
34# since some compile processes will try to read the partially written cache.
35module_path, module_filename = os.path.split(os.path.realpath(__file__))
36
37def read_config():
38    # pylint: disable=W0703
39    def json_to_object(data, output_base):
40        def json_object_hook(object_dict):
41            items = [(k, os.path.join(output_base, v) if k == "path" else v) for (k, v) in object_dict.items()]
42            items = [(k, os.path.join(output_base, v) if k == "output" else v) for (k, v) in items]
43            keys, values = list(zip(*items))
44            # 'async' is a python 3.7 keyword. Don't use namedtuple(rename=True)
45            # because that only renames it in python 3 but not python 2.
46            keys = tuple('async_' if k == 'async' else k for k in keys)
47            return collections.namedtuple('X', keys)(*values)
48        return json.loads(data, object_hook=json_object_hook)
49
50    def init_defaults(config_tuple, path, defaults):
51        keys = list(config_tuple._fields)  # pylint: disable=E1101
52        values = [getattr(config_tuple, k) for k in keys]
53        for i in range(len(keys)):
54            if hasattr(values[i], "_fields"):
55                values[i] = init_defaults(values[i], path + "." + keys[i], defaults)
56        for optional in defaults:
57            if optional.find(path + ".") != 0:
58                continue
59            optional_key = optional[len(path) + 1:]
60            if optional_key.find(".") == -1 and optional_key not in keys:
61                keys.append(optional_key)
62                values.append(defaults[optional])
63        return collections.namedtuple('X', keys)(*values)
64
65    try:
66        cmdline_parser = argparse.ArgumentParser()
67        cmdline_parser.add_argument("--output_base", type=unicode, required=True)
68        cmdline_parser.add_argument("--jinja_dir", type=unicode, required=True)
69        cmdline_parser.add_argument("--config", type=unicode, required=True)
70        cmdline_parser.add_argument("--config_value", default=[], action="append")
71        arg_options = cmdline_parser.parse_args()
72        jinja_dir = arg_options.jinja_dir
73        output_base = arg_options.output_base
74        config_file = arg_options.config
75        config_values = arg_options.config_value
76    except Exception:
77        # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.html
78        exc = sys.exc_info()[1]
79        sys.stderr.write("Failed to parse command-line arguments: %s\n\n" % exc)
80        exit(1)
81
82    try:
83        config_json_file = open(config_file, "r")
84        config_json_string = config_json_file.read()
85        config_partial = json_to_object(config_json_string, output_base)
86        config_json_file.close()
87        defaults = {
88            ".use_snake_file_names": False,
89            ".use_title_case_methods": False,
90            ".imported": False,
91            ".imported.export_macro": "",
92            ".imported.export_header": False,
93            ".imported.header": False,
94            ".imported.package": False,
95            ".imported.options": False,
96            ".protocol.export_macro": "",
97            ".protocol.export_header": False,
98            ".protocol.options": False,
99            ".protocol.file_name_prefix": "",
100            ".exported": False,
101            ".exported.export_macro": "",
102            ".exported.export_header": False,
103            ".lib": False,
104            ".lib.export_macro": "",
105            ".lib.export_header": False,
106            # The encoding lib consists of encoding/encoding.h and
107            # encoding/encoding.cc in its subdirectory, which binaries
108            # may link / depend on, instead of relying on the
109            # JINJA2 templates lib/encoding_{h,cc}.template.
110            # In that case, |header| identifies the include file
111            # and |namespace| is the namespace it's using. Usually
112            # inspector_protocol_encoding but for v8's copy it's
113            # v8_inspector_protocol_encoding.
114            # TODO(johannes): Migrate away from lib/encoding_{h,cc}.template
115            #                 in favor of this.
116            ".encoding_lib": { "header": "", "namespace": []},
117        }
118        for key_value in config_values:
119            parts = key_value.split("=")
120            if len(parts) == 2:
121                defaults["." + parts[0]] = parts[1]
122        return (jinja_dir, config_file, init_defaults(config_partial, "", defaults))
123    except Exception:
124        # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.html
125        exc = sys.exc_info()[1]
126        sys.stderr.write("Failed to parse config file: %s\n\n" % exc)
127        exit(1)
128
129
130# ---- Begin of utilities exposed to generator ----
131
132
133def to_title_case(name):
134    return name[:1].upper() + name[1:]
135
136
137def dash_to_camelcase(word):
138    prefix = ""
139    if word[0] == "-":
140        prefix = "Negative"
141        word = word[1:]
142    return prefix + "".join(to_title_case(x) or "-" for x in word.split("-"))
143
144
145def to_snake_case(name):
146    return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name, sys.maxsize).lower()
147
148
149def to_method_case(config, name):
150    if config.use_title_case_methods:
151        return to_title_case(name)
152    return name
153
154
155def join_arrays(dict, keys):
156    result = []
157    for key in keys:
158        if key in dict:
159            result += dict[key]
160    return result
161
162
163def format_include(config, header, file_name=None):
164    if file_name is not None:
165        header = header + "/" + file_name + ".h"
166    header = "\"" + header + "\"" if header[0] not in "<\"" else header
167    if config.use_snake_file_names:
168        header = to_snake_case(header)
169    return header
170
171
172def format_domain_include(config, header, file_name):
173    return format_include(config, header, config.protocol.file_name_prefix + file_name)
174
175
176def to_file_name(config, file_name):
177    if config.use_snake_file_names:
178        return to_snake_case(file_name).replace(".cpp", ".cc")
179    return file_name
180
181
182# ---- End of utilities exposed to generator ----
183
184
185def initialize_jinja_env(jinja_dir, cache_dir, config):
186    # pylint: disable=F0401
187    sys.path.insert(1, os.path.abspath(jinja_dir))
188    import jinja2
189
190    jinja_env = jinja2.Environment(
191        loader=jinja2.FileSystemLoader(module_path),
192        # Bytecode cache is not concurrency-safe unless pre-cached:
193        # if pre-cached this is read-only, but writing creates a race condition.
194        bytecode_cache=jinja2.FileSystemBytecodeCache(cache_dir),
195        keep_trailing_newline=True,  # newline-terminate generated files
196        lstrip_blocks=True,  # so can indent control flow tags
197        trim_blocks=True)
198    jinja_env.filters.update({"to_title_case": to_title_case, "dash_to_camelcase": dash_to_camelcase, "to_method_case": functools.partial(to_method_case, config)})
199    jinja_env.add_extension("jinja2.ext.loopcontrols")
200    return jinja_env
201
202
203def create_imported_type_definition(domain_name, type, imported_namespace):
204    # pylint: disable=W0622
205    return {
206        "return_type": "std::unique_ptr<%s::%s::API::%s>" % (imported_namespace, domain_name, type["id"]),
207        "pass_type": "std::unique_ptr<%s::%s::API::%s>" % (imported_namespace, domain_name, type["id"]),
208        "to_raw_type": "%s.get()",
209        "to_pass_type": "std::move(%s)",
210        "to_rvalue": "std::move(%s)",
211        "type": "std::unique_ptr<%s::%s::API::%s>" % (imported_namespace, domain_name, type["id"]),
212        "raw_type": "%s::%s::API::%s" % (imported_namespace, domain_name, type["id"]),
213        "raw_pass_type": "%s::%s::API::%s*" % (imported_namespace, domain_name, type["id"]),
214        "raw_return_type": "%s::%s::API::%s*" % (imported_namespace, domain_name, type["id"]),
215    }
216
217
218def create_user_type_definition(domain_name, type):
219    # pylint: disable=W0622
220    return {
221        "return_type": "std::unique_ptr<protocol::%s::%s>" % (domain_name, type["id"]),
222        "pass_type": "std::unique_ptr<protocol::%s::%s>" % (domain_name, type["id"]),
223        "to_raw_type": "%s.get()",
224        "to_pass_type": "std::move(%s)",
225        "to_rvalue": "std::move(%s)",
226        "type": "std::unique_ptr<protocol::%s::%s>" % (domain_name, type["id"]),
227        "raw_type": "protocol::%s::%s" % (domain_name, type["id"]),
228        "raw_pass_type": "protocol::%s::%s*" % (domain_name, type["id"]),
229        "raw_return_type": "protocol::%s::%s*" % (domain_name, type["id"]),
230    }
231
232
233def create_object_type_definition():
234    # pylint: disable=W0622
235    return {
236        "return_type": "std::unique_ptr<protocol::DictionaryValue>",
237        "pass_type": "std::unique_ptr<protocol::DictionaryValue>",
238        "to_raw_type": "%s.get()",
239        "to_pass_type": "std::move(%s)",
240        "to_rvalue": "std::move(%s)",
241        "type": "std::unique_ptr<protocol::DictionaryValue>",
242        "raw_type": "protocol::DictionaryValue",
243        "raw_pass_type": "protocol::DictionaryValue*",
244        "raw_return_type": "protocol::DictionaryValue*",
245    }
246
247
248def create_any_type_definition():
249    # pylint: disable=W0622
250    return {
251        "return_type": "std::unique_ptr<protocol::Value>",
252        "pass_type": "std::unique_ptr<protocol::Value>",
253        "to_raw_type": "%s.get()",
254        "to_pass_type": "std::move(%s)",
255        "to_rvalue": "std::move(%s)",
256        "type": "std::unique_ptr<protocol::Value>",
257        "raw_type": "protocol::Value",
258        "raw_pass_type": "protocol::Value*",
259        "raw_return_type": "protocol::Value*",
260    }
261
262
263def create_string_type_definition():
264    # pylint: disable=W0622
265    return {
266        "return_type": "String",
267        "pass_type": "const String&",
268        "to_pass_type": "%s",
269        "to_raw_type": "%s",
270        "to_rvalue": "%s",
271        "type": "String",
272        "raw_type": "String",
273        "raw_pass_type": "const String&",
274        "raw_return_type": "String",
275    }
276
277
278def create_binary_type_definition():
279    # pylint: disable=W0622
280    return {
281        "return_type": "Binary",
282        "pass_type": "const Binary&",
283        "to_pass_type": "%s",
284        "to_raw_type": "%s",
285        "to_rvalue": "%s",
286        "type": "Binary",
287        "raw_type": "Binary",
288        "raw_pass_type": "const Binary&",
289        "raw_return_type": "Binary",
290    }
291
292
293def create_primitive_type_definition(type):
294    # pylint: disable=W0622
295    typedefs = {
296        "number": "double",
297        "integer": "int",
298        "boolean": "bool"
299    }
300    defaults = {
301        "number": "0",
302        "integer": "0",
303        "boolean": "false"
304    }
305    jsontypes = {
306        "number": "TypeDouble",
307        "integer": "TypeInteger",
308        "boolean": "TypeBoolean",
309    }
310    return {
311        "return_type": typedefs[type],
312        "pass_type": typedefs[type],
313        "to_pass_type": "%s",
314        "to_raw_type": "%s",
315        "to_rvalue": "%s",
316        "type": typedefs[type],
317        "raw_type": typedefs[type],
318        "raw_pass_type": typedefs[type],
319        "raw_return_type": typedefs[type],
320        "default_value": defaults[type]
321    }
322
323
324def wrap_array_definition(type):
325    # pylint: disable=W0622
326    return {
327        "return_type": "std::unique_ptr<protocol::Array<%s>>" % type["raw_type"],
328        "pass_type": "std::unique_ptr<protocol::Array<%s>>" % type["raw_type"],
329        "to_raw_type": "%s.get()",
330        "to_pass_type": "std::move(%s)",
331        "to_rvalue": "std::move(%s)",
332        "type": "std::unique_ptr<protocol::Array<%s>>" % type["raw_type"],
333        "raw_type": "protocol::Array<%s>" % type["raw_type"],
334        "raw_pass_type": "protocol::Array<%s>*" % type["raw_type"],
335        "raw_return_type": "protocol::Array<%s>*" % type["raw_type"],
336        "out_type": "protocol::Array<%s>&" % type["raw_type"],
337    }
338
339
340class Protocol(object):
341    def __init__(self, config):
342        self.config = config
343        self.json_api = {"domains": []}
344        self.imported_domains = []
345        self.exported_domains = []
346        self.generate_domains = self.read_protocol_file(config.protocol.path)
347
348        if config.protocol.options:
349            self.generate_domains = [rule.domain for rule in config.protocol.options]
350            self.exported_domains = [rule.domain for rule in config.protocol.options if hasattr(rule, "exported")]
351
352        if config.imported:
353            self.imported_domains = self.read_protocol_file(config.imported.path)
354            if config.imported.options:
355                self.imported_domains = [rule.domain for rule in config.imported.options]
356
357        self.patch_full_qualified_refs()
358        self.create_notification_types()
359        self.create_type_definitions()
360        self.generate_used_types()
361
362
363    def read_protocol_file(self, file_name):
364        input_file = open(file_name, "r")
365        parsed_json = pdl.loads(input_file.read(), file_name)
366        input_file.close()
367        version = parsed_json["version"]["major"] + "." + parsed_json["version"]["minor"]
368        domains = []
369        for domain in parsed_json["domains"]:
370            domains.append(domain["domain"])
371            domain["version"] = version
372        self.json_api["domains"] += parsed_json["domains"]
373        return domains
374
375
376    def patch_full_qualified_refs(self):
377        def patch_full_qualified_refs_in_domain(json, domain_name):
378            if isinstance(json, list):
379                for item in json:
380                    patch_full_qualified_refs_in_domain(item, domain_name)
381            if not isinstance(json, dict):
382                return
383            for key in json:
384                if key == "type" and json[key] == "string":
385                    json[key] = domain_name + ".string"
386                if key != "$ref":
387                    patch_full_qualified_refs_in_domain(json[key], domain_name)
388                    continue
389                if json["$ref"].find(".") == -1:
390                    json["$ref"] = domain_name + "." + json["$ref"]
391            return
392
393        for domain in self.json_api["domains"]:
394            patch_full_qualified_refs_in_domain(domain, domain["domain"])
395
396
397    def all_references(self, json):
398        refs = set()
399        if isinstance(json, list):
400            for item in json:
401                refs |= self.all_references(item)
402        if not isinstance(json, dict):
403            return refs
404        for key in json:
405            if key != "$ref":
406                refs |= self.all_references(json[key])
407            else:
408                refs.add(json["$ref"])
409        return refs
410
411    def generate_used_types(self):
412        all_refs = set()
413        for domain in self.json_api["domains"]:
414            domain_name = domain["domain"]
415            if "commands" in domain:
416                for command in domain["commands"]:
417                    if self.generate_command(domain_name, command["name"]):
418                        all_refs |= self.all_references(command)
419            if "events" in domain:
420                for event in domain["events"]:
421                    if self.generate_event(domain_name, event["name"]):
422                        all_refs |= self.all_references(event)
423                        all_refs.add(domain_name + "." + to_title_case(event["name"]) + "Notification")
424
425        dependencies = self.generate_type_dependencies()
426        queue = set(all_refs)
427        while len(queue):
428            ref = queue.pop()
429            if ref in dependencies:
430                queue |= dependencies[ref] - all_refs
431                all_refs |= dependencies[ref]
432        self.used_types = all_refs
433
434
435    def generate_type_dependencies(self):
436        dependencies = dict()
437        domains_with_types = (x for x in self.json_api["domains"] if "types" in x)
438        for domain in domains_with_types:
439            domain_name = domain["domain"]
440            for type in domain["types"]:
441                related_types = self.all_references(type)
442                if len(related_types):
443                    dependencies[domain_name + "." + type["id"]] = related_types
444        return dependencies
445
446
447    def create_notification_types(self):
448        for domain in self.json_api["domains"]:
449            if "events" in domain:
450                for event in domain["events"]:
451                    event_type = dict()
452                    event_type["description"] = "Wrapper for notification params"
453                    event_type["type"] = "object"
454                    event_type["id"] = to_title_case(event["name"]) + "Notification"
455                    if "parameters" in event:
456                        event_type["properties"] = copy.deepcopy(event["parameters"])
457                    if "types" not in domain:
458                        domain["types"] = list()
459                    domain["types"].append(event_type)
460
461
462    def create_type_definitions(self):
463        imported_namespace = "::".join(self.config.imported.namespace) if self.config.imported else ""
464        self.type_definitions = {}
465        self.type_definitions["number"] = create_primitive_type_definition("number")
466        self.type_definitions["integer"] = create_primitive_type_definition("integer")
467        self.type_definitions["boolean"] = create_primitive_type_definition("boolean")
468        self.type_definitions["object"] = create_object_type_definition()
469        self.type_definitions["any"] = create_any_type_definition()
470        self.type_definitions["binary"] = create_binary_type_definition()
471        for domain in self.json_api["domains"]:
472            self.type_definitions[domain["domain"] + ".string"] = create_string_type_definition()
473            self.type_definitions[domain["domain"] + ".binary"] = create_binary_type_definition()
474            if not ("types" in domain):
475                continue
476            for type in domain["types"]:
477                type_name = domain["domain"] + "." + type["id"]
478                if type["type"] == "object" and domain["domain"] in self.imported_domains:
479                    self.type_definitions[type_name] = create_imported_type_definition(domain["domain"], type, imported_namespace)
480                elif type["type"] == "object":
481                    self.type_definitions[type_name] = create_user_type_definition(domain["domain"], type)
482                elif type["type"] == "array":
483                    self.type_definitions[type_name] = self.resolve_type(type)
484                elif type["type"] == domain["domain"] + ".string":
485                    self.type_definitions[type_name] = create_string_type_definition()
486                elif type["type"] == domain["domain"] + ".binary":
487                    self.type_definitions[type_name] = create_binary_type_definition()
488                else:
489                    self.type_definitions[type_name] = create_primitive_type_definition(type["type"])
490
491
492    def check_options(self, options, domain, name, include_attr, exclude_attr, default):
493        for rule in options:
494            if rule.domain != domain:
495                continue
496            if include_attr and hasattr(rule, include_attr):
497                return name in getattr(rule, include_attr)
498            if exclude_attr and hasattr(rule, exclude_attr):
499                return name not in getattr(rule, exclude_attr)
500            return default
501        return False
502
503
504    # ---- Begin of methods exposed to generator
505
506
507    def type_definition(self, name):
508        return self.type_definitions[name]
509
510
511    def resolve_type(self, prop):
512        if "$ref" in prop:
513            return self.type_definitions[prop["$ref"]]
514        if prop["type"] == "array":
515            return wrap_array_definition(self.resolve_type(prop["items"]))
516        return self.type_definitions[prop["type"]]
517
518
519    def generate_command(self, domain, command):
520        if not self.config.protocol.options:
521            return domain in self.generate_domains
522        return self.check_options(self.config.protocol.options, domain, command, "include", "exclude", True)
523
524
525    def generate_event(self, domain, event):
526        if not self.config.protocol.options:
527            return domain in self.generate_domains
528        return self.check_options(self.config.protocol.options, domain, event, "include_events", "exclude_events", True)
529
530
531    def generate_type(self, domain, typename):
532        return domain + "." + typename in self.used_types
533
534
535    def is_async_command(self, domain, command):
536        if not self.config.protocol.options:
537            return False
538        return self.check_options(self.config.protocol.options, domain, command, "async_", None, False)
539
540
541    def is_exported(self, domain, name):
542        if not self.config.protocol.options:
543            return False
544        return self.check_options(self.config.protocol.options, domain, name, "exported", None, False)
545
546
547    def is_imported(self, domain, name):
548        if not self.config.imported:
549            return False
550        if not self.config.imported.options:
551            return domain in self.imported_domains
552        return self.check_options(self.config.imported.options, domain, name, "imported", None, False)
553
554
555    def is_exported_domain(self, domain):
556        return domain in self.exported_domains
557
558
559    def generate_disable(self, domain):
560        if "commands" not in domain:
561            return True
562        for command in domain["commands"]:
563            if command["name"] == "disable" and self.generate_command(domain["domain"], "disable"):
564                return False
565        return True
566
567
568    def is_imported_dependency(self, domain):
569        return domain in self.generate_domains or domain in self.imported_domains
570
571
572def main():
573    jinja_dir, config_file, config = read_config()
574
575    protocol = Protocol(config)
576
577    if not config.exported and len(protocol.exported_domains):
578        sys.stderr.write("Domains [%s] are exported, but config is missing export entry\n\n" % ", ".join(protocol.exported_domains))
579        exit(1)
580
581    if not os.path.exists(config.protocol.output):
582        os.mkdir(config.protocol.output)
583    if len(protocol.exported_domains) and not os.path.exists(config.exported.output):
584        os.mkdir(config.exported.output)
585    jinja_env = initialize_jinja_env(jinja_dir, config.protocol.output, config)
586
587    inputs = []
588    inputs.append(__file__)
589    inputs.append(config_file)
590    inputs.append(config.protocol.path)
591    if config.imported:
592        inputs.append(config.imported.path)
593    templates_dir = os.path.join(module_path, "templates")
594    inputs.append(os.path.join(templates_dir, "TypeBuilder_h.template"))
595    inputs.append(os.path.join(templates_dir, "TypeBuilder_cpp.template"))
596    inputs.append(os.path.join(templates_dir, "Exported_h.template"))
597    inputs.append(os.path.join(templates_dir, "Imported_h.template"))
598
599    h_template = jinja_env.get_template("templates/TypeBuilder_h.template")
600    cpp_template = jinja_env.get_template("templates/TypeBuilder_cpp.template")
601    exported_template = jinja_env.get_template("templates/Exported_h.template")
602    imported_template = jinja_env.get_template("templates/Imported_h.template")
603
604    outputs = dict()
605
606    for domain in protocol.json_api["domains"]:
607        class_name = domain["domain"]
608        file_name = config.protocol.file_name_prefix + class_name
609        template_context = {
610            "protocol": protocol,
611            "config": config,
612            "domain": domain,
613            "join_arrays": join_arrays,
614            "format_include": functools.partial(format_include, config),
615            "format_domain_include": functools.partial(format_domain_include, config),
616        }
617
618        if domain["domain"] in protocol.generate_domains:
619            outputs[os.path.join(config.protocol.output, to_file_name(config, file_name + ".h"))] = h_template.render(template_context)
620            outputs[os.path.join(config.protocol.output, to_file_name(config, file_name + ".cpp"))] = cpp_template.render(template_context)
621            if domain["domain"] in protocol.exported_domains:
622                outputs[os.path.join(config.exported.output, to_file_name(config, file_name + ".h"))] = exported_template.render(template_context)
623        if domain["domain"] in protocol.imported_domains:
624            outputs[os.path.join(config.protocol.output, to_file_name(config, file_name + ".h"))] = imported_template.render(template_context)
625
626    if config.lib:
627        template_context = {
628            "config": config,
629            "format_include": functools.partial(format_include, config),
630        }
631
632        lib_templates_dir = os.path.join(module_path, "lib")
633        # Note these should be sorted in the right order.
634        # TODO(dgozman): sort them programmatically based on commented includes.
635        protocol_h_templates = [
636            "ErrorSupport_h.template",
637            "Values_h.template",
638            "Object_h.template",
639            "ValueConversions_h.template",
640            "Maybe_h.template",
641            "Array_h.template",
642            "DispatcherBase_h.template",
643            "Parser_h.template",
644            "encoding_h.template",
645        ]
646
647        protocol_cpp_templates = [
648            "Protocol_cpp.template",
649            "ErrorSupport_cpp.template",
650            "Values_cpp.template",
651            "Object_cpp.template",
652            "DispatcherBase_cpp.template",
653            "Parser_cpp.template",
654            "encoding_cpp.template",
655        ]
656
657        forward_h_templates = [
658            "Forward_h.template",
659            "Allocator_h.template",
660            "FrontendChannel_h.template",
661        ]
662
663        base_string_adapter_h_templates = [
664            "base_string_adapter_h.template",
665        ]
666
667        base_string_adapter_cc_templates = [
668            "base_string_adapter_cc.template",
669        ]
670
671        def generate_lib_file(file_name, template_files):
672            parts = []
673            for template_file in template_files:
674                inputs.append(os.path.join(lib_templates_dir, template_file))
675                template = jinja_env.get_template("lib/" + template_file)
676                parts.append(template.render(template_context))
677            outputs[file_name] = "\n\n".join(parts)
678
679        generate_lib_file(os.path.join(config.lib.output, to_file_name(config, "Forward.h")), forward_h_templates)
680        generate_lib_file(os.path.join(config.lib.output, to_file_name(config, "Protocol.h")), protocol_h_templates)
681        generate_lib_file(os.path.join(config.lib.output, to_file_name(config, "Protocol.cpp")), protocol_cpp_templates)
682        generate_lib_file(os.path.join(config.lib.output, to_file_name(config, "base_string_adapter.h")), base_string_adapter_h_templates)
683        generate_lib_file(os.path.join(config.lib.output, to_file_name(config, "base_string_adapter.cc")), base_string_adapter_cc_templates)
684
685    # Make gyp / make generatos happy, otherwise make rebuilds world.
686    inputs_ts = max(map(os.path.getmtime, inputs))
687    up_to_date = True
688    for output_file in outputs.keys():
689        if not os.path.exists(output_file) or os.path.getmtime(output_file) < inputs_ts:
690            up_to_date = False
691            break
692    if up_to_date:
693        sys.exit()
694
695    for file_name, content in outputs.items():
696        out_file = open(file_name, "w")
697        out_file.write(content)
698        out_file.close()
699
700
701main()
702