-
Notifications
You must be signed in to change notification settings - Fork 7
/
extension.py
2235 lines (1870 loc) · 83.4 KB
/
extension.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -*- coding: utf-8 -*-
"""
Sphinx DocFX YAML Top-level Extension.
This extension allows you to automagically generate DocFX YAML from your Python AutoAPI docs.
"""
import ast
from collections import defaultdict
from collections.abc import Mapping, MutableSet, Sequence
import copy
from functools import partial
import inspect
from itertools import zip_longest
import json
import logging
import os
from pathlib import Path
import re
import shutil
from typing import Any, Dict, Iterable, List, Optional
import black
from black import InvalidInput
try:
from subprocess import getoutput
except ImportError:
from commands import getoutput
from yaml import safe_dump as dump
import sphinx.application
from sphinx.util.console import darkgreen, bold
from sphinx.util import ensuredir
from sphinx.errors import ExtensionError
from sphinx.util.nodes import make_refnode
from sphinx.ext.napoleon import GoogleDocstring
from sphinx.ext.napoleon import Config
from sphinx.ext.napoleon import _process_docstring
from .utils import transform_node, transform_string
from .settings import API_ROOT
from .monkeypatch import patch_docfields
from .directives import RemarksDirective, TodoDirective
from .nodes import remarks
from docfx_yaml import markdown_utils
import subprocess
import ast
from docuploader import shell
class Bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
try:
from conf import *
except ImportError:
print(Bcolors.FAIL + 'can not import conf.py! '
'you should have a conf.py in working project folder' + Bcolors.ENDC)
METHOD = 'method'
FUNCTION = 'function'
MODULE = 'module'
CLASS = 'class'
EXCEPTION = 'exception'
ATTRIBUTE = 'attribute'
REFMETHOD = 'meth'
REFFUNCTION = 'func'
INITPY = '__init__.py'
# Regex expression for checking references of pattern like ":class:`~package_v1.module`"
REF_PATTERN = r':(py:)?(func|class|meth|mod|ref|attr|exc):`~?[a-zA-Z0-9_.<> ]*(\(\))?`'
# Regex expression for checking references of pattern like "~package_v1.subpackage.module"
REF_PATTERN_LAST = r'~([a-zA-Z0-9_<>]*\.)*[a-zA-Z0-9_<>]*(\(\))?'
# Regex expression for checking references of pattern like
# "[module][google.cloud.cloudkms_v1.module]"
REF_PATTERN_BRACKETS = r'\[[a-zA-Z0-9_<>\-. ]+\]\[[a-zA-Z0-9_<>\-. ]+\]'
REF_PATTERNS = [
REF_PATTERN,
REF_PATTERN_LAST,
REF_PATTERN_BRACKETS,
]
PROPERTY = 'property'
CODEBLOCK = "code-block"
CODE = "code"
PACKAGE = "package"
# DevSite specific notices that can be used.
NOTE = 'note'
CAUTION = 'caution'
WARNING = 'warning'
IMPORTANT = 'special'
KEYPOINT = 'key-point'
KEYTERM = 'key-term'
OBJECTIVE = 'objective'
SUCCESS = 'success'
BETA = 'beta'
PREVIEW = 'preview'
DEPRECATED = 'deprecated'
NOTICES = {
NOTE: 'Note',
CAUTION: 'Caution',
WARNING: 'Warning',
IMPORTANT: 'Important',
KEYPOINT: 'Key Point',
KEYTERM: 'Key Term',
OBJECTIVE: 'Objective',
SUCCESS: 'Success',
BETA: 'Beta',
PREVIEW: 'Preview',
DEPRECATED: 'deprecated',
}
_SUMMARY_TYPE_BY_ITEM_TYPE = {
# Modules and Classes are similar types.
MODULE: CLASS,
CLASS: CLASS,
# Methods and Functions are similar types.
METHOD: METHOD,
FUNCTION: METHOD,
# Properties and Attributes are similar types.
PROPERTY: PROPERTY,
ATTRIBUTE: PROPERTY,
}
# Construct a mapping of name and content for each unique summary type entry.
_ENTRY_NAME_AND_ENTRY_CONTENT_BY_SUMMARY_TYPE = {
summary_type: [[], []] # entry name then entry content
for summary_type in set(_SUMMARY_TYPE_BY_ITEM_TYPE.values())
}
# Mapping for each summary page entry's file name and entry name.
_FILE_NAME_AND_ENTRY_NAME_BY_SUMMARY_TYPE = {
CLASS: ('summary_class.yml', "Classes"),
METHOD: ('summary_method.yml', "Methods"),
PROPERTY: ('summary_property.yml', "Properties and Attributes"),
}
# Disable blib2to3 output that clutters debugging log.
logging.getLogger("blib2to3").setLevel(logging.ERROR)
def _grab_repo_metadata() -> Mapping[str, str] | None:
"""Retrieves the repository's metadata info if found."""
try:
with open('.repo-metadata.json', 'r') as metadata_file:
json_content = json.load(metadata_file)
# Return outside of context manager for safe close
return json_content
except Exception:
return None
def build_init(app):
print("Retrieving repository metadata.")
if not (repo_metadata := _grab_repo_metadata()):
print("Failed to retrieve repository metadata.")
app.env.library_shortname = ""
else:
print("Successfully retrieved repository metadata.")
app.env.library_shortname = repo_metadata["name"]
print("Running sphinx-build with Markdown first...")
markdown_utils.run_sphinx_markdown()
print("Completed running sphinx-build with Markdown files.")
"""
Set up environment data
"""
if not app.config.docfx_yaml_output:
raise ExtensionError('You must configure an docfx_yaml_output setting')
# This stores YAML object for modules
app.env.docfx_yaml_modules = {}
# This stores YAML object for classes
app.env.docfx_yaml_classes = {}
# This stores YAML object for functions
app.env.docfx_yaml_functions = {}
# This store the data extracted from the info fields
app.env.docfx_info_field_data = {}
# This stores signature for functions and methods
app.env.docfx_signature_funcs_methods = {}
# This store the uid-type mapping info
app.env.docfx_info_uid_types = {}
# This stores uidnames of docstrings already parsed
app.env.docfx_uid_names = {}
# This stores file path for class when inspect cannot retrieve file path
app.env.docfx_class_paths = {}
# This stores the name and href of the nested markdown pages.
app.env.markdown_pages = defaultdict(list)
# This stores all the markdown pages moved from the plugin, will be used
# to compare and delete unused pages.
app.env.moved_markdown_pages = set()
app.env.docfx_xrefs = {}
remote = getoutput('git remote -v')
try:
app.env.docfx_remote = remote.split('\t')[1].split(' ')[0]
except Exception:
app.env.docfx_remote = None
try:
app.env.docfx_branch = getoutput('git rev-parse --abbrev-ref HEAD').strip()
except Exception:
app.env.docfx_branch = None
try:
app.env.docfx_root = getoutput('git rev-parse --show-toplevel').strip()
except Exception:
app.env.docfx_root = None
patch_docfields(app)
app.docfx_transform_node = partial(transform_node, app)
app.docfx_transform_string = partial(transform_string, app)
def _get_cls_module(_type, name):
"""
Get the class and module name for an object
.. _sending:
Foo
"""
cls = None
if _type in [FUNCTION, EXCEPTION]:
module = '.'.join(name.split('.')[:-1])
elif _type in [METHOD, ATTRIBUTE, PROPERTY]:
cls = '.'.join(name.split('.')[:-1])
module = '.'.join(name.split('.')[:-2])
elif _type in [CLASS]:
cls = name
module = '.'.join(name.split('.')[:-1])
elif _type in [MODULE]:
module = name
else:
return (None, None)
return (cls, module)
def _create_reference(datam, parent, is_external=False):
return {
'uid': datam['uid'],
'parent': parent,
'isExternal': is_external,
'name': datam['source']['id'],
'fullName': datam['fullName'],
}
def _refact_example_in_module_summary(lines):
new_lines = []
block_lines = []
example_block_flag = False
for line in lines:
if line.startswith('.. admonition:: Example'):
example_block_flag = True
line = '### Example\n\n'
new_lines.append(line)
elif example_block_flag and len(line) != 0 and not line.startswith(' '):
example_block_flag = False
new_lines.append(''.join(block_lines))
new_lines.append(line)
block_lines[:] = []
elif example_block_flag:
if line == ' ': # origianl line is blank line ('\n').
line = '\n' # after outer ['\n'.join] operation,
# this '\n' will be appended to previous line then. BINGO!
elif line.startswith(' '):
# will be indented by 4 spaces according to yml block syntax.
# https://learnxinyminutes.com/docs/yaml/
line = ' ' + line + '\n'
block_lines.append(line)
else:
new_lines.append(line)
return new_lines
def _resolve_reference_in_module_summary(pattern, lines):
new_lines, xrefs = [], []
for line in lines:
matched_objs = list(re.finditer(pattern, line))
new_line = line
for matched_obj in matched_objs:
start = matched_obj.start()
end = matched_obj.end()
matched_str = line[start:end]
# TODO: separate this portion into a function per pattern.
if pattern == REF_PATTERN:
if '<' in matched_str and '>' in matched_str:
# match string like ':func:`***<***>`'
index = matched_str.index('<')
ref_name = matched_str[index+1:-2]
else:
# match string like ':func:`~***`' or ':func:`***`'
index = matched_str.index('~') if '~' in matched_str else matched_str.index('`')
ref_name = matched_str[index+1:-1]
index = ref_name.rfind('.') + 1
# Find the last component of the target. "~Queue.get" only returns <xref:get>
ref_name = ref_name[index:]
elif pattern == REF_PATTERN_LAST:
index = matched_str.rfind('.') + 1
if index == 0:
# If there is no dot, push index to not include tilde
index = 1
ref_name = matched_str[index:]
elif pattern == REF_PATTERN_BRACKETS:
lbracket = matched_str.find('[')+1
rbracket = matched_str.find(']')
ref_name = matched_str[lbracket:rbracket]
else:
raise ValueError(f'Encountered wrong ref pattern: \n{pattern}')
# Find the uid to add for xref
index = matched_str.find("google.cloud")
if index > -1:
xref = matched_str[index:]
while not xref[-1].isalnum():
xref = xref[:-1]
xrefs.append(xref)
# Check to see if we should create an xref for it.
if 'google.cloud' in matched_str:
new_line = new_line.replace(matched_str, '<xref uid=\"{}\">{}</xref>'.format(xref, ref_name))
# If it not a Cloud library, don't create xref for it.
else:
# Carefully extract the original uid
if pattern == REF_PATTERN:
index = matched_str.index('~') if '~' in matched_str else matched_str.index('`')
ref_name = matched_str[index+1:-1]
else:
ref_name = matched_str[1:]
new_line = new_line.replace(matched_str, '`{}`'.format(ref_name))
new_lines.append(new_line)
return new_lines, xrefs
# Given a line containing restructured keyword, returns which keyword it is.
def extract_keyword(line):
# Must be in the form of:
# .. keyword::
# where it begind with 2 dot prefix, followed by a space, then the keyword
# followed by 2 collon suffix.
try:
return line[ 3 : line.index("::") ]
except ValueError:
# TODO: handle reST template.
if line[3] != "_":
raise ValueError(f"Wrong formatting enoucntered for \n{line}")
return line
def indent_code_left(lines, tab_space):
"""Indents code lines left by tab_space.
Args:
lines: String lines of code.
tab_space: Number of spaces to indent to left by.
Returns:
String lines of left-indented code.
"""
parts = lines.split("\n")
parts = [part[tab_space:] for part in parts]
return "\n".join(parts)
def _parse_docstring_summary(summary):
summary_parts = []
attributes = []
attribute_type_token = ":type:"
enum_type_token = "Values:"
keyword = name = description = var_type = ""
notice_open_tag = '<aside class="{notice_tag}">\n<b>{notice_name}:</b>'
notice_close_tag = '</aside>'
# We need to separate in chunks, which is defined by 3 newline breaks.
# Otherwise when parsing for code and blocks of stuff, we will not be able
# to have the entire context when just splitting by single newlines.
# We should fix this from the library side for consistent docstring style,
# rather than monkey-patching it in the plugin.
for part in summary.split("\n\n\n"):
# Don't process empty string
if part == "":
continue
# Continue adding parts for code-block.
if keyword and keyword in [CODE, CODEBLOCK]:
# If we reach the end of keyword, close up the code block.
if not part.startswith(" "*tab_space) or part.startswith(".."):
if code_snippet:
parts = [indent_code_left(part, tab_space) for part in code_snippet]
summary_parts.append("\n\n".join(parts))
summary_parts.append("```\n")
keyword = ""
else:
if tab_space == -1:
parts = [split_part for split_part in part.split("\n") if split_part]
tab_space = len(parts[0]) - len(parts[0].lstrip(" "))
if tab_space == 0:
raise ValueError(f"Code in the code block should be indented. Please check the docstring: \n{summary}")
if not part.startswith(" "*tab_space):
# No longer looking at code-block, reset keyword.
if code_snippet:
parts = [indent_code_left(part, tab_space) for part in code_snippet]
summary_parts.append("\n\n".join(parts))
keyword = ""
summary_parts.append("```\n")
code_snippet.append(part)
continue
# Attributes come in 3 parts, parse the latter two here.
elif keyword and keyword == ATTRIBUTE:
# Second part, extract the description.
if not found_name:
description = part.strip()
found_name = True
continue
# Third part, extract the attribute type then add the completed one
# set to a list to be returned. Close up as needed.
else:
if attribute_type_token in part:
var_type = part.split(":type:")[1].strip()
keyword = ""
if name and description and var_type:
attributes.append({
"id": name,
"description": description,
"var_type": var_type
})
else:
print(f"Could not process the attribute. Please check the docstring: \n{summary}")
continue
elif keyword and keyword in NOTICES:
# Determine how much code block is indented to format properly.
if tab_space == -1:
parts = [split_part for split_part in part.split("\n") if split_part]
tab_space = len(parts[0]) - len(parts[0].lstrip(" "))
if tab_space == 0:
raise ValueError("Content in the block should be indented."\
f"Please check the docstring: \n{summary}")
if not part.startswith(" "*tab_space):
if notice_body:
parts = [indent_code_left(part, tab_space) for part in notice_body]
summary_parts.append("\n".join(parts))
summary_parts.append(notice_close_tag)
keyword = ""
notice_body.append(part)
continue
# Parse keywords if found.
# lstrip is added to parse code blocks that are not formatted well.
if (potential_keyword := part.lstrip('\n')) and (
potential_keyword.startswith('..') or
potential_keyword.startswith(enum_type_token)
):
if enum_type_token in potential_keyword:
# Handle the enum section starting with `Values:`
parts = [split_part for split_part in part.split("\n") if split_part][1:]
if not parts:
continue
tab_space = len(parts[0]) - len(parts[0].lstrip(" "))
if tab_space == 0:
raise ValueError("Content in the block should be indented."\
f"Please check the docstring: \n{summary}")
parts = "\n".join(
[indent_code_left(part, tab_space) for part in parts]
)
summary_parts.append(
"Enum values:\n\n```\n"
f"{parts}"
"\n```\n"
)
continue
try:
keyword = extract_keyword(part.lstrip('\n'))
except ValueError:
raise ValueError(f"Please check the docstring: \n{summary}")
# Works for both code-block and code
if keyword and keyword in [CODE, CODEBLOCK]:
# Retrieve the language found in the format of
# .. code-block:: lang
# {lang} is optional however.
language = part.split("::")[1].strip()
summary_parts.append(f"```{language}")
code_snippet = []
tab_space = -1
# Extract the name for attribute first.
elif keyword and keyword == ATTRIBUTE:
found_name = False
name = part.split("::")[1].strip()
# Extracts the notice content and format it.
elif keyword and keyword in NOTICES:
summary_parts.append(notice_open_tag.format(
notice_tag=keyword, notice_name=NOTICES[keyword]))
tab_space = -1
notice_body = []
parts = [split_part for split_part in part.split("\n") if split_part][1:]
if not parts:
continue
tab_space = len(parts[0]) - len(parts[0].lstrip(" "))
if tab_space == 0:
raise ValueError("Content in the block should be indented."\
f"Please check the docstring: \n{summary}")
parts = [indent_code_left(part, tab_space) for part in parts]
summary_parts.append("\n".join(parts))
summary_parts.append(notice_close_tag)
keyword = ""
# Reserve for additional parts
# elif keyword == keyword:
else:
summary_parts.append(part + "\n")
else:
summary_parts.append(part + "\n")
# Close up from the keyword if needed.
if keyword and keyword in [CODE, CODEBLOCK]:
# Check if it's already closed.
if code_snippet:
parts = [indent_code_left(part, tab_space) for part in code_snippet]
summary_parts.append("\n\n".join(parts))
if summary_parts[-1] != "```\n":
summary_parts.append("```\n")
if keyword and keyword in NOTICES:
if notice_body:
parts = [indent_code_left(part, tab_space) for part in notice_body]
summary_parts.append("\n\n".join(parts))
if summary_parts[-1] != notice_close_tag:
summary_parts.append(notice_close_tag)
# Requires 2 newline chars to properly show on cloud site.
return "\n".join(summary_parts), attributes
# Given documentation docstring, parse them into summary_info.
def _extract_docstring_info(summary_info, summary, name):
top_summary = ""
# Return clean summary if returning early.
parsed_text = summary
# Initialize known types needing further processing.
var_types = {
':rtype:': 'returns',
':returns:': 'returns',
':type': 'variables',
':param': 'variables',
':raises': 'exceptions',
':raises:': 'exceptions',
}
initial_index = -1
front_tag = '<xref'
end_tag = '/xref>'
end_len = len(end_tag)
# Prevent GoogleDocstring crashing on custom types and parse all xrefs to normal
if front_tag in parsed_text:
type_pairs = []
# Constant length for end of xref tag
initial_index = max(0, parsed_text.find(front_tag))
summary_part = parsed_text[initial_index:]
# Remove all occurrences of "<xref uid="uid">text</xref>"
while front_tag in summary_part:
# Expecting format of "<xref uid="uid">text</xref>"
if front_tag in summary_part:
# Retrieve the index for starting position of xref tag
initial_index += summary_part.find(front_tag)
# Find the index of the end of xref tag, relative to the start of xref tag
end_tag_index = initial_index + parsed_text[initial_index:].find(end_tag) + end_len
# Retrieve the entire xref tag
original_type = parsed_text[initial_index:end_tag_index]
initial_index += len(original_type)
original_type = " ".join(filter(None, re.split(r'\n| |\|\s|\t', original_type)))
# Extract text from "<xref uid="uid">text</xref>"
index = original_type.find(">")
safe_type = 'xref_' + original_type[index+1:index+(original_type[index:].find("<"))]
else:
raise ValueError("Encountered unexpected type in Exception docstring.")
type_pairs.append([original_type, safe_type])
summary_part = parsed_text[initial_index:]
# Replace all the found occurrences
for pairs in type_pairs:
original_type, safe_type = pairs[0], pairs[1]
parsed_text = parsed_text.replace(original_type, safe_type)
# Clean the string by cleaning newlines and backlashes, then split by white space.
config = Config(napoleon_use_param=True, napoleon_use_rtype=True)
# Convert Google style to reStructuredText
parsed_text = str(GoogleDocstring(parsed_text, config))
# Trim the top summary but maintain its formatting.
indexes = []
for types in var_types:
# Ensure that we look for exactly the string we want.
# Adding the extra space for non-colon ending types
# helps determine if we simply ran into desired occurrence
# or if we ran into a similar looking syntax but shouldn't
# parse upon it.
types += ' ' if types[-1] != ':' else ''
if types in parsed_text:
index = parsed_text.find(types)
if index > -1:
# For now, skip on parsing custom fields like attribute
if types == ':type ' and 'attribute::' in parsed_text:
continue
indexes.append(index)
# If we found types needing further processing, locate its index,
# if we found empty array for indexes, stop processing further.
index = min(indexes) if indexes else 0
# Store the top summary separately. Ensure that the docstring is not empty.
if index == 0 and not indexes:
return summary
top_summary = parsed_text[:index]
parsed_text = parsed_text[index:]
# Revert back to original type
if initial_index > -1:
for pairs in type_pairs:
original_type, safe_type = pairs[0], pairs[1]
parsed_text = parsed_text.replace(safe_type, original_type)
# Clean up whitespace and other characters
parsed_text = " ".join(filter(None, re.split(r'\|\s', parsed_text))).split()
cur_type = ''
words = []
arg_name = ''
index = 0
# Used to track return type and description
r_type, r_descr = '', ''
# Using counter iteration to easily extract names rather than
# coming up with more complicated stopping logic for each tags.
while index <= len(parsed_text):
word = parsed_text[index] if index < len(parsed_text) else ""
# Check if we encountered specific words.
if word in var_types or index == len(parsed_text):
# Finish processing previous section.
if cur_type:
if cur_type == ':type':
summary_info[var_types[cur_type]][arg_name]['var_type'] = " ".join(words)
elif cur_type == ':param':
summary_info[var_types[cur_type]][arg_name]['description'] = " ".join(words)
elif ":raises" in cur_type:
summary_info[var_types[cur_type]].append({
'var_type': arg_name,
'description': " ".join(words)
})
else:
if cur_type == ':rtype:':
r_type = " ".join(words)
else:
r_descr = " ".join(words)
if r_type and r_descr:
summary_info[var_types[cur_type]].append({
'var_type': r_type,
'description': r_descr
})
r_type, r_descr = '', ''
else:
# If after we processed the top summary and get in this state,
# likely we encountered a type that's not covered above or the docstring
# was formatted badly. This will likely break docfx job later on, should not
# process further.
if word not in var_types:
raise ValueError(f"Encountered wrong formatting, please check docstring for {name}")
# Reached end of string, break after finishing processing
if index == len(parsed_text):
break
# Start processing for new section
cur_type = word
if cur_type in [':type', ':param', ':raises', ':raises:']:
index += 1
# Exception that's not xref should be treated same as other names
if ':raises' not in cur_type or 'xref' not in parsed_text[index]:
arg_name = parsed_text[index][:-1]
# xrefs are treated by taking its second half and combining the two
elif ':raises' in cur_type and 'xref' in parsed_text[index]:
arg_name = f'{parsed_text[index]} {parsed_text[index+1][:-1]}'
index += 1
try:
# Initialize empty dictionary if it doesn't exist already
if arg_name not in summary_info[var_types[cur_type]] and ':raises' not in cur_type:
summary_info[var_types[cur_type]][arg_name] = {}
except KeyError:
raise KeyError(f"Encountered wrong formatting, please check docstring for {name}")
# Empty target string
words = []
else:
words.append(word)
index += 1
return top_summary
def reformat_summary(summary: str) -> str:
"""Applies any style changes to be made specifically for DocFX YAML.
Makes the following changes:
- converts ``text`` to `text`
Args:
summary: The summary to be modified.
Returns:
Converted summary suitable for DocFX YAML.
"""
reformatted_lines = []
single_backtick = '`'
double_backtick = '``'
triple_backtick = '```'
for line in summary.split('\n'):
# Check that we're only looking for double backtick (``) and not
# comments (```).
if triple_backtick not in line and double_backtick in line:
reformatted_lines.append(line.replace(double_backtick, single_backtick))
else:
reformatted_lines.append(line)
return '\n'.join(reformatted_lines)
# Returns appropriate product name to display for given full name of entry.
def extract_product_name(name):
if 'google.cloud' in name:
product_name = '.'.join(name.split('.')[2:])
elif 'google' in name:
product_name = '.'.join(name.split('.')[1:])
else:
# Use the short name for other formats.
product_name = name.split('.')[-1]
return product_name
def _extract_type_name(annotation: Any) -> str:
"""Extracts the type name for the given inspected object.
Used to identify and extract the type hints given through inspecting the
source code. Carefully extracts only the relevant part for the given
annotation.
Args:
annotation: the inspected object in its type format. The type hint used
is `Any`, because it's the type of the object inspected itself,
which can come as any type available.
Returns:
The extracted type hint in human-readable string format.
"""
annotation_dir = dir(annotation)
if '__args__' not in annotation_dir:
return annotation.__name__
# Try to extract names for more complicated types.
type_name = str(annotation)
# If ForwardRef references are found, recursively remove them.
prefix_to_remove_start = "ForwardRef('"
if prefix_to_remove_start not in type_name:
return type_name
prefix_to_remove_end = "')"
prefix_start_len = len(prefix_to_remove_start)
prefix_end_len = len(prefix_to_remove_end)
while prefix_to_remove_start in type_name:
start_index = type_name.find(prefix_to_remove_start)
end_index = type_name.find(prefix_to_remove_end, start_index)
type_name = ''.join([
type_name[:start_index],
type_name[start_index+prefix_start_len:end_index],
type_name[end_index+prefix_end_len:],
])
return type_name
def _create_datam(app, cls, module, name, _type, obj, lines=None):
"""
Build the data structure for an autodoc class
"""
def _update_friendly_package_name(path):
package_name_index = path.find(os.sep)
package_name = path[:package_name_index]
if len(package_name) > 0:
try:
for name in namespace_package_dict:
if re.match(name, package_name) is not None:
package_name = namespace_package_dict[name]
path = os.path.join(package_name, path[package_name_index + 1:])
return path
except NameError:
pass
return path
if lines is None:
lines = []
short_name = name.split(".")[-1]
args = []
# Check how many arguments are present in the function.
arg_count = 0
try:
if _type in [METHOD, FUNCTION, CLASS]:
argspec = inspect.getfullargspec(obj) # noqa
type_map = {}
if argspec.annotations:
for annotation in argspec.annotations:
if annotation == "return":
continue
try:
type_map[annotation] = _extract_type_name(
argspec.annotations[annotation])
except AttributeError:
print(f"Could not parse argument information for {annotation}.")
continue
# Add up the number of arguments. `argspec.args` contains a list of
# all the arguments from the function.
arg_count += len(argspec.args)
for arg in argspec.args:
arg_map = {}
# Ignore adding in entry for "self"
if arg != 'cls':
arg_map['id'] = arg
if arg in type_map:
arg_map['var_type'] = type_map[arg]
args.append(arg_map)
if argspec.varargs:
args.append({'id': argspec.varargs})
if argspec.varkw:
args.append({'id': argspec.varkw})
if argspec.defaults:
# Attempt to add default values to arguments.
try:
for count, default in enumerate(argspec.defaults):
# Find the first index which default arguments start at.
# Every argument after this offset_count all have default values.
offset_count = len(argspec.defaults)
# Find the index of the current default value argument
index = len(args) + count - offset_count
# Only add defaultValue when str(default) doesn't
# contain object address string, for example:
# (object at 0x) or <lambda> at 0x7fed4d57b5e0,
# otherwise inspect.getargspec method will return wrong
# defaults which contain object address for some,
# like sys.stdout.
default_string = str(default)
if 'at 0x' not in default_string:
args[index]['defaultValue'] = default_string
# If we cannot find the argument, it is missing a type and was taken out intentionally.
except IndexError:
pass
try:
if len(lines) == 0:
lines = inspect.getdoc(obj)
lines = lines.split("\n") if lines else []
except TypeError as e:
print("couldn't getdoc from method, function: {}".format(e))
elif _type in [PROPERTY]:
lines = inspect.getdoc(obj)
lines = lines.split("\n") if lines else []
except TypeError as e:
print("Can't get argspec for {}: {}. {}".format(type(obj), name, e))
if name in app.env.docfx_signature_funcs_methods:
sig = app.env.docfx_signature_funcs_methods[name]
else:
sig = None
try:
full_path = inspect.getsourcefile(obj)
if full_path is None: # Meet a .pyd file
raise TypeError()
# Sub git repo path
path = full_path.replace(app.env.docfx_root, '')
# Support global file imports, if it's installed already
import_path = os.path.dirname(inspect.getfile(os))
path = path.replace(os.path.join(import_path, 'site-packages'), '')
path = path.replace(import_path, '')
# Make relative
path = path.replace(os.sep, '', 1)
start_line = inspect.getsourcelines(obj)[1]
path = _update_friendly_package_name(path)
# Get folder name from conf.py
path = os.path.join(app.config.folder, path)
app.env.docfx_class_paths[cls] = path
# append relative path defined in conf.py (in case of "binding python" project)
try:
source_prefix # does source_prefix exist in the current namespace
path = source_prefix + path
app.env.docfx_class_paths[cls] = path
except NameError:
pass
except (TypeError, OSError):
# TODO: remove this once there is full handler for property
if _type in [PROPERTY]:
print("Skip inspecting for property: {}".format(name))
else:
print("Can't inspect type {}: {}".format(type(obj), name))
path = None
start_line = None
datam = {
'module': module,
'uid': name,
'type': _type,
'name': short_name,
'fullName': name,
'source': {
'id': short_name,
'path': path,
'startLine': start_line,
},
'langs': ['python'],
}
summary_info = {
'variables': {}, # Stores mapping of variables and its description & types
'returns': [], # Stores the return info
'exceptions': [] # Stores the exception info
}