Repository navigation
Expand file tree
/
Copy pathvalidate.py
More file actions
executable file
·358 lines (299 loc) · 13.5 KB
/
Copy pathvalidate.py
File metadata and controls
executable file
·358 lines (299 loc) · 13.5 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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = ["pyyaml>=6"]
# ///
"""Validate the smell corpus and regenerate the catalog.
uv run validate.py # check everything, exit 1 on any error
uv run validate.py --write-catalog # regenerate catalog.json from snippets/
Every check hard-blocks: for a data repository a soft warning is a warning nobody reads
and a schema that quietly fragments. See docs/002-snippet-design.md.
"""
from __future__ import annotations
import ast
import datetime as dt
import json
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
import yaml
ROOT = Path(__file__).parent
SNIPPETS = ROOT / "snippets"
TAXONOMY = ROOT / "TAXONOMY.md"
CATALOG = ROOT / "catalog.json"
SCHEMA_VERSION = 1
# The ceiling on a `## Smell` block, per group directory. See docs/002-snippet-design.md.
SNIPPET_LINES = {"code": 15, "architecture": 40}
SEVERITIES = ("bug", "trap", "taste")
SLUG_RE = re.compile(r"^[a-z0-9-]+$")
# Each language's version range lives in a field named after it: `python: ">=3.9"`, `rust: ">=1.70"`.
LANGUAGES = ("python", "rust", "typescript")
REQUIRED = (
"language",
"severity",
"category",
"topic",
"tags",
"keywords",
"signature",
"distinguish",
"added",
)
OPTIONAL = ("aliases", "source")
CATALOG_FIELDS = ("signature", "severity", "category", "topic", "tags", "keywords", "language")
SECTIONS = ("Smell", "Why it's bad", "Better")
FRONTMATTER_RE = re.compile(r"\A---\n(.*?)\n---\n(.*)\Z", re.DOTALL)
FENCE_RE = re.compile(r"```(\w*)\n(.*?)```", re.DOTALL)
class Errors:
def __init__(self) -> None:
self.items: list[str] = []
def add(self, where: str, field: str | None, message: str) -> None:
location = f"{where}:{field}" if field else where
self.items.append(f"{location}: {message}")
def report(self) -> int:
for item in self.items:
print(f"FAIL {item}", file=sys.stderr)
return 1 if self.items else 0
def load_taxonomy() -> dict[str, set[str]]:
"""Values are the backticked identifiers listed under each H2 of TAXONOMY.md."""
lists: dict[str, set[str]] = {}
heading = None
for line in TAXONOMY.read_text(encoding="utf-8").splitlines():
if line.startswith("## "):
heading = line[3:].strip().lower()
lists.setdefault(heading, set())
elif heading and (match := re.match(r"^- `([^`]+)`", line)):
lists[heading].add(match.group(1))
return lists
def split_sections(body: str) -> dict[str, str]:
sections: dict[str, str] = {}
current = None
for line in body.splitlines(keepends=True):
if line.startswith("## "):
current = line[3:].strip()
sections[current] = ""
elif current is not None:
sections[current] += line
return sections
def section_order(body: str) -> list[str]:
return [line[3:].strip() for line in body.splitlines() if line.startswith("## ")]
RUSTC = shutil.which("rustc")
# Snippets lean on tokio, serde, log and friends and, like Python ones, only have to parse.
# Everything rustc says after parsing — unresolved crates, macros, attributes, files named by
# #[path] or include!, type errors — is about what the snippet leaves out, not whether it is Rust.
NOT_A_PARSE_ERROR = re.compile(r"^error(\[E\d+\]: |: cannot find |: couldn't read |: aborting )")
def rust_parse_error(code: str) -> str | None:
"""None when the code parses as items, or as statements inside a function body."""
if RUSTC is None:
return "rustc not found; install Rust (https://rustup.rs) to validate Rust snippets"
found = []
for source in (code, f"fn _snippet() {{\n{code}\n}}"):
with tempfile.TemporaryDirectory() as out_dir:
result = subprocess.run(
[RUSTC, "--edition=2021", "--crate-type=lib", "--emit=metadata", "--out-dir", out_dir, "-"],
input=source,
capture_output=True,
text=True,
)
errors = [
line
for line in result.stderr.splitlines()
if line.startswith("error") and not NOT_A_PARSE_ERROR.match(line)
]
if not errors:
return None
found.append(errors[0])
# Statements fail at crate level with "expected item", so report the body's error instead.
return found[1] if "expected item" in found[0] else found[0]
TSC = shutil.which("tsc")
# Only the parser's own diagnostics count, the counterpart of ast.parse: unresolved imports and
# type errors are about what the snippet leaves out. A block that fails as .ts is retried as .tsx,
# so React snippets pass without a fence tag of their own.
TS_PARSE = """
const ts = require(process.argv[1]);
const code = require("fs").readFileSync(0, "utf8");
let first;
for (const kind of [ts.ScriptKind.TS, ts.ScriptKind.TSX]) {
const file = ts.createSourceFile("snippet", code, ts.ScriptTarget.Latest, false, kind);
const [diag] = file.parseDiagnostics;
if (!diag) process.exit(0);
if (!first) {
const { line } = file.getLineAndCharacterOfPosition(diag.start);
first = `${ts.flattenDiagnosticMessageText(diag.messageText, " ")} (line ${line + 1})`;
}
}
console.log(first);
process.exit(1);
"""
def typescript_parse_error(code: str) -> str | None:
"""None when the code parses as TypeScript, or as TSX."""
node = shutil.which("node")
if TSC is None or node is None:
return "tsc not found; install TypeScript (npm install -g typescript) to validate TypeScript snippets"
# tsc is <package>/bin/tsc, usually behind a symlink; the compiler API is <package>/lib/typescript.js.
compiler = Path(TSC).resolve().parent.parent / "lib" / "typescript.js"
result = subprocess.run([node, "-e", TS_PARSE, str(compiler)], input=code, capture_output=True, text=True)
if result.returncode == 0:
return None
return result.stdout.strip() or result.stderr.strip().splitlines()[-1]
def is_one_sentence(text: str) -> bool:
"""One trailing period and no internal sentence break. Abbreviations will trip this."""
stripped = text.strip()
return stripped.endswith(".") and ". " not in stripped
def check_file(path: Path, taxonomy: dict[str, set[str]], errors: Errors) -> dict | None:
where = str(path.relative_to(ROOT))
slug = path.stem
raw = path.read_text(encoding="utf-8")
match = FRONTMATTER_RE.match(raw)
if not match:
errors.add(where, None, "no YAML frontmatter delimited by --- at the top of the file")
return None
try:
meta = yaml.safe_load(match.group(1)) or {}
except yaml.YAMLError as exc:
errors.add(where, None, f"frontmatter is not valid YAML: {exc}")
return None
if not isinstance(meta, dict):
errors.add(where, None, "frontmatter must be a mapping")
return None
if not SLUG_RE.match(slug):
errors.add(where, None, "filename must match [a-z0-9-]+")
language = meta.get("language")
if language is not None and language not in LANGUAGES:
errors.add(where, "language", f"expected one of {', '.join(LANGUAGES)}, got {language!r}")
required = REQUIRED + ((language,) if language in LANGUAGES else ())
for field in required:
if field not in meta:
errors.add(where, field, "required field is missing")
elif meta[field] is None or (isinstance(meta[field], str) and not meta[field].strip()):
errors.add(where, field, "required field is empty")
for field in meta:
if field not in required + OPTIONAL:
errors.add(where, field, "unknown field")
if (severity := meta.get("severity")) and severity not in SEVERITIES:
errors.add(where, "severity", f"expected one of {', '.join(SEVERITIES)}, got {severity!r}")
for field, heading in (("category", "category"), ("topic", "topic")):
allowed = taxonomy.get(heading, set())
value = meta.get(field)
if value and value not in allowed:
errors.add(where, field, f"{value!r} is not listed under ## {heading.title()} in TAXONOMY.md")
group = path.parent.name
language_dir = path.parent.parent.name
if group not in SNIPPET_LINES:
errors.add(where, None, f"group directory {group!r} is not one of {', '.join(SNIPPET_LINES)}")
if language and language != language_dir:
errors.add(where, "language", f"{language!r} does not match directory {language_dir!r}")
for field in ("tags", "keywords", "aliases"):
if field in meta and not isinstance(meta[field], list):
errors.add(where, field, "must be a list")
for field in ("signature", "distinguish"):
value = meta.get(field)
if isinstance(value, str) and value.strip() and not is_one_sentence(value):
errors.add(where, field, "must be exactly one sentence ending in a period")
added = meta.get("added")
if added is not None:
if isinstance(added, dt.date):
pass
else:
try:
dt.date.fromisoformat(str(added))
except ValueError:
errors.add(where, "added", f"{added!r} is not an ISO 8601 date")
body = match.group(2)
headings = section_order(body)
if headings != list(SECTIONS):
errors.add(where, None, f"expected H2 sections {list(SECTIONS)} in order, got {headings}")
if not re.search(r"^# \S", body, re.MULTILINE):
errors.add(where, None, "body must open with an H1 title")
sections = split_sections(body)
for name in ("Smell", "Better"):
blocks = FENCE_RE.findall(sections.get(name, ""))
if len(blocks) != 1:
errors.add(where, name, f"expected exactly one fenced code block, found {len(blocks)}")
continue
language_tag, code = blocks[0]
if language_tag != language:
errors.add(where, name, f"code fence must be tagged {language}, got {language_tag!r}")
lines = code.rstrip("\n").splitlines()
limit = SNIPPET_LINES.get(group)
if name == "Smell" and limit is not None and len(lines) > limit:
errors.add(where, name, f"snippet is {len(lines)} lines, limit for {group}/ is {limit}")
if language == "python":
try:
ast.parse(code)
except SyntaxError as exc:
errors.add(where, name, f"does not parse: {exc.msg} (line {exc.lineno})")
elif language == "rust" and (message := rust_parse_error(code)):
errors.add(where, name, f"does not parse: {message}")
elif language == "typescript" and (message := typescript_parse_error(code)):
errors.add(where, name, f"does not parse: {message}")
if not sections.get("Why it's bad", "").strip():
errors.add(where, "Why it's bad", "section is empty")
entry = {"id": slug}
entry.update({field: meta.get(field) for field in CATALOG_FIELDS})
return {"entry": entry, "meta": meta, "path": path}
def check_identifiers(records: list[dict], errors: Errors) -> None:
seen_slugs: dict[str, str] = {}
for record in records:
slug = record["entry"]["id"]
where = str(record["path"].relative_to(ROOT))
if slug in seen_slugs:
errors.add(where, None, f"slug {slug!r} collides with {seen_slugs[slug]!r}")
else:
seen_slugs[slug] = where
slugs = set(seen_slugs.keys())
seen: dict[str, str] = {}
for record in records:
where = str(record["path"].relative_to(ROOT))
for alias in record["meta"].get("aliases") or []:
if alias in slugs:
errors.add(where, "aliases", f"{alias!r} collides with an existing smell id")
elif alias in seen:
errors.add(where, "aliases", f"{alias!r} is already an alias of {seen[alias]!r}")
else:
seen[alias] = record["entry"]["id"]
def build_catalog(records: list[dict]) -> str:
entries = sorted((record["entry"] for record in records), key=lambda entry: entry["id"])
languages = {record["meta"].get("language") for record in records}
catalog = {
"schema_version": SCHEMA_VERSION,
"language": languages.pop() if len(languages) == 1 else sorted(filter(None, languages)),
"count": len(entries),
"smells": entries,
}
return json.dumps(catalog, indent=2, ensure_ascii=False) + "\n"
def main() -> int:
write = "--write-catalog" in sys.argv[1:]
errors = Errors()
taxonomy = load_taxonomy()
paths = sorted(SNIPPETS.glob("*/*/*.md"))
if not paths:
print(f"FAIL no smell files found under {SNIPPETS}", file=sys.stderr)
return 1
records = [record for path in paths if (record := check_file(path, taxonomy, errors))]
check_identifiers(records, errors)
catalog = build_catalog(records)
if write:
if errors.items:
print("refusing to write catalog.json while validation fails", file=sys.stderr)
return errors.report()
CATALOG.write_text(catalog, encoding="utf-8")
print(f"wrote {CATALOG.relative_to(ROOT)} ({len(records)} smells)")
return 0
if not CATALOG.exists():
errors.add("catalog.json", None, "missing — run: uv run validate.py --write-catalog")
elif CATALOG.read_text(encoding="utf-8") != catalog:
errors.add(
"catalog.json",
None,
"is stale relative to snippets/ — run: uv run validate.py --write-catalog",
)
status = errors.report()
if not status:
print(f"ok: {len(records)} smells, catalog fresh")
return status
if __name__ == "__main__":
sys.exit(main())