blob: 8646d33592e9de0718b403562aa9dbfad6e2a3b9 [file] [log] [blame]
Liviu Rau3da5d4a2022-02-23 11:07:121#!/usr/bin/env vpython3
Blink Reformat4c46d092018-04-07 15:32:372# 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
Blink Reformat4c46d092018-04-07 15:32:3731import sys
32import string
Blink Reformat4c46d092018-04-07 15:32:3733import re
Tim van der Lippeb3b90762020-03-04 15:21:5234from os import path
35
Blink Reformat4c46d092018-04-07 15:32:3736try:
37 import json
38except ImportError:
39 import simplejson as json
40
Tim van der Lippeb3b90762020-03-04 15:21:5241ROOT_DIRECTORY = path.join(path.dirname(__file__), '..', '..')
42GENERATED_LOCATION = path.join(ROOT_DIRECTORY, 'front_end', 'generated', 'InspectorBackendCommands.js')
43READ_LOCATION = path.join(ROOT_DIRECTORY, 'third_party', 'blink', 'public', 'devtools_protocol', 'browser_protocol.json')
Blink Reformat4c46d092018-04-07 15:32:3744
45
46def fix_camel_case(name):
47 prefix = ""
48 if name[0] == "-":
49 prefix = "Negative"
50 name = name[1:]
51 refined = re.sub(r'-(\w)', lambda pat: pat.group(1).upper(), name)
52 refined = to_title_case(refined)
53 return prefix + re.sub(r'(?i)HTML|XML|WML|API', lambda pat: pat.group(0).upper(), refined)
54
55
56def to_title_case(name):
57 return name[:1].upper() + name[1:]
58
59
60class RawTypes(object):
61
62 @staticmethod
63 def get_js(json_type):
64 if json_type == "boolean":
65 return "boolean"
66 elif json_type == "string":
67 return "string"
Johannes Henkelff4efae2018-10-16 17:55:5868 elif json_type == "binary":
69 return "string"
Blink Reformat4c46d092018-04-07 15:32:3770 elif json_type == "array":
71 return "object"
72 elif json_type == "object":
73 return "object"
74 elif json_type == "integer":
75 return "number"
76 elif json_type == "number":
77 return "number"
78 elif json_type == "any":
79 raise Exception("Unsupported")
80 else:
81 raise Exception("Unknown type: %s" % json_type)
82
83
84class TypeData(object):
85
86 def __init__(self, json_type):
87 if "type" not in json_type:
88 raise Exception("Unknown type")
89 json_type_name = json_type["type"]
90 self.raw_type_js_ = RawTypes.get_js(json_type_name)
91
92 def get_raw_type_js(self):
93 return self.raw_type_js_
94
95
96class TypeMap:
97
98 def __init__(self, api):
99 self.map_ = {}
100 for json_domain in api["domains"]:
101 domain_name = json_domain["domain"]
102
103 domain_map = {}
104 self.map_[domain_name] = domain_map
105
106 if "types" in json_domain:
107 for json_type in json_domain["types"]:
108 type_name = json_type["id"]
109 type_data = TypeData(json_type)
110 domain_map[type_name] = type_data
111
112 def get(self, domain_name, type_name):
113 return self.map_[domain_name][type_name]
114
115
116def resolve_param_raw_type_js(json_parameter, scope_domain_name):
117 if "$ref" in json_parameter:
118 json_ref = json_parameter["$ref"]
119 return get_ref_data_js(json_ref, scope_domain_name)
120 elif "type" in json_parameter:
121 json_type = json_parameter["type"]
122 return RawTypes.get_js(json_type)
123 else:
124 raise Exception("Unknown type")
125
126
127def get_ref_data_js(json_ref, scope_domain_name):
128 dot_pos = json_ref.find(".")
129 if dot_pos == -1:
130 domain_name = scope_domain_name
131 type_name = json_ref
132 else:
133 domain_name = json_ref[:dot_pos]
134 type_name = json_ref[dot_pos + 1:]
135
136 return type_map.get(domain_name, type_name).get_raw_type_js()
137
138
Tim van der Lippeb3b90762020-03-04 15:21:52139input_file = open(READ_LOCATION, "r")
Blink Reformat4c46d092018-04-07 15:32:37140json_string = input_file.read()
141json_api = json.loads(json_string)
142
143
144class Templates:
145
146 def get_this_script_path_(absolute_path):
Tim van der Lippeb3b90762020-03-04 15:21:52147 absolute_path = path.abspath(absolute_path)
Blink Reformat4c46d092018-04-07 15:32:37148 components = []
149
150 def fill_recursive(path_part, depth):
151 if depth <= 0 or path_part == '/':
152 return
Tim van der Lippeb3b90762020-03-04 15:21:52153 fill_recursive(path.dirname(path_part), depth - 1)
154 components.append(path.basename(path_part))
Blink Reformat4c46d092018-04-07 15:32:37155
156 # Typical path is /Source/platform/inspector_protocol/CodeGenerator.py
157 # Let's take 4 components from the real path then.
158 fill_recursive(absolute_path, 4)
159
160 return "/".join(components)
161
Tim van der Lippe0a2971a2020-06-04 12:03:41162 file_header_ = (
163 """// Copyright (c) 2020 The Chromium Authors. All rights reserved.
Blink Reformat4c46d092018-04-07 15:32:37164// Use of this source code is governed by a BSD-style license that can be
165// found in the LICENSE file.
Sigurd Schneiderb509ae72021-08-05 10:38:20166""" + "// File is generated by %s\n" % get_this_script_path_(sys.argv[0]) + """
Tim van der Lippe5d2d79b2020-03-23 11:45:04167/**
168 * @typedef {{
Sigurd Schneider297b80b2021-07-05 09:46:54169 * registerCommand: function(string&any, !Array.<!{name: string, type: string, optional: boolean}>, !Array.<string>):void,
170 * registerEnum: function(string&any, !Object<string, string>):void,
171 * registerEvent: function(string&any, !Array<string>):void,
Tim van der Lippe5d2d79b2020-03-23 11:45:04172 * }}
173 */
174// @ts-ignore typedef
175export let InspectorBackendAPI;
176
177/**
178 * @param {!InspectorBackendAPI} inspectorBackend
179 */
Tim van der Lippe4d1ddf72020-01-23 13:02:14180export function registerCommands(inspectorBackend) {
Blink Reformat4c46d092018-04-07 15:32:37181""")
182
183 backend_js = string.Template(file_header_ + """
184
185$domainInitializers
Tim van der Lippe4d1ddf72020-01-23 13:02:14186}
Blink Reformat4c46d092018-04-07 15:32:37187""")
188
189
190type_map = TypeMap(json_api)
191
192
193class Generator:
194 backend_js_domain_initializer_list = []
195
196 @staticmethod
197 def go():
198 for json_domain in json_api["domains"]:
199 domain_name = json_domain["domain"]
200 domain_name_lower = domain_name.lower()
201 if domain_name_lower == "console":
202 continue
203
204 Generator.backend_js_domain_initializer_list.append("// %s.\n" % domain_name)
205
206 if "types" in json_domain:
207 for json_type in json_domain["types"]:
208 if "type" in json_type and json_type["type"] == "string" and "enum" in json_type:
209 enum_name = "%s.%s" % (domain_name, json_type["id"])
210 Generator.process_enum(json_type, enum_name)
211 elif json_type["type"] == "object":
212 if "properties" in json_type:
213 for json_property in json_type["properties"]:
214 if "type" in json_property and json_property["type"] == "string" and "enum" in json_property:
215 enum_name = "%s.%s%s" % (domain_name, json_type["id"], to_title_case(json_property["name"]))
216 Generator.process_enum(json_property, enum_name)
217
218 if "events" in json_domain:
219 for json_event in json_domain["events"]:
Sigurd Schneider66497cc2020-11-26 14:05:54220 if "parameters" in json_event:
221 for param in json_event["parameters"]:
222 if "enum" in param:
223 enum_name = "%s.%sEvent%s" % (
224 domain_name,
225 to_title_case(json_event["name"]),
226 to_title_case(param["name"]))
227 Generator.process_enum(param, enum_name)
Blink Reformat4c46d092018-04-07 15:32:37228 Generator.process_event(json_event, domain_name)
229
230 if "commands" in json_domain:
231 for json_command in json_domain["commands"]:
Jan Schefflere6ca9bd2020-05-15 13:35:34232 if "parameters" in json_command:
233 for param in json_command["parameters"]:
234 if "enum" in param:
235 enum_name = "%s.%sRequest%s" % (
236 domain_name,
237 to_title_case(json_command["name"]),
238 to_title_case(param["name"]))
239 Generator.process_enum(param, enum_name)
Blink Reformat4c46d092018-04-07 15:32:37240 Generator.process_command(json_command, domain_name)
241
242 Generator.backend_js_domain_initializer_list.append("\n")
243
244 @staticmethod
245 def process_enum(json_enum, enum_name):
246 enum_members = []
247 for member in json_enum["enum"]:
248 enum_members.append("%s: \"%s\"" % (fix_camel_case(member), member))
249
Yang Guo4fd355c2019-09-19 08:59:03250 Generator.backend_js_domain_initializer_list.append(
Tim van der Lippe4d1ddf72020-01-23 13:02:14251 "inspectorBackend.registerEnum(\"%s\", {%s});\n" % (enum_name, ", ".join(enum_members)))
Blink Reformat4c46d092018-04-07 15:32:37252
253 @staticmethod
254 def process_event(json_event, domain_name):
255 event_name = json_event["name"]
256
257 json_parameters = json_event.get("parameters")
258
259 backend_js_event_param_list = []
260 if json_parameters:
261 for parameter in json_parameters:
262 parameter_name = parameter["name"]
263 backend_js_event_param_list.append("\"%s\"" % parameter_name)
264
Tim van der Lippe4d1ddf72020-01-23 13:02:14265 Generator.backend_js_domain_initializer_list.append("inspectorBackend.registerEvent(\"%s.%s\", [%s]);\n" %
Blink Reformat4c46d092018-04-07 15:32:37266 (domain_name, event_name, ", ".join(backend_js_event_param_list)))
267
268 @staticmethod
269 def process_command(json_command, domain_name):
270 json_command_name = json_command["name"]
271
272 js_parameters_text = ""
273 if "parameters" in json_command:
274 json_params = json_command["parameters"]
275 js_param_list = []
276
277 for json_parameter in json_params:
278 json_param_name = json_parameter["name"]
279 js_bind_type = resolve_param_raw_type_js(json_parameter, domain_name)
280
281 optional = json_parameter.get("optional")
282
283 js_param_text = "{\"name\": \"%s\", \"type\": \"%s\", \"optional\": %s}" % (json_param_name, js_bind_type, (
284 "true" if ("optional" in json_parameter and json_parameter["optional"]) else "false"))
285
286 js_param_list.append(js_param_text)
287
288 js_parameters_text = ", ".join(js_param_list)
289
290 backend_js_reply_param_list = []
291 if "returns" in json_command:
292 for json_return in json_command["returns"]:
293 json_return_name = json_return["name"]
294 backend_js_reply_param_list.append("\"%s\"" % json_return_name)
295
296 js_reply_list = "[%s]" % ", ".join(backend_js_reply_param_list)
Blink Reformat4c46d092018-04-07 15:32:37297
298 Generator.backend_js_domain_initializer_list.append(
Tim van der Lippe0a2971a2020-06-04 12:03:41299 "inspectorBackend.registerCommand(\"%s.%s\", [%s], %s);\n" %
300 (domain_name, json_command_name, js_parameters_text,
301 js_reply_list))
Blink Reformat4c46d092018-04-07 15:32:37302
303
304Generator.go()
305
Tim van der Lippeb3b90762020-03-04 15:21:52306backend_js_file = open(GENERATED_LOCATION, "w+")
Blink Reformat4c46d092018-04-07 15:32:37307
308backend_js_file.write(
Yang Guo4fd355c2019-09-19 08:59:03309 Templates.backend_js.substitute(None, domainInitializers="".join(Generator.backend_js_domain_initializer_list)))
Blink Reformat4c46d092018-04-07 15:32:37310
311backend_js_file.close()