Repository navigation
Expand file tree
/
Copy pathreadmegen.py
More file actions
327 lines (275 loc) · 11.2 KB
/
Copy pathreadmegen.py
File metadata and controls
327 lines (275 loc) · 11.2 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
#!/usr/bin/env python3
"""
readmegen — Smart README generator. Analyzes your project and generates
a real README.md based on actual code, dependencies, and structure.
Not a generic template — reads package.json, setup.py, pyproject.toml,
requirements.txt, Makefile, Dockerfile, and source code to produce
accurate documentation.
Usage:
py readmegen.py /path/to/project # Generate README
py readmegen.py /path/to/project -o README.md # Write to file
py readmegen.py . # Current directory
py readmegen.py . --style minimal # Short README
py readmegen.py . --style detailed # Full README
"""
import argparse
import json
import os
import re
import sys
from pathlib import Path
from collections import Counter
# Skip dirs
SKIP = {"node_modules", ".git", "__pycache__", "venv", ".venv", "dist", "build", ".next", "target"}
LANG_MAP = {
".py": "Python", ".js": "JavaScript", ".ts": "TypeScript",
".go": "Go", ".rs": "Rust", ".java": "Java", ".rb": "Ruby",
".php": "PHP", ".cs": "C#", ".cpp": "C++", ".c": "C",
".swift": "Swift", ".kt": "Kotlin", ".dart": "Dart",
".vue": "Vue", ".svelte": "Svelte",
}
def detect_project_info(project_dir: Path) -> dict:
"""Extract project metadata from config files."""
info = {"name": project_dir.name, "description": "", "version": "",
"author": "", "license": "", "language": "", "scripts": {},
"dependencies": [], "dev_dependencies": []}
# package.json (Node.js)
pkg = project_dir / "package.json"
if pkg.exists():
try:
data = json.loads(pkg.read_text(encoding="utf-8"))
info["name"] = data.get("name", info["name"])
info["description"] = data.get("description", "")
info["version"] = data.get("version", "")
info["author"] = data.get("author", "")
info["license"] = data.get("license", "")
info["language"] = "JavaScript/TypeScript"
info["scripts"] = data.get("scripts", {})
info["dependencies"] = list(data.get("dependencies", {}).keys())
info["dev_dependencies"] = list(data.get("devDependencies", {}).keys())
except Exception:
pass
# pyproject.toml
pyproj = project_dir / "pyproject.toml"
if pyproj.exists():
try:
text = pyproj.read_text(encoding="utf-8")
name_m = re.search(r'name\s*=\s*"([^"]+)"', text)
desc_m = re.search(r'description\s*=\s*"([^"]+)"', text)
ver_m = re.search(r'version\s*=\s*"([^"]+)"', text)
if name_m: info["name"] = name_m.group(1)
if desc_m: info["description"] = desc_m.group(1)
if ver_m: info["version"] = ver_m.group(1)
info["language"] = info["language"] or "Python"
# Extract dependencies
deps = re.findall(r'dependencies\s*=\s*\[(.*?)\]', text, re.DOTALL)
if deps:
info["dependencies"] = re.findall(r'"([^"]+)"', deps[0])
except Exception:
pass
# setup.py
setup = project_dir / "setup.py"
if setup.exists() and not info["description"]:
try:
text = setup.read_text(encoding="utf-8")
name_m = re.search(r'name\s*=\s*["\']([^"\']+)["\']', text)
desc_m = re.search(r'description\s*=\s*["\']([^"\']+)["\']', text)
if name_m: info["name"] = name_m.group(1)
if desc_m: info["description"] = desc_m.group(1)
info["language"] = "Python"
except Exception:
pass
# requirements.txt
reqs = project_dir / "requirements.txt"
if reqs.exists() and not info["dependencies"]:
try:
lines = reqs.read_text(encoding="utf-8").splitlines()
info["dependencies"] = [l.split(">=")[0].split("==")[0].strip()
for l in lines if l.strip() and not l.startswith("#")]
info["language"] = info["language"] or "Python"
except Exception:
pass
# Cargo.toml (Rust)
cargo = project_dir / "Cargo.toml"
if cargo.exists():
try:
text = cargo.read_text(encoding="utf-8")
name_m = re.search(r'name\s*=\s*"([^"]+)"', text)
desc_m = re.search(r'description\s*=\s*"([^"]+)"', text)
if name_m: info["name"] = name_m.group(1)
if desc_m: info["description"] = desc_m.group(1)
info["language"] = "Rust"
except Exception:
pass
# go.mod
gomod = project_dir / "go.mod"
if gomod.exists():
info["language"] = info["language"] or "Go"
# LICENSE
for lf in ["LICENSE", "LICENSE.md", "LICENSE.txt"]:
lpath = project_dir / lf
if lpath.exists():
text = lpath.read_text(encoding="utf-8", errors="ignore")[:200]
if "MIT" in text: info["license"] = "MIT"
elif "Apache" in text: info["license"] = "Apache-2.0"
elif "GPL" in text: info["license"] = "GPL"
elif "BSD" in text: info["license"] = "BSD"
break
# Auto-detect primary language from files
if not info["language"]:
ext_count = Counter()
for f in project_dir.rglob("*"):
if f.is_file() and not any(s in f.parts for s in SKIP):
if f.suffix in LANG_MAP:
ext_count[LANG_MAP[f.suffix]] += 1
if ext_count:
info["language"] = ext_count.most_common(1)[0][0]
return info
def detect_install_method(project_dir: Path, info: dict) -> list[str]:
"""Detect how to install/setup the project."""
steps = []
if (project_dir / "package.json").exists():
lock = "package-lock.json" if (project_dir / "package-lock.json").exists() else \
"yarn.lock" if (project_dir / "yarn.lock").exists() else \
"pnpm-lock.yaml" if (project_dir / "pnpm-lock.yaml").exists() else None
if lock == "yarn.lock":
steps.append("yarn install")
elif lock == "pnpm-lock.yaml":
steps.append("pnpm install")
else:
steps.append("npm install")
if (project_dir / "requirements.txt").exists():
steps.append("pip install -r requirements.txt")
elif (project_dir / "pyproject.toml").exists():
steps.append("pip install .")
if (project_dir / "Cargo.toml").exists():
steps.append("cargo build")
if (project_dir / "go.mod").exists():
steps.append("go mod download")
if (project_dir / "Makefile").exists():
steps.append("make")
if (project_dir / "Dockerfile").exists():
steps.append("docker build -t " + info["name"] + " .")
return steps
def get_directory_tree(project_dir: Path, max_depth: int = 2) -> list[str]:
"""Generate a simple directory tree."""
tree = []
for item in sorted(project_dir.iterdir()):
if item.name.startswith(".") or item.name in SKIP:
continue
if item.is_dir():
tree.append(f"{item.name}/")
if max_depth > 1:
for sub in sorted(item.iterdir()):
if sub.name.startswith(".") or sub.name in SKIP:
continue
prefix = " " if sub.is_dir() else " "
suffix = "/" if sub.is_dir() else ""
tree.append(f" {sub.name}{suffix}")
else:
tree.append(item.name)
return tree
def detect_scripts(info: dict) -> dict:
"""Extract common development commands."""
commands = {}
scripts = info.get("scripts", {})
for key in ["dev", "start", "build", "test", "lint", "format", "deploy"]:
if key in scripts:
pkg_mgr = "npm run"
commands[key] = f"{pkg_mgr} {key}"
return commands
def generate_readme(project_dir: Path, style: str = "standard") -> str:
"""Generate README content."""
info = detect_project_info(project_dir)
install = detect_install_method(project_dir, info)
tree = get_directory_tree(project_dir)
commands = detect_scripts(info)
lines = []
# Title
title = info["name"].replace("-", " ").replace("_", " ").title()
lines.append(f"# {title}")
lines.append("")
# Description
if info["description"]:
lines.append(info["description"])
lines.append("")
# Badges (if we can detect)
badges = []
if info["language"]:
badges.append(f"})")
if info["license"]:
badges.append(f"})")
if info["version"]:
badges.append(f"})")
if badges:
lines.append(" ".join(badges))
lines.append("")
# Installation
if install:
lines.append("## Installation")
lines.append("")
lines.append("```bash")
for step in install:
lines.append(step)
lines.append("```")
lines.append("")
# Usage / Scripts
if commands:
lines.append("## Usage")
lines.append("")
lines.append("```bash")
for name, cmd in commands.items():
lines.append(f"# {name.capitalize()}")
lines.append(cmd)
lines.append("")
lines.append("```")
lines.append("")
# Project Structure (standard and detailed only)
if style != "minimal" and tree:
lines.append("## Project Structure")
lines.append("")
lines.append("```")
for entry in tree[:30]: # cap at 30 entries
lines.append(entry)
if len(tree) > 30:
lines.append(f"... and {len(tree) - 30} more")
lines.append("```")
lines.append("")
# Dependencies (detailed only)
if style == "detailed" and info["dependencies"]:
lines.append("## Dependencies")
lines.append("")
for dep in info["dependencies"][:20]:
lines.append(f"- `{dep}`")
if len(info["dependencies"]) > 20:
lines.append(f"- ... and {len(info['dependencies']) - 20} more")
lines.append("")
# License
if info["license"]:
lines.append("## License")
lines.append("")
lines.append(f"{info['license']}")
lines.append("")
return "\n".join(lines)
def _badge_url(label: str, value: str) -> str:
"""Generate shields.io badge URL."""
value_clean = value.replace("-", "--").replace(" ", "_")
return f"https://img.shields.io/badge/{label}-{value_clean}-blue"
def main():
parser = argparse.ArgumentParser(description="readmegen -- smart README generator")
parser.add_argument("path", nargs="?", default=".", help="Project directory")
parser.add_argument("-o", "--output", help="Output file (default: stdout)")
parser.add_argument("--style", choices=["minimal", "standard", "detailed"], default="standard")
args = parser.parse_args()
project = Path(args.path)
if not project.exists():
print(f"Error: {project} not found", file=sys.stderr)
sys.exit(1)
readme = generate_readme(project, args.style)
if args.output:
Path(args.output).write_text(readme, encoding="utf-8")
print(f"README written to {args.output}", file=sys.stderr)
else:
print(readme)
if __name__ == "__main__":
main()