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

Side by Side Diff: mojo/public/tools/bindings/run_code_generators.py

Issue 1413343006: Break the circular dependency in the new mojom bindings generation pipeline. (Closed) Base URL: https://github.com/domokit/mojo.git@master
Patch Set: Rename the file that is broken in the index. Created 5 years, 1 month 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
(Empty)
1 #!/usr/bin/env python
2 # Copyright 2015 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 #
6 # This script accepts the output of version 2 of the mojom parser and uses that
7 # data to invoke the code generators.
8 #
9 # This script is not related mojom_bindings_generator.py (which is part of v1
10 # of the mojom parser pipeline).
11
12 import argparse
13 import imp
14 import os
15 import sys
16
17
18 def _ParseCLIArgs():
19 """Parses the command line arguments.
20
21 Returns:
22 tuple<Namespace, list<str>> The first value of the tuple is a Namespace
23 holding the value of the optional args. The second value of the tuple is
24 a list of the remaining arguments.
25 """
26 parser = argparse.ArgumentParser(
27 description='Generate bindings from mojom parser output.')
28 parser.add_argument('-f', '--file-graph', dest='file_graph',
29 help='Location of the parser output. "-" for stdin. '
30 '(default "-")', default='-')
31 parser.add_argument('-p', '--python-bindings-dir', dest='py_bindings_dir',
32 default='out/Debug/python',
33 help='Location of the compiled python bindings')
34 parser.add_argument("-o", "--output-dir", dest="output_dir", default=".",
35 help="output directory for generated files")
36 parser.add_argument("-g", "--generators", dest="generators_string",
37 metavar="GENERATORS",
38 default="c++,dart,go,javascript,java,python",
39 help="comma-separated list of generators")
40 parser.add_argument("-d", "--depth", dest="depth", default=".",
41 help="relative path to the root of the source tree.")
42
43 return parser.parse_known_args()
44
45
46 def _FixPath():
47 # We need to parse command line args before imports so we can find out where
48 # the python bindings are located and add them to sys.path.
49 args, _ = _ParseCLIArgs()
50 sys.path.insert(0, args.py_bindings_dir)
51 sys.path.insert(0, os.path.join(os.path.dirname(
52 os.path.abspath(__file__)), "pylib"))
53
54
55 _FixPath()
56
57
58 from generated import mojom_files_mojom
59 from mojom.generate import mojom_translator
60 from mojo_bindings import serialization
61
62
63 def LoadGenerators(generators_string):
64 if not generators_string:
65 return [] # No generators.
66
67 script_dir = os.path.dirname(os.path.abspath(__file__))
68 generators = []
69 for generator_name in [s.strip() for s in generators_string.split(",")]:
70 # "Built-in" generators:
71 if generator_name.lower() == "c++":
72 generator_name = os.path.join(script_dir, "generators",
73 "mojom_cpp_generator.py")
74 elif generator_name.lower() == "dart":
75 generator_name = os.path.join(script_dir, "generators",
76 "mojom_dart_generator.py")
77 elif generator_name.lower() == "go":
78 generator_name = os.path.join(script_dir, "generators",
79 "mojom_go_generator.py")
80 elif generator_name.lower() == "javascript":
81 generator_name = os.path.join(script_dir, "generators",
82 "mojom_js_generator.py")
83 elif generator_name.lower() == "java":
84 generator_name = os.path.join(script_dir, "generators",
85 "mojom_java_generator.py")
86 elif generator_name.lower() == "python":
87 generator_name = os.path.join(script_dir, "generators",
88 "mojom_python_generator.py")
89 # Specified generator python module:
90 elif generator_name.endswith(".py"):
91 pass
92 else:
93 print "Unknown generator name %s" % generator_name
94 sys.exit(1)
95 generator_module = imp.load_source(os.path.basename(generator_name)[:-3],
96 generator_name)
97 generators.append(generator_module)
98 return generators
99
100
101 def ReadMojomFileGraphFromFile(fp):
102 """Reads a mojom_files_mojom.MojomFileGraph from a file.
103
104 Args:
105 fp: A file pointer from which a serialized mojom_fileS_mojom.MojomFileGraph
106 can be read.
107
108 Returns:
109 The mojom_files_mojom.MojomFileGraph that was deserialized from the file.
110 """
111 data = bytearray(fp.read())
112 context = serialization.RootDeserializationContext(data, [])
113 return mojom_files_mojom.MojomFileGraph.Deserialize(context)
114
115
116 def FixModulePath(module, src_root_path):
117 """Fix the path attribute of the provided module and its imports.
118
119 The path provided for the various modules is the absolute path to the mojom
120 file which the module represents. But the generators expect the path to be
121 relative to the root of the source tree.
122
123 Args:
124 module: {module.Module} whose path is to be updated.
125 abs_root: {str} absolute path to the root of the source tree.
126 """
127 module.path = os.path.relpath(module.path, src_root_path)
128 for import_dict in module.imports:
129 FixModulePath(import_dict['module'], src_root_path)
130
131
132 def main():
133 args, remaining_args = _ParseCLIArgs()
134
135 if args.file_graph == '-':
136 fp = sys.stdin
137 else:
138 fp = open(args.file_graph)
139
140 mojom_file_graph = ReadMojomFileGraphFromFile(fp)
141 modules = mojom_translator.TranslateFileGraph(mojom_file_graph)
142
143 generator_modules = LoadGenerators(args.generators_string)
144
145 for _, module in modules.iteritems():
146 FixModulePath(module, os.path.abspath(args.depth))
147 for generator_module in generator_modules:
148 generator = generator_module.Generator(module, args.output_dir)
149
150 # Look at unparsed args for generator-specific args.
151 filtered_args = []
152 if hasattr(generator_module, 'GENERATOR_PREFIX'):
153 prefix = '--' + generator_module.GENERATOR_PREFIX + '_'
154 filtered_args = [arg for arg in remaining_args
155 if arg.startswith(prefix)]
156
157 generator.GenerateFiles(filtered_args)
158
159
160 if __name__ == "__main__":
161 sys.exit(main())
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698