-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_source_quality.py
More file actions
351 lines (315 loc) · 10.7 KB
/
Copy pathcheck_source_quality.py
File metadata and controls
351 lines (315 loc) · 10.7 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
from __future__ import annotations
import ast
from dataclasses import dataclass
from pathlib import Path
import sys
import tokenize
from typing import Iterable
REPOSITORY_ROOT = Path(__file__).resolve().parent
PACKAGE_ROOT = REPOSITORY_ROOT / "src" / "cyphersyntax"
MAX_LINE_LENGTH = 100
FORBIDDEN_COMMENT_MARKERS = ("todo", "fixme", "xxx", "placeholder")
FORBIDDEN_IMPORT_ROOTS = frozenset(
{
"cloudpickle",
"dill",
"marshal",
"pickle",
"shelve",
}
)
FORBIDDEN_CALLS = frozenset(
{
"__import__",
"breakpoint",
"compile",
"eval",
"exec",
}
)
MUTABLE_DEFAULT_CALLS = frozenset({"dict", "list", "set"})
@dataclass(frozen=True, order=True, slots=True)
class QualityViolation:
path: str
line: int
code: str
message: str
def render(self) -> str:
return f"{self.path}:{self.line}: {self.code} {self.message}"
def _relative_path(path: Path) -> str:
try:
return path.resolve().relative_to(REPOSITORY_ROOT).as_posix()
except ValueError:
return path.as_posix()
def _violation(path: Path, line: int, code: str, message: str) -> QualityViolation:
return QualityViolation(
path=_relative_path(path),
line=line,
code=code,
message=message,
)
def _check_text(path: Path, text: str) -> list[QualityViolation]:
violations: list[QualityViolation] = []
if text and not text.endswith("\n"):
violations.append(
_violation(path, max(1, len(text.splitlines())), "TXT001", "missing final newline")
)
for line_number, line in enumerate(text.splitlines(), start=1):
if "\t" in line:
violations.append(
_violation(path, line_number, "TXT002", "tab character is not permitted")
)
if line.rstrip() != line:
violations.append(
_violation(path, line_number, "TXT003", "trailing whitespace")
)
if len(line) > MAX_LINE_LENGTH:
violations.append(
_violation(
path,
line_number,
"TXT004",
f"line exceeds {MAX_LINE_LENGTH} characters",
)
)
try:
tokens = tokenize.generate_tokens(iter(text.splitlines(keepends=True)).__next__)
for token in tokens:
if token.type != tokenize.COMMENT:
continue
normalized = token.string.casefold()
for marker in FORBIDDEN_COMMENT_MARKERS:
if marker in normalized:
violations.append(
_violation(
path,
token.start[0],
"TXT005",
f"forbidden unfinished-work marker: {marker}",
)
)
except (IndentationError, tokenize.TokenError) as exc:
line = getattr(exc, "lineno", 1) or 1
violations.append(
_violation(path, line, "SYN001", f"tokenization failed: {exc}")
)
return violations
def _call_name(node: ast.Call) -> str | None:
if isinstance(node.func, ast.Name):
return node.func.id
if (
isinstance(node.func, ast.Attribute)
and isinstance(node.func.value, ast.Name)
and node.func.value.id == "builtins"
):
return node.func.attr
return None
def _has_mutable_default(node: ast.expr) -> bool:
if isinstance(
node,
(
ast.Dict,
ast.DictComp,
ast.List,
ast.ListComp,
ast.Set,
ast.SetComp,
),
):
return True
return (
isinstance(node, ast.Call)
and isinstance(node.func, ast.Name)
and node.func.id in MUTABLE_DEFAULT_CALLS
)
def _function_violations(
path: Path,
node: ast.FunctionDef | ast.AsyncFunctionDef,
) -> list[QualityViolation]:
violations: list[QualityViolation] = []
parameters = [
*node.args.posonlyargs,
*node.args.args,
*node.args.kwonlyargs,
]
for parameter in parameters:
if parameter.arg in {"self", "cls"}:
continue
if parameter.annotation is None:
violations.append(
_violation(
path,
parameter.lineno,
"TYP001",
f"parameter {parameter.arg!r} is missing a type annotation",
)
)
if node.args.vararg is not None and node.args.vararg.annotation is None:
violations.append(
_violation(
path,
node.args.vararg.lineno,
"TYP001",
f"parameter '*{node.args.vararg.arg}' is missing a type annotation",
)
)
if node.args.kwarg is not None and node.args.kwarg.annotation is None:
violations.append(
_violation(
path,
node.args.kwarg.lineno,
"TYP001",
f"parameter '**{node.args.kwarg.arg}' is missing a type annotation",
)
)
if node.returns is None:
violations.append(
_violation(
path,
node.lineno,
"TYP002",
f"function {node.name!r} is missing a return annotation",
)
)
positional_defaults = node.args.defaults
keyword_defaults = [default for default in node.args.kw_defaults if default is not None]
for default in [*positional_defaults, *keyword_defaults]:
if _has_mutable_default(default):
violations.append(
_violation(
path,
default.lineno,
"TYP003",
f"function {node.name!r} has a mutable default argument",
)
)
return violations
def _check_ast(path: Path, text: str, *, require_annotations: bool) -> list[QualityViolation]:
try:
tree = ast.parse(text, filename=str(path), type_comments=True)
except SyntaxError as exc:
return [
_violation(
path,
exc.lineno or 1,
"SYN002",
exc.msg,
)
]
violations: list[QualityViolation] = []
if require_annotations:
has_future_annotations = any(
isinstance(statement, ast.ImportFrom)
and statement.module == "__future__"
and any(alias.name == "annotations" for alias in statement.names)
for statement in tree.body
)
if not has_future_annotations:
violations.append(
_violation(
path,
1,
"TYP004",
"package module must import annotations from __future__",
)
)
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root = alias.name.partition(".")[0]
if root in FORBIDDEN_IMPORT_ROOTS:
violations.append(
_violation(
path,
node.lineno,
"SEC001",
f"forbidden unsafe serialization import: {root}",
)
)
elif isinstance(node, ast.ImportFrom):
if any(alias.name == "*" for alias in node.names):
violations.append(
_violation(path, node.lineno, "IMP001", "wildcard import")
)
root = (node.module or "").partition(".")[0]
if root in FORBIDDEN_IMPORT_ROOTS:
violations.append(
_violation(
path,
node.lineno,
"SEC001",
f"forbidden unsafe serialization import: {root}",
)
)
elif isinstance(node, ast.Call):
name = _call_name(node)
if name in FORBIDDEN_CALLS:
violations.append(
_violation(
path,
node.lineno,
"SEC002",
f"forbidden dynamic execution call: {name}",
)
)
elif isinstance(node, ast.Assert):
violations.append(
_violation(
path,
node.lineno,
"SEC003",
"runtime package code must not use assert",
)
)
elif isinstance(node, ast.ExceptHandler) and node.type is None:
violations.append(
_violation(path, node.lineno, "ERR001", "bare except clause")
)
elif require_annotations and isinstance(
node,
(ast.FunctionDef, ast.AsyncFunctionDef),
):
violations.extend(_function_violations(path, node))
return violations
def inspect_python_file(
path: Path,
*,
require_annotations: bool,
) -> list[QualityViolation]:
try:
text = path.read_text(encoding="utf-8", errors="strict")
except (OSError, UnicodeError) as exc:
return [_violation(path, 1, "TXT000", f"failed to read UTF-8 source: {exc}")]
return [
*_check_text(path, text),
*_check_ast(path, text, require_annotations=require_annotations),
]
def repository_python_files() -> Iterable[tuple[Path, bool]]:
for path in sorted(PACKAGE_ROOT.rglob("*.py")):
yield path, True
for name in ("check_green.py", "check_source_quality.py", "demo.py"):
yield REPOSITORY_ROOT / name, False
def collect_repository_violations() -> list[QualityViolation]:
violations: list[QualityViolation] = []
for path, require_annotations in repository_python_files():
if not path.is_file():
violations.append(
_violation(path, 1, "REP001", "required Python file is missing")
)
continue
violations.extend(
inspect_python_file(path, require_annotations=require_annotations)
)
return sorted(violations)
def main() -> int:
violations = collect_repository_violations()
if violations:
print("SOURCE QUALITY CHECK FAILED", file=sys.stderr)
for violation in violations:
print(violation.render(), file=sys.stderr)
return 1
inspected = sum(1 for _ in repository_python_files())
print(f"SOURCE QUALITY CHECK PASSED ({inspected} files)")
return 0
if __name__ == "__main__":
raise SystemExit(main())