Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(726)

Side by Side Diff: third_party/WebKit/Source/platform/inspector_protocol/CodeGenerator.py

Issue 2282283002: [DevTools] Prepare inspector_protocol build to move. (Closed)
Patch Set: NOTREACHED Created 4 years, 3 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 # Copyright 2016 The Chromium Authors. All rights reserved. 1 # Copyright 2016 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be 2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file. 3 # found in the LICENSE file.
4 4
5 import os.path 5 import os.path
6 import sys 6 import sys
7 import optparse 7 import optparse
8 import collections 8 import collections
9 import functools 9 import functools
10 try: 10 try:
11 import json 11 import json
12 except ImportError: 12 except ImportError:
13 import simplejson as json 13 import simplejson as json
14 14
15 # Path handling for libraries and templates 15 # Path handling for libraries and templates
16 # Paths have to be normalized because Jinja uses the exact template path to 16 # Paths have to be normalized because Jinja uses the exact template path to
17 # determine the hash used in the cache filename, and we need a pre-caching step 17 # determine the hash used in the cache filename, and we need a pre-caching step
18 # to be concurrency-safe. Use absolute path because __file__ is absolute if 18 # to be concurrency-safe. Use absolute path because __file__ is absolute if
19 # module is imported, and relative if executed directly. 19 # module is imported, and relative if executed directly.
20 # If paths differ between pre-caching and individual file compilation, the cache 20 # If paths differ between pre-caching and individual file compilation, the cache
21 # is regenerated, which causes a race condition and breaks concurrent build, 21 # is regenerated, which causes a race condition and breaks concurrent build,
22 # since some compile processes will try to read the partially written cache. 22 # since some compile processes will try to read the partially written cache.
23 module_path, module_filename = os.path.split(os.path.realpath(__file__)) 23 module_path, module_filename = os.path.split(os.path.realpath(__file__))
24 templates_dir = module_path
25
26 # In Blink, jinja2 is in chromium's third_party directory.
27 # Insert at 1 so at front to override system libraries, and
28 # after path[0] == invoking script dir
29 blink_third_party_dir = os.path.normpath(os.path.join(
30 module_path, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir,
31 "third_party"))
32 if os.path.isdir(blink_third_party_dir):
33 sys.path.insert(1, blink_third_party_dir)
34
35 # In V8, it is in third_party folder
36 v8_third_party_dir = os.path.normpath(os.path.join(
37 module_path, os.pardir, os.pardir, "third_party"))
38
39 if os.path.isdir(v8_third_party_dir):
40 sys.path.insert(1, v8_third_party_dir)
41
42 # In Node, it is in deps folder
43 deps_dir = os.path.normpath(os.path.join(
44 module_path, os.pardir, os.pardir, os.pardir, os.pardir, "third_party"))
45
46 if os.path.isdir(deps_dir):
47 sys.path.insert(1, os.path.join(deps_dir, "jinja2"))
48 sys.path.insert(1, os.path.join(deps_dir, "markupsafe"))
49
50 import jinja2
51
52 24
53 def read_config(): 25 def read_config():
54 # pylint: disable=W0703 26 # pylint: disable=W0703
55 def json_to_object(data, output_base, config_base): 27 def json_to_object(data, output_base, config_base):
56 def json_object_hook(object_dict): 28 def json_object_hook(object_dict):
57 items = [(k, os.path.join(config_base, v) if k == "path" else v) for (k, v) in object_dict.items()] 29 items = [(k, os.path.join(config_base, v) if k == "path" else v) for (k, v) in object_dict.items()]
58 items = [(k, os.path.join(output_base, v) if k == "output" else v) f or (k, v) in items] 30 items = [(k, os.path.join(output_base, v) if k == "output" else v) f or (k, v) in items]
59 keys, values = zip(*items) 31 keys, values = zip(*items)
60 return collections.namedtuple('X', keys)(*values) 32 return collections.namedtuple('X', keys)(*values)
61 return json.loads(data, object_hook=json_object_hook) 33 return json.loads(data, object_hook=json_object_hook)
62 34
63 try: 35 try:
64 cmdline_parser = optparse.OptionParser() 36 cmdline_parser = optparse.OptionParser()
65 cmdline_parser.add_option("--output_base") 37 cmdline_parser.add_option("--output_base")
38 cmdline_parser.add_option("--jinja_dir")
66 cmdline_parser.add_option("--config") 39 cmdline_parser.add_option("--config")
67 arg_options, _ = cmdline_parser.parse_args() 40 arg_options, _ = cmdline_parser.parse_args()
41 jinja_dir = arg_options.jinja_dir
42 if not jinja_dir:
43 raise Exception("jinja directory must be specified")
68 output_base = arg_options.output_base 44 output_base = arg_options.output_base
69 if not output_base: 45 if not output_base:
70 raise Exception("Base output directory must be specified") 46 raise Exception("Base output directory must be specified")
71 config_file = arg_options.config 47 config_file = arg_options.config
72 if not config_file: 48 if not config_file:
73 raise Exception("Config file name must be specified") 49 raise Exception("Config file name must be specified")
74 config_base = os.path.dirname(config_file) 50 config_base = os.path.dirname(config_file)
75 except Exception: 51 except Exception:
76 # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.h tml 52 # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.h tml
77 exc = sys.exc_info()[1] 53 exc = sys.exc_info()[1]
78 sys.stderr.write("Failed to parse command-line arguments: %s\n\n" % exc) 54 sys.stderr.write("Failed to parse command-line arguments: %s\n\n" % exc)
79 exit(1) 55 exit(1)
80 56
81 try: 57 try:
82 config_json_file = open(config_file, "r") 58 config_json_file = open(config_file, "r")
83 config_json_string = config_json_file.read() 59 config_json_string = config_json_file.read()
84 config_partial = json_to_object(config_json_string, output_base, config_ base) 60 config_partial = json_to_object(config_json_string, output_base, config_ base)
85 keys = list(config_partial._fields) # pylint: disable=E1101 61 keys = list(config_partial._fields) # pylint: disable=E1101
86 values = [getattr(config_partial, k) for k in keys] 62 values = [getattr(config_partial, k) for k in keys]
87 for optional in ["imported", "exported", "lib"]: 63 for optional in ["imported", "exported", "lib"]:
88 if optional not in keys: 64 if optional not in keys:
89 keys.append(optional) 65 keys.append(optional)
90 values.append(False) 66 values.append(False)
91 config_json_file.close() 67 config_json_file.close()
92 return (config_file, collections.namedtuple('X', keys)(*values)) 68 return (jinja_dir, config_file, collections.namedtuple('X', keys)(*value s))
93 except Exception: 69 except Exception:
94 # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.h tml 70 # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.h tml
95 exc = sys.exc_info()[1] 71 exc = sys.exc_info()[1]
96 sys.stderr.write("Failed to parse config file: %s\n\n" % exc) 72 sys.stderr.write("Failed to parse config file: %s\n\n" % exc)
97 exit(1) 73 exit(1)
98 74
99 75
100 def to_title_case(name): 76 def to_title_case(name):
101 return name[:1].upper() + name[1:] 77 return name[:1].upper() + name[1:]
102 78
103 79
104 def dash_to_camelcase(word): 80 def dash_to_camelcase(word):
105 prefix = "" 81 prefix = ""
106 if word[0] == "-": 82 if word[0] == "-":
107 prefix = "Negative" 83 prefix = "Negative"
108 word = word[1:] 84 word = word[1:]
109 return prefix + "".join(to_title_case(x) or "-" for x in word.split("-")) 85 return prefix + "".join(to_title_case(x) or "-" for x in word.split("-"))
110 86
111 87
112 def initialize_jinja_env(cache_dir): 88 def initialize_jinja_env(jinja_dir, cache_dir):
89 # pylint: disable=F0401
90 sys.path.insert(1, os.path.abspath(jinja_dir))
91 import jinja2
92
113 jinja_env = jinja2.Environment( 93 jinja_env = jinja2.Environment(
114 loader=jinja2.FileSystemLoader(templates_dir), 94 loader=jinja2.FileSystemLoader(module_path),
115 # Bytecode cache is not concurrency-safe unless pre-cached: 95 # Bytecode cache is not concurrency-safe unless pre-cached:
116 # if pre-cached this is read-only, but writing creates a race condition. 96 # if pre-cached this is read-only, but writing creates a race condition.
117 bytecode_cache=jinja2.FileSystemBytecodeCache(cache_dir), 97 bytecode_cache=jinja2.FileSystemBytecodeCache(cache_dir),
118 keep_trailing_newline=True, # newline-terminate generated files 98 keep_trailing_newline=True, # newline-terminate generated files
119 lstrip_blocks=True, # so can indent control flow tags 99 lstrip_blocks=True, # so can indent control flow tags
120 trim_blocks=True) 100 trim_blocks=True)
121 jinja_env.filters.update({"to_title_case": to_title_case, "dash_to_camelcase ": dash_to_camelcase}) 101 jinja_env.filters.update({"to_title_case": to_title_case, "dash_to_camelcase ": dash_to_camelcase})
122 jinja_env.add_extension("jinja2.ext.loopcontrols") 102 jinja_env.add_extension("jinja2.ext.loopcontrols")
123 return jinja_env 103 return jinja_env
124 104
(...skipping 230 matching lines...) Expand 10 before | Expand all | Expand 10 after
355 335
356 336
357 class Protocol(object): 337 class Protocol(object):
358 def __init__(self): 338 def __init__(self):
359 self.json_api = {} 339 self.json_api = {}
360 self.generate_domains = [] 340 self.generate_domains = []
361 self.imported_domains = [] 341 self.imported_domains = []
362 342
363 343
364 def main(): 344 def main():
365 config_file, config = read_config() 345 jinja_dir, config_file, config = read_config()
366 346
367 protocol = Protocol() 347 protocol = Protocol()
368 protocol.json_api = {"domains": []} 348 protocol.json_api = {"domains": []}
369 protocol.generate_domains = read_protocol_file(config.protocol.path, protoco l.json_api) 349 protocol.generate_domains = read_protocol_file(config.protocol.path, protoco l.json_api)
370 protocol.imported_domains = read_protocol_file(config.imported.path, protoco l.json_api) if config.imported else [] 350 protocol.imported_domains = read_protocol_file(config.imported.path, protoco l.json_api) if config.imported else []
371 patch_full_qualified_refs(protocol) 351 patch_full_qualified_refs(protocol)
372 calculate_exports(protocol) 352 calculate_exports(protocol)
373 create_type_definitions(protocol, "::".join(config.imported.namespace) if co nfig.imported else "") 353 create_type_definitions(protocol, "::".join(config.imported.namespace) if co nfig.imported else "")
374 354
375 if not config.exported: 355 if not config.exported:
376 for domain_json in protocol.json_api["domains"]: 356 for domain_json in protocol.json_api["domains"]:
377 if domain_json["has_exports"] and domain_json["domain"] in protocol. generate_domains: 357 if domain_json["has_exports"] and domain_json["domain"] in protocol. generate_domains:
378 sys.stderr.write("Domain %s is exported, but config is missing e xport entry\n\n" % domain_json["domain"]) 358 sys.stderr.write("Domain %s is exported, but config is missing e xport entry\n\n" % domain_json["domain"])
379 exit(1) 359 exit(1)
380 360
381 if not os.path.exists(config.protocol.output): 361 if not os.path.exists(config.protocol.output):
382 os.mkdir(config.protocol.output) 362 os.mkdir(config.protocol.output)
383 if protocol.json_api["has_exports"] and not os.path.exists(config.exported.o utput): 363 if protocol.json_api["has_exports"] and not os.path.exists(config.exported.o utput):
384 os.mkdir(config.exported.output) 364 os.mkdir(config.exported.output)
385 jinja_env = initialize_jinja_env(config.protocol.output) 365 jinja_env = initialize_jinja_env(jinja_dir, config.protocol.output)
386 366
387 inputs = [] 367 inputs = []
388 inputs.append(__file__) 368 inputs.append(__file__)
389 inputs.append(config_file) 369 inputs.append(config_file)
390 inputs.append(config.protocol.path) 370 inputs.append(config.protocol.path)
391 if config.imported: 371 if config.imported:
392 inputs.append(config.imported.path) 372 inputs.append(config.imported.path)
373 templates_dir = os.path.join(module_path, "templates")
393 inputs.append(os.path.join(templates_dir, "TypeBuilder_h.template")) 374 inputs.append(os.path.join(templates_dir, "TypeBuilder_h.template"))
394 inputs.append(os.path.join(templates_dir, "TypeBuilder_cpp.template")) 375 inputs.append(os.path.join(templates_dir, "TypeBuilder_cpp.template"))
395 inputs.append(os.path.join(templates_dir, "Exported_h.template")) 376 inputs.append(os.path.join(templates_dir, "Exported_h.template"))
396 inputs.append(os.path.join(templates_dir, "Imported_h.template")) 377 inputs.append(os.path.join(templates_dir, "Imported_h.template"))
397 378
398 h_template = jinja_env.get_template("TypeBuilder_h.template") 379 h_template = jinja_env.get_template("templates/TypeBuilder_h.template")
399 cpp_template = jinja_env.get_template("TypeBuilder_cpp.template") 380 cpp_template = jinja_env.get_template("templates/TypeBuilder_cpp.template")
400 exported_template = jinja_env.get_template("Exported_h.template") 381 exported_template = jinja_env.get_template("templates/Exported_h.template")
401 imported_template = jinja_env.get_template("Imported_h.template") 382 imported_template = jinja_env.get_template("templates/Imported_h.template")
402 383
403 outputs = dict() 384 outputs = dict()
404 385
405 for domain in protocol.json_api["domains"]: 386 for domain in protocol.json_api["domains"]:
406 class_name = domain["domain"] 387 class_name = domain["domain"]
407 template_context = { 388 template_context = {
408 "config": config, 389 "config": config,
409 "domain": domain, 390 "domain": domain,
410 "join_arrays": join_arrays, 391 "join_arrays": join_arrays,
411 "resolve_type": functools.partial(resolve_type, protocol), 392 "resolve_type": functools.partial(resolve_type, protocol),
412 "type_definition": functools.partial(type_definition, protocol), 393 "type_definition": functools.partial(type_definition, protocol),
413 "has_disable": has_disable 394 "has_disable": has_disable
414 } 395 }
415 396
416 if domain["domain"] in protocol.generate_domains: 397 if domain["domain"] in protocol.generate_domains:
417 outputs[os.path.join(config.protocol.output, class_name + ".h")] = h _template.render(template_context) 398 outputs[os.path.join(config.protocol.output, class_name + ".h")] = h _template.render(template_context)
418 outputs[os.path.join(config.protocol.output, class_name + ".cpp")] = cpp_template.render(template_context) 399 outputs[os.path.join(config.protocol.output, class_name + ".cpp")] = cpp_template.render(template_context)
419 if domain["has_exports"]: 400 if domain["has_exports"]:
420 outputs[os.path.join(config.exported.output, class_name + ".h")] = exported_template.render(template_context) 401 outputs[os.path.join(config.exported.output, class_name + ".h")] = exported_template.render(template_context)
421 if domain["domain"] in protocol.imported_domains and domain["has_exports "]: 402 if domain["domain"] in protocol.imported_domains and domain["has_exports "]:
422 outputs[os.path.join(config.protocol.output, class_name + ".h")] = i mported_template.render(template_context) 403 outputs[os.path.join(config.protocol.output, class_name + ".h")] = i mported_template.render(template_context)
423 404
424 if config.lib: 405 if config.lib:
425 template_context = { 406 template_context = {
426 "config": config 407 "config": config
427 } 408 }
428 409
410 lib_templates_dir = os.path.join(module_path, "lib")
429 # Note these should be sorted in the right order. 411 # Note these should be sorted in the right order.
430 # TODO(dgozman): sort them programmatically based on commented includes. 412 # TODO(dgozman): sort them programmatically based on commented includes.
431 lib_h_templates = [ 413 lib_h_templates = [
432 "Collections_h.template", 414 "Collections_h.template",
433 "ErrorSupport_h.template", 415 "ErrorSupport_h.template",
434 "Values_h.template", 416 "Values_h.template",
435 "Object_h.template", 417 "Object_h.template",
436 "ValueConversions_h.template", 418 "ValueConversions_h.template",
437 "Maybe_h.template", 419 "Maybe_h.template",
438 "Array_h.template", 420 "Array_h.template",
(...skipping 13 matching lines...) Expand all
452 434
453 forward_h_templates = [ 435 forward_h_templates = [
454 "Forward_h.template", 436 "Forward_h.template",
455 "Allocator_h.template", 437 "Allocator_h.template",
456 "FrontendChannel_h.template", 438 "FrontendChannel_h.template",
457 ] 439 ]
458 440
459 def generate_lib_file(file_name, template_files): 441 def generate_lib_file(file_name, template_files):
460 parts = [] 442 parts = []
461 for template_file in template_files: 443 for template_file in template_files:
462 inputs.append(os.path.join(templates_dir, template_file)) 444 inputs.append(os.path.join(lib_templates_dir, template_file))
463 template = jinja_env.get_template(template_file) 445 template = jinja_env.get_template("lib/" + template_file)
464 parts.append(template.render(template_context)) 446 parts.append(template.render(template_context))
465 outputs[file_name] = "\n\n".join(parts) 447 outputs[file_name] = "\n\n".join(parts)
466 448
467 generate_lib_file(os.path.join(config.lib.output, "Forward.h"), forward_ h_templates) 449 generate_lib_file(os.path.join(config.lib.output, "Forward.h"), forward_ h_templates)
468 generate_lib_file(os.path.join(config.lib.output, "Protocol.h"), lib_h_t emplates) 450 generate_lib_file(os.path.join(config.lib.output, "Protocol.h"), lib_h_t emplates)
469 generate_lib_file(os.path.join(config.lib.output, "Protocol.cpp"), lib_c pp_templates) 451 generate_lib_file(os.path.join(config.lib.output, "Protocol.cpp"), lib_c pp_templates)
470 452
471 # Make gyp / make generatos happy, otherwise make rebuilds world. 453 # Make gyp / make generatos happy, otherwise make rebuilds world.
472 inputs_ts = max(map(os.path.getmtime, inputs)) 454 inputs_ts = max(map(os.path.getmtime, inputs))
473 up_to_date = True 455 up_to_date = True
474 for output_file in outputs.iterkeys(): 456 for output_file in outputs.iterkeys():
475 if not os.path.exists(output_file) or os.path.getmtime(output_file) < in puts_ts: 457 if not os.path.exists(output_file) or os.path.getmtime(output_file) < in puts_ts:
476 up_to_date = False 458 up_to_date = False
477 break 459 break
478 if up_to_date: 460 if up_to_date:
479 sys.exit() 461 sys.exit()
480 462
481 for file_name, content in outputs.iteritems(): 463 for file_name, content in outputs.iteritems():
482 out_file = open(file_name, "w") 464 out_file = open(file_name, "w")
483 out_file.write(content) 465 out_file.write(content)
484 out_file.close() 466 out_file.close()
485 467
486 468
487 main() 469 main()
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698