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

Side by Side Diff: third_party/WebKit/Source/devtools/scripts/generate_protocol_externs.py

Issue 2441163002: DevTools: clean up scripts folder (Closed)
Patch Set: Created 4 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 (c) 2011 Google Inc. All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
6 # met:
7 #
8 # * Redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer.
10 # * Redistributions in binary form must reproduce the above
11 # copyright notice, this list of conditions and the following disclaimer
12 # in the documentation and/or other materials provided with the
13 # distribution.
14 # * Neither the name of Google Inc. nor the names of its
15 # contributors may be used to endorse or promote products derived from
16 # this software without specific prior written permission.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 import os
31 import re
32 try:
33 import json
34 except ImportError:
35 import simplejson as json
36
37 type_traits = {
38 "any": "*",
39 "string": "string",
40 "integer": "number",
41 "number": "number",
42 "boolean": "boolean",
43 "array": "!Array.<*>",
44 "object": "!Object",
45 }
46
47 promisified_domains = {
48 "Accessibility",
49 "Animation",
50 "Browser",
51 "CSS",
52 "Emulation",
53 "Profiler"
54 }
55
56 ref_types = {}
57
58 def full_qualified_type_id(domain_name, type_id):
59 if type_id.find(".") == -1:
60 return "%s.%s" % (domain_name, type_id)
61 return type_id
62
63
64 def fix_camel_case(name):
65 prefix = ""
66 if name[0] == "-":
67 prefix = "Negative"
68 name = name[1:]
69 refined = re.sub(r'-(\w)', lambda pat: pat.group(1).upper(), name)
70 refined = to_title_case(refined)
71 return prefix + re.sub(r'(?i)HTML|XML|WML|API', lambda pat: pat.group(0).upp er(), refined)
72
73
74 def to_title_case(name):
75 return name[:1].upper() + name[1:]
76
77
78 def generate_enum(name, json):
79 enum_members = []
80 for member in json["enum"]:
81 enum_members.append(" %s: \"%s\"" % (fix_camel_case(member), member))
82 return "\n/** @enum {string} */\n%s = {\n%s\n};\n" % (name, (",\n".join(enum _members)))
83
84
85 def param_type(domain_name, param):
86 if "type" in param:
87 if param["type"] == "array":
88 items = param["items"]
89 return "!Array.<%s>" % param_type(domain_name, items)
90 else:
91 return type_traits[param["type"]]
92 if "$ref" in param:
93 type_id = full_qualified_type_id(domain_name, param["$ref"])
94 if type_id in ref_types:
95 return ref_types[type_id]
96 else:
97 print "Type not found: " + type_id
98 return "!! Type not found: " + type_id
99
100
101 def load_schema(file, domains):
102 input_file = open(file, "r")
103 json_string = input_file.read()
104 parsed_json = json.loads(json_string)
105 domains.extend(parsed_json["domains"])
106
107
108 def generate_protocol_externs(output_path, file1, file2):
109 domains = []
110 load_schema(file1, domains)
111 load_schema(file2, domains)
112 output_file = open(output_path, "w")
113
114 output_file.write(
115 """
116 var InspectorBackend = {}
117
118 var Protocol = {};
119 /** @typedef {string}*/
120 Protocol.Error;
121 """)
122
123 for domain in domains:
124 domain_name = domain["domain"]
125 if "types" in domain:
126 for type in domain["types"]:
127 type_id = full_qualified_type_id(domain_name, type["id"])
128 ref_types[type_id] = "%sAgent.%s" % (domain_name, type["id"])
129
130 for domain in domains:
131 domain_name = domain["domain"]
132 promisified = domain_name in promisified_domains
133
134 output_file.write("\n\n/**\n * @constructor\n*/\n")
135 output_file.write("Protocol.%sAgent = function(){};\n" % domain_name)
136
137 if "commands" in domain:
138 for command in domain["commands"]:
139 output_file.write("\n/**\n")
140 params = []
141 has_return_value = "returns" in command
142 explicit_parameters = promisified and has_return_value
143 if "parameters" in command:
144 for in_param in command["parameters"]:
145 if "optional" in in_param:
146 if explicit_parameters:
147 params.append("%s" % in_param["name"])
148 output_file.write(" * @param {%s|undefined} %s\n " %
149 (param_type(domain_name, in_pa ram), in_param["name"]))
150 else:
151 params.append("opt_%s" % in_param["name"])
152 output_file.write(" * @param {%s=} opt_%s\n" %
153 (param_type(domain_name, in_pa ram), in_param["name"]))
154 else:
155 params.append(in_param["name"])
156 output_file.write(" * @param {%s} %s\n" % (param_typ e(domain_name, in_param), in_param["name"]))
157 returns = []
158 returns.append("?Protocol.Error")
159 if ("error" in command):
160 returns.append("%s=" % param_type(domain_name, command["erro r"]))
161 if (has_return_value):
162 for out_param in command["returns"]:
163 if ("optional" in out_param):
164 returns.append("%s=" % param_type(domain_name, out_p aram))
165 else:
166 returns.append("%s" % param_type(domain_name, out_pa ram))
167 callback_return_type = "void="
168 if explicit_parameters:
169 callback_return_type = "T"
170 elif promisified:
171 callback_return_type = "T="
172 output_file.write(" * @param {function(%s):%s} opt_callback\n" % (", ".join(returns), callback_return_type))
173 if (promisified):
174 output_file.write(" * @return {!Promise.<T>}\n")
175 output_file.write(" * @template T\n")
176 params.append("opt_callback")
177
178 output_file.write(" */\n")
179 output_file.write("Protocol.%sAgent.prototype.%s = function(%s) {}\n" % (domain_name, command["name"], ", ".join(params)))
180 output_file.write("/** @param {function(%s):void=} opt_callback */\n" % ", ".join(returns))
181 output_file.write("Protocol.%sAgent.prototype.invoke_%s = functi on(obj, opt_callback) {}\n" % (domain_name, command["name"]))
182
183 output_file.write("\n\n\nvar %sAgent = function(){};\n" % domain_name)
184
185 if "types" in domain:
186 for type in domain["types"]:
187 if type["type"] == "object":
188 typedef_args = []
189 if "properties" in type:
190 for property in type["properties"]:
191 suffix = ""
192 if ("optional" in property):
193 suffix = "|undefined"
194 if "enum" in property:
195 enum_name = "%sAgent.%s%s" % (domain_name, type[ "id"], to_title_case(property["name"]))
196 output_file.write(generate_enum(enum_name, prope rty))
197 typedef_args.append("%s:(%s%s)" % (property["nam e"], enum_name, suffix))
198 else:
199 typedef_args.append("%s:(%s%s)" % (property["nam e"], param_type(domain_name, property), suffix))
200 if (typedef_args):
201 output_file.write("\n/** @typedef {!{%s}} */\n%sAgent.%s ;\n" % (", ".join(typedef_args), domain_name, type["id"]))
202 else:
203 output_file.write("\n/** @typedef {!Object} */\n%sAgent. %s;\n" % (domain_name, type["id"]))
204 elif type["type"] == "string" and "enum" in type:
205 output_file.write(generate_enum("%sAgent.%s" % (domain_name, type["id"]), type))
206 elif type["type"] == "array":
207 output_file.write("\n/** @typedef {!Array.<!%s>} */\n%sAgent .%s;\n" % (param_type(domain_name, type["items"]), domain_name, type["id"]))
208 else:
209 output_file.write("\n/** @typedef {%s} */\n%sAgent.%s;\n" % (type_traits[type["type"]], domain_name, type["id"]))
210
211 output_file.write("/** @interface */\n")
212 output_file.write("%sAgent.Dispatcher = function() {};\n" % domain_name)
213 if "events" in domain:
214 for event in domain["events"]:
215 params = []
216 if ("parameters" in event):
217 output_file.write("/**\n")
218 for param in event["parameters"]:
219 if ("optional" in param):
220 params.append("opt_%s" % param["name"])
221 output_file.write(" * @param {%s=} opt_%s\n" % (para m_type(domain_name, param), param["name"]))
222 else:
223 params.append(param["name"])
224 output_file.write(" * @param {%s} %s\n" % (param_typ e(domain_name, param), param["name"]))
225 output_file.write(" */\n")
226 output_file.write("%sAgent.Dispatcher.prototype.%s = function(%s ) {};\n" % (domain_name, event["name"], ", ".join(params)))
227
228 output_file.write("\n/** @constructor\n * @param {!Object.<string, !Object>} agentsMap\n */\n")
229 output_file.write("Protocol.Agents = function(agentsMap){this._agentsMap;};\ n")
230 output_file.write("/**\n * @param {string} domain\n * @param {!Object} dispa tcher\n */\n")
231 output_file.write("Protocol.Agents.prototype.registerDispatcher = function(d omain, dispatcher){};\n")
232 for domain in domains:
233 domain_name = domain["domain"]
234 uppercase_length = 0
235 while uppercase_length < len(domain_name) and domain_name[uppercase_leng th].isupper():
236 uppercase_length += 1
237
238 output_file.write("/** @return {!Protocol.%sAgent}*/\n" % domain_name)
239 output_file.write("Protocol.Agents.prototype.%s = function(){};\n" % (do main_name[:uppercase_length].lower() + domain_name[uppercase_length:] + "Agent") )
240
241 output_file.write("/**\n * @param {!%sAgent.Dispatcher} dispatcher\n */\ n" % domain_name)
242 output_file.write("Protocol.Agents.prototype.register%sDispatcher = func tion(dispatcher) {}\n" % domain_name)
243
244
245 output_file.close()
246
247 if __name__ == "__main__":
248 import sys
249 import os.path
250 program_name = os.path.basename(__file__)
251 if len(sys.argv) < 5 or sys.argv[1] != "-o":
252 sys.stderr.write("Usage: %s -o OUTPUT_FILE INPUT_FILE_1 INPUT_FILE_2\n" % program_name)
253 exit(1)
254 output_path = sys.argv[2]
255 input_path_1 = sys.argv[3]
256 input_path_2 = sys.argv[4]
257 generate_protocol_externs(output_path, input_path_1, input_path_2)
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698