-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdoc_generator.py
More file actions
193 lines (157 loc) Β· 5.6 KB
/
doc_generator.py
File metadata and controls
193 lines (157 loc) Β· 5.6 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
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""
Generate and manage project documentation.
Usage:
python doc_generator.py [--type TYPE] [--output OUTPUT]
"""
logger = logging.getLogger(__name__)
import sys
from pathlib import Path
try:
import codomyrmex
except ImportError:
project_root = Path(__file__).resolve().parent.parent.parent
sys.path.insert(0, str(project_root / "src"))
import argparse
import ast
import logging
def extract_module_info(file_path: Path) -> dict:
"""Extract info from a Python module."""
with open(file_path) as f:
source = f.read()
info = {
"name": file_path.stem,
"docstring": None,
"functions": [],
"classes": [],
}
try:
tree = ast.parse(source)
info["docstring"] = ast.get_docstring(tree)
for node in ast.iter_child_nodes(tree):
if isinstance(node, ast.FunctionDef):
info["functions"].append(
{
"name": node.name,
"docstring": ast.get_docstring(node),
"args": [a.arg for a in node.args.args],
}
)
elif isinstance(node, ast.ClassDef):
methods = []
for item in node.body:
if isinstance(item, ast.FunctionDef):
methods.append(item.name)
info["classes"].append(
{
"name": node.name,
"docstring": ast.get_docstring(node),
"methods": methods,
}
)
except Exception as e:
logger.debug("Could not parse %s: %s", filepath, e)
return info
def generate_markdown(info: dict) -> str:
"""Generate markdown documentation."""
lines = [f"# {info['name']}\n"]
if info["docstring"]:
lines.append(f"{info['docstring']}\n")
if info["classes"]:
lines.append("## Classes\n")
for cls in info["classes"]:
lines.append(f"### `{cls['name']}`\n")
if cls["docstring"]:
lines.append(f"{cls['docstring']}\n")
if cls["methods"]:
lines.append("**Methods:**\n")
for m in cls["methods"]:
lines.append(f"- `{m}()`\n")
lines.append("")
if info["functions"]:
lines.append("## Functions\n")
for func in info["functions"]:
args = ", ".join(func["args"])
lines.append(f"### `{func['name']}({args})`\n")
if func["docstring"]:
lines.append(f"{func['docstring']}\n")
lines.append("")
return "\n".join(lines)
def main():
# Auto-injected: Load configuration
from pathlib import Path
import yaml
config_path = (
Path(__file__).resolve().parent.parent.parent
/ "config"
/ "documentation"
/ "config.yaml"
)
if config_path.exists():
with open(config_path) as f:
yaml.safe_load(f) or {}
print("Loaded config from config/documentation/config.yaml")
parser = argparse.ArgumentParser(description="Generate documentation")
parser.add_argument("path", nargs="?", help="Python file or directory")
parser.add_argument("--output", "-o", default=None, help="Output file")
parser.add_argument(
"--format", "-f", choices=["markdown", "json"], default="markdown"
)
parser.add_argument(
"--list", "-l", action="store_true", help="List undocumented items"
)
args = parser.parse_args()
if not args.path:
print("π Documentation Generator\n")
print("Usage:")
print(" python doc_generator.py module.py")
print(" python doc_generator.py src/ --output docs/")
print(" python doc_generator.py module.py --list")
return 0
target = Path(args.path)
if not target.exists():
print(f"β Path not found: {args.path}")
return 1
files = [target] if target.is_file() else list(target.rglob("*.py"))
files = [
f for f in files if "__pycache__" not in str(f) and not f.name.startswith("_")
]
print(f"π Generating docs for {len(files)} file(s)\n")
undocumented = []
for f in files[:20]:
info = extract_module_info(f)
if args.list:
if not info["docstring"]:
undocumented.append(f"Module: {f.name}")
for func in info["functions"]:
if not func["docstring"] and not func["name"].startswith("_"):
undocumented.append(f" Function: {f.name}:{func['name']}")
for cls in info["classes"]:
if not cls["docstring"]:
undocumented.append(f" Class: {f.name}:{cls['name']}")
continue
doc = generate_markdown(info)
if args.output:
out_dir = Path(args.output)
out_dir.mkdir(parents=True, exist_ok=True)
out_file = out_dir / f"{f.stem}.md"
out_file.write_text(doc)
print(f" β
{f.name} β {out_file}")
else:
print(f"π {f.name}:")
print(f" Functions: {len(info['functions'])}")
print(f" Classes: {len(info['classes'])}")
if args.list:
if undocumented:
print(f"β οΈ Undocumented items ({len(undocumented)}):\n")
for item in undocumented[:30]:
print(f" {item}")
else:
print("β
All items documented")
return 0
if __name__ == "__main__":
sys.exit(main())