blob: 1887dc2cbc3ca11705cbd07e73b223350108c428 [file] [log] [blame]
Joe Gregorio79daca02013-03-29 16:25:52 -04001#!/usr/bin/python
Joe Gregorio20a5aa92011-04-01 17:44:25 -04002#
Craig Citro751b7fb2014-09-23 11:20:38 -07003# Copyright 2014 Google Inc. All Rights Reserved.
Joe Gregorio20a5aa92011-04-01 17:44:25 -04004#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
Joe Gregorio81d92cc2012-07-09 16:46:02 -040017"""Create documentation for generate API surfaces.
18
19Command-line tool that creates documentation for all APIs listed in discovery.
20The documentation is generated from a combination of the discovery document and
21the generated API surface itself.
22"""
Christian Clauss9fdc2b22019-07-22 19:43:21 +020023from __future__ import print_function
Joe Gregorio81d92cc2012-07-09 16:46:02 -040024
Bu Sun Kim66bb32c2019-10-30 10:11:58 -070025__author__ = "jcgregorio@google.com (Joe Gregorio)"
Joe Gregorio20a5aa92011-04-01 17:44:25 -040026
Bu Sun Kimc9773042019-07-17 14:03:17 -070027from collections import OrderedDict
Joe Gregorio79daca02013-03-29 16:25:52 -040028import argparse
Bu Sun Kimc9773042019-07-17 14:03:17 -070029import collections
Craig Citro6ae34d72014-08-18 23:10:09 -070030import json
Joe Gregorioafc45f22011-02-20 16:11:28 -050031import os
Joe Gregorioafc45f22011-02-20 16:11:28 -050032import re
Joe Gregorio79daca02013-03-29 16:25:52 -040033import string
Joe Gregorio20a5aa92011-04-01 17:44:25 -040034import sys
Joe Gregorioafc45f22011-02-20 16:11:28 -050035
John Asmuth864311d2014-04-24 15:46:08 -040036from googleapiclient.discovery import DISCOVERY_URI
37from googleapiclient.discovery import build
38from googleapiclient.discovery import build_from_document
Jon Wayne Parrottfd2f99c2016-02-19 16:02:04 -080039from googleapiclient.discovery import UnknownApiNameOrVersion
Igor Maravić22435292017-01-19 22:28:22 +010040from googleapiclient.http import build_http
Joe Gregorio81d92cc2012-07-09 16:46:02 -040041import uritemplate
42
Joe Gregorio81d92cc2012-07-09 16:46:02 -040043CSS = """<style>
44
45body, h1, h2, h3, div, span, p, pre, a {
46 margin: 0;
47 padding: 0;
48 border: 0;
49 font-weight: inherit;
50 font-style: inherit;
51 font-size: 100%;
52 font-family: inherit;
53 vertical-align: baseline;
54}
55
56body {
57 font-size: 13px;
58 padding: 1em;
59}
60
61h1 {
62 font-size: 26px;
63 margin-bottom: 1em;
64}
65
66h2 {
67 font-size: 24px;
68 margin-bottom: 1em;
69}
70
71h3 {
72 font-size: 20px;
73 margin-bottom: 1em;
74 margin-top: 1em;
75}
76
77pre, code {
78 line-height: 1.5;
79 font-family: Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Lucida Console', monospace;
80}
81
82pre {
83 margin-top: 0.5em;
84}
85
86h1, h2, h3, p {
87 font-family: Arial, sans serif;
88}
89
90h1, h2, h3 {
91 border-bottom: solid #CCC 1px;
92}
93
94.toc_element {
95 margin-top: 0.5em;
96}
97
98.firstline {
99 margin-left: 2 em;
100}
101
102.method {
103 margin-top: 1em;
104 border: solid 1px #CCC;
105 padding: 1em;
106 background: #EEE;
107}
108
109.details {
110 font-weight: bold;
111 font-size: 14px;
112}
113
114</style>
115"""
116
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400117METHOD_TEMPLATE = """<div class="method">
118 <code class="details" id="$name">$name($params)</code>
119 <pre>$doc</pre>
120</div>
121"""
122
123COLLECTION_LINK = """<p class="toc_element">
124 <code><a href="$href">$name()</a></code>
125</p>
126<p class="firstline">Returns the $name Resource.</p>
127"""
128
129METHOD_LINK = """<p class="toc_element">
130 <code><a href="#$name">$name($params)</a></code></p>
131<p class="firstline">$firstline</p>"""
132
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700133BASE = "docs/dyn"
Joe Gregoriobb964352013-03-03 20:45:29 -0500134
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700135DIRECTORY_URI = "https://www.googleapis.com/discovery/v1/apis"
Joe Gregoriobb964352013-03-03 20:45:29 -0500136
Joe Gregorio79daca02013-03-29 16:25:52 -0400137parser = argparse.ArgumentParser(description=__doc__)
Joe Gregoriobb964352013-03-03 20:45:29 -0500138
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700139parser.add_argument(
140 "--discovery_uri_template",
141 default=DISCOVERY_URI,
142 help="URI Template for discovery.",
143)
Joe Gregoriobb964352013-03-03 20:45:29 -0500144
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700145parser.add_argument(
146 "--discovery_uri",
147 default="",
148 help=(
149 "URI of discovery document. If supplied then only "
150 "this API will be documented."
151 ),
152)
Joe Gregoriobb964352013-03-03 20:45:29 -0500153
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700154parser.add_argument(
155 "--directory_uri",
156 default=DIRECTORY_URI,
157 help=("URI of directory document. Unused if --discovery_uri" " is supplied."),
158)
Joe Gregoriobb964352013-03-03 20:45:29 -0500159
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700160parser.add_argument(
161 "--dest", default=BASE, help="Directory name to write documents into."
162)
Joe Gregoriobb964352013-03-03 20:45:29 -0500163
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400164
165def safe_version(version):
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700166 """Create a safe version of the verion string.
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400167
168 Needed so that we can distinguish between versions
169 and sub-collections in URIs. I.e. we don't want
170 adsense_v1.1 to refer to the '1' collection in the v1
171 version of the adsense api.
172
173 Args:
174 version: string, The version string.
175 Returns:
176 The string with '.' replaced with '_'.
177 """
178
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700179 return version.replace(".", "_")
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400180
181
182def unsafe_version(version):
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700183 """Undoes what safe_version() does.
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400184
185 See safe_version() for the details.
186
187
188 Args:
189 version: string, The safe version string.
190 Returns:
191 The string with '_' replaced with '.'.
192 """
193
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700194 return version.replace("_", ".")
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400195
196
197def method_params(doc):
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700198 """Document the parameters of a method.
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400199
200 Args:
201 doc: string, The method's docstring.
202
203 Returns:
204 The method signature as a string.
205 """
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700206 doclines = doc.splitlines()
207 if "Args:" in doclines:
208 begin = doclines.index("Args:")
209 if "Returns:" in doclines[begin + 1 :]:
210 end = doclines.index("Returns:", begin)
211 args = doclines[begin + 1 : end]
212 else:
213 args = doclines[begin + 1 :]
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400214
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700215 parameters = []
216 pname = None
217 desc = ""
218
219 def add_param(pname, desc):
220 if pname is None:
221 return
222 if "(required)" not in desc:
223 pname = pname + "=None"
224 parameters.append(pname)
225
226 for line in args:
227 m = re.search("^\s+([a-zA-Z0-9_]+): (.*)", line)
228 if m is None:
229 desc += line
230 continue
231 add_param(pname, desc)
232 pname = m.group(1)
233 desc = m.group(2)
234 add_param(pname, desc)
235 parameters = ", ".join(parameters)
236 else:
237 parameters = ""
238 return parameters
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400239
240
241def method(name, doc):
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700242 """Documents an individual method.
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400243
244 Args:
245 name: string, Name of the method.
246 doc: string, The methods docstring.
247 """
248
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700249 params = method_params(doc)
250 return string.Template(METHOD_TEMPLATE).substitute(
251 name=name, params=params, doc=doc
252 )
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400253
254
255def breadcrumbs(path, root_discovery):
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700256 """Create the breadcrumb trail to this page of documentation.
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400257
258 Args:
259 path: string, Dot separated name of the resource.
260 root_discovery: Deserialized discovery document.
261
262 Returns:
263 HTML with links to each of the parent resources of this resource.
264 """
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700265 parts = path.split(".")
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400266
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700267 crumbs = []
268 accumulated = []
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400269
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700270 for i, p in enumerate(parts):
271 prefix = ".".join(accumulated)
272 # The first time through prefix will be [], so we avoid adding in a
273 # superfluous '.' to prefix.
274 if prefix:
275 prefix += "."
276 display = p
277 if i == 0:
278 display = root_discovery.get("title", display)
279 crumbs.append('<a href="%s.html">%s</a>' % (prefix + p, display))
280 accumulated.append(p)
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400281
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700282 return " . ".join(crumbs)
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400283
284
285def document_collection(resource, path, root_discovery, discovery, css=CSS):
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700286 """Document a single collection in an API.
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400287
288 Args:
289 resource: Collection or service being documented.
290 path: string, Dot separated name of the resource.
291 root_discovery: Deserialized discovery document.
292 discovery: Deserialized discovery document, but just the portion that
293 describes the resource.
294 css: string, The CSS to include in the generated file.
295 """
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700296 collections = []
297 methods = []
298 resource_name = path.split(".")[-2]
299 html = [
300 "<html><body>",
301 css,
302 "<h1>%s</h1>" % breadcrumbs(path[:-1], root_discovery),
303 "<h2>Instance Methods</h2>",
304 ]
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400305
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700306 # Which methods are for collections.
307 for name in dir(resource):
308 if not name.startswith("_") and callable(getattr(resource, name)):
309 if hasattr(getattr(resource, name), "__is_resource__"):
310 collections.append(name)
311 else:
312 methods.append(name)
Joe Gregorioafc45f22011-02-20 16:11:28 -0500313
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700314 # TOC
315 if collections:
316 for name in collections:
317 if not name.startswith("_") and callable(getattr(resource, name)):
318 href = path + name + ".html"
319 html.append(
320 string.Template(COLLECTION_LINK).substitute(href=href, name=name)
321 )
Joe Gregorioafc45f22011-02-20 16:11:28 -0500322
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700323 if methods:
324 for name in methods:
325 if not name.startswith("_") and callable(getattr(resource, name)):
326 doc = getattr(resource, name).__doc__
327 params = method_params(doc)
328 firstline = doc.splitlines()[0]
329 html.append(
330 string.Template(METHOD_LINK).substitute(
331 name=name, params=params, firstline=firstline
332 )
333 )
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400334
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700335 if methods:
336 html.append("<h3>Method Details</h3>")
337 for name in methods:
338 dname = name.rsplit("_")[0]
339 html.append(method(name, getattr(resource, name).__doc__))
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400340
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700341 html.append("</body></html>")
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400342
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700343 return "\n".join(html)
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400344
345
346def document_collection_recursive(resource, path, root_discovery, discovery):
347
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700348 html = document_collection(resource, path, root_discovery, discovery)
Joe Gregorioafc45f22011-02-20 16:11:28 -0500349
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700350 f = open(os.path.join(FLAGS.dest, path + "html"), "w")
Billy SU84d45612020-04-21 06:15:56 +0800351 if sys.version_info.major < 3:
352 html = html.encode("utf-8")
353
354 f.write(html)
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700355 f.close()
Joe Gregorioafc45f22011-02-20 16:11:28 -0500356
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700357 for name in dir(resource):
358 if (
359 not name.startswith("_")
360 and callable(getattr(resource, name))
361 and hasattr(getattr(resource, name), "__is_resource__")
362 and discovery != {}
363 ):
364 dname = name.rsplit("_")[0]
365 collection = getattr(resource, name)()
366 document_collection_recursive(
367 collection,
368 path + name + ".",
369 root_discovery,
370 discovery["resources"].get(dname, {}),
371 )
372
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400373
Joe Gregorioafc45f22011-02-20 16:11:28 -0500374def document_api(name, version):
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700375 """Document the given API.
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400376
377 Args:
378 name: string, Name of the API.
379 version: string, Version of the API.
380 """
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700381 try:
382 service = build(name, version)
383 except UnknownApiNameOrVersion as e:
384 print("Warning: {} {} found but could not be built.".format(name, version))
385 return
Jon Wayne Parrottfd2f99c2016-02-19 16:02:04 -0800386
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700387 http = build_http()
388 response, content = http.request(
389 uritemplate.expand(
390 FLAGS.discovery_uri_template, {"api": name, "apiVersion": version}
391 )
392 )
393 discovery = json.loads(content)
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400394
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700395 version = safe_version(version)
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400396
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700397 document_collection_recursive(
398 service, "%s_%s." % (name, version), discovery, discovery
399 )
Joe Gregorio81d92cc2012-07-09 16:46:02 -0400400
Joe Gregorioafc45f22011-02-20 16:11:28 -0500401
Joe Gregoriobb964352013-03-03 20:45:29 -0500402def document_api_from_discovery_document(uri):
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700403 """Document the given API.
Joe Gregoriobb964352013-03-03 20:45:29 -0500404
405 Args:
406 uri: string, URI of discovery document.
407 """
Igor Maravić22435292017-01-19 22:28:22 +0100408 http = build_http()
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700409 response, content = http.request(FLAGS.discovery_uri)
410 discovery = json.loads(content)
Bu Sun Kimc9773042019-07-17 14:03:17 -0700411
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700412 service = build_from_document(discovery)
Bu Sun Kimc9773042019-07-17 14:03:17 -0700413
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700414 name = discovery["version"]
415 version = safe_version(discovery["version"])
Bu Sun Kimc9773042019-07-17 14:03:17 -0700416
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700417 document_collection_recursive(
418 service, "%s_%s." % (name, version), discovery, discovery
419 )
420
421
422if __name__ == "__main__":
423 FLAGS = parser.parse_args(sys.argv[1:])
424 if FLAGS.discovery_uri:
425 document_api_from_discovery_document(FLAGS.discovery_uri)
Joe Gregoriobb964352013-03-03 20:45:29 -0500426 else:
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700427 api_directory = collections.defaultdict(list)
428 http = build_http()
429 resp, content = http.request(
430 FLAGS.directory_uri, headers={"X-User-IP": "0.0.0.0"}
431 )
432 if resp.status == 200:
433 directory = json.loads(content)["items"]
434 for api in directory:
435 document_api(api["name"], api["version"])
436 api_directory[api["name"]].append(api["version"])
437
438 # sort by api name and version number
439 for api in api_directory:
440 api_directory[api] = sorted(api_directory[api])
441 api_directory = OrderedDict(
442 sorted(api_directory.items(), key=lambda x: x[0])
443 )
444
445 markdown = []
446 for api, versions in api_directory.items():
447 markdown.append("## %s" % api)
448 for version in versions:
449 markdown.append(
450 "* [%s](http://googleapis.github.io/google-api-python-client/docs/dyn/%s_%s.html)"
451 % (version, api, version)
452 )
453 markdown.append("\n")
454
455 with open("docs/dyn/index.md", "w") as f:
Billy SU84d45612020-04-21 06:15:56 +0800456 markdown = "\n".join(markdown)
457 if sys.version_info.major < 3:
458 markdown = markdown.encode("utf-8")
459 f.write(markdown)
Bu Sun Kim66bb32c2019-10-30 10:11:58 -0700460
461 else:
462 sys.exit("Failed to load the discovery document.")