blob: 12226dc55426224b347e2b064d051fb06bb60f6c [file] [log] [blame]
Blink Reformat4c46d092018-04-07 15:32:37 +00001#!/usr/bin/env python
2# Copyright (c) 2011 Google Inc. All rights reserved.
3# Copyright (c) 2012 Intel Corporation. All rights reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9# * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11# * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15# * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31import os.path
32import sys
33import string
34import optparse
35import re
36try:
37 import json
38except ImportError:
39 import simplejson as json
40
41cmdline_parser = optparse.OptionParser()
42cmdline_parser.add_option("--output_js_dir")
43
44try:
45 arg_options, arg_values = cmdline_parser.parse_args()
46 if (len(arg_values) != 1):
47 raise Exception("Exactly one plain argument expected (found %s)" % len(arg_values))
48 input_json_filename = arg_values[0]
49 output_js_dirname = arg_options.output_js_dir
50 if not output_js_dirname:
51 raise Exception("Output .js directory must be specified")
52except Exception:
53 # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.html
54 exc = sys.exc_info()[1]
55 sys.stderr.write("Failed to parse command-line arguments: %s\n\n" % exc)
56 sys.stderr.write("Usage: <script> some.json --output_js_dir <output_js_dir>\n")
57 exit(1)
58
59
60def fix_camel_case(name):
61 prefix = ""
62 if name[0] == "-":
63 prefix = "Negative"
64 name = name[1:]
65 refined = re.sub(r'-(\w)', lambda pat: pat.group(1).upper(), name)
66 refined = to_title_case(refined)
67 return prefix + re.sub(r'(?i)HTML|XML|WML|API', lambda pat: pat.group(0).upper(), refined)
68
69
70def to_title_case(name):
71 return name[:1].upper() + name[1:]
72
73
74class RawTypes(object):
75
76 @staticmethod
77 def get_js(json_type):
78 if json_type == "boolean":
79 return "boolean"
80 elif json_type == "string":
81 return "string"
82 elif json_type == "array":
83 return "object"
84 elif json_type == "object":
85 return "object"
86 elif json_type == "integer":
87 return "number"
88 elif json_type == "number":
89 return "number"
90 elif json_type == "any":
91 raise Exception("Unsupported")
92 else:
93 raise Exception("Unknown type: %s" % json_type)
94
95
96class TypeData(object):
97
98 def __init__(self, json_type):
99 if "type" not in json_type:
100 raise Exception("Unknown type")
101 json_type_name = json_type["type"]
102 self.raw_type_js_ = RawTypes.get_js(json_type_name)
103
104 def get_raw_type_js(self):
105 return self.raw_type_js_
106
107
108class TypeMap:
109
110 def __init__(self, api):
111 self.map_ = {}
112 for json_domain in api["domains"]:
113 domain_name = json_domain["domain"]
114
115 domain_map = {}
116 self.map_[domain_name] = domain_map
117
118 if "types" in json_domain:
119 for json_type in json_domain["types"]:
120 type_name = json_type["id"]
121 type_data = TypeData(json_type)
122 domain_map[type_name] = type_data
123
124 def get(self, domain_name, type_name):
125 return self.map_[domain_name][type_name]
126
127
128def resolve_param_raw_type_js(json_parameter, scope_domain_name):
129 if "$ref" in json_parameter:
130 json_ref = json_parameter["$ref"]
131 return get_ref_data_js(json_ref, scope_domain_name)
132 elif "type" in json_parameter:
133 json_type = json_parameter["type"]
134 return RawTypes.get_js(json_type)
135 else:
136 raise Exception("Unknown type")
137
138
139def get_ref_data_js(json_ref, scope_domain_name):
140 dot_pos = json_ref.find(".")
141 if dot_pos == -1:
142 domain_name = scope_domain_name
143 type_name = json_ref
144 else:
145 domain_name = json_ref[:dot_pos]
146 type_name = json_ref[dot_pos + 1:]
147
148 return type_map.get(domain_name, type_name).get_raw_type_js()
149
150
151input_file = open(input_json_filename, "r")
152json_string = input_file.read()
153json_api = json.loads(json_string)
154
155
156class Templates:
157
158 def get_this_script_path_(absolute_path):
159 absolute_path = os.path.abspath(absolute_path)
160 components = []
161
162 def fill_recursive(path_part, depth):
163 if depth <= 0 or path_part == '/':
164 return
165 fill_recursive(os.path.dirname(path_part), depth - 1)
166 components.append(os.path.basename(path_part))
167
168 # Typical path is /Source/platform/inspector_protocol/CodeGenerator.py
169 # Let's take 4 components from the real path then.
170 fill_recursive(absolute_path, 4)
171
172 return "/".join(components)
173
174 file_header_ = ("// File is generated by %s\n\n" % get_this_script_path_(sys.argv[0]) +
175 """// Copyright (c) 2011 The Chromium Authors. All rights reserved.
176// Use of this source code is governed by a BSD-style license that can be
177// found in the LICENSE file.
178""")
179
180 backend_js = string.Template(file_header_ + """
181
182$domainInitializers
183""")
184
185
186type_map = TypeMap(json_api)
187
188
189class Generator:
190 backend_js_domain_initializer_list = []
191
192 @staticmethod
193 def go():
194 for json_domain in json_api["domains"]:
195 domain_name = json_domain["domain"]
196 domain_name_lower = domain_name.lower()
197 if domain_name_lower == "console":
198 continue
199
200 Generator.backend_js_domain_initializer_list.append("// %s.\n" % domain_name)
201
202 if "types" in json_domain:
203 for json_type in json_domain["types"]:
204 if "type" in json_type and json_type["type"] == "string" and "enum" in json_type:
205 enum_name = "%s.%s" % (domain_name, json_type["id"])
206 Generator.process_enum(json_type, enum_name)
207 elif json_type["type"] == "object":
208 if "properties" in json_type:
209 for json_property in json_type["properties"]:
210 if "type" in json_property and json_property["type"] == "string" and "enum" in json_property:
211 enum_name = "%s.%s%s" % (domain_name, json_type["id"], to_title_case(json_property["name"]))
212 Generator.process_enum(json_property, enum_name)
213
214 if "events" in json_domain:
215 for json_event in json_domain["events"]:
216 Generator.process_event(json_event, domain_name)
217
218 if "commands" in json_domain:
219 for json_command in json_domain["commands"]:
220 Generator.process_command(json_command, domain_name)
221
222 Generator.backend_js_domain_initializer_list.append("\n")
223
224 @staticmethod
225 def process_enum(json_enum, enum_name):
226 enum_members = []
227 for member in json_enum["enum"]:
228 enum_members.append("%s: \"%s\"" % (fix_camel_case(member), member))
229
230 Generator.backend_js_domain_initializer_list.append("Protocol.inspectorBackend.registerEnum(\"%s\", {%s});\n" %
231 (enum_name, ", ".join(enum_members)))
232
233 @staticmethod
234 def process_event(json_event, domain_name):
235 event_name = json_event["name"]
236
237 json_parameters = json_event.get("parameters")
238
239 backend_js_event_param_list = []
240 if json_parameters:
241 for parameter in json_parameters:
242 parameter_name = parameter["name"]
243 backend_js_event_param_list.append("\"%s\"" % parameter_name)
244
245 Generator.backend_js_domain_initializer_list.append("Protocol.inspectorBackend.registerEvent(\"%s.%s\", [%s]);\n" %
246 (domain_name, event_name, ", ".join(backend_js_event_param_list)))
247
248 @staticmethod
249 def process_command(json_command, domain_name):
250 json_command_name = json_command["name"]
251
252 js_parameters_text = ""
253 if "parameters" in json_command:
254 json_params = json_command["parameters"]
255 js_param_list = []
256
257 for json_parameter in json_params:
258 json_param_name = json_parameter["name"]
259 js_bind_type = resolve_param_raw_type_js(json_parameter, domain_name)
260
261 optional = json_parameter.get("optional")
262
263 js_param_text = "{\"name\": \"%s\", \"type\": \"%s\", \"optional\": %s}" % (json_param_name, js_bind_type, (
264 "true" if ("optional" in json_parameter and json_parameter["optional"]) else "false"))
265
266 js_param_list.append(js_param_text)
267
268 js_parameters_text = ", ".join(js_param_list)
269
270 backend_js_reply_param_list = []
271 if "returns" in json_command:
272 for json_return in json_command["returns"]:
273 json_return_name = json_return["name"]
274 backend_js_reply_param_list.append("\"%s\"" % json_return_name)
275
276 js_reply_list = "[%s]" % ", ".join(backend_js_reply_param_list)
277 if "error" in json_command:
278 has_error_data_param = "true"
279 else:
280 has_error_data_param = "false"
281
282 Generator.backend_js_domain_initializer_list.append(
283 "Protocol.inspectorBackend.registerCommand(\"%s.%s\", [%s], %s, %s);\n" %
284 (domain_name, json_command_name, js_parameters_text, js_reply_list, has_error_data_param))
285
286
287Generator.go()
288
289backend_js_file = open(output_js_dirname + "/InspectorBackendCommands.js", "w")
290
291backend_js_file.write(
292 Templates.backend_js.substitute(
293 None, domainInitializers="".join(Generator.backend_js_domain_initializer_list)))
294
295backend_js_file.close()