@hxp-tools/godplans 0.0.0-stage → 2.0.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 +1176 -0
- package/LICENSE +21 -0
- package/PROMPT.md +4006 -0
- package/README.md +201 -2
- package/assets/README.md +11 -0
- package/assets/hero.svg +44 -0
- package/assets/plan-loop.svg +62 -0
- package/assets/quest-map.svg +80 -0
- package/bin/godplans.js +93 -0
- package/docs/ARCHITECTURE.md +136 -0
- package/docs/RELEASING.md +107 -0
- package/evals/README.md +295 -0
- package/evals/cases/brownfield-cli/EXPECTATIONS +15 -0
- package/evals/cases/brownfield-cli/INPUT/package.json +9 -0
- package/evals/cases/brownfield-cli/INPUT/src/cli.js +4 -0
- package/evals/cases/brownfield-cli/INPUT/src/format.js +3 -0
- package/evals/cases/brownfield-cli/INPUT/test/cli.test.js +7 -0
- package/evals/cases/brownfield-cli/REQUEST.baseline.md +10 -0
- package/evals/cases/brownfield-cli/REQUEST.md +10 -0
- package/evals/cases/compliance-refusal/EXPECTATIONS +4 -0
- package/evals/cases/compliance-refusal/REQUEST.baseline.md +9 -0
- package/evals/cases/compliance-refusal/REQUEST.md +8 -0
- package/evals/cases/greenfield-saas/EXPECTATIONS +21 -0
- package/evals/cases/greenfield-saas/REQUEST.baseline.md +11 -0
- package/evals/cases/greenfield-saas/REQUEST.md +11 -0
- package/evals/cases/nested-pillars/EXPECTATIONS +12 -0
- package/evals/cases/nested-pillars/REQUEST.baseline.md +10 -0
- package/evals/cases/nested-pillars/REQUEST.md +11 -0
- package/evals/cases/observability-evidence/EXPECTATIONS +10 -0
- package/evals/cases/observability-evidence/REQUEST.baseline.md +10 -0
- package/evals/cases/observability-evidence/REQUEST.md +11 -0
- package/evals/cases/product-business/EXPECTATIONS +18 -0
- package/evals/cases/product-business/REQUEST.baseline.md +13 -0
- package/evals/cases/product-business/REQUEST.md +14 -0
- package/evals/cases/product-form-routing/EXPECTATIONS +13 -0
- package/evals/cases/product-form-routing/REQUEST.baseline.md +11 -0
- package/evals/cases/product-form-routing/REQUEST.md +11 -0
- package/evals/cases/prose-integrity/EXPECTATIONS +19 -0
- package/evals/cases/prose-integrity/REQUEST.baseline.md +19 -0
- package/evals/cases/prose-integrity/REQUEST.md +20 -0
- package/evals/cases/replan-preserves-history/EXPECTATIONS +9 -0
- package/evals/cases/replan-preserves-history/INPUT/.godplans/PLAN.mdx +115 -0
- package/evals/cases/replan-preserves-history/INPUT/package.json +5 -0
- package/evals/cases/replan-preserves-history/REQUEST.baseline.md +10 -0
- package/evals/cases/replan-preserves-history/REQUEST.md +10 -0
- package/evals/cases/stale-prepublication/EXPECTATIONS +10 -0
- package/evals/cases/stale-prepublication/REQUEST.baseline.md +12 -0
- package/evals/cases/stale-prepublication/REQUEST.md +13 -0
- package/evals/cases/stale-source-evidence/EXPECTATIONS +10 -0
- package/evals/cases/stale-source-evidence/INPUT/package.json +8 -0
- package/evals/cases/stale-source-evidence/REQUEST.baseline.md +11 -0
- package/evals/cases/stale-source-evidence/REQUEST.md +12 -0
- package/evals/cases/weekend-library/EXPECTATIONS +19 -0
- package/evals/cases/weekend-library/REQUEST.baseline.md +10 -0
- package/evals/cases/weekend-library/REQUEST.md +11 -0
- package/evals/cases-roster.txt +19 -0
- package/evals/external/GRADE.schema.json +39 -0
- package/evals/external/README.md +42 -0
- package/evals/external/RUBRIC.md +32 -0
- package/evals/metrics/context-cost.json +154 -0
- package/evals/outcomes/README.md +65 -0
- package/evals/outcomes/cases/tenant-notes-api/REQUEST.baseline.md +14 -0
- package/evals/outcomes/cases/tenant-notes-api/REQUEST.md +13 -0
- package/evals/outcomes/cases/tenant-notes-api/VERIFY.sh +13 -0
- package/evals/outcomes/results/2026-07-23-tenant-notes-api-codex/README.md +93 -0
- package/evals/outcomes/results/2026-07-23-tenant-notes-api-codex/treatment/plan/PLAN.json +547 -0
- package/evals/runners/claude-baseline.sh +4 -0
- package/evals/runners/claude-grade.sh +3 -0
- package/evals/runners/claude.sh +4 -0
- package/evals/runners/codex-baseline.sh +181 -0
- package/evals/runners/codex-builder.sh +96 -0
- package/evals/runners/codex-godaudits.sh +84 -0
- package/evals/runners/codex.sh +147 -0
- package/evals/runners/gemini-baseline.sh +4 -0
- package/evals/runners/gemini-grade.sh +3 -0
- package/evals/runners/gemini.sh +4 -0
- package/evals/runners/vendor-cli.sh +257 -0
- package/evals/runners/vendor-grade.sh +82 -0
- package/install.sh +323 -0
- package/package.json +92 -4
- package/requirements/skills-ref.txt +2 -0
- package/scripts/build-catalog.js +114 -0
- package/scripts/build-prompt.sh +257 -0
- package/scripts/context-metrics.js +118 -0
- package/scripts/eval-external.js +226 -0
- package/scripts/eval-matrix.sh +172 -0
- package/scripts/eval-outcome.js +143 -0
- package/scripts/eval.sh +321 -0
- package/scripts/lint-parity.js +331 -0
- package/scripts/lint.sh +743 -0
- package/scripts/outcome-summary.js +126 -0
- package/scripts/release-check.sh +108 -0
- package/scripts/release-prepare.js +41 -0
- package/scripts/summarize-eval.js +91 -0
- package/scripts/summarize-matrix.js +101 -0
- package/scripts/version-sync.js +65 -0
- package/skills/godplans/SKILL.md +192 -0
- package/skills/godplans/references/agent-memory.md +168 -0
- package/skills/godplans/references/architecture.md +189 -0
- package/skills/godplans/references/build.md +130 -0
- package/skills/godplans/references/business.md +252 -0
- package/skills/godplans/references/code-quality.md +165 -0
- package/skills/godplans/references/compliance.md +59 -0
- package/skills/godplans/references/database.md +157 -0
- package/skills/godplans/references/deploy.md +146 -0
- package/skills/godplans/references/discovery.md +297 -0
- package/skills/godplans/references/doc-set.md +243 -0
- package/skills/godplans/references/exemplar.md +228 -0
- package/skills/godplans/references/launch.md +162 -0
- package/skills/godplans/references/llm.md +132 -0
- package/skills/godplans/references/observe.md +178 -0
- package/skills/godplans/references/plan-format.md +340 -0
- package/skills/godplans/references/product.md +130 -0
- package/skills/godplans/references/repo.md +184 -0
- package/skills/godplans/references/roadmap.md +158 -0
- package/skills/godplans/references/security.md +156 -0
- package/skills/godplans/references/seo.md +133 -0
- package/skills/godplans/references/stack.md +133 -0
- package/skills/godplans/references/style-genome.md +198 -0
- package/skills/godplans/references/ui.md +153 -0
- package/skills/godplans/references/ux.md +150 -0
- package/skills/godplans/schemas/PLAN.schema.json +275 -0
- package/skills/godplans/schemas/PLAN.v1.schema.json +258 -0
- package/skills/godplans/scripts/plan-halflife.sh +76 -0
- package/skills/godplans/scripts/style-stats.py +630 -0
- package/skills/godplans/scripts/validate-plan.sh +1709 -0
- package/skills/godplans/templates/PLAN.template.mdx +269 -0
- package/tests/agent-memory-guidance.sh +32 -0
- package/tests/build-catalog.sh +81 -0
- package/tests/codex-runner.sh +139 -0
- package/tests/eval-harness.sh +377 -0
- package/tests/evidence-harnesses.sh +243 -0
- package/tests/fixtures/plan-json-v1-1.13.0.json +472 -0
- package/tests/install-regression.sh +246 -0
- package/tests/lib/plan-schema-check.js +163 -0
- package/tests/lint-selftest.sh +582 -0
- package/tests/package-contents.sh +140 -0
- package/tests/portable-prompt.test.sh +261 -0
- package/tests/release-tooling.sh +204 -0
- package/tests/run.sh +14 -0
- package/tests/script-usage.sh +37 -0
- package/tests/style-stats.sh +170 -0
- package/tests/validate-plan.sh +1970 -0
- package/tests/vendor-runner.sh +291 -0
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Best-effort style statistics for the godplans style-genome pass.
|
|
3
|
+
|
|
4
|
+
Vendored by copy from hannsxpeter/codedna v1.0.4 (commit 645ea5a,
|
|
5
|
+
skill/scripts/codedna_stats.py, MIT). godplans depends on nothing from codedna
|
|
6
|
+
at runtime and codedna depends on nothing from godplans; fixes travel between
|
|
7
|
+
the two repositories as edits to this file, never as a reference. When either
|
|
8
|
+
copy changes, diff the two and port fixes in both directions. Stdlib only, so
|
|
9
|
+
it runs wherever the plan does.
|
|
10
|
+
|
|
11
|
+
Local fixes since that base: bodyless declarations and .d.ts files are not
|
|
12
|
+
measured, an identifier counts under one kind only, and a Python comparison
|
|
13
|
+
is not an assignment (godplans 1.14.0); wrapped Python signatures, docstrings
|
|
14
|
+
after them, and arrow functions whose parameters wrap are measured, and
|
|
15
|
+
languages with equal file counts sort by name. Taken from codedna v1.1.1:
|
|
16
|
+
sorted paths, sampled evenly above the per-language cap. Not taken: its git
|
|
17
|
+
file listing, extra extensions, comment-aware quote counts, and prose voice.
|
|
18
|
+
|
|
19
|
+
R-DNA-5 asks for a numeric function-size norm and R-DNA-20 asks for measured
|
|
20
|
+
frequencies rather than an eyeballed sample. This produces those numbers.
|
|
21
|
+
Numbers are evidence to interpret: when they disagree with the code, the code
|
|
22
|
+
wins, and a percentage is never pasted into a plan as a rule on its own.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
import argparse
|
|
26
|
+
import json
|
|
27
|
+
import os
|
|
28
|
+
import re
|
|
29
|
+
from collections import Counter, defaultdict
|
|
30
|
+
from statistics import median
|
|
31
|
+
|
|
32
|
+
MAX_FILES_PER_LANG = 800
|
|
33
|
+
MAX_FILE_BYTES = 1_000_000
|
|
34
|
+
MAX_BYTES_PER_LINE = 400
|
|
35
|
+
|
|
36
|
+
IGNORE = {
|
|
37
|
+
".git",
|
|
38
|
+
"node_modules",
|
|
39
|
+
"dist",
|
|
40
|
+
"build",
|
|
41
|
+
"out",
|
|
42
|
+
"target",
|
|
43
|
+
"vendor",
|
|
44
|
+
".next",
|
|
45
|
+
".svelte-kit",
|
|
46
|
+
"venv",
|
|
47
|
+
".venv",
|
|
48
|
+
"__pycache__",
|
|
49
|
+
"coverage",
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
EXT = {
|
|
53
|
+
".js": "js",
|
|
54
|
+
".jsx": "js",
|
|
55
|
+
".mjs": "js",
|
|
56
|
+
".cjs": "js",
|
|
57
|
+
".ts": "ts",
|
|
58
|
+
".tsx": "ts",
|
|
59
|
+
".py": "py",
|
|
60
|
+
".go": "go",
|
|
61
|
+
".rs": "rs",
|
|
62
|
+
".java": "java",
|
|
63
|
+
".rb": "rb",
|
|
64
|
+
".php": "php",
|
|
65
|
+
".c": "c",
|
|
66
|
+
".cpp": "cpp",
|
|
67
|
+
".cs": "cs",
|
|
68
|
+
".swift": "swift",
|
|
69
|
+
".kt": "kt",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
HASH_COMMENT = {"py", "rb"}
|
|
73
|
+
QUOTE_LANGS = {"js", "ts", "py", "rb", "php"}
|
|
74
|
+
BOOLEAN_PREFIX_RE = re.compile(r"^(?:is|has|should|can|will|did)(?:[A-Z_]|$)")
|
|
75
|
+
TODO_RE = re.compile(r"\b(?:TODO|FIXME)\b")
|
|
76
|
+
STRING_RE = re.compile(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'')
|
|
77
|
+
# An arrow function whose parameter list wraps: `const handler = async (` alone.
|
|
78
|
+
WRAPPED_ARROW_RE = re.compile(r"\b(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*(?:async\s*)?(\()[^)]*$")
|
|
79
|
+
|
|
80
|
+
DOC_MARKERS = {
|
|
81
|
+
"default": ("/**", "///"),
|
|
82
|
+
"go": ("//",),
|
|
83
|
+
"rs": ("///", "//!", "/**"),
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
PATS = {
|
|
87
|
+
"js": {
|
|
88
|
+
"function": [
|
|
89
|
+
r"\bfunction\s+([A-Za-z_$][\w$]*)\s*\(",
|
|
90
|
+
r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?function\b",
|
|
91
|
+
r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>",
|
|
92
|
+
],
|
|
93
|
+
"variable": [r"\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\b"],
|
|
94
|
+
"type": [r"\b(?:interface|type)\s+([A-Za-z_$][\w$]*)"],
|
|
95
|
+
"class": [r"\bclass\s+([A-Za-z_$][\w$]*)"],
|
|
96
|
+
"constant": [r"\bconst\s+([A-Z_][A-Z0-9_]{2,})\b"],
|
|
97
|
+
},
|
|
98
|
+
"py": {
|
|
99
|
+
"function": [r"^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)"],
|
|
100
|
+
"variable": [r"^\s*([A-Za-z_]\w*)\s*=(?!=)"],
|
|
101
|
+
"class": [r"^\s*class\s+([A-Za-z_]\w*)"],
|
|
102
|
+
"constant": [r"^([A-Z_][A-Z0-9_]{2,})\s*=(?!=)"],
|
|
103
|
+
},
|
|
104
|
+
"go": {
|
|
105
|
+
"function": [r"\bfunc\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)"],
|
|
106
|
+
"type": [r"\btype\s+([A-Za-z_]\w*)"],
|
|
107
|
+
},
|
|
108
|
+
"rs": {
|
|
109
|
+
"function": [r"\bfn\s+([A-Za-z_]\w*)"],
|
|
110
|
+
"type": [r"\b(?:struct|enum|trait)\s+([A-Za-z_]\w*)"],
|
|
111
|
+
},
|
|
112
|
+
}
|
|
113
|
+
PATS["ts"] = PATS["js"]
|
|
114
|
+
|
|
115
|
+
# One identifier can match several kinds (`const isReady = () =>` is both a
|
|
116
|
+
# function and a variable). The first kind in this order claims it.
|
|
117
|
+
KIND_ORDER = ("function", "class", "type", "constant", "variable")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def case(name):
|
|
121
|
+
text = name.strip("_")
|
|
122
|
+
if not text:
|
|
123
|
+
return "other"
|
|
124
|
+
if "-" in text:
|
|
125
|
+
return "kebab"
|
|
126
|
+
if "_" in text:
|
|
127
|
+
if text.isupper():
|
|
128
|
+
return "SCREAMING_SNAKE"
|
|
129
|
+
if text.islower():
|
|
130
|
+
return "snake_case"
|
|
131
|
+
return "mixed"
|
|
132
|
+
if text.isupper():
|
|
133
|
+
return "UPPER"
|
|
134
|
+
if text.islower():
|
|
135
|
+
return "lower"
|
|
136
|
+
return "PascalCase" if text[0].isupper() else "camelCase"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def collect_files(target):
|
|
140
|
+
files = defaultdict(list)
|
|
141
|
+
for root, dirs, names in os.walk(target):
|
|
142
|
+
dirs[:] = [d for d in dirs if d not in IGNORE and not d.startswith(".")]
|
|
143
|
+
for name in names:
|
|
144
|
+
lang = EXT.get(os.path.splitext(name)[1].lower())
|
|
145
|
+
if lang:
|
|
146
|
+
files[lang].append(os.path.join(root, name))
|
|
147
|
+
return {lang: sorted(paths) for lang, paths in files.items()}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def sample_paths(paths):
|
|
151
|
+
if len(paths) <= MAX_FILES_PER_LANG:
|
|
152
|
+
return paths
|
|
153
|
+
step = len(paths) / MAX_FILES_PER_LANG
|
|
154
|
+
return [paths[int(index * step)] for index in range(MAX_FILES_PER_LANG)]
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def read_text(path):
|
|
158
|
+
with open(path, encoding="utf-8-sig", errors="replace") as handle:
|
|
159
|
+
return handle.read()
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def comment_config(lang):
|
|
163
|
+
token = "#" if lang in HASH_COMMENT else "//"
|
|
164
|
+
if lang == "py":
|
|
165
|
+
block = [('"""', '"""'), ("'''", "'''")]
|
|
166
|
+
elif lang in HASH_COMMENT:
|
|
167
|
+
block = []
|
|
168
|
+
else:
|
|
169
|
+
block = [("/*", "*/")]
|
|
170
|
+
return token, block
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def open_block(stripped, block, token):
|
|
174
|
+
if not any(opener == closer for opener, closer in block):
|
|
175
|
+
return None
|
|
176
|
+
index = 0
|
|
177
|
+
limit = len(stripped)
|
|
178
|
+
while index < limit:
|
|
179
|
+
rest = stripped[index:]
|
|
180
|
+
if rest.startswith(token):
|
|
181
|
+
return None
|
|
182
|
+
for opener, closer in block:
|
|
183
|
+
if opener == closer and rest.startswith(opener):
|
|
184
|
+
end = stripped.find(closer, index + len(opener))
|
|
185
|
+
if end < 0:
|
|
186
|
+
return closer
|
|
187
|
+
index = end + len(closer)
|
|
188
|
+
break
|
|
189
|
+
else:
|
|
190
|
+
char = stripped[index]
|
|
191
|
+
if char in "'\"`":
|
|
192
|
+
end = stripped.find(char, index + 1)
|
|
193
|
+
index = limit if end < 0 else end + 1
|
|
194
|
+
else:
|
|
195
|
+
index += 1
|
|
196
|
+
return None
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def count_lines(lang, text):
|
|
200
|
+
token, block = comment_config(lang)
|
|
201
|
+
code = comment = tabs = spaces = 0
|
|
202
|
+
pending = None
|
|
203
|
+
for line in text.splitlines():
|
|
204
|
+
stripped = line.strip()
|
|
205
|
+
if pending is not None:
|
|
206
|
+
closer, is_comment = pending
|
|
207
|
+
if stripped:
|
|
208
|
+
if is_comment:
|
|
209
|
+
comment += 1
|
|
210
|
+
else:
|
|
211
|
+
code += 1
|
|
212
|
+
if closer in line:
|
|
213
|
+
pending = None
|
|
214
|
+
continue
|
|
215
|
+
if not stripped:
|
|
216
|
+
continue
|
|
217
|
+
if stripped.startswith(token):
|
|
218
|
+
comment += 1
|
|
219
|
+
continue
|
|
220
|
+
hit = False
|
|
221
|
+
for opener, closer in block:
|
|
222
|
+
if stripped.startswith(opener):
|
|
223
|
+
comment += 1
|
|
224
|
+
if closer not in stripped[len(opener):]:
|
|
225
|
+
pending = (closer, True)
|
|
226
|
+
hit = True
|
|
227
|
+
break
|
|
228
|
+
if hit:
|
|
229
|
+
continue
|
|
230
|
+
code += 1
|
|
231
|
+
leading = line[: len(line) - len(line.lstrip())]
|
|
232
|
+
if leading.startswith("\t"):
|
|
233
|
+
tabs += 1
|
|
234
|
+
elif leading.startswith(" "):
|
|
235
|
+
spaces += 1
|
|
236
|
+
closer = open_block(stripped, block, token)
|
|
237
|
+
if closer:
|
|
238
|
+
pending = (closer, False)
|
|
239
|
+
return code, comment, tabs, spaces
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def count_quotes(lang, text):
|
|
243
|
+
if lang not in QUOTE_LANGS:
|
|
244
|
+
return Counter()
|
|
245
|
+
counts = Counter()
|
|
246
|
+
counts["double"] = len(re.findall(r'"(?:[^"\\]|\\.)*"', text))
|
|
247
|
+
counts["single"] = len(re.findall(r"'(?:[^'\\]|\\.)*'", text))
|
|
248
|
+
if lang in {"js", "ts"}:
|
|
249
|
+
counts["backtick"] = len(re.findall(r"`(?:[^`\\]|\\.)*`", text, re.S))
|
|
250
|
+
return counts
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def percentile(values, pct):
|
|
254
|
+
if not values:
|
|
255
|
+
return 0
|
|
256
|
+
ordered = sorted(values)
|
|
257
|
+
index = round((pct / 100) * (len(ordered) - 1))
|
|
258
|
+
return ordered[index]
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def summarize(values):
|
|
262
|
+
if not values:
|
|
263
|
+
return {"count": 0, "median": 0, "p90": 0}
|
|
264
|
+
return {
|
|
265
|
+
"count": len(values),
|
|
266
|
+
"median": median(values),
|
|
267
|
+
"p90": percentile(values, 90),
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def add_file_case(naming, path):
|
|
272
|
+
base = os.path.splitext(os.path.basename(path))[0]
|
|
273
|
+
if base:
|
|
274
|
+
naming["file"][case(base)] += 1
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def add_identifier_cases(lang, text, naming, lengths, boolean_names):
|
|
278
|
+
seen = set()
|
|
279
|
+
pats = PATS.get(lang, {})
|
|
280
|
+
for kind in KIND_ORDER:
|
|
281
|
+
for pattern in pats.get(kind, []):
|
|
282
|
+
for match in re.finditer(pattern, text, re.M):
|
|
283
|
+
name = match.group(1)
|
|
284
|
+
if (match.start(1), name) in seen:
|
|
285
|
+
continue
|
|
286
|
+
seen.add((match.start(1), name))
|
|
287
|
+
naming[kind][case(name)] += 1
|
|
288
|
+
lengths[kind].append(len(name.strip("_")))
|
|
289
|
+
if name and name[0].islower():
|
|
290
|
+
boolean_names.add(name)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def leading_indent(line):
|
|
294
|
+
return len(line) - len(line.lstrip())
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def signature_end(lines, index):
|
|
298
|
+
# A wrapped signature ends where its brackets close, which in black style
|
|
299
|
+
# is a `):` line at the def's own indent; that line is not the body's end.
|
|
300
|
+
depth = 0
|
|
301
|
+
for cursor in range(index, len(lines)):
|
|
302
|
+
code = STRING_RE.sub("", lines[cursor]).split("#", 1)[0]
|
|
303
|
+
depth += sum(code.count(char) for char in "([{") - sum(code.count(char) for char in ")]}")
|
|
304
|
+
if depth <= 0:
|
|
305
|
+
return cursor
|
|
306
|
+
return index
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def py_function_lengths(text):
|
|
310
|
+
lengths = []
|
|
311
|
+
lines = text.splitlines()
|
|
312
|
+
for index, line in enumerate(lines):
|
|
313
|
+
if not re.match(r"^\s*(?:async\s+)?def\s+[A-Za-z_]\w*", line):
|
|
314
|
+
continue
|
|
315
|
+
indent = leading_indent(line)
|
|
316
|
+
body = signature_end(lines, index)
|
|
317
|
+
end = body + 1
|
|
318
|
+
for cursor in range(body + 1, len(lines)):
|
|
319
|
+
stripped = lines[cursor].strip()
|
|
320
|
+
if not stripped:
|
|
321
|
+
continue
|
|
322
|
+
if leading_indent(lines[cursor]) <= indent and not stripped.startswith("#"):
|
|
323
|
+
break
|
|
324
|
+
end = cursor + 1
|
|
325
|
+
lengths.append(max(1, end - index))
|
|
326
|
+
return lengths
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def wrapped_arrow(lines, index):
|
|
330
|
+
# (closing line, text after the closing paren) when lines[index] opens an
|
|
331
|
+
# arrow function whose parameters wrap; None for a wrapped parenthesized
|
|
332
|
+
# expression such as `const view = (` ... `);`.
|
|
333
|
+
match = WRAPPED_ARROW_RE.search(lines[index])
|
|
334
|
+
if not match:
|
|
335
|
+
return None
|
|
336
|
+
depth = 0
|
|
337
|
+
for cursor in range(index, len(lines)):
|
|
338
|
+
text = lines[cursor][match.start(1):] if cursor == index else lines[cursor]
|
|
339
|
+
for position, char in enumerate(text):
|
|
340
|
+
if char == "(":
|
|
341
|
+
depth += 1
|
|
342
|
+
elif char == ")":
|
|
343
|
+
depth -= 1
|
|
344
|
+
if not depth:
|
|
345
|
+
rest = text[position + 1:].strip()
|
|
346
|
+
if rest.startswith("=>") or (rest.startswith(":") and "=>" in rest):
|
|
347
|
+
return cursor, rest
|
|
348
|
+
return None
|
|
349
|
+
return None
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def brace_function_lengths(text):
|
|
353
|
+
starts = re.compile(
|
|
354
|
+
r"\bfunction\s+[A-Za-z_$][\w$]*\s*\(|"
|
|
355
|
+
r"\b(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)|"
|
|
356
|
+
r"\bfunc\s+(?:\([^)]*\)\s*)?[A-Za-z_]\w*|"
|
|
357
|
+
r"\bfn\s+[A-Za-z_]\w*"
|
|
358
|
+
)
|
|
359
|
+
lengths = []
|
|
360
|
+
lines = text.splitlines()
|
|
361
|
+
for index, line in enumerate(lines):
|
|
362
|
+
first = index
|
|
363
|
+
if not starts.search(line):
|
|
364
|
+
arrow = wrapped_arrow(lines, index)
|
|
365
|
+
if not arrow:
|
|
366
|
+
continue
|
|
367
|
+
first, rest = arrow
|
|
368
|
+
# A concise body is measured to the arrow, as on a one-line arrow.
|
|
369
|
+
if "{" not in rest:
|
|
370
|
+
lengths.append(first - index + 1)
|
|
371
|
+
continue
|
|
372
|
+
elif "=>" in line and "{" not in line:
|
|
373
|
+
lengths.append(1)
|
|
374
|
+
continue
|
|
375
|
+
balance = 0
|
|
376
|
+
saw_brace = False
|
|
377
|
+
end = index
|
|
378
|
+
for cursor in range(first, len(lines)):
|
|
379
|
+
# A signature that ends in `;` before any brace is a bodyless
|
|
380
|
+
# declaration (TS overload, `declare`, Rust trait item); measuring
|
|
381
|
+
# it would run into whatever block follows.
|
|
382
|
+
if not saw_brace and "{" not in lines[cursor] and lines[cursor].rstrip().endswith(";"):
|
|
383
|
+
end = None
|
|
384
|
+
break
|
|
385
|
+
balance += lines[cursor].count("{")
|
|
386
|
+
balance -= lines[cursor].count("}")
|
|
387
|
+
saw_brace = saw_brace or "{" in lines[cursor]
|
|
388
|
+
end = cursor
|
|
389
|
+
if saw_brace and balance <= 0:
|
|
390
|
+
break
|
|
391
|
+
if end is not None:
|
|
392
|
+
lengths.append(max(1, end - index + 1))
|
|
393
|
+
return lengths
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def function_lengths(lang, text):
|
|
397
|
+
if lang == "py":
|
|
398
|
+
return py_function_lengths(text)
|
|
399
|
+
if lang in {"js", "ts", "go", "rs"}:
|
|
400
|
+
return brace_function_lengths(text)
|
|
401
|
+
return []
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def closes_doc_block(lines, cursor):
|
|
405
|
+
if not lines[cursor].strip().endswith("*/"):
|
|
406
|
+
return False
|
|
407
|
+
opener = cursor
|
|
408
|
+
while opener >= 0 and "/*" not in lines[opener]:
|
|
409
|
+
opener -= 1
|
|
410
|
+
return opener >= 0 and lines[opener].strip().startswith("/**")
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def doc_coverage(lang, text):
|
|
414
|
+
lines = text.splitlines()
|
|
415
|
+
total = 0
|
|
416
|
+
documented = 0
|
|
417
|
+
for index, line in enumerate(lines):
|
|
418
|
+
if lang == "py":
|
|
419
|
+
match = re.match(r"^\s*(?:async\s+)?def\s+[A-Za-z_]\w*", line)
|
|
420
|
+
else:
|
|
421
|
+
match = re.search(
|
|
422
|
+
r"\bfunction\s+[A-Za-z_$][\w$]*\s*\(|"
|
|
423
|
+
r"\b(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*(?:async\s*)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)|"
|
|
424
|
+
r"\bfunc\s+(?:\([^)]*\)\s*)?[A-Za-z_]\w*|"
|
|
425
|
+
r"\bfn\s+[A-Za-z_]\w*",
|
|
426
|
+
line,
|
|
427
|
+
) or wrapped_arrow(lines, index)
|
|
428
|
+
if not match:
|
|
429
|
+
continue
|
|
430
|
+
total += 1
|
|
431
|
+
if lang == "py":
|
|
432
|
+
for cursor in range(signature_end(lines, index) + 1, len(lines)):
|
|
433
|
+
stripped = lines[cursor].strip()
|
|
434
|
+
if not stripped:
|
|
435
|
+
continue
|
|
436
|
+
if stripped.startswith(('"""', "'''")):
|
|
437
|
+
documented += 1
|
|
438
|
+
break
|
|
439
|
+
else:
|
|
440
|
+
cursor = index - 1
|
|
441
|
+
while cursor >= 0 and not lines[cursor].strip():
|
|
442
|
+
cursor -= 1
|
|
443
|
+
if cursor < 0:
|
|
444
|
+
continue
|
|
445
|
+
markers = DOC_MARKERS.get(lang, DOC_MARKERS["default"])
|
|
446
|
+
if lines[cursor].strip().startswith(markers) or closes_doc_block(lines, cursor):
|
|
447
|
+
documented += 1
|
|
448
|
+
return documented, total
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def analyze_language(lang, paths):
|
|
452
|
+
result = {
|
|
453
|
+
"language": lang,
|
|
454
|
+
"files_total": len(paths),
|
|
455
|
+
"files_read": 0,
|
|
456
|
+
"files_skipped_large": 0,
|
|
457
|
+
"files_skipped_minified": 0,
|
|
458
|
+
"read_errors": 0,
|
|
459
|
+
"code_lines": 0,
|
|
460
|
+
"comment_lines": 0,
|
|
461
|
+
"indent": {"tabs": 0, "spaces": 0, "style": "spaces"},
|
|
462
|
+
"quotes": {},
|
|
463
|
+
"naming": {},
|
|
464
|
+
"identifier_lengths": {},
|
|
465
|
+
"function_lengths": {"count": 0, "median": 0, "p90": 0},
|
|
466
|
+
"boolean_prefix_share": {"count": 0, "prefixed": 0, "percent": 0},
|
|
467
|
+
"todo_markers": 0,
|
|
468
|
+
"doc_comment_coverage": {"functions": 0, "documented": 0, "percent": 0},
|
|
469
|
+
}
|
|
470
|
+
naming = defaultdict(Counter)
|
|
471
|
+
lengths = defaultdict(list)
|
|
472
|
+
quotes = Counter()
|
|
473
|
+
fn_lengths = []
|
|
474
|
+
boolean_names = set()
|
|
475
|
+
documented_functions = 0
|
|
476
|
+
total_functions = 0
|
|
477
|
+
|
|
478
|
+
for path in sample_paths(paths):
|
|
479
|
+
try:
|
|
480
|
+
if os.path.getsize(path) > MAX_FILE_BYTES:
|
|
481
|
+
result["files_skipped_large"] += 1
|
|
482
|
+
continue
|
|
483
|
+
text = read_text(path)
|
|
484
|
+
except OSError:
|
|
485
|
+
result["read_errors"] += 1
|
|
486
|
+
continue
|
|
487
|
+
|
|
488
|
+
lines = text.splitlines()
|
|
489
|
+
if lines and len(text) / len(lines) > MAX_BYTES_PER_LINE:
|
|
490
|
+
result["files_skipped_minified"] += 1
|
|
491
|
+
continue
|
|
492
|
+
|
|
493
|
+
result["files_read"] += 1
|
|
494
|
+
code, comment, tabs, spaces = count_lines(lang, text)
|
|
495
|
+
result["code_lines"] += code
|
|
496
|
+
result["comment_lines"] += comment
|
|
497
|
+
result["indent"]["tabs"] += tabs
|
|
498
|
+
result["indent"]["spaces"] += spaces
|
|
499
|
+
quotes.update(count_quotes(lang, text))
|
|
500
|
+
add_file_case(naming, path)
|
|
501
|
+
add_identifier_cases(lang, text, naming, lengths, boolean_names)
|
|
502
|
+
# Type declaration files hold signatures only; they have no function bodies to measure.
|
|
503
|
+
if not path.endswith(".d.ts"):
|
|
504
|
+
fn_lengths.extend(function_lengths(lang, text))
|
|
505
|
+
documented, total = doc_coverage(lang, text)
|
|
506
|
+
documented_functions += documented
|
|
507
|
+
total_functions += total
|
|
508
|
+
result["todo_markers"] += len(TODO_RE.findall(text))
|
|
509
|
+
|
|
510
|
+
result["files_capped"] = max(len(paths) - MAX_FILES_PER_LANG, 0)
|
|
511
|
+
total_lines = result["code_lines"] + result["comment_lines"]
|
|
512
|
+
result["comment_density"] = round(100 * result["comment_lines"] / total_lines, 1) if total_lines else 0
|
|
513
|
+
result["indent"]["style"] = "tabs" if result["indent"]["tabs"] > result["indent"]["spaces"] else "spaces"
|
|
514
|
+
result["quotes"] = dict(quotes)
|
|
515
|
+
result["naming"] = {kind: dict(counter) for kind, counter in naming.items()}
|
|
516
|
+
result["identifier_lengths"] = {kind: summarize(values) for kind, values in lengths.items()}
|
|
517
|
+
result["function_lengths"] = summarize(fn_lengths)
|
|
518
|
+
prefixed = sum(1 for name in boolean_names if BOOLEAN_PREFIX_RE.match(name))
|
|
519
|
+
result["boolean_prefix_share"] = {
|
|
520
|
+
"count": len(boolean_names),
|
|
521
|
+
"prefixed": prefixed,
|
|
522
|
+
"percent": round(100 * prefixed / len(boolean_names), 1) if boolean_names else 0,
|
|
523
|
+
}
|
|
524
|
+
result["doc_comment_coverage"] = {
|
|
525
|
+
"functions": total_functions,
|
|
526
|
+
"documented": documented_functions,
|
|
527
|
+
"percent": round(100 * documented_functions / total_functions, 1) if total_functions else 0,
|
|
528
|
+
}
|
|
529
|
+
return result
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def analyze(target):
|
|
533
|
+
files = collect_files(target)
|
|
534
|
+
return [
|
|
535
|
+
analyze_language(lang, paths)
|
|
536
|
+
for lang, paths in sorted(files.items(), key=lambda item: (-len(item[1]), item[0]))
|
|
537
|
+
]
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def pct(counter, key):
|
|
541
|
+
total = sum(counter.values())
|
|
542
|
+
return round(100 * counter[key] / total) if total else 0
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def print_text(results, target):
|
|
546
|
+
if not results:
|
|
547
|
+
print("No recognized source files under", target)
|
|
548
|
+
return
|
|
549
|
+
|
|
550
|
+
for result in results:
|
|
551
|
+
lang = result["language"]
|
|
552
|
+
total = result["files_total"]
|
|
553
|
+
read = result["files_read"]
|
|
554
|
+
if read == total:
|
|
555
|
+
sample = "%d files" % total
|
|
556
|
+
else:
|
|
557
|
+
sample = "read %d of %d files" % (read, total)
|
|
558
|
+
print("\n== %s (%s, %d code lines) ==" % (lang, sample, result["code_lines"]))
|
|
559
|
+
if result["files_capped"]:
|
|
560
|
+
print(" sampled : capped at %d files, spread evenly by path" % MAX_FILES_PER_LANG)
|
|
561
|
+
if result["files_skipped_large"]:
|
|
562
|
+
print(" skipped : %d oversized files" % result["files_skipped_large"])
|
|
563
|
+
if result["files_skipped_minified"]:
|
|
564
|
+
print(" skipped : %d minified or generated files" % result["files_skipped_minified"])
|
|
565
|
+
if result["read_errors"]:
|
|
566
|
+
print(" unread : %d files" % result["read_errors"])
|
|
567
|
+
print(" comments : %s%% of non-blank lines" % result["comment_density"])
|
|
568
|
+
print(
|
|
569
|
+
" indent : %s (tabs %d / spaces %d indented lines)"
|
|
570
|
+
% (
|
|
571
|
+
result["indent"]["style"],
|
|
572
|
+
result["indent"]["tabs"],
|
|
573
|
+
result["indent"]["spaces"],
|
|
574
|
+
)
|
|
575
|
+
)
|
|
576
|
+
|
|
577
|
+
quotes = Counter(result["quotes"])
|
|
578
|
+
if quotes:
|
|
579
|
+
parts = ["%s %d%%" % (name, pct(quotes, name)) for name in ["double", "single", "backtick"] if quotes.get(name)]
|
|
580
|
+
print(" quotes : " + " / ".join(parts))
|
|
581
|
+
if result["function_lengths"]["count"]:
|
|
582
|
+
print(
|
|
583
|
+
" fn size : median %s lines / p90 %s (%d functions)"
|
|
584
|
+
% (
|
|
585
|
+
result["function_lengths"]["median"],
|
|
586
|
+
result["function_lengths"]["p90"],
|
|
587
|
+
result["function_lengths"]["count"],
|
|
588
|
+
)
|
|
589
|
+
)
|
|
590
|
+
if result["doc_comment_coverage"]["functions"]:
|
|
591
|
+
print(" doc cov : %s%% of functions" % result["doc_comment_coverage"]["percent"])
|
|
592
|
+
if result["todo_markers"]:
|
|
593
|
+
print(" markers : TODO/FIXME %d" % result["todo_markers"])
|
|
594
|
+
|
|
595
|
+
for kind, counts in result["naming"].items():
|
|
596
|
+
counter = Counter(counts)
|
|
597
|
+
total_names = sum(counter.values())
|
|
598
|
+
if not total_names:
|
|
599
|
+
continue
|
|
600
|
+
top = ", ".join(
|
|
601
|
+
"%s %d%%" % (name, round(100 * count / total_names))
|
|
602
|
+
for name, count in counter.most_common(3)
|
|
603
|
+
)
|
|
604
|
+
print(" %-9s: %s" % (kind, top))
|
|
605
|
+
for kind, length in result["identifier_lengths"].items():
|
|
606
|
+
if length["count"]:
|
|
607
|
+
print(" %-9s: median len %s / p90 %s" % (kind + " len", length["median"], length["p90"]))
|
|
608
|
+
if result["boolean_prefix_share"]["count"]:
|
|
609
|
+
print(" bool pref: %s%% of lowercase identifiers" % result["boolean_prefix_share"]["percent"])
|
|
610
|
+
if any("lower" in counts for counts in result["naming"].values()):
|
|
611
|
+
print(" note : lower means single-word names compatible with snake_case or camelCase")
|
|
612
|
+
if any("UPPER" in result["naming"].get(kind, {}) for kind in ("constant", "variable")):
|
|
613
|
+
print(" note : UPPER means a single-word all-caps constant, compatible with SCREAMING_SNAKE")
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def main(argv=None):
|
|
617
|
+
parser = argparse.ArgumentParser(description="Print best-effort code style statistics.")
|
|
618
|
+
parser.add_argument("target", nargs="?", default=".")
|
|
619
|
+
parser.add_argument("--json", action="store_true", help="emit JSON instead of text")
|
|
620
|
+
args = parser.parse_args(argv)
|
|
621
|
+
|
|
622
|
+
results = analyze(args.target)
|
|
623
|
+
if args.json:
|
|
624
|
+
print(json.dumps(results, indent=2, sort_keys=True))
|
|
625
|
+
else:
|
|
626
|
+
print_text(results, args.target)
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
if __name__ == "__main__":
|
|
630
|
+
main()
|