@hxp-tools/codedna 0.0.0-stage → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +179 -0
- package/LICENSE +21 -0
- package/README.md +136 -2
- package/assets/achievements.svg +87 -0
- package/assets/fingerprint-engine.svg +60 -0
- package/assets/hero.svg +44 -0
- package/assets/quest-map.svg +55 -0
- package/bin/codedna.js +98 -0
- package/install.sh +95 -0
- package/package.json +50 -4
- package/skill/SKILL.md +286 -0
- package/skill/scripts/__pycache__/codedna_stats.cpython-315.pyc +0 -0
- package/skill/scripts/__pycache__/codedna_wire.cpython-315.pyc +0 -0
- package/skill/scripts/codedna_stats.py +802 -0
- package/skill/scripts/codedna_wire.py +133 -0
|
@@ -0,0 +1,802 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Best-effort style statistics for codedna."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
from collections import Counter, defaultdict
|
|
10
|
+
from statistics import median
|
|
11
|
+
|
|
12
|
+
MAX_FILES_PER_LANG = 800
|
|
13
|
+
MAX_FILE_BYTES = 1_000_000
|
|
14
|
+
MAX_BYTES_PER_LINE = 400
|
|
15
|
+
|
|
16
|
+
IGNORE = {
|
|
17
|
+
".git",
|
|
18
|
+
"node_modules",
|
|
19
|
+
"dist",
|
|
20
|
+
"build",
|
|
21
|
+
"out",
|
|
22
|
+
"target",
|
|
23
|
+
"vendor",
|
|
24
|
+
".next",
|
|
25
|
+
".svelte-kit",
|
|
26
|
+
"venv",
|
|
27
|
+
".venv",
|
|
28
|
+
"__pycache__",
|
|
29
|
+
"coverage",
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
EXT = {
|
|
33
|
+
".js": "js",
|
|
34
|
+
".jsx": "js",
|
|
35
|
+
".mjs": "js",
|
|
36
|
+
".cjs": "js",
|
|
37
|
+
".ts": "ts",
|
|
38
|
+
".tsx": "ts",
|
|
39
|
+
".mts": "ts",
|
|
40
|
+
".cts": "ts",
|
|
41
|
+
".py": "py",
|
|
42
|
+
".go": "go",
|
|
43
|
+
".rs": "rs",
|
|
44
|
+
".java": "java",
|
|
45
|
+
".rb": "rb",
|
|
46
|
+
".php": "php",
|
|
47
|
+
".c": "c",
|
|
48
|
+
".cpp": "cpp",
|
|
49
|
+
".cc": "cpp",
|
|
50
|
+
".cxx": "cpp",
|
|
51
|
+
".hpp": "cpp",
|
|
52
|
+
".cs": "cs",
|
|
53
|
+
".swift": "swift",
|
|
54
|
+
".kt": "kt",
|
|
55
|
+
".kts": "kt",
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
HASH_COMMENT = {"py", "rb"}
|
|
59
|
+
QUOTE_LANGS = {"js", "ts", "py", "rb", "php"}
|
|
60
|
+
BOOLEAN_PREFIX_RE = re.compile(r"^(?:is|has|should|can|will|did)(?:[A-Z_]|$)")
|
|
61
|
+
TODO_RE = re.compile(r"\b(?:TODO|FIXME)\b")
|
|
62
|
+
WORD_RE = re.compile(r"\b[\w][\w'-]*\b", re.UNICODE)
|
|
63
|
+
FIRST_PERSON_RE = re.compile(r"\b(?:I|me|my|mine|we|us|our|ours)\b", re.I)
|
|
64
|
+
SECOND_PERSON_RE = re.compile(r"\b(?:you|your|yours)\b", re.I)
|
|
65
|
+
CONTRACTION_RE = re.compile(
|
|
66
|
+
r"\b(?:[A-Za-z]+n't|(?:I|you|we|they|he|she|it)'(?:m|re|ve|ll|d|s))\b",
|
|
67
|
+
re.I,
|
|
68
|
+
)
|
|
69
|
+
MESSAGE_LITERAL = r'(?:"((?:\\.|[^"\\\r\n])*)"|\'((?:\\.|[^\'\\\r\n])*)\'|`((?:\\.|[^`\\\r\n])*)`)'
|
|
70
|
+
QUOTE_KINDS = {'"': "double", "'": "single", "`": "backtick"}
|
|
71
|
+
REGEX_LITERAL = (
|
|
72
|
+
r"(?:(?<=[(,=:\[!&|?{};])|(?<=\breturn)|^)[ \t]*"
|
|
73
|
+
r"/(?![/*])(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\\[\n])+/"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
ERROR_PREFIXES = {
|
|
77
|
+
"js": r"\b(?:new\s+)?(?:[A-Za-z_$][\w$]*Error|Error)\s*\(\s*",
|
|
78
|
+
"ts": r"\b(?:new\s+)?(?:[A-Za-z_$][\w$]*Error|Error)\s*\(\s*",
|
|
79
|
+
"py": r"\braise\s+(?:[A-Za-z_]\w*(?:Error|Exception)|Error|Exception)\s*\(\s*",
|
|
80
|
+
"go": r"\b(?:errors\.New|fmt\.Errorf)\s*\(\s*",
|
|
81
|
+
"rs": r"(?:\bpanic!|\bbail!|\banyhow!|\.expect)\s*\(\s*",
|
|
82
|
+
"java": r"\bthrow\s+new\s+(?:[A-Za-z_]\w*(?:Exception|Error)|Exception|Error)\s*\(\s*",
|
|
83
|
+
"kt": r"\bthrow\s+(?:[A-Za-z_]\w*(?:Exception|Error)|Exception|Error)\s*\(\s*",
|
|
84
|
+
"cs": r"\bthrow\s+new\s+(?:[A-Za-z_]\w*(?:Exception|Error)|Exception|Error)\s*\(\s*",
|
|
85
|
+
"php": r"\bthrow\s+new\s+\\?(?:[A-Za-z_]\w*(?:Exception|Error)|Exception|Error)\s*\(\s*",
|
|
86
|
+
"rb": r"\braise(?:\s+[A-Za-z_:]+\s*,)?\s*",
|
|
87
|
+
"swift": r"\b(?:fatalError|preconditionFailure)\s*\(\s*",
|
|
88
|
+
"cpp": r"\bthrow\s+(?:std::)?[A-Za-z_]\w*(?:error|exception)\s*\(\s*",
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
DOC_MARKERS = {
|
|
92
|
+
"default": ("/**", "///"),
|
|
93
|
+
"go": ("//",),
|
|
94
|
+
"rs": ("///", "//!", "/**"),
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
PATS = {
|
|
98
|
+
"js": {
|
|
99
|
+
"function": [
|
|
100
|
+
r"\bfunction\s+([A-Za-z_$][\w$]*)\s*\(",
|
|
101
|
+
r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?function\b",
|
|
102
|
+
r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>",
|
|
103
|
+
],
|
|
104
|
+
"type": [r"\b(?:interface|type)\s+([A-Za-z_$][\w$]*)"],
|
|
105
|
+
"class": [r"\bclass\s+([A-Za-z_$][\w$]*)"],
|
|
106
|
+
"constant": [r"\bconst\s+([A-Z_][A-Z0-9_]{2,})\b"],
|
|
107
|
+
"variable": [r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\b"],
|
|
108
|
+
},
|
|
109
|
+
"py": {
|
|
110
|
+
"function": [r"^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)"],
|
|
111
|
+
"class": [r"^\s*class\s+([A-Za-z_]\w*)"],
|
|
112
|
+
"constant": [r"^([A-Z_][A-Z0-9_]{2,})\s*="],
|
|
113
|
+
"variable": [r"^\s*([A-Za-z_]\w*)\s*="],
|
|
114
|
+
},
|
|
115
|
+
"go": {
|
|
116
|
+
"function": [r"\bfunc\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)"],
|
|
117
|
+
"type": [r"\btype\s+([A-Za-z_]\w*)"],
|
|
118
|
+
},
|
|
119
|
+
"rs": {
|
|
120
|
+
"function": [r"\bfn\s+([A-Za-z_]\w*)"],
|
|
121
|
+
"type": [r"\b(?:struct|enum|trait)\s+([A-Za-z_]\w*)"],
|
|
122
|
+
},
|
|
123
|
+
}
|
|
124
|
+
PATS["ts"] = PATS["js"]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def case(name):
|
|
128
|
+
text = name.strip("_")
|
|
129
|
+
if not text:
|
|
130
|
+
return "other"
|
|
131
|
+
if "-" in text:
|
|
132
|
+
return "kebab"
|
|
133
|
+
if "_" in text:
|
|
134
|
+
if text.isupper():
|
|
135
|
+
return "SCREAMING_SNAKE"
|
|
136
|
+
if text.islower():
|
|
137
|
+
return "snake_case"
|
|
138
|
+
return "mixed"
|
|
139
|
+
if text.isupper():
|
|
140
|
+
return "UPPER"
|
|
141
|
+
if text.islower():
|
|
142
|
+
return "lower"
|
|
143
|
+
return "PascalCase" if text[0].isupper() else "camelCase"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def walk_files(target):
|
|
147
|
+
for root, dirs, names in os.walk(target):
|
|
148
|
+
dirs[:] = [d for d in dirs if d not in IGNORE and not d.startswith(".")]
|
|
149
|
+
for name in names:
|
|
150
|
+
yield os.path.join(root, name)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def git_files(target):
|
|
154
|
+
try:
|
|
155
|
+
proc = subprocess.run(
|
|
156
|
+
["git", "-C", str(target), "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
|
|
157
|
+
capture_output=True,
|
|
158
|
+
check=True,
|
|
159
|
+
)
|
|
160
|
+
except (OSError, subprocess.CalledProcessError):
|
|
161
|
+
return []
|
|
162
|
+
paths = []
|
|
163
|
+
for raw in proc.stdout.split(b"\0"):
|
|
164
|
+
parts = os.fsdecode(raw).split("/")
|
|
165
|
+
if not raw or any(part in IGNORE or part.startswith(".") for part in parts[:-1]):
|
|
166
|
+
continue
|
|
167
|
+
path = os.path.join(target, *parts)
|
|
168
|
+
if parts[-1]:
|
|
169
|
+
paths.append(path)
|
|
170
|
+
else:
|
|
171
|
+
paths.extend(source_files(path))
|
|
172
|
+
return paths
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def source_files(target):
|
|
176
|
+
return git_files(target) or list(walk_files(target))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def collect_files(target):
|
|
180
|
+
files = defaultdict(set)
|
|
181
|
+
for path in source_files(target):
|
|
182
|
+
lang = EXT.get(os.path.splitext(path)[1].lower())
|
|
183
|
+
if lang and os.path.isfile(path):
|
|
184
|
+
files[lang].add(path)
|
|
185
|
+
return {lang: sorted(paths) for lang, paths in files.items()}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def sample_paths(paths):
|
|
189
|
+
if len(paths) <= MAX_FILES_PER_LANG:
|
|
190
|
+
return paths
|
|
191
|
+
step = len(paths) / MAX_FILES_PER_LANG
|
|
192
|
+
return [paths[int(index * step)] for index in range(MAX_FILES_PER_LANG)]
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def read_text(path):
|
|
196
|
+
with open(path, encoding="utf-8-sig", errors="replace") as handle:
|
|
197
|
+
return handle.read()
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def comment_config(lang):
|
|
201
|
+
token = "#" if lang in HASH_COMMENT else "//"
|
|
202
|
+
if lang == "py":
|
|
203
|
+
block = [('"""', '"""'), ("'''", "'''")]
|
|
204
|
+
elif lang in HASH_COMMENT:
|
|
205
|
+
block = []
|
|
206
|
+
else:
|
|
207
|
+
block = [("/*", "*/")]
|
|
208
|
+
return token, block
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def open_block(stripped, block, token):
|
|
212
|
+
if not any(opener == closer for opener, closer in block):
|
|
213
|
+
return None
|
|
214
|
+
index = 0
|
|
215
|
+
limit = len(stripped)
|
|
216
|
+
while index < limit:
|
|
217
|
+
rest = stripped[index:]
|
|
218
|
+
if rest.startswith(token):
|
|
219
|
+
return None
|
|
220
|
+
for opener, closer in block:
|
|
221
|
+
if opener == closer and rest.startswith(opener):
|
|
222
|
+
end = stripped.find(closer, index + len(opener))
|
|
223
|
+
if end < 0:
|
|
224
|
+
return closer
|
|
225
|
+
index = end + len(closer)
|
|
226
|
+
break
|
|
227
|
+
else:
|
|
228
|
+
char = stripped[index]
|
|
229
|
+
if char in "'\"`":
|
|
230
|
+
end = stripped.find(char, index + 1)
|
|
231
|
+
index = limit if end < 0 else end + 1
|
|
232
|
+
else:
|
|
233
|
+
index += 1
|
|
234
|
+
return None
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def count_lines(lang, text):
|
|
238
|
+
token, block = comment_config(lang)
|
|
239
|
+
code = comment = tabs = spaces = 0
|
|
240
|
+
pending = None
|
|
241
|
+
for line in text.splitlines():
|
|
242
|
+
stripped = line.strip()
|
|
243
|
+
if pending is not None:
|
|
244
|
+
closer, is_comment = pending
|
|
245
|
+
if stripped:
|
|
246
|
+
if is_comment:
|
|
247
|
+
comment += 1
|
|
248
|
+
else:
|
|
249
|
+
code += 1
|
|
250
|
+
if closer in line:
|
|
251
|
+
pending = None
|
|
252
|
+
continue
|
|
253
|
+
if not stripped:
|
|
254
|
+
continue
|
|
255
|
+
if stripped.startswith(token):
|
|
256
|
+
comment += 1
|
|
257
|
+
continue
|
|
258
|
+
hit = False
|
|
259
|
+
for opener, closer in block:
|
|
260
|
+
if stripped.startswith(opener):
|
|
261
|
+
comment += 1
|
|
262
|
+
if closer not in stripped[len(opener):]:
|
|
263
|
+
pending = (closer, True)
|
|
264
|
+
hit = True
|
|
265
|
+
break
|
|
266
|
+
if hit:
|
|
267
|
+
continue
|
|
268
|
+
code += 1
|
|
269
|
+
leading = line[: len(line) - len(line.lstrip())]
|
|
270
|
+
if leading.startswith("\t"):
|
|
271
|
+
tabs += 1
|
|
272
|
+
elif leading.startswith(" "):
|
|
273
|
+
spaces += 1
|
|
274
|
+
closer = open_block(stripped, block, token)
|
|
275
|
+
if closer:
|
|
276
|
+
pending = (closer, False)
|
|
277
|
+
return code, comment, tabs, spaces
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def literal_pattern(lang):
|
|
281
|
+
if lang in HASH_COMMENT:
|
|
282
|
+
parts = [r"#[^\n]*"]
|
|
283
|
+
else:
|
|
284
|
+
parts = [r"//[^\n]*", r"(?<![\\\[])/\*[\s\S]*?\*/"]
|
|
285
|
+
if lang == "py":
|
|
286
|
+
parts += [r'"""[\s\S]*?"""', r"'''[\s\S]*?'''"]
|
|
287
|
+
parts += [r'"(?:[^"\\\n]|\\.)*"', r"'(?:[^'\\\n]|\\.)*'"]
|
|
288
|
+
if lang in {"js", "ts"}:
|
|
289
|
+
parts.append(r"`(?:[^`\\]|\\[\s\S])*`")
|
|
290
|
+
parts.append(REGEX_LITERAL)
|
|
291
|
+
return re.compile("|".join(parts), re.M)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def count_quotes(lang, text):
|
|
295
|
+
if lang not in QUOTE_LANGS:
|
|
296
|
+
return Counter()
|
|
297
|
+
counts = Counter({"double": 0, "single": 0})
|
|
298
|
+
if lang in {"js", "ts"}:
|
|
299
|
+
counts["backtick"] = 0
|
|
300
|
+
for match in literal_pattern(lang).finditer(text):
|
|
301
|
+
literal = match.group()
|
|
302
|
+
if literal[:3] not in ('"""', "'''") and literal[0] in QUOTE_KINDS:
|
|
303
|
+
counts[QUOTE_KINDS[literal[0]]] += 1
|
|
304
|
+
return counts
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def clean_comment_text(value):
|
|
308
|
+
text = value.strip()
|
|
309
|
+
if text.startswith("*"):
|
|
310
|
+
text = text[1:].strip()
|
|
311
|
+
return text
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def comment_texts(lang, text):
|
|
315
|
+
token, block = comment_config(lang)
|
|
316
|
+
comments = []
|
|
317
|
+
pending = None
|
|
318
|
+
|
|
319
|
+
for line in text.splitlines():
|
|
320
|
+
stripped = line.strip()
|
|
321
|
+
if pending is not None:
|
|
322
|
+
closer, is_comment = pending
|
|
323
|
+
end = stripped.find(closer)
|
|
324
|
+
if is_comment:
|
|
325
|
+
value = stripped if end < 0 else stripped[:end]
|
|
326
|
+
value = clean_comment_text(value)
|
|
327
|
+
if value:
|
|
328
|
+
comments.append(value)
|
|
329
|
+
if end >= 0:
|
|
330
|
+
pending = None
|
|
331
|
+
continue
|
|
332
|
+
if not stripped:
|
|
333
|
+
continue
|
|
334
|
+
if stripped.startswith(token):
|
|
335
|
+
value = clean_comment_text(stripped[len(token):])
|
|
336
|
+
if value:
|
|
337
|
+
comments.append(value)
|
|
338
|
+
continue
|
|
339
|
+
for opener, closer in block:
|
|
340
|
+
if not stripped.startswith(opener):
|
|
341
|
+
continue
|
|
342
|
+
value = stripped[len(opener):]
|
|
343
|
+
end = value.find(closer)
|
|
344
|
+
if end >= 0:
|
|
345
|
+
value = value[:end]
|
|
346
|
+
else:
|
|
347
|
+
pending = (closer, True)
|
|
348
|
+
value = clean_comment_text(value)
|
|
349
|
+
if value:
|
|
350
|
+
comments.append(value)
|
|
351
|
+
break
|
|
352
|
+
else:
|
|
353
|
+
closer = open_block(stripped, block, token)
|
|
354
|
+
if closer:
|
|
355
|
+
pending = (closer, False)
|
|
356
|
+
|
|
357
|
+
return comments
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def code_text_lines(lang, text):
|
|
361
|
+
token, block = comment_config(lang)
|
|
362
|
+
pending = None
|
|
363
|
+
|
|
364
|
+
for line in text.splitlines():
|
|
365
|
+
stripped = line.strip()
|
|
366
|
+
if pending is not None:
|
|
367
|
+
if pending in line:
|
|
368
|
+
pending = None
|
|
369
|
+
continue
|
|
370
|
+
if not stripped or stripped.startswith(token):
|
|
371
|
+
continue
|
|
372
|
+
for opener, closer in block:
|
|
373
|
+
if not stripped.startswith(opener):
|
|
374
|
+
continue
|
|
375
|
+
if closer not in stripped[len(opener):]:
|
|
376
|
+
pending = closer
|
|
377
|
+
break
|
|
378
|
+
else:
|
|
379
|
+
yield line
|
|
380
|
+
closer = open_block(stripped, block, token)
|
|
381
|
+
if closer:
|
|
382
|
+
pending = closer
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def error_messages(lang, text):
|
|
386
|
+
prefix = ERROR_PREFIXES.get(lang)
|
|
387
|
+
if not prefix:
|
|
388
|
+
return []
|
|
389
|
+
messages = []
|
|
390
|
+
for line in code_text_lines(lang, text):
|
|
391
|
+
for match in re.finditer(prefix + MESSAGE_LITERAL, line, re.I):
|
|
392
|
+
messages.append(next(group for group in match.groups() if group is not None))
|
|
393
|
+
return messages
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def is_capitalized(text):
|
|
397
|
+
first = next((char for char in text if char.isalpha()), "")
|
|
398
|
+
return bool(first and first.isupper())
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def has_terminal_punctuation(text):
|
|
402
|
+
trimmed = text.rstrip().rstrip("`*_)]}'\"")
|
|
403
|
+
return bool(trimmed and trimmed[-1] in ".?!")
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def share(count, total):
|
|
407
|
+
return round(100 * count / total, 1) if total else 0
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def comment_voice(texts):
|
|
411
|
+
samples = [text for text in texts if WORD_RE.search(text)]
|
|
412
|
+
word_lengths = [len(WORD_RE.findall(text)) for text in samples]
|
|
413
|
+
capitalized = sum(1 for text in samples if is_capitalized(text))
|
|
414
|
+
punctuated = sum(1 for text in samples if has_terminal_punctuation(text))
|
|
415
|
+
sentence_like = sum(
|
|
416
|
+
1 for text in samples if is_capitalized(text) and has_terminal_punctuation(text)
|
|
417
|
+
)
|
|
418
|
+
first_person = sum(1 for text in samples if FIRST_PERSON_RE.search(text))
|
|
419
|
+
second_person = sum(1 for text in samples if SECOND_PERSON_RE.search(text))
|
|
420
|
+
contractions = sum(1 for text in samples if CONTRACTION_RE.search(text))
|
|
421
|
+
total = len(samples)
|
|
422
|
+
return {
|
|
423
|
+
"lines": total,
|
|
424
|
+
"word_lengths": summarize(word_lengths),
|
|
425
|
+
"sentence_like_percent": share(sentence_like, total),
|
|
426
|
+
"fragment_like_percent": share(total - sentence_like, total),
|
|
427
|
+
"capitalized_percent": share(capitalized, total),
|
|
428
|
+
"terminal_punctuation_percent": share(punctuated, total),
|
|
429
|
+
"first_person_percent": share(first_person, total),
|
|
430
|
+
"second_person_percent": share(second_person, total),
|
|
431
|
+
"contractions_percent": share(contractions, total),
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def message_voice(messages):
|
|
436
|
+
samples = [message.strip() for message in messages if WORD_RE.search(message)]
|
|
437
|
+
total = len(samples)
|
|
438
|
+
capitalized = sum(1 for message in samples if is_capitalized(message))
|
|
439
|
+
punctuated = sum(1 for message in samples if has_terminal_punctuation(message))
|
|
440
|
+
return {
|
|
441
|
+
"messages": total,
|
|
442
|
+
"capitalized_percent": share(capitalized, total),
|
|
443
|
+
"terminal_punctuation_percent": share(punctuated, total),
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def percentile(values, pct):
|
|
448
|
+
if not values:
|
|
449
|
+
return 0
|
|
450
|
+
ordered = sorted(values)
|
|
451
|
+
index = round((pct / 100) * (len(ordered) - 1))
|
|
452
|
+
return ordered[index]
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def summarize(values):
|
|
456
|
+
if not values:
|
|
457
|
+
return {"count": 0, "median": 0, "p90": 0}
|
|
458
|
+
return {
|
|
459
|
+
"count": len(values),
|
|
460
|
+
"median": median(values),
|
|
461
|
+
"p90": percentile(values, 90),
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def add_file_case(naming, path):
|
|
466
|
+
base = os.path.splitext(os.path.basename(path))[0]
|
|
467
|
+
if base:
|
|
468
|
+
naming["file"][case(base)] += 1
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def add_identifier_cases(lang, text, naming, lengths, boolean_names):
|
|
472
|
+
claimed = set()
|
|
473
|
+
for kind, patterns in PATS.get(lang, {}).items():
|
|
474
|
+
for pattern in patterns:
|
|
475
|
+
for match in re.finditer(pattern, text, re.M):
|
|
476
|
+
if match.start(1) in claimed:
|
|
477
|
+
continue
|
|
478
|
+
claimed.add(match.start(1))
|
|
479
|
+
name = match.group(1)
|
|
480
|
+
naming[kind][case(name)] += 1
|
|
481
|
+
lengths[kind].append(len(name.strip("_")))
|
|
482
|
+
if name and name[0].islower():
|
|
483
|
+
boolean_names.append(name)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def leading_indent(line):
|
|
487
|
+
return len(line) - len(line.lstrip())
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def py_function_lengths(text):
|
|
491
|
+
lengths = []
|
|
492
|
+
lines = text.splitlines()
|
|
493
|
+
for index, line in enumerate(lines):
|
|
494
|
+
if not re.match(r"^\s*(?:async\s+)?def\s+[A-Za-z_]\w*", line):
|
|
495
|
+
continue
|
|
496
|
+
indent = leading_indent(line)
|
|
497
|
+
end = index + 1
|
|
498
|
+
for cursor in range(index + 1, len(lines)):
|
|
499
|
+
stripped = lines[cursor].strip()
|
|
500
|
+
if not stripped:
|
|
501
|
+
continue
|
|
502
|
+
if leading_indent(lines[cursor]) <= indent and not stripped.startswith("#"):
|
|
503
|
+
break
|
|
504
|
+
end = cursor + 1
|
|
505
|
+
lengths.append(max(1, end - index))
|
|
506
|
+
return lengths
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def brace_function_lengths(text):
|
|
510
|
+
starts = re.compile(
|
|
511
|
+
r"\bfunction\s+[A-Za-z_$][\w$]*\s*\(|"
|
|
512
|
+
r"\b(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)|"
|
|
513
|
+
r"\bfunc\s+(?:\([^)]*\)\s*)?[A-Za-z_]\w*|"
|
|
514
|
+
r"\bfn\s+[A-Za-z_]\w*"
|
|
515
|
+
)
|
|
516
|
+
lengths = []
|
|
517
|
+
lines = text.splitlines()
|
|
518
|
+
for index, line in enumerate(lines):
|
|
519
|
+
if not starts.search(line):
|
|
520
|
+
continue
|
|
521
|
+
if "=>" in line and "{" not in line:
|
|
522
|
+
lengths.append(1)
|
|
523
|
+
continue
|
|
524
|
+
balance = 0
|
|
525
|
+
saw_brace = False
|
|
526
|
+
end = index
|
|
527
|
+
for cursor in range(index, len(lines)):
|
|
528
|
+
balance += lines[cursor].count("{")
|
|
529
|
+
balance -= lines[cursor].count("}")
|
|
530
|
+
saw_brace = saw_brace or "{" in lines[cursor]
|
|
531
|
+
end = cursor
|
|
532
|
+
if saw_brace and balance <= 0:
|
|
533
|
+
break
|
|
534
|
+
lengths.append(max(1, end - index + 1))
|
|
535
|
+
return lengths
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def function_lengths(lang, text):
|
|
539
|
+
if lang == "py":
|
|
540
|
+
return py_function_lengths(text)
|
|
541
|
+
if lang in {"js", "ts", "go", "rs"}:
|
|
542
|
+
return brace_function_lengths(text)
|
|
543
|
+
return []
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def closes_doc_block(lines, cursor):
|
|
547
|
+
if not lines[cursor].strip().endswith("*/"):
|
|
548
|
+
return False
|
|
549
|
+
opener = cursor
|
|
550
|
+
while opener >= 0 and "/*" not in lines[opener]:
|
|
551
|
+
opener -= 1
|
|
552
|
+
return opener >= 0 and lines[opener].strip().startswith("/**")
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def doc_coverage(lang, text):
|
|
556
|
+
lines = text.splitlines()
|
|
557
|
+
total = 0
|
|
558
|
+
documented = 0
|
|
559
|
+
for index, line in enumerate(lines):
|
|
560
|
+
if lang == "py":
|
|
561
|
+
match = re.match(r"^\s*(?:async\s+)?def\s+[A-Za-z_]\w*", line)
|
|
562
|
+
else:
|
|
563
|
+
match = re.search(
|
|
564
|
+
r"\bfunction\s+[A-Za-z_$][\w$]*\s*\(|"
|
|
565
|
+
r"\b(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)|"
|
|
566
|
+
r"\bfunc\s+(?:\([^)]*\)\s*)?[A-Za-z_]\w*|"
|
|
567
|
+
r"\bfn\s+[A-Za-z_]\w*",
|
|
568
|
+
line,
|
|
569
|
+
)
|
|
570
|
+
if not match:
|
|
571
|
+
continue
|
|
572
|
+
total += 1
|
|
573
|
+
if lang == "py":
|
|
574
|
+
for cursor in range(index + 1, len(lines)):
|
|
575
|
+
stripped = lines[cursor].strip()
|
|
576
|
+
if not stripped:
|
|
577
|
+
continue
|
|
578
|
+
if stripped.startswith(('"""', "'''")):
|
|
579
|
+
documented += 1
|
|
580
|
+
break
|
|
581
|
+
else:
|
|
582
|
+
cursor = index - 1
|
|
583
|
+
while cursor >= 0 and not lines[cursor].strip():
|
|
584
|
+
cursor -= 1
|
|
585
|
+
if cursor < 0:
|
|
586
|
+
continue
|
|
587
|
+
markers = DOC_MARKERS.get(lang, DOC_MARKERS["default"])
|
|
588
|
+
if lines[cursor].strip().startswith(markers) or closes_doc_block(lines, cursor):
|
|
589
|
+
documented += 1
|
|
590
|
+
return documented, total
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def analyze_language(lang, paths):
|
|
594
|
+
result = {
|
|
595
|
+
"language": lang,
|
|
596
|
+
"files_total": len(paths),
|
|
597
|
+
"files_read": 0,
|
|
598
|
+
"files_skipped_large": 0,
|
|
599
|
+
"files_skipped_minified": 0,
|
|
600
|
+
"read_errors": 0,
|
|
601
|
+
"code_lines": 0,
|
|
602
|
+
"comment_lines": 0,
|
|
603
|
+
"indent": {"tabs": 0, "spaces": 0, "style": "spaces"},
|
|
604
|
+
"quotes": {},
|
|
605
|
+
"naming": {},
|
|
606
|
+
"identifier_lengths": {},
|
|
607
|
+
"function_lengths": {"count": 0, "median": 0, "p90": 0},
|
|
608
|
+
"boolean_prefix_share": {"count": 0, "prefixed": 0, "percent": 0},
|
|
609
|
+
"todo_markers": 0,
|
|
610
|
+
"doc_comment_coverage": {"functions": 0, "documented": 0, "percent": 0},
|
|
611
|
+
"comment_voice": comment_voice([]),
|
|
612
|
+
"error_message_voice": message_voice([]),
|
|
613
|
+
}
|
|
614
|
+
naming = defaultdict(Counter)
|
|
615
|
+
lengths = defaultdict(list)
|
|
616
|
+
quotes = Counter()
|
|
617
|
+
fn_lengths = []
|
|
618
|
+
boolean_names = []
|
|
619
|
+
documented_functions = 0
|
|
620
|
+
total_functions = 0
|
|
621
|
+
comments = []
|
|
622
|
+
messages = []
|
|
623
|
+
|
|
624
|
+
for path in sample_paths(paths):
|
|
625
|
+
try:
|
|
626
|
+
if os.path.getsize(path) > MAX_FILE_BYTES:
|
|
627
|
+
result["files_skipped_large"] += 1
|
|
628
|
+
continue
|
|
629
|
+
text = read_text(path)
|
|
630
|
+
except OSError:
|
|
631
|
+
result["read_errors"] += 1
|
|
632
|
+
continue
|
|
633
|
+
|
|
634
|
+
lines = text.splitlines()
|
|
635
|
+
if lines and len(text) / len(lines) > MAX_BYTES_PER_LINE:
|
|
636
|
+
result["files_skipped_minified"] += 1
|
|
637
|
+
continue
|
|
638
|
+
|
|
639
|
+
result["files_read"] += 1
|
|
640
|
+
code, comment, tabs, spaces = count_lines(lang, text)
|
|
641
|
+
result["code_lines"] += code
|
|
642
|
+
result["comment_lines"] += comment
|
|
643
|
+
result["indent"]["tabs"] += tabs
|
|
644
|
+
result["indent"]["spaces"] += spaces
|
|
645
|
+
quotes.update(count_quotes(lang, text))
|
|
646
|
+
add_file_case(naming, path)
|
|
647
|
+
add_identifier_cases(lang, text, naming, lengths, boolean_names)
|
|
648
|
+
fn_lengths.extend(function_lengths(lang, text))
|
|
649
|
+
documented, total = doc_coverage(lang, text)
|
|
650
|
+
documented_functions += documented
|
|
651
|
+
total_functions += total
|
|
652
|
+
result["todo_markers"] += len(TODO_RE.findall(text))
|
|
653
|
+
comments.extend(comment_texts(lang, text))
|
|
654
|
+
messages.extend(error_messages(lang, text))
|
|
655
|
+
|
|
656
|
+
result["files_capped"] = max(len(paths) - MAX_FILES_PER_LANG, 0)
|
|
657
|
+
total_lines = result["code_lines"] + result["comment_lines"]
|
|
658
|
+
result["comment_density"] = round(100 * result["comment_lines"] / total_lines, 1) if total_lines else 0
|
|
659
|
+
result["indent"]["style"] = "tabs" if result["indent"]["tabs"] > result["indent"]["spaces"] else "spaces"
|
|
660
|
+
result["quotes"] = dict(quotes)
|
|
661
|
+
result["naming"] = {kind: dict(counter) for kind, counter in naming.items()}
|
|
662
|
+
result["identifier_lengths"] = {kind: summarize(values) for kind, values in lengths.items()}
|
|
663
|
+
result["function_lengths"] = summarize(fn_lengths)
|
|
664
|
+
prefixed = sum(1 for name in boolean_names if BOOLEAN_PREFIX_RE.match(name))
|
|
665
|
+
result["boolean_prefix_share"] = {
|
|
666
|
+
"count": len(boolean_names),
|
|
667
|
+
"prefixed": prefixed,
|
|
668
|
+
"percent": round(100 * prefixed / len(boolean_names), 1) if boolean_names else 0,
|
|
669
|
+
}
|
|
670
|
+
result["doc_comment_coverage"] = {
|
|
671
|
+
"functions": total_functions,
|
|
672
|
+
"documented": documented_functions,
|
|
673
|
+
"percent": round(100 * documented_functions / total_functions, 1) if total_functions else 0,
|
|
674
|
+
}
|
|
675
|
+
result["comment_voice"] = comment_voice(comments)
|
|
676
|
+
result["error_message_voice"] = message_voice(messages)
|
|
677
|
+
return result
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def analyze(target):
|
|
681
|
+
files = collect_files(target)
|
|
682
|
+
return [
|
|
683
|
+
analyze_language(lang, paths)
|
|
684
|
+
for lang, paths in sorted(files.items(), key=lambda item: -len(item[1]))
|
|
685
|
+
]
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def pct(counter, key):
|
|
689
|
+
total = sum(counter.values())
|
|
690
|
+
return round(100 * counter[key] / total) if total else 0
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
def print_text(results, target):
|
|
694
|
+
if not results:
|
|
695
|
+
print("No recognized source files under", target)
|
|
696
|
+
return
|
|
697
|
+
|
|
698
|
+
for result in results:
|
|
699
|
+
lang = result["language"]
|
|
700
|
+
total = result["files_total"]
|
|
701
|
+
read = result["files_read"]
|
|
702
|
+
if read == total:
|
|
703
|
+
sample = "%d files" % total
|
|
704
|
+
else:
|
|
705
|
+
sample = "read %d of %d files" % (read, total)
|
|
706
|
+
print("\n== %s (%s, %d code lines) ==" % (lang, sample, result["code_lines"]))
|
|
707
|
+
if result["files_capped"]:
|
|
708
|
+
print(" sampled : capped at %d files, spread evenly by path" % MAX_FILES_PER_LANG)
|
|
709
|
+
if result["files_skipped_large"]:
|
|
710
|
+
print(" skipped : %d oversized files" % result["files_skipped_large"])
|
|
711
|
+
if result["files_skipped_minified"]:
|
|
712
|
+
print(" skipped : %d minified or generated files" % result["files_skipped_minified"])
|
|
713
|
+
if result["read_errors"]:
|
|
714
|
+
print(" unread : %d files" % result["read_errors"])
|
|
715
|
+
print(" comments : %s%% of non-blank lines" % result["comment_density"])
|
|
716
|
+
print(
|
|
717
|
+
" indent : %s (tabs %d / spaces %d indented lines)"
|
|
718
|
+
% (
|
|
719
|
+
result["indent"]["style"],
|
|
720
|
+
result["indent"]["tabs"],
|
|
721
|
+
result["indent"]["spaces"],
|
|
722
|
+
)
|
|
723
|
+
)
|
|
724
|
+
|
|
725
|
+
quotes = Counter(result["quotes"])
|
|
726
|
+
if sum(quotes.values()):
|
|
727
|
+
parts = ["%s %d%%" % (name, pct(quotes, name)) for name in ["double", "single", "backtick"] if quotes.get(name)]
|
|
728
|
+
print(" quotes : " + " / ".join(parts))
|
|
729
|
+
if result["function_lengths"]["count"]:
|
|
730
|
+
print(
|
|
731
|
+
" fn size : median %s lines / p90 %s (%d functions)"
|
|
732
|
+
% (
|
|
733
|
+
result["function_lengths"]["median"],
|
|
734
|
+
result["function_lengths"]["p90"],
|
|
735
|
+
result["function_lengths"]["count"],
|
|
736
|
+
)
|
|
737
|
+
)
|
|
738
|
+
if result["doc_comment_coverage"]["functions"]:
|
|
739
|
+
print(" doc cov : %s%% of functions" % result["doc_comment_coverage"]["percent"])
|
|
740
|
+
if result["todo_markers"]:
|
|
741
|
+
print(" markers : TODO/FIXME %d" % result["todo_markers"])
|
|
742
|
+
if result["comment_voice"]["lines"]:
|
|
743
|
+
voice = result["comment_voice"]
|
|
744
|
+
print(
|
|
745
|
+
" voice : comments median %s words / %s%% sentence-like / %s%% first person"
|
|
746
|
+
% (
|
|
747
|
+
voice["word_lengths"]["median"],
|
|
748
|
+
voice["sentence_like_percent"],
|
|
749
|
+
voice["first_person_percent"],
|
|
750
|
+
)
|
|
751
|
+
)
|
|
752
|
+
print(
|
|
753
|
+
" %s%% second person / %s%% contractions"
|
|
754
|
+
% (voice["second_person_percent"], voice["contractions_percent"])
|
|
755
|
+
)
|
|
756
|
+
if result["error_message_voice"]["messages"]:
|
|
757
|
+
voice = result["error_message_voice"]
|
|
758
|
+
print(
|
|
759
|
+
" errors : %s%% capitalized / %s%% terminal punctuation (%d messages)"
|
|
760
|
+
% (
|
|
761
|
+
voice["capitalized_percent"],
|
|
762
|
+
voice["terminal_punctuation_percent"],
|
|
763
|
+
voice["messages"],
|
|
764
|
+
)
|
|
765
|
+
)
|
|
766
|
+
|
|
767
|
+
for kind, counts in result["naming"].items():
|
|
768
|
+
counter = Counter(counts)
|
|
769
|
+
total_names = sum(counter.values())
|
|
770
|
+
if not total_names:
|
|
771
|
+
continue
|
|
772
|
+
top = ", ".join(
|
|
773
|
+
"%s %d%%" % (name, round(100 * count / total_names))
|
|
774
|
+
for name, count in counter.most_common(3)
|
|
775
|
+
)
|
|
776
|
+
print(" %-9s: %s" % (kind, top))
|
|
777
|
+
for kind, length in result["identifier_lengths"].items():
|
|
778
|
+
if length["count"]:
|
|
779
|
+
print(" %-9s: median len %s / p90 %s" % (kind + " len", length["median"], length["p90"]))
|
|
780
|
+
if result["boolean_prefix_share"]["count"]:
|
|
781
|
+
print(" bool pref: %s%% of lowercase identifiers" % result["boolean_prefix_share"]["percent"])
|
|
782
|
+
if any("lower" in counts for counts in result["naming"].values()):
|
|
783
|
+
print(" note : lower means single-word names compatible with snake_case or camelCase")
|
|
784
|
+
if any("UPPER" in result["naming"].get(kind, {}) for kind in ("constant", "variable")):
|
|
785
|
+
print(" note : UPPER means a single-word all-caps constant, compatible with SCREAMING_SNAKE")
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def main(argv=None):
|
|
789
|
+
parser = argparse.ArgumentParser(description="Print best-effort code and prose style statistics.")
|
|
790
|
+
parser.add_argument("target", nargs="?", default=".")
|
|
791
|
+
parser.add_argument("--json", action="store_true", help="emit JSON instead of text")
|
|
792
|
+
args = parser.parse_args(argv)
|
|
793
|
+
|
|
794
|
+
results = analyze(args.target)
|
|
795
|
+
if args.json:
|
|
796
|
+
print(json.dumps(results, indent=2, sort_keys=True))
|
|
797
|
+
else:
|
|
798
|
+
print_text(results, args.target)
|
|
799
|
+
|
|
800
|
+
|
|
801
|
+
if __name__ == "__main__":
|
|
802
|
+
main()
|