-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
makedoc.py
196 lines (186 loc) · 6.89 KB
/
makedoc.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
import glob
import inspect
import json
import os
import re
import TkEasyGUI as eg
SCRIPT_DIR = os.path.dirname(__file__)
OUTPUT_DIR = os.path.join(SCRIPT_DIR, "docs", "TkEasyGUI")
DOCS_SCRIPTS_DIR = os.path.join(SCRIPT_DIR, "docs", "scripts")
REPO = "https://github.com/kujirahand/tkeasygui-python/blob/main"
def main():
package_path = eg.__path__[0]
print(package_path)
print(eg.__doc__)
root_name = eg.__package__
# get modules
files = glob.glob(os.path.join(package_path, "*.py"))
for file in files:
read_module(file, root_name)
def read_module(file: str, root_name: str):
module_name = os.path.basename(file).replace(".py", "")
if module_name == "__init__":
return
mod = getattr(eg, module_name)
doc = trim_docstring(str(mod.__doc__))
print("---------------------------")
output_file = os.path.join(OUTPUT_DIR, f"{module_name}-py.md")
result = ""
head = f"# Module {root_name}.{module_name}\n\n"
head += doc + "\n\n"
head += "---------------------------\n\n"
print(head)
head_link = []
# classes
elements = []
classes = ""
for prop in dir(mod):
if prop.startswith("__"):
continue
p = getattr(mod, prop)
if str(type(p)) == "<class 'type'>":
mod2 = inspect.getmodule(p)
if mod2 != mod:
continue
pclass = p
class_name = pclass.__name__
doc = trim_docstring(p.__doc__)
classes += f"## {prop}\n\n"
classes += doc + "\n\n"
elements.append(class_name)
# get init code
if p.__init__ is not None:
print("@@@", prop)
code_def = get_function_definition(p.__init__, skip_self=True)
code_def = re.sub("^def __init__", f"class {class_name}", code_def)
code_def = re.sub("->\s*None\s*:", "", code_def)
if prop == "Button":
print("@@@", code_def)
# print(inspect.getsource(p.__init__))
if code_def != "":
classes += "```py\n"
classes += code_def
classes += "```\n\n"
code = p.__init__.__code__
fname = code.co_filename.replace(SCRIPT_DIR, "")
classes += f"- [source]({REPO}{fname}#L{code.co_firstlineno})\n"
classes += "\n"
# get methods
method_doc = ""
method_link = []
methods = inspect.getmembers(pclass)
for name, method in methods:
if name.startswith("_"):
continue
print("###", class_name, name)
method_doc += f"### {class_name}.{name}\n\n"
doc = trim_docstring(method.__doc__)
if doc.strip() != "":
method_doc += doc.strip() + "\n\n"
try:
code = method.__code__
except Exception as e:
print("###", e)
continue
def_code = get_function_definition(method, skip_self=True)
method_doc += "```py\n"
method_doc += def_code
method_doc += "```\n\n"
method_doc += f"- [source]({REPO}{fname}#L{code.co_firstlineno})\n"
method_doc += "\n"
method_link.append(f"- [{name}](#{class_name.lower()}{name.lower()})")
if method_doc != "":
classes += f"### Methods of {class_name}\n\n"
classes += "\n".join(method_link) + "\n\n"
classes += method_doc
if classes:
result += f"# Classes of {root_name}.{module_name}\n\n"
result += classes
head_link.append(f"- [Classes](#classes-of-{root_name.lower()}{module_name.lower()})")
# elements
if len(elements) > 0 and os.path.basename(file) == "widgets.py":
print("* elements:\n", elements)
if "Window" in elements:
elements.remove("Window")
if "Element" in elements:
elements.remove("Element")
if "TkEasyError" in elements:
elements.remove("TkEasyError")
file_elements = os.path.join(DOCS_SCRIPTS_DIR, "elements.json")
with open(file_elements, "w", encoding="utf-8") as fp:
elements = list(sorted(elements))
json.dump(elements, fp, ensure_ascii=False, indent=2)
# functions
functions = ""
function_link = []
for prop in dir(mod):
if prop.startswith("_"):
continue
p = getattr(mod, prop)
if str(type(p)) == "<class 'function'>":
doc = trim_docstring(p.__doc__)
code = p.__code__
def_code = get_function_definition(p)
fname = code.co_filename.replace(SCRIPT_DIR, "")
functions += f"## {prop}\n\n"
functions += doc + "\n\n"
functions += "```py\n"
functions += def_code
functions += "```\n\n"
functions += f"- [source]({REPO}{fname}#L{code.co_firstlineno})\n"
functions += "\n"
function_link.append(f"- [{prop}](#{prop.lower()})")
if functions:
result += f"# Functions of {root_name}.{module_name}\n\n"
result += "\n".join(function_link) + "\n\n"
result += functions
head_link.append(f"- [Functions](#functions-of-{root_name.lower()}{module_name.lower()})")
print("---------------------------")
result = head + "\n".join(head_link) + "\n\n" + result
# print(result)
with open(output_file, "w", encoding="utf-8") as fp:
fp.write(result)
def trim_docstring(doc):
"""docstringのインデントを整形する"""
if not doc or doc == "":
return ""
lines = doc.expandtabs().splitlines()
indent = 0
stripped = ""
for line in lines:
if line.strip() == "":
continue
stripped = line.lstrip()
if stripped:
indent = line.find(stripped)
break
trimmed = [lines[0].strip()]
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
res = "\n".join(trimmed).strip()
return res
def get_function_definition(func, skip_self=False):
"""関数の定義部分を取得する"""
# 関数のソースコードを取得
src = str(inspect.getsource(func))
src = src.strip()
res = []
flag = False
lines = src.split("\n")
for line in lines:
if not flag:
if line.startswith("@"):
flag = True
if line.startswith("def "):
flag = True
if not flag:
continue
line = line.rstrip()
if line != "" and line[0] == " ":
line = " " + line.strip()
res.append(line)
if line.endswith(":"):
break
return "\n".join(res).strip() + "\n"
if __name__ == "__main__":
main()