forked from JerJohn15/blender
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsphinx_doc_gen.py
More file actions
2350 lines (1910 loc) · 77.7 KB
/
Copy pathsphinx_doc_gen.py
File metadata and controls
2350 lines (1910 loc) · 77.7 KB
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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# <pep8 compliant>
SCRIPT_HELP_MSG = """
API dump in RST files
---------------------
Run this script from Blender's root path once you have compiled Blender
blender --background --factory-startup -noaudio --python doc/python_api/sphinx_doc_gen.py
This will generate python files in doc/python_api/sphinx-in/
providing ./blender is or links to the blender executable
To choose sphinx-in directory:
blender --background --factory-startup --python doc/python_api/sphinx_doc_gen.py -- --output ../python_api
For quick builds:
blender --background --factory-startup --python doc/python_api/sphinx_doc_gen.py -- --partial bmesh.*
Sphinx: HTML generation
-----------------------
After you have built doc/python_api/sphinx-in (see above),
generate html docs by running:
sphinx-build doc/python_api/sphinx-in doc/python_api/sphinx-out
Sphinx: PDF generation
----------------------
After you have built doc/python_api/sphinx-in (see above),
generate the pdf doc by running:
sphinx-build -b latex doc/python_api/sphinx-in doc/python_api/sphinx-out
cd doc/python_api/sphinx-out
make
"""
try:
import bpy # Blender module
except ImportError:
print("\nERROR: this script must run from inside Blender")
print(SCRIPT_HELP_MSG)
import sys
sys.exit()
import rna_info # Blender module
def rna_info_BuildRNAInfo_cache():
if rna_info_BuildRNAInfo_cache.ret is None:
rna_info_BuildRNAInfo_cache.ret = rna_info.BuildRNAInfo()
return rna_info_BuildRNAInfo_cache.ret
rna_info_BuildRNAInfo_cache.ret = None
# --- end rna_info cache
import os
import sys
import inspect
import shutil
import logging
import warnings
from textwrap import indent
from platform import platform
PLATFORM = platform().split('-')[0].lower() # 'linux', 'darwin', 'windows'
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
# For now, ignore add-ons and internal subclasses of 'bpy.types.PropertyGroup'.
#
# Besides disabling this line, the main change will be to add a
# 'toctree' to 'write_rst_index' which contains the generated rst files.
# This 'toctree' can be generated automatically.
#
# See: D6261 for reference.
USE_ONLY_BUILTIN_RNA_TYPES = True
def handle_args():
'''
Parse the args passed to Blender after "--", ignored by Blender
'''
import argparse
# When --help is given, print the usage text
parser = argparse.ArgumentParser(
formatter_class=argparse.RawTextHelpFormatter,
usage=SCRIPT_HELP_MSG
)
# optional arguments
parser.add_argument("-p", "--partial",
dest="partial",
type=str,
default="",
help="Use a wildcard to only build specific module(s)\n"
"Example: --partial bmesh*\n",
required=False)
parser.add_argument("-f", "--fullrebuild",
dest="full_rebuild",
default=False,
action='store_true',
help="Rewrite all rst files in sphinx-in/ "
"(default=False)",
required=False)
parser.add_argument("-b", "--bpy",
dest="bpy",
default=False,
action='store_true',
help="Write the rst file of the bpy module "
"(default=False)",
required=False)
parser.add_argument("-o", "--output",
dest="output_dir",
type=str,
default=SCRIPT_DIR,
help="Path of the API docs (default=<script dir>)",
required=False)
parser.add_argument("-B", "--sphinx-build",
dest="sphinx_build",
default=False,
action='store_true',
help="Build the html docs by running:\n"
"sphinx-build SPHINX_IN SPHINX_OUT\n"
"(default=False; does not depend on -P)",
required=False)
parser.add_argument("-P", "--sphinx-build-pdf",
dest="sphinx_build_pdf",
default=False,
action='store_true',
help="Build the pdf by running:\n"
"sphinx-build -b latex SPHINX_IN SPHINX_OUT_PDF\n"
"(default=False; does not depend on -B)",
required=False)
parser.add_argument("-R", "--pack-reference",
dest="pack_reference",
default=False,
action='store_true',
help="Pack all necessary files in the deployed dir.\n"
"(default=False; use with -B and -P)",
required=False)
parser.add_argument("-l", "--log",
dest="log",
default=False,
action='store_true',
help="Log the output of the API dump and sphinx|latex "
"warnings and errors (default=False).\n"
"If given, save logs in:\n"
"* OUTPUT_DIR/.bpy.log\n"
"* OUTPUT_DIR/.sphinx-build.log\n"
"* OUTPUT_DIR/.sphinx-build_pdf.log\n"
"* OUTPUT_DIR/.latex_make.log",
required=False)
# parse only the args passed after '--'
argv = []
if "--" in sys.argv:
argv = sys.argv[sys.argv.index("--") + 1:] # get all args after "--"
return parser.parse_args(argv)
ARGS = handle_args()
# ----------------------------------BPY-----------------------------------------
BPY_LOGGER = logging.getLogger('bpy')
BPY_LOGGER.setLevel(logging.DEBUG)
"""
# for quick rebuilds
rm -rf /b/doc/python_api/sphinx-* && \
./blender -b -noaudio --factory-startup -P doc/python_api/sphinx_doc_gen.py && \
sphinx-build doc/python_api/sphinx-in doc/python_api/sphinx-out
or
./blender -b -noaudio --factory-startup -P doc/python_api/sphinx_doc_gen.py -- -f -B
"""
# Switch for quick testing so doc-builds don't take so long
if not ARGS.partial:
# full build
FILTER_BPY_OPS = None
FILTER_BPY_TYPES = None
EXCLUDE_INFO_DOCS = False
EXCLUDE_MODULES = []
else:
# can manually edit this too:
# FILTER_BPY_OPS = ("import.scene", ) # allow
# FILTER_BPY_TYPES = ("bpy_struct", "Operator", "ID") # allow
EXCLUDE_INFO_DOCS = True
EXCLUDE_MODULES = [
"aud",
"bgl",
"blf",
"bl_math",
"imbuf",
"imbuf.types",
"bmesh",
"bmesh.ops",
"bmesh.types",
"bmesh.utils",
"bmesh.geometry",
"bpy.app",
"bpy.app.handlers",
"bpy.app.timers",
"bpy.app.translations",
"bpy.context",
"bpy.data",
"bpy.ops", # supports filtering
"bpy.path",
"bpy.props",
"bpy.types", # supports filtering
"bpy.utils",
"bpy.utils.previews",
"bpy.utils.units",
"bpy_extras",
"gpu",
"gpu.types",
"gpu.matrix",
"gpu.select",
"gpu.shader",
"gpu.state",
"gpu.texture",
"gpu_extras",
"idprop.types",
"mathutils",
"mathutils.bvhtree",
"mathutils.geometry",
"mathutils.interpolate",
"mathutils.kdtree",
"mathutils.noise",
"freestyle",
"freestyle.chainingiterators",
"freestyle.functions",
"freestyle.predicates",
"freestyle.shaders",
"freestyle.types",
"freestyle.utils",
]
# ------
# Filter
#
# TODO, support bpy.ops and bpy.types filtering
import fnmatch
m = None
EXCLUDE_MODULES = [m for m in EXCLUDE_MODULES if not fnmatch.fnmatchcase(m, ARGS.partial)]
# special support for bpy.types.XXX
FILTER_BPY_OPS = tuple([m[8:] for m in ARGS.partial.split(":") if m.startswith("bpy.ops.")])
if FILTER_BPY_OPS:
EXCLUDE_MODULES.remove("bpy.ops")
FILTER_BPY_TYPES = tuple([m[10:] for m in ARGS.partial.split(":") if m.startswith("bpy.types.")])
if FILTER_BPY_TYPES:
EXCLUDE_MODULES.remove("bpy.types")
print(FILTER_BPY_TYPES)
EXCLUDE_INFO_DOCS = (not fnmatch.fnmatchcase("info", ARGS.partial))
del m
del fnmatch
BPY_LOGGER.debug(
"Partial Doc Build, Skipping: %s\n" %
"\n ".join(sorted(EXCLUDE_MODULES)))
#
# done filtering
# --------------
try:
__import__("aud")
except ImportError:
BPY_LOGGER.debug("Warning: Built without 'aud' module, docs incomplete...")
EXCLUDE_MODULES.append("aud")
try:
__import__("freestyle")
except ImportError:
BPY_LOGGER.debug("Warning: Built without 'freestyle' module, docs incomplete...")
EXCLUDE_MODULES.extend([
"freestyle",
"freestyle.chainingiterators",
"freestyle.functions",
"freestyle.predicates",
"freestyle.shaders",
"freestyle.types",
"freestyle.utils",
])
# Source files we use, and need to copy to the OUTPUT_DIR
# to have working out-of-source builds.
# Note that ".." is replaced by "__" in the RST files,
# to avoid having to match Blender's source tree.
EXTRA_SOURCE_FILES = (
"../../../release/scripts/templates_py/bmesh_simple.py",
"../../../release/scripts/templates_py/gizmo_operator.py",
"../../../release/scripts/templates_py/gizmo_operator_target.py",
"../../../release/scripts/templates_py/gizmo_simple.py",
"../../../release/scripts/templates_py/operator_simple.py",
"../../../release/scripts/templates_py/ui_panel_simple.py",
"../../../release/scripts/templates_py/ui_previews_custom_icon.py",
"../examples/bmesh.ops.1.py",
"../examples/bpy.app.translations.py",
)
# examples
EXAMPLES_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, "examples"))
EXAMPLE_SET = set()
for f in os.listdir(EXAMPLES_DIR):
if f.endswith(".py"):
EXAMPLE_SET.add(os.path.splitext(f)[0])
EXAMPLE_SET_USED = set()
# rst files dir
RST_DIR = os.path.abspath(os.path.join(SCRIPT_DIR, "rst"))
# extra info, not api reference docs
# stored in ./rst/info_*
INFO_DOCS = (
("info_quickstart.rst",
"Quickstart: New to Blender or scripting and want to get your feet wet?"),
("info_overview.rst",
"API Overview: A more complete explanation of Python integration"),
("info_api_reference.rst",
"API Reference Usage: examples of how to use the API reference docs"),
("info_best_practice.rst",
"Best Practice: Conventions to follow for writing good scripts"),
("info_tips_and_tricks.rst",
"Tips and Tricks: Hints to help you while writing scripts for Blender"),
("info_gotcha.rst",
"Gotcha's: Some of the problems you may encounter when writing scripts"),
("change_log.rst", "Change Log: List of changes since last Blender release"),
)
# only support for properties atm.
RNA_BLACKLIST = {
# XXX messes up PDF!, really a bug but for now just workaround.
"PreferencesSystem": {"language", }
}
MODULE_GROUPING = {
"bmesh.types": (
("Base Mesh Type", '-'),
"BMesh",
("Mesh Elements", '-'),
"BMVert",
"BMEdge",
"BMFace",
"BMLoop",
("Sequence Accessors", '-'),
"BMElemSeq",
"BMVertSeq",
"BMEdgeSeq",
"BMFaceSeq",
"BMLoopSeq",
"BMIter",
("Selection History", '-'),
"BMEditSelSeq",
"BMEditSelIter",
("Custom-Data Layer Access", '-'),
"BMLayerAccessVert",
"BMLayerAccessEdge",
"BMLayerAccessFace",
"BMLayerAccessLoop",
"BMLayerCollection",
"BMLayerItem",
("Custom-Data Layer Types", '-'),
"BMLoopUV",
"BMDeformVert"
)
}
# --------------------configure compile time options----------------------------
# -------------------------------BLENDER----------------------------------------
# converting bytes to strings, due to T30154
BLENDER_REVISION = str(bpy.app.build_hash, 'utf_8')
# '2.83.0 Beta' or '2.83.0' or '2.83.1'
BLENDER_VERSION_DOTS = bpy.app.version_string
if BLENDER_REVISION != "Unknown":
# SHA1 Git hash
BLENDER_VERSION_HASH = BLENDER_REVISION
else:
# Fallback: Should not be used
BLENDER_VERSION_HASH = "Hash Unknown"
# '2_83'
BLENDER_VERSION_PATH = "%d_%d" % (bpy.app.version[0], bpy.app.version[1])
# --------------------------DOWNLOADABLE FILES----------------------------------
REFERENCE_NAME = "blender_python_reference_%s" % BLENDER_VERSION_PATH
REFERENCE_PATH = os.path.join(ARGS.output_dir, REFERENCE_NAME)
BLENDER_PDF_FILENAME = "%s.pdf" % REFERENCE_NAME
BLENDER_ZIP_FILENAME = "%s.zip" % REFERENCE_NAME
# -------------------------------SPHINX-----------------------------------------
SPHINX_IN = os.path.join(ARGS.output_dir, "sphinx-in")
SPHINX_IN_TMP = SPHINX_IN + "-tmp"
SPHINX_OUT = os.path.join(ARGS.output_dir, "sphinx-out")
# html build
if ARGS.sphinx_build:
SPHINX_BUILD = ["sphinx-build", SPHINX_IN, SPHINX_OUT]
if ARGS.log:
SPHINX_BUILD_LOG = os.path.join(ARGS.output_dir, ".sphinx-build.log")
SPHINX_BUILD = [
"sphinx-build",
"-w", SPHINX_BUILD_LOG,
SPHINX_IN, SPHINX_OUT,
]
# pdf build
if ARGS.sphinx_build_pdf:
SPHINX_OUT_PDF = os.path.join(ARGS.output_dir, "sphinx-out_pdf")
SPHINX_BUILD_PDF = [
"sphinx-build",
"-b", "latex",
SPHINX_IN, SPHINX_OUT_PDF,
]
SPHINX_MAKE_PDF = ["make", "-C", SPHINX_OUT_PDF]
SPHINX_MAKE_PDF_STDOUT = None
if ARGS.log:
SPHINX_BUILD_PDF_LOG = os.path.join(ARGS.output_dir, ".sphinx-build_pdf.log")
SPHINX_BUILD_PDF = [
"sphinx-build", "-b", "latex",
"-w", SPHINX_BUILD_PDF_LOG,
SPHINX_IN, SPHINX_OUT_PDF,
]
sphinx_make_pdf_log = os.path.join(ARGS.output_dir, ".latex_make.log")
SPHINX_MAKE_PDF_STDOUT = open(sphinx_make_pdf_log, "w", encoding="utf-8")
# --------------------------------API DUMP--------------------------------------
# lame, python won't give some access
ClassMethodDescriptorType = type(dict.__dict__['fromkeys'])
MethodDescriptorType = type(dict.get)
GetSetDescriptorType = type(int.real)
StaticMethodType = type(staticmethod(lambda: None))
from types import (
MemberDescriptorType,
MethodType,
FunctionType,
)
_BPY_STRUCT_FAKE = "bpy_struct"
_BPY_PROP_COLLECTION_FAKE = "bpy_prop_collection"
if _BPY_PROP_COLLECTION_FAKE:
_BPY_PROP_COLLECTION_ID = ":class:`%s`" % _BPY_PROP_COLLECTION_FAKE
else:
_BPY_PROP_COLLECTION_ID = "collection"
if _BPY_STRUCT_FAKE:
bpy_struct = bpy.types.bpy_struct
else:
bpy_struct = None
def import_value_from_module(module_name, import_name):
ns = {}
exec_str = "from %s import %s as value" % (module_name, import_name)
exec(exec_str, ns, ns)
return ns["value"]
def escape_rst(text):
""" Escape plain text which may contain characters used by RST.
"""
return text.translate(escape_rst.trans)
escape_rst.trans = str.maketrans({
"`": "\\`",
"|": "\\|",
"*": "\\*",
"\\": "\\\\",
})
def is_struct_seq(value):
return isinstance(value, tuple) and type(tuple) != tuple and hasattr(value, "n_fields")
def undocumented_message(module_name, type_name, identifier):
return "Undocumented, consider `contributing <https://developer.blender.org/T51061>`__."
def range_str(val):
'''
Converts values to strings for the range directive.
(unused function it seems)
'''
if val < -10000000:
return '-inf'
elif val > 10000000:
return 'inf'
elif type(val) == float:
return '%g' % val
else:
return str(val)
def example_extract_docstring(filepath):
'''
Return (text, line_no, line_no_has_content) where:
- ``text`` is the doc-string text.
- ``line_no`` is the line the doc-string text ends.
- ``line_no_has_content`` when False, this file only contains a doc-string.
There is no need to include the remainder.
'''
file = open(filepath, "r", encoding="utf-8")
line = file.readline()
line_no = 0
text = []
if line.startswith('"""'): # assume nothing here
line_no += 1
else:
file.close()
return "", 0, True
for line in file:
line_no += 1
if line.startswith('"""'):
break
else:
text.append(line.rstrip())
line_no += 1
line_no_has_content = False
# Skip over blank lines so the Python code doesn't have blank lines at the top.
for line in file:
if line.strip():
line_no_has_content = True
break
line_no += 1
file.close()
return "\n".join(text), line_no, line_no_has_content
def title_string(text, heading_char, double=False):
filler = len(text) * heading_char
if double:
return "%s\n%s\n%s\n\n" % (filler, text, filler)
else:
return "%s\n%s\n\n" % (text, filler)
def write_example_ref(ident, fw, example_id, ext="py"):
if example_id in EXAMPLE_SET:
# extract the comment
filepath = os.path.join("..", "examples", "%s.%s" % (example_id, ext))
filepath_full = os.path.join(os.path.dirname(fw.__self__.name), filepath)
text, line_no, line_no_has_content = example_extract_docstring(filepath_full)
for line in text.split("\n"):
fw("%s\n" % (ident + line).rstrip())
fw("\n")
# Some files only contain a doc-string.
if line_no_has_content:
fw("%s.. literalinclude:: %s\n" % (ident, filepath))
if line_no > 0:
fw("%s :lines: %d-\n" % (ident, line_no))
fw("\n")
EXAMPLE_SET_USED.add(example_id)
else:
if bpy.app.debug:
BPY_LOGGER.debug("\tskipping example: " + example_id)
# Support for numbered files bpy.types.Operator -> bpy.types.Operator.1.py
i = 1
while True:
example_id_num = "%s.%d" % (example_id, i)
if example_id_num in EXAMPLE_SET:
write_example_ref(ident, fw, example_id_num, ext)
i += 1
else:
break
def write_indented_lines(ident, fn, text, strip=True):
'''
Apply same indentation to all lines in a multilines text.
'''
if text is None:
return
lines = text.split("\n")
# strip empty lines from the start/end
while lines and not lines[0].strip():
del lines[0]
while lines and not lines[-1].strip():
del lines[-1]
if strip:
# set indentation to <indent>
ident_strip = 1000
for l in lines:
if l.strip():
ident_strip = min(ident_strip, len(l) - len(l.lstrip()))
for l in lines:
fn(ident + l[ident_strip:] + "\n")
else:
# add <indent> number of blanks to the current indentation
for l in lines:
fn(ident + l + "\n")
def pymethod2sphinx(ident, fw, identifier, py_func):
'''
class method to sphinx
'''
arg_str = inspect.formatargspec(*inspect.getargspec(py_func))
if arg_str.startswith("(self, "):
arg_str = "(" + arg_str[7:]
func_type = "method"
elif arg_str.startswith("(cls, "):
arg_str = "(" + arg_str[6:]
func_type = "classmethod"
else:
func_type = "staticmethod"
fw(ident + ".. %s:: %s%s\n\n" % (func_type, identifier, arg_str))
if py_func.__doc__:
write_indented_lines(ident + " ", fw, py_func.__doc__)
fw("\n")
def pyfunc2sphinx(ident, fw, module_name, type_name, identifier, py_func, is_class=True):
'''
function or class method to sphinx
'''
if type(py_func) == MethodType:
return
arg_str = str(inspect.signature(py_func))
if not is_class:
func_type = "function"
# the rest are class methods
elif arg_str.startswith("(self, ") or arg_str == "(self)":
arg_str = "()" if (arg_str == "(self)") else ("(" + arg_str[7:])
func_type = "method"
elif arg_str.startswith("(cls, "):
arg_str = "()" if (arg_str == "(cls)") else ("(" + arg_str[6:])
func_type = "classmethod"
else:
func_type = "staticmethod"
doc = py_func.__doc__
if (not doc) or (not doc.startswith(".. %s:: " % func_type)):
fw(ident + ".. %s:: %s%s\n\n" % (func_type, identifier, arg_str))
ident_temp = ident + " "
else:
ident_temp = ident
if doc:
write_indented_lines(ident_temp, fw, doc)
fw("\n")
del doc, ident_temp
if is_class:
write_example_ref(ident + " ", fw, module_name + "." + type_name + "." + identifier)
else:
write_example_ref(ident + " ", fw, module_name + "." + identifier)
def py_descr2sphinx(ident, fw, descr, module_name, type_name, identifier):
if identifier.startswith("_"):
return
doc = descr.__doc__
if not doc:
doc = undocumented_message(module_name, type_name, identifier)
if type(descr) == GetSetDescriptorType:
fw(ident + ".. attribute:: %s\n\n" % identifier)
write_indented_lines(ident + " ", fw, doc, False)
fw("\n")
elif type(descr) == MemberDescriptorType: # same as above but use 'data'
fw(ident + ".. data:: %s\n\n" % identifier)
write_indented_lines(ident + " ", fw, doc, False)
fw("\n")
elif type(descr) in {MethodDescriptorType, ClassMethodDescriptorType}:
write_indented_lines(ident, fw, doc, False)
fw("\n")
else:
raise TypeError("type was not GetSetDescriptorType, MethodDescriptorType or ClassMethodDescriptorType")
write_example_ref(ident + " ", fw, module_name + "." + type_name + "." + identifier)
fw("\n")
def py_c_func2sphinx(ident, fw, module_name, type_name, identifier, py_func, is_class=True):
'''
c defined function to sphinx.
'''
# dump the docstring, assume its formatted correctly
if py_func.__doc__:
write_indented_lines(ident, fw, py_func.__doc__, False)
fw("\n")
else:
fw(ident + ".. function:: %s()\n\n" % identifier)
fw(ident + " " + undocumented_message(module_name, type_name, identifier))
if is_class:
write_example_ref(ident + " ", fw, module_name + "." + type_name + "." + identifier)
else:
write_example_ref(ident + " ", fw, module_name + "." + identifier)
fw("\n")
def pyprop2sphinx(ident, fw, identifier, py_prop):
'''
Python property to sphinx
'''
# readonly properties use "data" directive, variables use "attribute" directive
if py_prop.fset is None:
fw(ident + ".. data:: %s\n\n" % identifier)
else:
fw(ident + ".. attribute:: %s\n\n" % identifier)
write_indented_lines(ident + " ", fw, py_prop.__doc__)
fw("\n")
if py_prop.fset is None:
fw(ident + " (readonly)\n\n")
def pymodule2sphinx(basepath, module_name, module, title, module_all_extra):
import types
attribute_set = set()
filepath = os.path.join(basepath, module_name + ".rst")
module_all = getattr(module, "__all__", None)
module_dir = sorted(dir(module))
if module_all:
module_dir = module_all
# TODO - currently only used for classes
# grouping support
module_grouping = MODULE_GROUPING.get(module_name)
def module_grouping_index(name):
if module_grouping is not None:
try:
return module_grouping.index(name)
except ValueError:
pass
return -1
def module_grouping_heading(name):
if module_grouping is not None:
i = module_grouping_index(name) - 1
if i >= 0 and type(module_grouping[i]) == tuple:
return module_grouping[i]
return None, None
def module_grouping_sort_key(name):
return module_grouping_index(name)
# done grouping support
file = open(filepath, "w", encoding="utf-8")
fw = file.write
fw(title_string("%s (%s)" % (title, module_name), "="))
fw(".. module:: %s\n\n" % module_name)
if module.__doc__:
# Note, may contain sphinx syntax, don't mangle!
fw(module.__doc__.strip())
fw("\n\n")
# write submodules
# we could also scan files but this ensures __all__ is used correctly
if module_all or module_all_extra:
submod_name = None
submod = None
submod_ls = []
for submod_name in (module_all or ()):
submod = import_value_from_module(module_name, submod_name)
if type(submod) == types.ModuleType:
submod_ls.append((submod_name, submod))
for submod_name in module_all_extra:
if submod_name in attribute_set:
continue
submod = import_value_from_module(module_name, submod_name)
# No type checks, since there are non-module types we treat as modules
# such as `bpy.app.translations` & `bpy.app.handlers`.
submod_ls.append((submod_name, submod))
del submod_name
del submod
if submod_ls:
fw(".. toctree::\n")
fw(" :maxdepth: 1\n")
fw(" :caption: Submodules\n\n")
for submod_name, submod in submod_ls:
submod_name_full = "%s.%s" % (module_name, submod_name)
fw(" %s.rst\n" % submod_name_full)
pymodule2sphinx(basepath, submod_name_full, submod, "%s submodule" % module_name, ())
fw("\n")
del submod_ls
# done writing submodules!
write_example_ref("", fw, module_name)
# write members of the module
# only tested with PyStructs which are not exactly modules
for key, descr in sorted(type(module).__dict__.items()):
if key.startswith("__"):
continue
if key in module_all_extra:
continue
# naughty, we also add getset's into PyStructs, this is not typical py but also not incorrect.
# type_name is only used for examples and messages
# "<class 'bpy.app.handlers'>" --> bpy.app.handlers
type_name = str(type(module)).strip("<>").split(" ", 1)[-1][1:-1]
if type(descr) == types.GetSetDescriptorType:
py_descr2sphinx("", fw, descr, module_name, type_name, key)
attribute_set.add(key)
descr_sorted = []
for key, descr in sorted(type(module).__dict__.items()):
if key.startswith("__"):
continue
if type(descr) == MemberDescriptorType:
if descr.__doc__:
value = getattr(module, key, None)
value_type = type(value)
descr_sorted.append((key, descr, value, type(value)))
# sort by the valye type
descr_sorted.sort(key=lambda descr_data: str(descr_data[3]))
for key, descr, value, value_type in descr_sorted:
if key in module_all_extra:
continue
# must be documented as a submodule
if is_struct_seq(value):
continue
type_name = value_type.__name__
py_descr2sphinx("", fw, descr, module_name, type_name, key)
attribute_set.add(key)
del key, descr, descr_sorted
classes = []
submodules = []
# use this list so we can sort by type
module_dir_value_type = []
for attribute in module_dir:
if attribute.startswith("_"):
continue
if attribute in attribute_set:
continue
if attribute.startswith("n_"): # annoying exception, needed for bpy.app
continue
# workaround for bpy.app documenting .index() and .count()
if isinstance(module, tuple) and hasattr(tuple, attribute):
continue
value = getattr(module, attribute)
module_dir_value_type.append((attribute, value, type(value)))
# sort by str of each type
# this way lists, functions etc are grouped.
module_dir_value_type.sort(key=lambda triple: str(triple[2]))
for attribute, value, value_type in module_dir_value_type:
if attribute in module_all_extra:
continue
if value_type == FunctionType:
pyfunc2sphinx("", fw, module_name, None, attribute, value, is_class=False)
# both the same at the moment but to be future proof
elif value_type in {types.BuiltinMethodType, types.BuiltinFunctionType}:
# note: can't get args from these, so dump the string as is
# this means any module used like this must have fully formatted docstrings.
py_c_func2sphinx("", fw, module_name, None, attribute, value, is_class=False)
elif value_type == type:
classes.append((attribute, value))
elif issubclass(value_type, types.ModuleType):
submodules.append((attribute, value))
elif issubclass(value_type, (bool, int, float, str, tuple)):
# constant, not much fun we can do here except to list it.
# TODO, figure out some way to document these!
fw(".. data:: %s\n\n" % attribute)
write_indented_lines(" ", fw, "Constant value %s" % repr(value), False)
fw("\n")
else:
BPY_LOGGER.debug("\tnot documenting %s.%s of %r type" % (module_name, attribute, value_type.__name__))
continue
attribute_set.add(attribute)
# TODO, more types...
del module_dir_value_type
# TODO, bpy_extras does this already, mathutils not.
'''
if submodules:
fw("\n"
"**********\n"
"Submodules\n"
"**********\n"
"\n"
)
for attribute, submod in submodules:
fw("* :mod:`%s.%s`\n" % (module_name, attribute))
fw("\n")
'''
if module_grouping is not None:
classes.sort(key=lambda pair: module_grouping_sort_key(pair[0]))
# write collected classes now
for (type_name, value) in classes:
if module_grouping is not None:
heading, heading_char = module_grouping_heading(type_name)
if heading:
fw(title_string(heading, heading_char))
# May need to be its own function
if value.__doc__:
if value.__doc__.startswith(".. class::"):
fw(value.__doc__)
else:
fw(".. class:: %s\n\n" % type_name)
write_indented_lines(" ", fw, value.__doc__, True)
else:
fw(".. class:: %s\n\n" % type_name)