Skip to content

Commit d35c912

Browse files
authored
chore: code clean up (#1442)
Thank you for opening a Pull Request! Before submitting your PR, there are a few things you can do to make sure it goes smoothly: - [x] Make sure to open an issue as a [bug/issue](https://github.com/googleapis/google-api-python-client/issues/new/choose) before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea - [x] Ensure the tests and linter pass - [x] Code coverage does not decrease (if any source code was changed) - [x] Appropriate docs were updated (if necessary) Fixes #1441 🦕
1 parent 5489f52 commit d35c912

File tree

4 files changed

+719
-681
lines changed

4 files changed

+719
-681
lines changed

describe.py

Lines changed: 90 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424

2525
__author__ = "[email protected] (Joe Gregorio)"
2626

27-
from collections import OrderedDict
2827
import argparse
2928
import collections
3029
import json
@@ -36,14 +35,15 @@
3635
from googleapiclient.discovery import DISCOVERY_URI
3736
from googleapiclient.discovery import build
3837
from googleapiclient.discovery import build_from_document
39-
from googleapiclient.discovery import UnknownApiNameOrVersion
4038
from googleapiclient.http import build_http
41-
from googleapiclient.errors import HttpError
4239

4340
import uritemplate
4441

4542
DISCOVERY_DOC_DIR = (
46-
pathlib.Path(__file__).parent.resolve() / "googleapiclient" / "discovery_cache" / "documents"
43+
pathlib.Path(__file__).parent.resolve()
44+
/ "googleapiclient"
45+
/ "discovery_cache"
46+
/ "documents"
4747
)
4848

4949
CSS = """<style>
@@ -171,44 +171,44 @@
171171
def safe_version(version):
172172
"""Create a safe version of the verion string.
173173
174-
Needed so that we can distinguish between versions
175-
and sub-collections in URIs. I.e. we don't want
176-
adsense_v1.1 to refer to the '1' collection in the v1
177-
version of the adsense api.
174+
Needed so that we can distinguish between versions
175+
and sub-collections in URIs. I.e. we don't want
176+
adsense_v1.1 to refer to the '1' collection in the v1
177+
version of the adsense api.
178178
179-
Args:
180-
version: string, The version string.
181-
Returns:
182-
The string with '.' replaced with '_'.
183-
"""
179+
Args:
180+
version: string, The version string.
181+
Returns:
182+
The string with '.' replaced with '_'.
183+
"""
184184

185185
return version.replace(".", "_")
186186

187187

188188
def unsafe_version(version):
189189
"""Undoes what safe_version() does.
190190
191-
See safe_version() for the details.
191+
See safe_version() for the details.
192192
193193
194-
Args:
195-
version: string, The safe version string.
196-
Returns:
197-
The string with '_' replaced with '.'.
198-
"""
194+
Args:
195+
version: string, The safe version string.
196+
Returns:
197+
The string with '_' replaced with '.'.
198+
"""
199199

200200
return version.replace("_", ".")
201201

202202

203203
def method_params(doc):
204204
"""Document the parameters of a method.
205205
206-
Args:
207-
doc: string, The method's docstring.
206+
Args:
207+
doc: string, The method's docstring.
208208
209-
Returns:
210-
The method signature as a string.
211-
"""
209+
Returns:
210+
The method signature as a string.
211+
"""
212212
doclines = doc.splitlines()
213213
if "Args:" in doclines:
214214
begin = doclines.index("Args:")
@@ -253,10 +253,10 @@ def add_param(pname, desc):
253253
def method(name, doc):
254254
"""Documents an individual method.
255255
256-
Args:
257-
name: string, Name of the method.
258-
doc: string, The methods docstring.
259-
"""
256+
Args:
257+
name: string, Name of the method.
258+
doc: string, The methods docstring.
259+
"""
260260
import html
261261

262262
params = method_params(doc)
@@ -269,13 +269,13 @@ def method(name, doc):
269269
def breadcrumbs(path, root_discovery):
270270
"""Create the breadcrumb trail to this page of documentation.
271271
272-
Args:
273-
path: string, Dot separated name of the resource.
274-
root_discovery: Deserialized discovery document.
272+
Args:
273+
path: string, Dot separated name of the resource.
274+
root_discovery: Deserialized discovery document.
275275
276-
Returns:
277-
HTML with links to each of the parent resources of this resource.
278-
"""
276+
Returns:
277+
HTML with links to each of the parent resources of this resource.
278+
"""
279279
parts = path.split(".")
280280

281281
crumbs = []
@@ -299,14 +299,14 @@ def breadcrumbs(path, root_discovery):
299299
def document_collection(resource, path, root_discovery, discovery, css=CSS):
300300
"""Document a single collection in an API.
301301
302-
Args:
303-
resource: Collection or service being documented.
304-
path: string, Dot separated name of the resource.
305-
root_discovery: Deserialized discovery document.
306-
discovery: Deserialized discovery document, but just the portion that
307-
describes the resource.
308-
css: string, The CSS to include in the generated file.
309-
"""
302+
Args:
303+
resource: Collection or service being documented.
304+
path: string, Dot separated name of the resource.
305+
root_discovery: Deserialized discovery document.
306+
discovery: Deserialized discovery document, but just the portion that
307+
describes the resource.
308+
css: string, The CSS to include in the generated file.
309+
"""
310310
collections = []
311311
methods = []
312312
resource_name = path.split(".")[-2]
@@ -357,7 +357,9 @@ def document_collection(resource, path, root_discovery, discovery, css=CSS):
357357
return "\n".join(html)
358358

359359

360-
def document_collection_recursive(resource, path, root_discovery, discovery, doc_destination_dir):
360+
def document_collection_recursive(
361+
resource, path, root_discovery, discovery, doc_destination_dir
362+
):
361363
html = document_collection(resource, path, root_discovery, discovery)
362364

363365
f = open(pathlib.Path(doc_destination_dir).joinpath(path + "html"), "w")
@@ -379,7 +381,7 @@ def document_collection_recursive(resource, path, root_discovery, discovery, doc
379381
path + name + ".",
380382
root_discovery,
381383
discovery["resources"].get(dname, {}),
382-
doc_destination_dir
384+
doc_destination_dir,
383385
)
384386

385387

@@ -392,10 +394,11 @@ def document_api(name, version, uri, doc_destination_dir):
392394
uri (str): URI of the API's discovery document
393395
doc_destination_dir (str): relative path where the reference
394396
documentation should be saved.
395-
"""
397+
"""
396398
http = build_http()
397399
resp, content = http.request(
398-
uri or uritemplate.expand(
400+
uri
401+
or uritemplate.expand(
399402
FLAGS.discovery_uri_template, {"api": name, "apiVersion": version}
400403
)
401404
)
@@ -413,11 +416,11 @@ def document_api(name, version, uri, doc_destination_dir):
413416
with open(discovery_file_path, "r+") as f:
414417
try:
415418
json_data = json.load(f)
416-
revision = json_data['revision']
419+
revision = json_data["revision"]
417420
except json.JSONDecodeError:
418421
revision = None
419422

420-
if revision is None or discovery['revision'] >= revision:
423+
if revision is None or discovery["revision"] >= revision:
421424
# Reset position to the beginning
422425
f.seek(0)
423426
# Write the changes to disk
@@ -426,25 +429,35 @@ def document_api(name, version, uri, doc_destination_dir):
426429
f.truncate()
427430

428431
elif resp.status == 404:
429-
print("Warning: {} {} not found. HTTP Code: {}".format(name, version, resp.status))
432+
print(
433+
"Warning: {} {} not found. HTTP Code: {}".format(name, version, resp.status)
434+
)
430435
return
431436
else:
432-
print("Warning: {} {} could not be built. HTTP Code: {}".format(name, version, resp.status))
437+
print(
438+
"Warning: {} {} could not be built. HTTP Code: {}".format(
439+
name, version, resp.status
440+
)
441+
)
433442
return
434443

435444
document_collection_recursive(
436-
service, "{}_{}.".format(name, safe_version(version)), discovery, discovery, doc_destination_dir
445+
service,
446+
"{}_{}.".format(name, safe_version(version)),
447+
discovery,
448+
discovery,
449+
doc_destination_dir,
437450
)
438451

439452

440453
def document_api_from_discovery_document(discovery_url, doc_destination_dir):
441454
"""Document the given API.
442455
443-
Args:
444-
discovery_url (str): URI of discovery document.
445-
doc_destination_dir (str): relative path where the reference
446-
documentation should be saved.
447-
"""
456+
Args:
457+
discovery_url (str): URI of discovery document.
458+
doc_destination_dir (str): relative path where the reference
459+
documentation should be saved.
460+
"""
448461
http = build_http()
449462
response, content = http.request(discovery_url)
450463
discovery = json.loads(content)
@@ -455,11 +468,16 @@ def document_api_from_discovery_document(discovery_url, doc_destination_dir):
455468
version = safe_version(discovery["version"])
456469

457470
document_collection_recursive(
458-
service, "{}_{}.".format(name, version), discovery, discovery, doc_destination_dir
471+
service,
472+
"{}_{}.".format(name, version),
473+
discovery,
474+
discovery,
475+
doc_destination_dir,
459476
)
460477

478+
461479
def generate_all_api_documents(directory_uri=DIRECTORY_URI, doc_destination_dir=BASE):
462-
""" Retrieve discovery artifacts and fetch reference documentations
480+
"""Retrieve discovery artifacts and fetch reference documentations
463481
for all apis listed in the public discovery directory.
464482
args:
465483
directory_uri (str): uri of the public discovery directory.
@@ -472,13 +490,18 @@ def generate_all_api_documents(directory_uri=DIRECTORY_URI, doc_destination_dir=
472490
if resp.status == 200:
473491
directory = json.loads(content)["items"]
474492
for api in directory:
475-
document_api(api["name"], api["version"], api["discoveryRestUrl"], doc_destination_dir)
493+
document_api(
494+
api["name"],
495+
api["version"],
496+
api["discoveryRestUrl"],
497+
doc_destination_dir,
498+
)
476499
api_directory[api["name"]].append(api["version"])
477500

478501
# sort by api name and version number
479502
for api in api_directory:
480503
api_directory[api] = sorted(api_directory[api])
481-
api_directory = OrderedDict(
504+
api_directory = collections.OrderedDict(
482505
sorted(api_directory.items(), key=lambda x: x[0])
483506
)
484507

@@ -499,9 +522,14 @@ def generate_all_api_documents(directory_uri=DIRECTORY_URI, doc_destination_dir=
499522
else:
500523
sys.exit("Failed to load the discovery document.")
501524

525+
502526
if __name__ == "__main__":
503527
FLAGS = parser.parse_args(sys.argv[1:])
504528
if FLAGS.discovery_uri:
505-
document_api_from_discovery_document(discovery_url=FLAGS.discovery_uri, doc_destination_dir=FLAGS.dest)
529+
document_api_from_discovery_document(
530+
discovery_url=FLAGS.discovery_uri, doc_destination_dir=FLAGS.dest
531+
)
506532
else:
507-
generate_all_api_documents(directory_uri=FLAGS.directory_uri, doc_destination_dir=FLAGS.dest)
533+
generate_all_api_documents(
534+
directory_uri=FLAGS.directory_uri, doc_destination_dir=FLAGS.dest
535+
)

0 commit comments

Comments
 (0)