-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocsGenerator.py
More file actions
158 lines (123 loc) · 5.79 KB
/
Copy pathdocsGenerator.py
File metadata and controls
158 lines (123 loc) · 5.79 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
import inspect
import json
import logging
import os
import sys
from glob import glob
from discord.ext import commands
from project.data import CACHE, VERSION
logging.basicConfig(level=logging.INFO, format="%(message)s")
class DocGenerator():
def __init__(self):
self.command_cache = {}
self.start()
self.create_cache_File()
# ============================================================
def start(self):
logging.info("===Generating Documentation===")
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
count = 1
if os.path.exists('docs/commands/'):
for f in os.listdir('docs/commands/'):
os.remove(os.path.join('docs/commands/', f))
for file in glob(os.path.join(os.path.dirname(os.path.abspath(__file__)), "modules", "*.py")):
if file.split("\\")[-1].lower() in ['logs.py', 'lobbyevents.py', 'QueueTask.py', 'whitelist.py',
'devtools.py', 'inviteinfo.py', 'tasks.py', 'databasetasks.py', 'refresher.py', 'security.py', 'queuetask.py']:
continue
self.load_file(file, nav=count)
count += 1
# ============================================================
def load_file(self, file, nav=1):
name = os.path.splitext(os.path.basename(file))[0]
document = f"docs/commands/{name}.md"
if name == "__init__":
return
# create the document
for dirc in ["docs", "docs/commands"]:
if not os.path.exists(dirc):
os.mkdir(dirc)
# add package prefix to name
module_name = f"modules.{name}"
module = __import__(module_name, fromlist=[name])
with open(document, "w", encoding="utf-8") as docfile:
for member in dir(module):
# do something with the member named ``member``
if member == name:
tclass = getattr(module, member)
if inspect.ismodule(tclass):
continue
logging.info(f"- Documenting Module: {name}")
docfile.write(self.document_header(tclass, name, nav))
for _, member_obj in inspect.getmembers(module, inspect.isclass):
# Check if the class is defined in the module we are inspecting
if member_obj.__module__ == module_name:
# Correctly check for inheritance using the class objects
if issubclass(member_obj, (commands.Cog, commands.GroupCog)):
domain = name
break
for function in tclass.__dict__:
self.command_line(docfile, function, tclass, domain, )
# ============================================================
def document_header(self, module, module_name: str, nav):
return f"""---
layout: default
title: {module_name}
parent: Commands
nav_order: {nav}
---
<h1>{module_name}</h1>
<h6>version: {VERSION}</h6>
<h6>Documentation automatically generated from docstrings.</h6>
{inspect.getdoc(module)}
"""
# ============================================================
def command_line(self, docfile, function, tclass, domain, cachefile=None):
if function.startswith("_") or function.startswith('cog') or function.startswith('cog') or function.startswith(
'before_'):
return
func_obj = getattr(tclass, function)
if not (hasattr(func_obj, 'callback') or callable(func_obj)):
return
docstring = ""
# Check if it's a decorated command with a callback
if hasattr(func_obj, 'callback'):
docstring = inspect.getdoc(func_obj.callback)
# Check if it's a callable function
elif callable(func_obj):
docstring = inspect.getdoc(func_obj)
if not docstring:
docstring = "Missing Documentation"
if docstring.startswith("skip") or docstring.startswith("[skip]"):
return
param_string = ""
try:
# Use the callback if it exists, otherwise use the function object itself
target_func = func_obj.callback if hasattr(func_obj, 'callback') else func_obj
sig = inspect.signature(target_func)
# Filter out 'self' and 'interaction' from the parameters
params = [p for p in sig.parameters if p not in ('self', 'interaction')]
if params:
# Format parameters like: <param1> <param2>
param_string = " " + " ".join([f"<{p}>" for p in params])
except (ValueError, TypeError):
logging.warning(f"Could not retrieve signature for function: {function}")
# This can happen for objects that are not inspectable
pass
self.add_command_to_cache(domain, function, docstring)
docfile.write(f"### `{function}`\n\n"
f"**Usage:** `/{domain.lower()} {function}{param_string}`\n\n"
f"> {docstring}\n\n"
f"---\n\n")
# ============================================================
def add_command_to_cache(self, domain, function, docstring):
# if domain not in self.command_cache :
# self.command_cache[domain] = {}
# self.command_cache[domain][function] = docstring
self.command_cache[function] = docstring
# ============================================================
def create_cache_File(self):
logging.info("===Creating command cache file===")
with open(CACHE, "w", encoding="utf-8") as cachefile:
json.dump(self.command_cache, cachefile, indent=4)
logging.info("===Command cache file created===")
DocGenerator()