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

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

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

Powered by Google App Engine
This is Rietveld 408576698