codeveto 0.1.0__py3-none-any.whl
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.
- codeveto/__init__.py +3 -0
- codeveto/__main__.py +8 -0
- codeveto/ai/__init__.py +19 -0
- codeveto/ai/harness.py +303 -0
- codeveto/ai/packets.py +855 -0
- codeveto/ai/policy.py +222 -0
- codeveto/ai/prompt.py +101 -0
- codeveto/ai/providers/__init__.py +178 -0
- codeveto/ai/providers/claude.py +247 -0
- codeveto/ai/providers/openai_compat.py +246 -0
- codeveto/ai/runner.py +293 -0
- codeveto/ai/verify.py +324 -0
- codeveto/anchor.py +211 -0
- codeveto/cli.py +247 -0
- codeveto/cli_explain.py +49 -0
- codeveto/cli_hook.py +31 -0
- codeveto/cli_init.py +254 -0
- codeveto/cli_mcp.py +29 -0
- codeveto/cli_packets.py +35 -0
- codeveto/cli_publish.py +29 -0
- codeveto/cli_review.py +362 -0
- codeveto/cli_rules.py +78 -0
- codeveto/cli_verify.py +47 -0
- codeveto/config.py +1229 -0
- codeveto/data/README.md +16 -0
- codeveto/data/ai-wire.schema.json +53 -0
- codeveto/data/prompts/system.md +57 -0
- codeveto/data/report-v1.schema.json +268 -0
- codeveto/data/templates/forgejo-codeveto.yml +104 -0
- codeveto/data/templates/github-codeveto.yml +18 -0
- codeveto/embedded.py +311 -0
- codeveto/engine.py +1570 -0
- codeveto/git.py +1549 -0
- codeveto/globs.py +348 -0
- codeveto/integrations/__init__.py +1 -0
- codeveto/integrations/hooks.py +327 -0
- codeveto/integrations/mcp.py +770 -0
- codeveto/integrations/mcp_ai.py +77 -0
- codeveto/integrations/prepush.py +222 -0
- codeveto/jsonsafe.py +60 -0
- codeveto/languages.py +539 -0
- codeveto/lexers.py +2560 -0
- codeveto/model.py +372 -0
- codeveto/publish/__init__.py +28 -0
- codeveto/publish/action.py +330 -0
- codeveto/publish/common.py +84 -0
- codeveto/publish/diff.py +208 -0
- codeveto/publish/event.py +241 -0
- codeveto/publish/forgejo.py +184 -0
- codeveto/publish/github.py +380 -0
- codeveto/publish/http.py +263 -0
- codeveto/publish/pull.py +218 -0
- codeveto/publish/untrusted.py +110 -0
- codeveto/py.typed +0 -0
- codeveto/redact.py +113 -0
- codeveto/render/__init__.py +64 -0
- codeveto/render/agent.py +43 -0
- codeveto/render/github.py +101 -0
- codeveto/render/json.py +23 -0
- codeveto/render/markdown.py +208 -0
- codeveto/render/safe.py +249 -0
- codeveto/render/sarif.py +217 -0
- codeveto/render/text.py +210 -0
- codeveto/report.py +252 -0
- codeveto/rules/__init__.py +84 -0
- codeveto/rules/agent.py +2972 -0
- codeveto/rules/base.py +1026 -0
- codeveto/rules/ci.py +1708 -0
- codeveto/rules/config.py +493 -0
- codeveto/rules/deps.py +1693 -0
- codeveto/rules/docker.py +479 -0
- codeveto/rules/examples/__init__.py +148 -0
- codeveto/rules/examples/agent.py +839 -0
- codeveto/rules/examples/ci.py +1046 -0
- codeveto/rules/examples/config.py +191 -0
- codeveto/rules/examples/deps.py +369 -0
- codeveto/rules/examples/docker.py +157 -0
- codeveto/rules/examples/go.py +241 -0
- codeveto/rules/examples/hygiene.py +466 -0
- codeveto/rules/examples/js.py +462 -0
- codeveto/rules/examples/python.py +595 -0
- codeveto/rules/examples/rust.py +268 -0
- codeveto/rules/examples/secrets.py +561 -0
- codeveto/rules/examples/security.py +608 -0
- codeveto/rules/examples/shell.py +174 -0
- codeveto/rules/examples/sql.py +194 -0
- codeveto/rules/examples/tests.py +497 -0
- codeveto/rules/go.py +328 -0
- codeveto/rules/hygiene.py +1094 -0
- codeveto/rules/js.py +768 -0
- codeveto/rules/python.py +1642 -0
- codeveto/rules/rust.py +209 -0
- codeveto/rules/secrets.py +1335 -0
- codeveto/rules/security.py +3680 -0
- codeveto/rules/shell.py +867 -0
- codeveto/rules/sql.py +629 -0
- codeveto/rules/tests.py +1404 -0
- codeveto/schema.py +384 -0
- codeveto/statements.py +607 -0
- codeveto/worktree.py +1176 -0
- codeveto/yamlish.py +1179 -0
- codeveto-0.1.0.dist-info/METADATA +253 -0
- codeveto-0.1.0.dist-info/RECORD +106 -0
- codeveto-0.1.0.dist-info/WHEEL +4 -0
- codeveto-0.1.0.dist-info/entry_points.txt +2 -0
- codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
codeveto/rules/python.py
ADDED
|
@@ -0,0 +1,1642 @@
|
|
|
1
|
+
"""Python pack (SPEC 6.1, 6.5): language bug patterns."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import builtins
|
|
7
|
+
import sys
|
|
8
|
+
import warnings
|
|
9
|
+
from collections.abc import Iterator
|
|
10
|
+
|
|
11
|
+
from codeveto.rules.base import FileContext, Hit, PartialCoverage, rule
|
|
12
|
+
|
|
13
|
+
NEWEST_PYTHON = (3, 15)
|
|
14
|
+
"""Newest Python CodeVeto supports (SPEC 6.5); a parse failure there is not newer syntax.
|
|
15
|
+
|
|
16
|
+
A test keeps it at or above the newest ``Programming Language :: Python :: 3.x``
|
|
17
|
+
classifier in ``pyproject.toml``.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
_PARSE_ERRORS = (SyntaxError, ValueError, RecursionError, MemoryError)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _compile_error(
|
|
24
|
+
text: str, tree: ast.Module | None, parse_error: BaseException | None, filename: str
|
|
25
|
+
) -> BaseException | None:
|
|
26
|
+
"""Why ``text`` is not valid Python on this interpreter, or ``None``.
|
|
27
|
+
|
|
28
|
+
``ast.parse`` (the context's cached ``tree`` or ``parse_error``) and then
|
|
29
|
+
``compile(..., dont_inherit=True)`` as legacy did: the compiler pass
|
|
30
|
+
catches what the parser accepts but Python rejects (``return`` outside a
|
|
31
|
+
function, ``nonlocal`` at module level). Text with surrogate escapes
|
|
32
|
+
(non-UTF-8 bytes) is parsed again as bytes, so a coding cookie decides its
|
|
33
|
+
encoding as Python would. Compiling an AST never runs it.
|
|
34
|
+
"""
|
|
35
|
+
with warnings.catch_warnings():
|
|
36
|
+
warnings.simplefilter("ignore", SyntaxWarning)
|
|
37
|
+
warnings.simplefilter("ignore", DeprecationWarning)
|
|
38
|
+
try:
|
|
39
|
+
try:
|
|
40
|
+
text.encode("utf-8")
|
|
41
|
+
except UnicodeEncodeError:
|
|
42
|
+
tree = ast.parse(text.encode("utf-8", "surrogateescape"), filename=filename)
|
|
43
|
+
else:
|
|
44
|
+
if tree is None:
|
|
45
|
+
return parse_error
|
|
46
|
+
compile(tree, filename, "exec", dont_inherit=True, optimize=0)
|
|
47
|
+
except _PARSE_ERRORS as exc:
|
|
48
|
+
return exc
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _nearest(target: int, candidates: frozenset[int]) -> int | None:
|
|
53
|
+
if not candidates:
|
|
54
|
+
return None
|
|
55
|
+
return min(candidates, key=lambda n: (abs(n - target), n))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@rule(
|
|
59
|
+
id="python/syntax-error",
|
|
60
|
+
severity="error",
|
|
61
|
+
title="Python file no longer parses",
|
|
62
|
+
languages={"python"},
|
|
63
|
+
scope="file",
|
|
64
|
+
rationale=(
|
|
65
|
+
"The change leaves a Python file that the interpreter rejects, so importing or "
|
|
66
|
+
"running it fails."
|
|
67
|
+
),
|
|
68
|
+
hint="Fix the syntax near the reported line; run the file through python -m py_compile.",
|
|
69
|
+
tags={"python", "correctness"},
|
|
70
|
+
)
|
|
71
|
+
def syntax_error(ctx: FileContext) -> Iterator[Hit]:
|
|
72
|
+
"""New side fails to parse on the newest supported Python (SPEC 5.2, 6.5).
|
|
73
|
+
|
|
74
|
+
Reported at the changed line or deletion point nearest the error. Only
|
|
75
|
+
the newest supported Python (or a newer one) can tell newer syntax from a
|
|
76
|
+
real error, so on an older interpreter a failure only makes coverage
|
|
77
|
+
partial; an old side that already failed to parse is existing breakage
|
|
78
|
+
(partial too).
|
|
79
|
+
"""
|
|
80
|
+
new = ctx.new_text
|
|
81
|
+
if new is None:
|
|
82
|
+
return
|
|
83
|
+
error = _compile_error(new, ctx.python_ast, ctx.python_ast_error, ctx.path)
|
|
84
|
+
if error is None:
|
|
85
|
+
return
|
|
86
|
+
if sys.version_info[:2] < NEWEST_PYTHON:
|
|
87
|
+
major, minor = NEWEST_PYTHON
|
|
88
|
+
raise PartialCoverage(f"run on Python {major}.{minor} to parse this file")
|
|
89
|
+
old = ctx.old_text
|
|
90
|
+
if old is not None:
|
|
91
|
+
old_name = ctx.old_path or ctx.path
|
|
92
|
+
if _compile_error(old, ctx.old_python_ast, ctx.old_python_ast_error, old_name) is not None:
|
|
93
|
+
raise PartialCoverage("the old side already fails to parse")
|
|
94
|
+
reported = getattr(error, "lineno", None)
|
|
95
|
+
target = reported if isinstance(reported, int) and reported > 0 else 1
|
|
96
|
+
line = _nearest(target, ctx.added_lines | ctx.deletion_points)
|
|
97
|
+
if line is None:
|
|
98
|
+
raise PartialCoverage("the parse error has no changed line to report at")
|
|
99
|
+
kind = type(error).__name__
|
|
100
|
+
yield Hit(line, message=f"Python no longer parses ({kind} near line {target})", evidence=kind)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# --- AST helpers -------------------------------------------------------------------
|
|
104
|
+
#
|
|
105
|
+
# Every rule below works on ``ctx.python_ast`` (and ``old_python_ast`` where it
|
|
106
|
+
# compares sides). When the AST is unavailable the rule yields nothing:
|
|
107
|
+
# ``python/syntax-error`` covers a file that does not parse. Hits span the
|
|
108
|
+
# reported node, so the engine anchors them at the node's first changed line.
|
|
109
|
+
|
|
110
|
+
_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)
|
|
111
|
+
_FUNCS = (ast.FunctionDef, ast.AsyncFunctionDef)
|
|
112
|
+
_LOOPS = (ast.For, ast.AsyncFor, ast.While)
|
|
113
|
+
_TRY = (ast.Try, ast.TryStar)
|
|
114
|
+
_EVIDENCE_CHARS = 160
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _lone_cr_map(text: str) -> list[int] | None:
|
|
118
|
+
"""AST line -> Git line when a lone CR (a line end to Python, not to Git) occurs."""
|
|
119
|
+
if "\r" not in text or "\r" not in text.replace("\r\n", ""):
|
|
120
|
+
return None
|
|
121
|
+
mapping = [1, 1] # index 0 unused; AST line 1 is Git line 1
|
|
122
|
+
git = 1
|
|
123
|
+
i, n = 0, len(text)
|
|
124
|
+
while i < n:
|
|
125
|
+
ch = text[i]
|
|
126
|
+
if ch == "\n":
|
|
127
|
+
git += 1
|
|
128
|
+
mapping.append(git)
|
|
129
|
+
elif ch == "\r":
|
|
130
|
+
if i + 1 < n and text[i + 1] == "\n":
|
|
131
|
+
i += 1
|
|
132
|
+
git += 1
|
|
133
|
+
mapping.append(git)
|
|
134
|
+
i += 1
|
|
135
|
+
return mapping
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class _Source:
|
|
139
|
+
"""The parsed new side of a context with line, column and parent lookups."""
|
|
140
|
+
|
|
141
|
+
def __init__(self, ctx: FileContext, tree: ast.Module) -> None:
|
|
142
|
+
self.ctx = ctx
|
|
143
|
+
self.tree = tree
|
|
144
|
+
self.lines = ctx.lines
|
|
145
|
+
self._parents: dict[int, ast.AST] | None = None
|
|
146
|
+
self._map = _lone_cr_map(ctx.new_text or "")
|
|
147
|
+
|
|
148
|
+
def parent(self, node: ast.AST) -> ast.AST | None:
|
|
149
|
+
if self._parents is None:
|
|
150
|
+
parents: dict[int, ast.AST] = {}
|
|
151
|
+
for current in ast.walk(self.tree):
|
|
152
|
+
for child in ast.iter_child_nodes(current):
|
|
153
|
+
parents[id(child)] = current
|
|
154
|
+
self._parents = parents
|
|
155
|
+
return self._parents.get(id(node))
|
|
156
|
+
|
|
157
|
+
def line(self, ast_line: int) -> int:
|
|
158
|
+
"""Git line of AST line ``ast_line`` (they differ only after a lone CR)."""
|
|
159
|
+
if self._map is not None:
|
|
160
|
+
ast_line = self._map[min(ast_line, len(self._map) - 1)]
|
|
161
|
+
return max(1, min(ast_line, max(len(self.lines), 1)))
|
|
162
|
+
|
|
163
|
+
def column(self, ast_line: int, col_offset: int) -> int | None:
|
|
164
|
+
"""1-based character column of a UTF-8 byte offset on an AST line."""
|
|
165
|
+
if self._map is not None or not 1 <= ast_line <= len(self.lines):
|
|
166
|
+
return None
|
|
167
|
+
text = self.lines[ast_line - 1]
|
|
168
|
+
extra = 0
|
|
169
|
+
if ast_line == 1 and text.startswith(""):
|
|
170
|
+
text, extra = text[1:], 1 # the parser never saw the byte order mark
|
|
171
|
+
prefix = text.encode("utf-8", "surrogateescape")[:col_offset]
|
|
172
|
+
return len(prefix.decode("utf-8", "replace")) + 1 + extra
|
|
173
|
+
|
|
174
|
+
def hit(
|
|
175
|
+
self,
|
|
176
|
+
node: ast.AST,
|
|
177
|
+
*,
|
|
178
|
+
message: str,
|
|
179
|
+
evidence: str | None = None,
|
|
180
|
+
end: int | None = None,
|
|
181
|
+
) -> Hit:
|
|
182
|
+
"""A hit spanning ``node`` (or its first line through AST line ``end``)."""
|
|
183
|
+
first: int = node.lineno # type: ignore[attr-defined]
|
|
184
|
+
last: int = end if end is not None else getattr(node, "end_lineno", None) or first
|
|
185
|
+
start = self.line(first)
|
|
186
|
+
stop = max(start, self.line(last))
|
|
187
|
+
return Hit(
|
|
188
|
+
start,
|
|
189
|
+
end_line=stop if stop > start else None,
|
|
190
|
+
column=self.column(first, node.col_offset), # type: ignore[attr-defined]
|
|
191
|
+
message=message,
|
|
192
|
+
evidence=evidence,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _source(ctx: FileContext) -> _Source | None:
|
|
197
|
+
tree = ctx.python_ast
|
|
198
|
+
if tree is None:
|
|
199
|
+
return None
|
|
200
|
+
return _Source(ctx, tree)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _short(node: ast.AST, limit: int = _EVIDENCE_CHARS) -> str:
|
|
204
|
+
"""Whitespace-collapsed ``ast.unparse(node)``, at most ``limit`` characters."""
|
|
205
|
+
try:
|
|
206
|
+
text = ast.unparse(node)
|
|
207
|
+
except (RecursionError, ValueError, AttributeError, TypeError):
|
|
208
|
+
return type(node).__name__
|
|
209
|
+
text = " ".join(text.split())
|
|
210
|
+
return text if len(text) <= limit else text[: limit - 3] + "..."
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _scoped(roots: list[ast.AST] | list[ast.stmt]) -> Iterator[ast.AST]:
|
|
214
|
+
"""Nodes under ``roots`` in the same scope: nested defs, lambdas and classes are
|
|
215
|
+
yielded but not entered."""
|
|
216
|
+
stack: list[ast.AST] = list(reversed(roots))
|
|
217
|
+
while stack:
|
|
218
|
+
node = stack.pop()
|
|
219
|
+
yield node
|
|
220
|
+
if isinstance(node, _SCOPES):
|
|
221
|
+
continue
|
|
222
|
+
stack.extend(reversed(list(ast.iter_child_nodes(node))))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _blocks(tree: ast.AST) -> Iterator[list[ast.stmt]]:
|
|
226
|
+
"""Every statement list in ``tree`` (bodies, else, finally, handlers, cases)."""
|
|
227
|
+
for node in ast.walk(tree):
|
|
228
|
+
for field in ("body", "orelse", "finalbody"):
|
|
229
|
+
value = getattr(node, field, None)
|
|
230
|
+
if isinstance(value, list) and value and isinstance(value[0], ast.stmt):
|
|
231
|
+
yield value
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _final_name(func: ast.expr) -> str | None:
|
|
235
|
+
"""``f`` for ``f(...)``, ``attr`` for ``x.attr(...)``."""
|
|
236
|
+
if isinstance(func, ast.Name):
|
|
237
|
+
return func.id
|
|
238
|
+
if isinstance(func, ast.Attribute):
|
|
239
|
+
return func.attr
|
|
240
|
+
return None
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _dotted(node: ast.AST) -> str | None:
|
|
244
|
+
"""``a.b.c`` for a chain of attributes on a name, else ``None``."""
|
|
245
|
+
parts: list[str] = []
|
|
246
|
+
while isinstance(node, ast.Attribute):
|
|
247
|
+
parts.append(node.attr)
|
|
248
|
+
node = node.value
|
|
249
|
+
if not isinstance(node, ast.Name):
|
|
250
|
+
return None
|
|
251
|
+
parts.append(node.id)
|
|
252
|
+
return ".".join(reversed(parts))
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _header_end(node: ast.AST) -> int:
|
|
256
|
+
"""Last AST line of a compound statement's header (``def ...:``, ``except ...:``)."""
|
|
257
|
+
start: int = node.lineno # type: ignore[attr-defined]
|
|
258
|
+
body = getattr(node, "body", None)
|
|
259
|
+
if isinstance(body, list) and body:
|
|
260
|
+
return max(start, body[0].lineno - 1)
|
|
261
|
+
return start
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _bound_names(tree: ast.AST) -> set[str]:
|
|
265
|
+
"""Names the module binds itself (defs, classes, imports, assignment targets)."""
|
|
266
|
+
names: set[str] = set()
|
|
267
|
+
for node in ast.walk(tree):
|
|
268
|
+
if isinstance(node, (*_FUNCS, ast.ClassDef)):
|
|
269
|
+
names.add(node.name)
|
|
270
|
+
elif isinstance(node, (ast.Import, ast.ImportFrom)):
|
|
271
|
+
for alias in node.names:
|
|
272
|
+
names.add(alias.asname or alias.name.split(".")[0])
|
|
273
|
+
elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
|
|
274
|
+
names.add(node.id)
|
|
275
|
+
return names
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _path_parts(path: str) -> list[str]:
|
|
279
|
+
return [p for p in path.split("/") if p]
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _decorator_names(node: ast.AST) -> set[str]:
|
|
283
|
+
"""Final names of a def's decorators (``overload``, ``setter``, ``property``)."""
|
|
284
|
+
names: set[str] = set()
|
|
285
|
+
for deco in getattr(node, "decorator_list", ()):
|
|
286
|
+
target = deco.func if isinstance(deco, ast.Call) else deco
|
|
287
|
+
name = _final_name(target)
|
|
288
|
+
if name is not None:
|
|
289
|
+
names.add(name)
|
|
290
|
+
return names
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _numeric_literal(node: ast.expr) -> bool:
|
|
294
|
+
return (
|
|
295
|
+
isinstance(node, ast.UnaryOp)
|
|
296
|
+
and isinstance(node.op, (ast.USub, ast.UAdd))
|
|
297
|
+
and isinstance(node.operand, ast.Constant)
|
|
298
|
+
and type(node.operand.value) in (int, float, complex)
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
# --- Errors: code that cannot do what it says ------------------------------------
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
_LITERAL_DISPLAYS = (
|
|
306
|
+
ast.List,
|
|
307
|
+
ast.Tuple,
|
|
308
|
+
ast.Dict,
|
|
309
|
+
ast.Set,
|
|
310
|
+
ast.ListComp,
|
|
311
|
+
ast.SetComp,
|
|
312
|
+
ast.DictComp,
|
|
313
|
+
ast.JoinedStr,
|
|
314
|
+
)
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
_FRESH_DISPLAYS = (ast.List, ast.Dict, ast.Set, ast.ListComp, ast.SetComp, ast.DictComp)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _is_literal(node: ast.expr) -> bool:
|
|
321
|
+
if isinstance(node, ast.Constant):
|
|
322
|
+
value = node.value
|
|
323
|
+
return value is not None and value is not Ellipsis and not isinstance(value, bool)
|
|
324
|
+
return _numeric_literal(node) or isinstance(node, _LITERAL_DISPLAYS)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
@rule(
|
|
328
|
+
id="python/is-literal",
|
|
329
|
+
severity="error",
|
|
330
|
+
title="Identity comparison with a literal",
|
|
331
|
+
languages={"python"},
|
|
332
|
+
rationale=(
|
|
333
|
+
"'is' compares object identity. Whether two equal strings or numbers are the same "
|
|
334
|
+
"object is an interpreter detail, and a list, dict or f-string literal is a new "
|
|
335
|
+
"object every time, so the comparison is unreliable or always false."
|
|
336
|
+
),
|
|
337
|
+
hint="Compare values with == or != (keep 'is' for None, True, False and sentinels).",
|
|
338
|
+
tags={"python", "correctness"},
|
|
339
|
+
)
|
|
340
|
+
def is_literal(ctx: FileContext) -> Iterator[Hit]:
|
|
341
|
+
"""``x is "a"``, ``x is not 0``, ``x is []`` (CPython's own SyntaxWarning).
|
|
342
|
+
|
|
343
|
+
None, True, False and ``...`` are singletons and stay silent, and so does a
|
|
344
|
+
comparison of two list, dict or set displays (``[] is not []``), which only
|
|
345
|
+
tests that each display builds a new object.
|
|
346
|
+
"""
|
|
347
|
+
src = _source(ctx)
|
|
348
|
+
if src is None:
|
|
349
|
+
return
|
|
350
|
+
for node in ast.walk(src.tree):
|
|
351
|
+
if not isinstance(node, ast.Compare):
|
|
352
|
+
continue
|
|
353
|
+
operands = [node.left, *node.comparators]
|
|
354
|
+
for i, op in enumerate(node.ops):
|
|
355
|
+
left, right = operands[i], operands[i + 1]
|
|
356
|
+
if isinstance(left, _FRESH_DISPLAYS) and isinstance(right, _FRESH_DISPLAYS):
|
|
357
|
+
continue # ``[] is not []``: a deliberate check that displays are new objects
|
|
358
|
+
if isinstance(op, (ast.Is, ast.IsNot)) and (_is_literal(left) or _is_literal(right)):
|
|
359
|
+
yield src.hit(
|
|
360
|
+
node,
|
|
361
|
+
message="'is' compares identity with a literal; use == or !=",
|
|
362
|
+
evidence=_short(node),
|
|
363
|
+
)
|
|
364
|
+
break
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
@rule(
|
|
368
|
+
id="python/assert-tuple",
|
|
369
|
+
severity="error",
|
|
370
|
+
title="Assertion on a tuple is always true",
|
|
371
|
+
languages={"python"},
|
|
372
|
+
rationale=(
|
|
373
|
+
"assert (cond, 'message') tests a non-empty tuple, which is always true, so the "
|
|
374
|
+
"assertion can never fail."
|
|
375
|
+
),
|
|
376
|
+
hint="Drop the parentheses: assert cond, 'message'.",
|
|
377
|
+
tags={"python", "correctness"},
|
|
378
|
+
)
|
|
379
|
+
def assert_tuple(ctx: FileContext) -> Iterator[Hit]:
|
|
380
|
+
src = _source(ctx)
|
|
381
|
+
if src is None:
|
|
382
|
+
return
|
|
383
|
+
for node in ast.walk(src.tree):
|
|
384
|
+
if isinstance(node, ast.Assert) and isinstance(node.test, ast.Tuple) and node.test.elts:
|
|
385
|
+
yield src.hit(
|
|
386
|
+
node, message="assert on a non-empty tuple never fails", evidence=_short(node)
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _key_value(node: ast.expr | None) -> tuple[object, ...] | None:
|
|
391
|
+
"""Identity of a literal dict key under Python's equality (1 == 1.0 == True)."""
|
|
392
|
+
if node is None:
|
|
393
|
+
return None
|
|
394
|
+
if isinstance(node, ast.Constant):
|
|
395
|
+
value = node.value
|
|
396
|
+
elif _numeric_literal(node):
|
|
397
|
+
operand = node.operand.value # type: ignore[attr-defined]
|
|
398
|
+
value = -operand if isinstance(node.op, ast.USub) else +operand # type: ignore[attr-defined]
|
|
399
|
+
else:
|
|
400
|
+
return None
|
|
401
|
+
if isinstance(value, (bool, int, float, complex)):
|
|
402
|
+
return ("number", value)
|
|
403
|
+
if isinstance(value, str):
|
|
404
|
+
return ("str", value)
|
|
405
|
+
if isinstance(value, bytes):
|
|
406
|
+
return ("bytes", value)
|
|
407
|
+
if value is None:
|
|
408
|
+
return ("none",)
|
|
409
|
+
if value is Ellipsis:
|
|
410
|
+
return ("ellipsis",)
|
|
411
|
+
return None
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
@rule(
|
|
415
|
+
id="python/duplicate-dict-key",
|
|
416
|
+
severity="error",
|
|
417
|
+
title="Dictionary literal repeats a key",
|
|
418
|
+
languages={"python"},
|
|
419
|
+
rationale=(
|
|
420
|
+
"A dict literal keeps only the last value of a repeated key, so the earlier entry "
|
|
421
|
+
"is silently lost. Python treats 1, 1.0 and True as the same key."
|
|
422
|
+
),
|
|
423
|
+
hint="Remove or rename one of the entries.",
|
|
424
|
+
tags={"python", "correctness"},
|
|
425
|
+
)
|
|
426
|
+
def duplicate_dict_key(ctx: FileContext) -> Iterator[Hit]:
|
|
427
|
+
"""Literal keys only (strings, bytes, numbers, None, ``...``); computed keys, names
|
|
428
|
+
and tuples are ignored. Reported at the repeated key."""
|
|
429
|
+
src = _source(ctx)
|
|
430
|
+
if src is None:
|
|
431
|
+
return
|
|
432
|
+
for node in ast.walk(src.tree):
|
|
433
|
+
if not isinstance(node, ast.Dict):
|
|
434
|
+
continue
|
|
435
|
+
seen: dict[tuple[object, ...], ast.expr] = {}
|
|
436
|
+
for key in node.keys:
|
|
437
|
+
value = _key_value(key)
|
|
438
|
+
if value is None or key is None:
|
|
439
|
+
continue
|
|
440
|
+
first = seen.get(value)
|
|
441
|
+
if first is None:
|
|
442
|
+
seen[value] = key
|
|
443
|
+
continue
|
|
444
|
+
yield src.hit(
|
|
445
|
+
key,
|
|
446
|
+
message=f"dict key repeated; the entry on line {src.line(first.lineno)} is lost",
|
|
447
|
+
evidence=f"duplicate key {_short(key, 80)}",
|
|
448
|
+
)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
@rule(
|
|
452
|
+
id="python/return-in-finally",
|
|
453
|
+
severity="error",
|
|
454
|
+
title="return, break or continue in finally",
|
|
455
|
+
languages={"python"},
|
|
456
|
+
rationale=(
|
|
457
|
+
"Leaving a finally block with return, break or continue discards the exception "
|
|
458
|
+
"that is propagating, so errors vanish silently (PEP 765 makes this a warning)."
|
|
459
|
+
),
|
|
460
|
+
hint="Move the return after the try statement, or re-raise explicitly.",
|
|
461
|
+
tags={"python", "correctness"},
|
|
462
|
+
)
|
|
463
|
+
def return_in_finally(ctx: FileContext) -> Iterator[Hit]:
|
|
464
|
+
"""``return`` anywhere in a ``finally`` of the same function, and ``break`` or
|
|
465
|
+
``continue`` that leave it (not those of a loop inside the ``finally``).
|
|
466
|
+
|
|
467
|
+
The catalogue names ``return``; ``break`` and ``continue`` swallow the
|
|
468
|
+
exception the same way (PEP 765), so they are reported too.
|
|
469
|
+
"""
|
|
470
|
+
src = _source(ctx)
|
|
471
|
+
if src is None:
|
|
472
|
+
return
|
|
473
|
+
for node in ast.walk(src.tree):
|
|
474
|
+
if not isinstance(node, _TRY) or not node.finalbody:
|
|
475
|
+
continue
|
|
476
|
+
stack: list[tuple[ast.AST, bool]] = [(s, False) for s in reversed(node.finalbody)]
|
|
477
|
+
while stack:
|
|
478
|
+
current, in_loop = stack.pop()
|
|
479
|
+
if isinstance(current, _SCOPES):
|
|
480
|
+
continue
|
|
481
|
+
if isinstance(current, ast.Return) or (
|
|
482
|
+
isinstance(current, (ast.Break, ast.Continue)) and not in_loop
|
|
483
|
+
):
|
|
484
|
+
word = type(current).__name__.lower()
|
|
485
|
+
yield src.hit(
|
|
486
|
+
current,
|
|
487
|
+
message=f"'{word}' in finally discards any exception in flight",
|
|
488
|
+
evidence=f"{word} in finally",
|
|
489
|
+
)
|
|
490
|
+
continue
|
|
491
|
+
if isinstance(current, _LOOPS):
|
|
492
|
+
children = [(c, True) for c in current.body]
|
|
493
|
+
children += [(c, in_loop) for c in current.orelse]
|
|
494
|
+
stack.extend(reversed(children))
|
|
495
|
+
continue
|
|
496
|
+
stack.extend((c, in_loop) for c in reversed(list(ast.iter_child_nodes(current))))
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
_DEBUG_MODULES = frozenset(
|
|
500
|
+
{"pdb", "ipdb", "pudb", "bpdb", "remote_pdb", "web_pdb", "rpdb", "wdb", "pdbr"}
|
|
501
|
+
)
|
|
502
|
+
_DEBUG_FUNCS = frozenset({"set_trace", "sset_trace"})
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _mentions_debug(test: ast.expr) -> bool:
|
|
506
|
+
for node in ast.walk(test):
|
|
507
|
+
text = None
|
|
508
|
+
if isinstance(node, ast.Name):
|
|
509
|
+
text = node.id
|
|
510
|
+
elif isinstance(node, ast.Attribute):
|
|
511
|
+
text = node.attr
|
|
512
|
+
elif isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
513
|
+
text = node.value
|
|
514
|
+
if text is not None and ("debug" in text.lower() or "pdb" in text.lower()):
|
|
515
|
+
return True
|
|
516
|
+
return False
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _bound_in_function(src: _Source, node: ast.AST, name: str) -> bool:
|
|
520
|
+
"""Does the function around ``node`` bind ``name`` itself, other than by an import?
|
|
521
|
+
|
|
522
|
+
``pdb = Pdb(...)`` or a parameter named ``pdb`` makes ``pdb.set_trace()`` a
|
|
523
|
+
method call on a debugger object (the debugger's own implementation), even
|
|
524
|
+
when another function of the module imports the ``pdb`` module.
|
|
525
|
+
"""
|
|
526
|
+
scope = src.parent(node)
|
|
527
|
+
while scope is not None and not isinstance(scope, (*_FUNCS, ast.Lambda)):
|
|
528
|
+
scope = src.parent(scope)
|
|
529
|
+
if scope is None:
|
|
530
|
+
return False # module level: the module-wide check covers it
|
|
531
|
+
bound = imported = False
|
|
532
|
+
for n in ast.walk(scope):
|
|
533
|
+
if (isinstance(n, ast.Name) and n.id == name and isinstance(n.ctx, ast.Store)) or (
|
|
534
|
+
isinstance(n, ast.arg) and n.arg == name
|
|
535
|
+
):
|
|
536
|
+
bound = True
|
|
537
|
+
elif isinstance(n, (ast.Import, ast.ImportFrom)) and any(
|
|
538
|
+
(a.asname or a.name.split(".")[0]) == name for a in n.names
|
|
539
|
+
):
|
|
540
|
+
imported = True
|
|
541
|
+
return bound and not imported
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _debug_guarded(src: _Source, node: ast.AST) -> bool:
|
|
545
|
+
"""Is ``node`` inside the body of an ``if``/``while`` whose condition names debugging?"""
|
|
546
|
+
current: ast.AST | None = node
|
|
547
|
+
while current is not None:
|
|
548
|
+
parent = src.parent(current)
|
|
549
|
+
if (
|
|
550
|
+
isinstance(parent, (ast.If, ast.IfExp, ast.While))
|
|
551
|
+
and current is not parent.test
|
|
552
|
+
and _mentions_debug(parent.test)
|
|
553
|
+
):
|
|
554
|
+
return True
|
|
555
|
+
current = parent
|
|
556
|
+
return False
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
@rule(
|
|
560
|
+
id="python/debugger",
|
|
561
|
+
severity="error",
|
|
562
|
+
title="Debugger breakpoint left in source",
|
|
563
|
+
languages={"python"},
|
|
564
|
+
classes={"source", "agent-config"},
|
|
565
|
+
rationale=(
|
|
566
|
+
"breakpoint() and pdb.set_trace() stop the program and wait for a debugger "
|
|
567
|
+
"session; in a server, worker or CI job that hangs it."
|
|
568
|
+
),
|
|
569
|
+
hint="Remove the breakpoint before merging.",
|
|
570
|
+
tags={"python", "debug"},
|
|
571
|
+
)
|
|
572
|
+
def debugger(ctx: FileContext) -> Iterator[Hit]:
|
|
573
|
+
"""``breakpoint()`` and ``set_trace()`` of pdb, ipdb, pudb, remote_pdb and friends
|
|
574
|
+
(also via ``from pdb import set_trace``, an import alias or ``__import__("pdb")``)
|
|
575
|
+
in non-test source.
|
|
576
|
+
|
|
577
|
+
Silent when the module binds ``breakpoint`` itself, when the function binds
|
|
578
|
+
``pdb`` to a debugger object (``pdb = Pdb()``, a parameter), for ``pdb.post_mortem`` and
|
|
579
|
+
``pdb.run`` (deliberate tooling such as a ``--pdb`` flag), and inside an ``if``
|
|
580
|
+
whose condition names debugging (``if __debug__``, ``if settings.DEBUG``,
|
|
581
|
+
``if os.environ.get("PDB")``): a guarded breakpoint is developer tooling.
|
|
582
|
+
"""
|
|
583
|
+
src = _source(ctx)
|
|
584
|
+
if src is None:
|
|
585
|
+
return
|
|
586
|
+
stored = {
|
|
587
|
+
n.id
|
|
588
|
+
for n in ast.walk(src.tree)
|
|
589
|
+
if isinstance(n, ast.Name) and not isinstance(n.ctx, ast.Load)
|
|
590
|
+
}
|
|
591
|
+
modules = set(_DEBUG_MODULES - stored) # ``pdb = Pdb()`` is a debugger object, not a call site
|
|
592
|
+
funcs: set[str] = set()
|
|
593
|
+
for node in ast.walk(src.tree):
|
|
594
|
+
if isinstance(node, ast.Import):
|
|
595
|
+
for alias in node.names:
|
|
596
|
+
if alias.name in _DEBUG_MODULES:
|
|
597
|
+
modules.add(alias.asname or alias.name)
|
|
598
|
+
elif isinstance(node, ast.ImportFrom) and node.module:
|
|
599
|
+
root = node.module.split(".")[0]
|
|
600
|
+
if root in _DEBUG_MODULES or root == "IPython":
|
|
601
|
+
for alias in node.names:
|
|
602
|
+
if alias.name in _DEBUG_FUNCS:
|
|
603
|
+
funcs.add(alias.asname or alias.name)
|
|
604
|
+
own = _bound_names(src.tree)
|
|
605
|
+
for node in ast.walk(src.tree):
|
|
606
|
+
if not isinstance(node, ast.Call):
|
|
607
|
+
continue
|
|
608
|
+
func = node.func
|
|
609
|
+
found = False
|
|
610
|
+
if isinstance(func, ast.Name):
|
|
611
|
+
found = (func.id == "breakpoint" and "breakpoint" not in own) or func.id in funcs
|
|
612
|
+
elif isinstance(func, ast.Attribute) and func.attr in _DEBUG_FUNCS:
|
|
613
|
+
base = func.value
|
|
614
|
+
if isinstance(base, ast.Name):
|
|
615
|
+
found = base.id in modules and not _bound_in_function(src, node, base.id)
|
|
616
|
+
else:
|
|
617
|
+
found = (
|
|
618
|
+
isinstance(base, ast.Call)
|
|
619
|
+
and isinstance(base.func, ast.Name)
|
|
620
|
+
and base.func.id == "__import__"
|
|
621
|
+
and bool(base.args)
|
|
622
|
+
and isinstance(base.args[0], ast.Constant)
|
|
623
|
+
and base.args[0].value in _DEBUG_MODULES
|
|
624
|
+
)
|
|
625
|
+
if found and not _debug_guarded(src, node):
|
|
626
|
+
yield src.hit(
|
|
627
|
+
node, message="debugger breakpoint stops the program", evidence=_short(func, 60)
|
|
628
|
+
)
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
_BUILTIN_EXCEPTIONS = frozenset(
|
|
632
|
+
name
|
|
633
|
+
for name, value in vars(builtins).items()
|
|
634
|
+
if isinstance(value, type) and issubclass(value, BaseException)
|
|
635
|
+
)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _exception_like(name: str) -> bool:
|
|
639
|
+
return name[:1].isupper() and name.endswith(("Error", "Exception")) and name != "Error"
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
def _expects_exception(func: ast.expr) -> bool:
|
|
643
|
+
"""A context manager that expects its body to raise or warn: ``pytest.raises``,
|
|
644
|
+
``self.assertRaises(Regex)``, ``pytest.warns``, ``deprecated_call``, or a test
|
|
645
|
+
helper such as ``self.check_suggestion(...)`` or ``expect_error(...)``."""
|
|
646
|
+
name = _final_name(func) or ""
|
|
647
|
+
lowered = name.lower()
|
|
648
|
+
return (
|
|
649
|
+
"raises" in lowered
|
|
650
|
+
or "warns" in lowered
|
|
651
|
+
or name.startswith(("assert", "expect", "check_"))
|
|
652
|
+
or name == "deprecated_call"
|
|
653
|
+
)
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def _expecting_bodies(tree: ast.AST) -> set[int]:
|
|
657
|
+
"""IDs of statements inside a ``with`` whose context manager expects an exception."""
|
|
658
|
+
inside: set[int] = set()
|
|
659
|
+
for node in ast.walk(tree):
|
|
660
|
+
if not isinstance(node, (ast.With, ast.AsyncWith)):
|
|
661
|
+
continue
|
|
662
|
+
if not any(
|
|
663
|
+
isinstance(item.context_expr, ast.Call) and _expects_exception(item.context_expr.func)
|
|
664
|
+
for item in node.items
|
|
665
|
+
):
|
|
666
|
+
continue
|
|
667
|
+
for statement in node.body:
|
|
668
|
+
inside.update(id(n) for n in ast.walk(statement))
|
|
669
|
+
return inside
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
@rule(
|
|
673
|
+
id="python/missing-raise",
|
|
674
|
+
severity="error",
|
|
675
|
+
title="Exception created but not raised",
|
|
676
|
+
languages={"python"},
|
|
677
|
+
rationale=(
|
|
678
|
+
"A statement that only constructs an exception (ValueError('bad input')) does "
|
|
679
|
+
"nothing: the 'raise' is missing, so the error case falls through."
|
|
680
|
+
),
|
|
681
|
+
hint="Add 'raise' in front of the exception.",
|
|
682
|
+
tags={"python", "correctness"},
|
|
683
|
+
)
|
|
684
|
+
def missing_raise(ctx: FileContext) -> Iterator[Hit]:
|
|
685
|
+
"""An expression statement that only calls an exception class: a builtin one
|
|
686
|
+
(``ValueError(...)``), or a CamelCase name ending in ``Error``/``Exception`` that
|
|
687
|
+
the module defines as a class or imports by name, or reaches through an imported
|
|
688
|
+
module (``errors.ValidationError(...)``).
|
|
689
|
+
|
|
690
|
+
Silent for methods (``self.LogError(...)`` in CamelCase-method code bases), for
|
|
691
|
+
a name the module defines as a function, for a bare ``Error(...)``, which
|
|
692
|
+
result-type libraries use as a constructor, and inside a ``with`` block that
|
|
693
|
+
expects an exception or warning (``pytest.raises``, ``self.assertRaises``,
|
|
694
|
+
``self.assertRaisesRegex``, ``pytest.warns``): there the constructor call is
|
|
695
|
+
the code under test.
|
|
696
|
+
"""
|
|
697
|
+
src = _source(ctx)
|
|
698
|
+
if src is None:
|
|
699
|
+
return
|
|
700
|
+
expecting = _expecting_bodies(src.tree)
|
|
701
|
+
functions: set[str] = set()
|
|
702
|
+
known: set[str] = set()
|
|
703
|
+
modules: set[str] = set()
|
|
704
|
+
for node in ast.walk(src.tree):
|
|
705
|
+
if isinstance(node, _FUNCS):
|
|
706
|
+
functions.add(node.name)
|
|
707
|
+
elif isinstance(node, ast.ClassDef):
|
|
708
|
+
known.add(node.name)
|
|
709
|
+
elif isinstance(node, ast.ImportFrom):
|
|
710
|
+
known.update(a.asname or a.name for a in node.names)
|
|
711
|
+
if node.module is None:
|
|
712
|
+
modules.update(a.asname or a.name for a in node.names)
|
|
713
|
+
elif isinstance(node, ast.Import):
|
|
714
|
+
modules.update(a.asname or a.name.split(".")[0] for a in node.names)
|
|
715
|
+
for node in ast.walk(src.tree):
|
|
716
|
+
if not isinstance(node, ast.Expr) or not isinstance(node.value, ast.Call):
|
|
717
|
+
continue
|
|
718
|
+
if id(node) in expecting:
|
|
719
|
+
continue
|
|
720
|
+
func = node.value.func
|
|
721
|
+
name = _final_name(func)
|
|
722
|
+
if name is None or name in functions:
|
|
723
|
+
continue
|
|
724
|
+
if isinstance(func, ast.Name):
|
|
725
|
+
found = name in _BUILTIN_EXCEPTIONS or (name in known and _exception_like(name))
|
|
726
|
+
else:
|
|
727
|
+
root = _dotted(func)
|
|
728
|
+
found = (
|
|
729
|
+
root is not None
|
|
730
|
+
and root.split(".")[0] in modules | known
|
|
731
|
+
and (_exception_like(name) or name in _BUILTIN_EXCEPTIONS)
|
|
732
|
+
)
|
|
733
|
+
if found:
|
|
734
|
+
yield src.hit(
|
|
735
|
+
node,
|
|
736
|
+
message=f"{name}(...) is created but never raised",
|
|
737
|
+
evidence=f"bare {_short(node.value.func, 80)}()",
|
|
738
|
+
)
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
# --- Warnings: likely bugs -------------------------------------------------------
|
|
742
|
+
|
|
743
|
+
_MUTABLE_CALLS = frozenset(
|
|
744
|
+
{"list", "dict", "set", "bytearray", "defaultdict", "OrderedDict", "deque", "Counter"}
|
|
745
|
+
)
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def _mutable(node: ast.expr) -> bool:
|
|
749
|
+
if isinstance(node, (ast.List, ast.Dict, ast.Set, ast.ListComp, ast.DictComp, ast.SetComp)):
|
|
750
|
+
return True
|
|
751
|
+
if isinstance(node, ast.Call):
|
|
752
|
+
return _final_name(node.func) in _MUTABLE_CALLS
|
|
753
|
+
return False
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
@rule(
|
|
757
|
+
id="python/mutable-default",
|
|
758
|
+
severity="warning",
|
|
759
|
+
title="Mutable default argument",
|
|
760
|
+
languages={"python"},
|
|
761
|
+
rationale=(
|
|
762
|
+
"A default value is created once, when the function is defined, so a list, dict "
|
|
763
|
+
"or set default is shared by every call and keeps what earlier calls put in it."
|
|
764
|
+
),
|
|
765
|
+
hint="Default to None and create the container inside the function.",
|
|
766
|
+
tags={"python", "correctness"},
|
|
767
|
+
)
|
|
768
|
+
def mutable_default(ctx: FileContext) -> Iterator[Hit]:
|
|
769
|
+
src = _source(ctx)
|
|
770
|
+
if src is None:
|
|
771
|
+
return
|
|
772
|
+
for node in ast.walk(src.tree):
|
|
773
|
+
if not isinstance(node, (*_FUNCS, ast.Lambda)):
|
|
774
|
+
continue
|
|
775
|
+
args = node.args
|
|
776
|
+
positional = [*args.posonlyargs, *args.args]
|
|
777
|
+
pairs = list(
|
|
778
|
+
zip(positional[len(positional) - len(args.defaults) :], args.defaults, strict=True)
|
|
779
|
+
)
|
|
780
|
+
pairs += [
|
|
781
|
+
(a, d) for a, d in zip(args.kwonlyargs, args.kw_defaults, strict=True) if d is not None
|
|
782
|
+
]
|
|
783
|
+
for arg, default in pairs:
|
|
784
|
+
if _mutable(default):
|
|
785
|
+
yield src.hit(
|
|
786
|
+
default,
|
|
787
|
+
message=f"default of '{arg.arg}' is one mutable object shared by every call",
|
|
788
|
+
evidence=f"{arg.arg}={_short(default, 80)}",
|
|
789
|
+
)
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def _reraises(handler: ast.ExceptHandler) -> bool:
|
|
793
|
+
return any(isinstance(n, ast.Raise) and n.exc is None for n in _scoped(handler.body))
|
|
794
|
+
|
|
795
|
+
|
|
796
|
+
@rule(
|
|
797
|
+
id="python/bare-except",
|
|
798
|
+
severity="warning",
|
|
799
|
+
title="Bare except catches everything",
|
|
800
|
+
languages={"python"},
|
|
801
|
+
rationale=(
|
|
802
|
+
"'except:' also catches KeyboardInterrupt, SystemExit and GeneratorExit, so Ctrl-C "
|
|
803
|
+
"and shutdown are swallowed along with real errors."
|
|
804
|
+
),
|
|
805
|
+
hint="Catch Exception (or the specific errors you expect) instead.",
|
|
806
|
+
tags={"python", "error-handling"},
|
|
807
|
+
)
|
|
808
|
+
def bare_except(ctx: FileContext) -> Iterator[Hit]:
|
|
809
|
+
"""``except:`` whose handler does not re-raise with a bare ``raise`` (cleanup then
|
|
810
|
+
re-raise is the one sound use)."""
|
|
811
|
+
src = _source(ctx)
|
|
812
|
+
if src is None:
|
|
813
|
+
return
|
|
814
|
+
for node in ast.walk(src.tree):
|
|
815
|
+
if isinstance(node, ast.ExceptHandler) and node.type is None and not _reraises(node):
|
|
816
|
+
yield src.hit(
|
|
817
|
+
node, message="bare 'except:' also catches Ctrl-C and SystemExit", end=node.lineno
|
|
818
|
+
)
|
|
819
|
+
|
|
820
|
+
|
|
821
|
+
_BROAD = frozenset({"Exception", "BaseException"})
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
def _broad(handler: ast.ExceptHandler) -> bool:
|
|
825
|
+
kind = handler.type
|
|
826
|
+
if kind is None:
|
|
827
|
+
return True
|
|
828
|
+
names = kind.elts if isinstance(kind, ast.Tuple) else [kind]
|
|
829
|
+
return any(_final_name(n) in _BROAD for n in names)
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def _does_nothing(stmt: ast.stmt) -> bool:
|
|
833
|
+
if isinstance(stmt, (ast.Pass, ast.Continue)):
|
|
834
|
+
return True
|
|
835
|
+
return isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant)
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
@rule(
|
|
839
|
+
id="python/swallowed-exception",
|
|
840
|
+
severity="warning",
|
|
841
|
+
title="Broad exception silently swallowed",
|
|
842
|
+
languages={"python"},
|
|
843
|
+
rationale=(
|
|
844
|
+
"Catching every exception and doing nothing hides bugs: the failure leaves no "
|
|
845
|
+
"trace and the program continues in an unknown state."
|
|
846
|
+
),
|
|
847
|
+
hint="Catch the specific exception you expect, or at least log it.",
|
|
848
|
+
tags={"python", "error-handling"},
|
|
849
|
+
)
|
|
850
|
+
def swallowed_exception(ctx: FileContext) -> Iterator[Hit]:
|
|
851
|
+
"""A bare ``except:``, ``except Exception`` or ``except BaseException`` (alone or in
|
|
852
|
+
a tuple) whose body is only ``pass``, ``...``, a string or ``continue``.
|
|
853
|
+
|
|
854
|
+
Narrower than "any handler that does nothing": ``except KeyError: pass`` or
|
|
855
|
+
``except ImportError: pass`` names what is expected and is deliberate.
|
|
856
|
+
"""
|
|
857
|
+
src = _source(ctx)
|
|
858
|
+
if src is None:
|
|
859
|
+
return
|
|
860
|
+
for node in ast.walk(src.tree):
|
|
861
|
+
if (
|
|
862
|
+
isinstance(node, ast.ExceptHandler)
|
|
863
|
+
and _broad(node)
|
|
864
|
+
and all(_does_nothing(s) for s in node.body)
|
|
865
|
+
):
|
|
866
|
+
caught = "except:" if node.type is None else f"except {_short(node.type, 60)}:"
|
|
867
|
+
yield src.hit(
|
|
868
|
+
node,
|
|
869
|
+
message="exception caught and ignored without a trace",
|
|
870
|
+
evidence=f"{caught} {type(node.body[0]).__name__.lower()}",
|
|
871
|
+
)
|
|
872
|
+
|
|
873
|
+
|
|
874
|
+
_TERMINATORS = (ast.Return, ast.Raise, ast.Continue, ast.Break)
|
|
875
|
+
|
|
876
|
+
|
|
877
|
+
def _harmless_dead(stmt: ast.stmt) -> bool:
|
|
878
|
+
"""``pass``, ``...`` or a bare ``yield`` after ``return``/``raise`` (the idiom that
|
|
879
|
+
turns a function into an empty generator)."""
|
|
880
|
+
if isinstance(stmt, ast.Pass):
|
|
881
|
+
return True
|
|
882
|
+
if isinstance(stmt, ast.Expr):
|
|
883
|
+
return isinstance(stmt.value, (ast.Constant, ast.Yield, ast.YieldFrom))
|
|
884
|
+
return False
|
|
885
|
+
|
|
886
|
+
|
|
887
|
+
@rule(
|
|
888
|
+
id="python/unreachable-code",
|
|
889
|
+
severity="warning",
|
|
890
|
+
title="Code after return, raise, break or continue",
|
|
891
|
+
languages={"python"},
|
|
892
|
+
rationale=(
|
|
893
|
+
"Statements after return, raise, break or continue in the same block never run; "
|
|
894
|
+
"usually a misplaced line or a leftover early return."
|
|
895
|
+
),
|
|
896
|
+
hint="Remove the dead code or move the return.",
|
|
897
|
+
tags={"python", "correctness"},
|
|
898
|
+
)
|
|
899
|
+
def unreachable_code(ctx: FileContext) -> Iterator[Hit]:
|
|
900
|
+
"""Spans from the terminating statement to the end of the dead code, so adding
|
|
901
|
+
either reports. Dead ``pass``/``...``/``yield`` alone is the empty-generator idiom
|
|
902
|
+
and stays silent."""
|
|
903
|
+
src = _source(ctx)
|
|
904
|
+
if src is None:
|
|
905
|
+
return
|
|
906
|
+
for block in _blocks(src.tree):
|
|
907
|
+
for i, stmt in enumerate(block[:-1]):
|
|
908
|
+
if not isinstance(stmt, _TERMINATORS):
|
|
909
|
+
continue
|
|
910
|
+
dead = block[i + 1 :]
|
|
911
|
+
if all(_harmless_dead(s) for s in dead):
|
|
912
|
+
break
|
|
913
|
+
word = type(stmt).__name__.lower()
|
|
914
|
+
first = _short(dead[0], 80).split("\n")[0]
|
|
915
|
+
yield src.hit(
|
|
916
|
+
stmt,
|
|
917
|
+
message=f"code after '{word}' never runs (line {src.line(dead[0].lineno)})",
|
|
918
|
+
evidence=f"{word} then {first}",
|
|
919
|
+
end=dead[-1].end_lineno or dead[-1].lineno,
|
|
920
|
+
)
|
|
921
|
+
break
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
@rule(
|
|
925
|
+
id="python/redefined-function",
|
|
926
|
+
severity="warning",
|
|
927
|
+
title="Function redefined before use",
|
|
928
|
+
languages={"python"},
|
|
929
|
+
rationale=(
|
|
930
|
+
"A second def with the same name in the same block replaces the first before "
|
|
931
|
+
"anything used it, so one of them is dead code, often a copy-paste slip that "
|
|
932
|
+
"hides a test or a method."
|
|
933
|
+
),
|
|
934
|
+
hint="Rename one of the functions or remove the stale one.",
|
|
935
|
+
tags={"python", "correctness"},
|
|
936
|
+
)
|
|
937
|
+
def redefined_function(ctx: FileContext) -> Iterator[Hit]:
|
|
938
|
+
"""Same name defined twice in one statement list with no use of the name in
|
|
939
|
+
between.
|
|
940
|
+
|
|
941
|
+
Silent for ``@overload`` stubs, for a later def whose decorator names the
|
|
942
|
+
function (``@x.setter``, ``@handler.register``), for ``_`` and for conditional
|
|
943
|
+
definitions (``if``/``else`` and ``try``/``except`` are separate blocks).
|
|
944
|
+
"""
|
|
945
|
+
src = _source(ctx)
|
|
946
|
+
if src is None:
|
|
947
|
+
return
|
|
948
|
+
for block in _blocks(src.tree):
|
|
949
|
+
seen: dict[str, ast.stmt] = {}
|
|
950
|
+
for stmt in block:
|
|
951
|
+
if isinstance(stmt, _FUNCS):
|
|
952
|
+
name = stmt.name
|
|
953
|
+
deco_uses = {
|
|
954
|
+
n.id
|
|
955
|
+
for d in stmt.decorator_list
|
|
956
|
+
for n in ast.walk(d)
|
|
957
|
+
if isinstance(n, ast.Name)
|
|
958
|
+
}
|
|
959
|
+
earlier = seen.get(name)
|
|
960
|
+
if (
|
|
961
|
+
earlier is not None
|
|
962
|
+
and name != "_"
|
|
963
|
+
and name not in deco_uses
|
|
964
|
+
and "overload" not in _decorator_names(stmt)
|
|
965
|
+
and "overload" not in _decorator_names(earlier)
|
|
966
|
+
):
|
|
967
|
+
yield src.hit(
|
|
968
|
+
stmt,
|
|
969
|
+
message=(
|
|
970
|
+
f"'{name}' redefined; the definition on line "
|
|
971
|
+
f"{src.line(earlier.lineno)} is never used"
|
|
972
|
+
),
|
|
973
|
+
evidence=f"def {name}",
|
|
974
|
+
end=_header_end(stmt),
|
|
975
|
+
)
|
|
976
|
+
for used in deco_uses:
|
|
977
|
+
seen.pop(used, None)
|
|
978
|
+
for child in stmt.args.defaults + [d for d in stmt.args.kw_defaults if d]:
|
|
979
|
+
for n in ast.walk(child):
|
|
980
|
+
if isinstance(n, ast.Name):
|
|
981
|
+
seen.pop(n.id, None)
|
|
982
|
+
seen[name] = stmt
|
|
983
|
+
continue
|
|
984
|
+
for n in ast.walk(stmt):
|
|
985
|
+
if isinstance(n, ast.Name):
|
|
986
|
+
seen.pop(n.id, None)
|
|
987
|
+
elif isinstance(n, (*_FUNCS, ast.ClassDef)) and n is not stmt:
|
|
988
|
+
seen.pop(n.name, None)
|
|
989
|
+
if isinstance(stmt, ast.ClassDef):
|
|
990
|
+
seen.pop(stmt.name, None)
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
@rule(
|
|
994
|
+
id="python/star-import",
|
|
995
|
+
severity="warning",
|
|
996
|
+
title="Wildcard import",
|
|
997
|
+
languages={"python"},
|
|
998
|
+
rationale=(
|
|
999
|
+
"'from module import *' pulls in names nobody can see at the import site; they "
|
|
1000
|
+
"can shadow builtins or local names and change when the module changes."
|
|
1001
|
+
),
|
|
1002
|
+
hint="Import the names you use explicitly.",
|
|
1003
|
+
tags={"python", "maintainability"},
|
|
1004
|
+
)
|
|
1005
|
+
def star_import(ctx: FileContext) -> Iterator[Hit]:
|
|
1006
|
+
"""Silent for relative star imports in a package's ``__init__.py`` (re-exports)."""
|
|
1007
|
+
src = _source(ctx)
|
|
1008
|
+
if src is None:
|
|
1009
|
+
return
|
|
1010
|
+
init = _path_parts(ctx.path)[-1:] == ["__init__.py"]
|
|
1011
|
+
for node in ast.walk(src.tree):
|
|
1012
|
+
if not isinstance(node, ast.ImportFrom) or not any(a.name == "*" for a in node.names):
|
|
1013
|
+
continue
|
|
1014
|
+
if init and node.level > 0:
|
|
1015
|
+
continue
|
|
1016
|
+
module = "." * node.level + (node.module or "")
|
|
1017
|
+
yield src.hit(
|
|
1018
|
+
node, message=f"wildcard import from {module}", evidence=f"from {module} import *"
|
|
1019
|
+
)
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
_CLIENT_CONSTRUCTORS = {"requests": ("Session", "session"), "httpx": ("Client", "AsyncClient")}
|
|
1023
|
+
_HTTP_METHODS = frozenset({"get", "post", "put", "patch", "delete", "request", "head", "options"})
|
|
1024
|
+
|
|
1025
|
+
|
|
1026
|
+
def _timeout_problem(call: ast.Call, *, missing_counts: bool) -> str | None:
|
|
1027
|
+
"""Why ``call`` has no usable timeout, or ``None`` when it has one or may have one."""
|
|
1028
|
+
for kw in call.keywords:
|
|
1029
|
+
if kw.arg is None:
|
|
1030
|
+
return None # **kwargs may carry a timeout
|
|
1031
|
+
if kw.arg == "timeout":
|
|
1032
|
+
if isinstance(kw.value, ast.Constant) and kw.value.value is None:
|
|
1033
|
+
return "timeout=None"
|
|
1034
|
+
return None
|
|
1035
|
+
if len(call.args) >= 8:
|
|
1036
|
+
return None # Session.request takes timeout positionally
|
|
1037
|
+
return "no timeout" if missing_counts else None
|
|
1038
|
+
|
|
1039
|
+
|
|
1040
|
+
@rule(
|
|
1041
|
+
id="python/requests-without-timeout",
|
|
1042
|
+
severity="warning",
|
|
1043
|
+
title="HTTP request without a timeout",
|
|
1044
|
+
languages={"python"},
|
|
1045
|
+
rationale=(
|
|
1046
|
+
"requests waits forever by default, so a server that stops answering hangs the "
|
|
1047
|
+
"caller (a worker, a web request, a CI job) indefinitely. httpx has a 5-second "
|
|
1048
|
+
"default, but timeout=None disables it."
|
|
1049
|
+
),
|
|
1050
|
+
hint="Pass timeout=(connect, read) seconds.",
|
|
1051
|
+
tags={"python", "reliability"},
|
|
1052
|
+
)
|
|
1053
|
+
def requests_without_timeout(ctx: FileContext) -> Iterator[Hit]:
|
|
1054
|
+
"""requests calls (``requests.get`` and the other verbs, names imported from
|
|
1055
|
+
requests, and methods of a ``requests.Session()`` assigned or bound with ``with``)
|
|
1056
|
+
without ``timeout=`` or with ``timeout=None``.
|
|
1057
|
+
|
|
1058
|
+
httpx is refined against the catalogue: httpx functions and clients default to a
|
|
1059
|
+
5 s timeout, so a missing ``timeout=`` is not a hang. They are reported only when
|
|
1060
|
+
``timeout=None`` turns the default off (on the call, or on a client created with
|
|
1061
|
+
``timeout=None`` whose call sets no timeout). A call with ``**kwargs`` may carry a
|
|
1062
|
+
timeout and stays silent. Modules count only when the file imports them.
|
|
1063
|
+
"""
|
|
1064
|
+
src = _source(ctx)
|
|
1065
|
+
if src is None:
|
|
1066
|
+
return
|
|
1067
|
+
lib_alias: dict[str, str] = {} # local name -> "requests" | "httpx"
|
|
1068
|
+
lib_funcs: dict[str, str] = {} # from requests import get -> {"get": "requests"}
|
|
1069
|
+
lib_classes: dict[str, str] = {} # Session / Client -> library
|
|
1070
|
+
for node in ast.walk(src.tree):
|
|
1071
|
+
if isinstance(node, ast.Import):
|
|
1072
|
+
for alias in node.names:
|
|
1073
|
+
if alias.name in ("requests", "httpx"):
|
|
1074
|
+
lib_alias[alias.asname or alias.name] = alias.name
|
|
1075
|
+
elif isinstance(node, ast.ImportFrom) and node.module in ("requests", "httpx"):
|
|
1076
|
+
for alias in node.names:
|
|
1077
|
+
local = alias.asname or alias.name
|
|
1078
|
+
if alias.name in _HTTP_METHODS:
|
|
1079
|
+
lib_funcs[local] = node.module
|
|
1080
|
+
elif alias.name in ("Session", "session", "Client", "AsyncClient"):
|
|
1081
|
+
lib_classes[local] = node.module
|
|
1082
|
+
if not lib_alias and not lib_funcs and not lib_classes:
|
|
1083
|
+
return
|
|
1084
|
+
|
|
1085
|
+
def client_kind(value: ast.expr) -> str | None:
|
|
1086
|
+
"""``requests``, ``httpx`` (default timeout) or ``httpx-none`` for a client call."""
|
|
1087
|
+
if not isinstance(value, ast.Call):
|
|
1088
|
+
return None
|
|
1089
|
+
func = value.func
|
|
1090
|
+
lib = None
|
|
1091
|
+
if isinstance(func, ast.Name):
|
|
1092
|
+
lib = lib_classes.get(func.id)
|
|
1093
|
+
elif isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name):
|
|
1094
|
+
owner = lib_alias.get(func.value.id)
|
|
1095
|
+
constructors = _CLIENT_CONSTRUCTORS.get(owner or "", ())
|
|
1096
|
+
if func.attr in constructors:
|
|
1097
|
+
lib = owner
|
|
1098
|
+
if lib != "httpx":
|
|
1099
|
+
return lib
|
|
1100
|
+
if _timeout_problem(value, missing_counts=False) == "timeout=None":
|
|
1101
|
+
return "httpx-none"
|
|
1102
|
+
return "httpx"
|
|
1103
|
+
|
|
1104
|
+
clients: dict[str, str] = {}
|
|
1105
|
+
for node in ast.walk(src.tree):
|
|
1106
|
+
pairs: list[tuple[ast.expr, ast.expr]] = []
|
|
1107
|
+
if isinstance(node, ast.Assign):
|
|
1108
|
+
pairs = [(t, node.value) for t in node.targets]
|
|
1109
|
+
elif isinstance(node, ast.AnnAssign) and node.value is not None:
|
|
1110
|
+
pairs = [(node.target, node.value)]
|
|
1111
|
+
elif isinstance(node, (ast.With, ast.AsyncWith)):
|
|
1112
|
+
pairs = [(i.optional_vars, i.context_expr) for i in node.items if i.optional_vars]
|
|
1113
|
+
for target, value in pairs:
|
|
1114
|
+
name = _dotted(target)
|
|
1115
|
+
kind = client_kind(value)
|
|
1116
|
+
if name is not None and kind is not None:
|
|
1117
|
+
clients[name] = kind
|
|
1118
|
+
for node in ast.walk(src.tree):
|
|
1119
|
+
if not isinstance(node, ast.Call):
|
|
1120
|
+
continue
|
|
1121
|
+
func = node.func
|
|
1122
|
+
lib = None
|
|
1123
|
+
if isinstance(func, ast.Name):
|
|
1124
|
+
lib = lib_funcs.get(func.id)
|
|
1125
|
+
elif isinstance(func, ast.Attribute) and func.attr in _HTTP_METHODS:
|
|
1126
|
+
owner = func.value
|
|
1127
|
+
if isinstance(owner, ast.Name) and owner.id in lib_alias:
|
|
1128
|
+
lib = lib_alias[owner.id]
|
|
1129
|
+
else:
|
|
1130
|
+
name = _dotted(owner)
|
|
1131
|
+
lib = clients.get(name) if name is not None else None
|
|
1132
|
+
if lib is None and isinstance(owner, ast.Call):
|
|
1133
|
+
lib = client_kind(owner)
|
|
1134
|
+
if lib is None:
|
|
1135
|
+
continue
|
|
1136
|
+
problem = _timeout_problem(node, missing_counts=lib in ("requests", "httpx-none"))
|
|
1137
|
+
if problem is None:
|
|
1138
|
+
continue
|
|
1139
|
+
yield src.hit(
|
|
1140
|
+
node,
|
|
1141
|
+
message=f"HTTP call with {problem} can wait forever",
|
|
1142
|
+
evidence=f"{_short(func, 60)} {problem}",
|
|
1143
|
+
)
|
|
1144
|
+
|
|
1145
|
+
|
|
1146
|
+
# --- signature-break -------------------------------------------------------------
|
|
1147
|
+
|
|
1148
|
+
_PUBLIC_DUNDERS = frozenset({"__init__", "__new__", "__call__"})
|
|
1149
|
+
_ACCESSOR_DECORATORS = frozenset(
|
|
1150
|
+
{"property", "cached_property", "setter", "getter", "deleter", "overload"}
|
|
1151
|
+
)
|
|
1152
|
+
|
|
1153
|
+
|
|
1154
|
+
def _public(name: str) -> bool:
|
|
1155
|
+
return not name.startswith("_") or name in _PUBLIC_DUNDERS
|
|
1156
|
+
|
|
1157
|
+
|
|
1158
|
+
def _api(tree: ast.Module) -> dict[str, ast.FunctionDef | ast.AsyncFunctionDef | None]:
|
|
1159
|
+
"""Public module functions and methods of public module classes, by qualified name.
|
|
1160
|
+
|
|
1161
|
+
A name defined more than once on one side maps to ``None`` (ambiguous).
|
|
1162
|
+
"""
|
|
1163
|
+
found: dict[str, ast.FunctionDef | ast.AsyncFunctionDef | None] = {}
|
|
1164
|
+
|
|
1165
|
+
def add(key: str, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
|
|
1166
|
+
found[key] = None if key in found else node
|
|
1167
|
+
|
|
1168
|
+
for stmt in tree.body:
|
|
1169
|
+
if isinstance(stmt, _FUNCS) and not stmt.name.startswith("_"):
|
|
1170
|
+
add(stmt.name, stmt)
|
|
1171
|
+
elif isinstance(stmt, ast.ClassDef) and not stmt.name.startswith("_"):
|
|
1172
|
+
for item in stmt.body:
|
|
1173
|
+
if isinstance(item, _FUNCS) and _public(item.name):
|
|
1174
|
+
add(f"{stmt.name}.{item.name}", item)
|
|
1175
|
+
return found
|
|
1176
|
+
|
|
1177
|
+
|
|
1178
|
+
def _signature_break(
|
|
1179
|
+
old: ast.FunctionDef | ast.AsyncFunctionDef, new: ast.FunctionDef | ast.AsyncFunctionDef
|
|
1180
|
+
) -> str | None:
|
|
1181
|
+
"""How ``new`` breaks callers of ``old``, or ``None``."""
|
|
1182
|
+
o, n = old.args, new.args
|
|
1183
|
+
old_pos = [*o.posonlyargs, *o.args]
|
|
1184
|
+
new_pos = [*n.posonlyargs, *n.args]
|
|
1185
|
+
old_required = len(old_pos) - len(o.defaults)
|
|
1186
|
+
new_required = len(new_pos) - len(n.defaults)
|
|
1187
|
+
old_posonly = len(o.posonlyargs)
|
|
1188
|
+
new_posonly = len(n.posonlyargs)
|
|
1189
|
+
for i, arg in enumerate(old_pos[:old_required]):
|
|
1190
|
+
if i >= len(new_pos):
|
|
1191
|
+
if n.vararg is None:
|
|
1192
|
+
return f"required parameter '{arg.arg}' was removed"
|
|
1193
|
+
continue
|
|
1194
|
+
other = new_pos[i]
|
|
1195
|
+
if i >= old_posonly and n.kwarg is None:
|
|
1196
|
+
if other.arg != arg.arg:
|
|
1197
|
+
if any(p.arg == arg.arg for p in [*new_pos, *n.kwonlyargs]):
|
|
1198
|
+
return f"required parameter '{arg.arg}' moved"
|
|
1199
|
+
return f"required parameter '{arg.arg}' was renamed to '{other.arg}'"
|
|
1200
|
+
if i < new_posonly:
|
|
1201
|
+
return f"required parameter '{arg.arg}' became positional-only"
|
|
1202
|
+
new_kw = {p.arg for p in [*new_pos[new_posonly:], *n.kwonlyargs]}
|
|
1203
|
+
for arg, default in zip(o.kwonlyargs, o.kw_defaults, strict=True):
|
|
1204
|
+
if default is None and arg.arg not in new_kw and n.kwarg is None:
|
|
1205
|
+
return f"required keyword parameter '{arg.arg}' was removed"
|
|
1206
|
+
old_kw_required = {a.arg for a, d in zip(o.kwonlyargs, o.kw_defaults, strict=True) if d is None}
|
|
1207
|
+
for i in range(old_required, new_required):
|
|
1208
|
+
arg = new_pos[i]
|
|
1209
|
+
if arg.arg in old_kw_required and i >= new_posonly:
|
|
1210
|
+
continue # every caller already passed it by keyword
|
|
1211
|
+
if i < len(old_pos) and old_pos[i].arg == arg.arg:
|
|
1212
|
+
return f"parameter '{arg.arg}' is now required"
|
|
1213
|
+
return f"new required parameter '{arg.arg}'"
|
|
1214
|
+
old_names = {p.arg: p for p in [*old_pos, *o.kwonlyargs]}
|
|
1215
|
+
old_pos_required = {a.arg for a in old_pos[:old_required]}
|
|
1216
|
+
for arg, default in zip(n.kwonlyargs, n.kw_defaults, strict=True):
|
|
1217
|
+
if default is None and (
|
|
1218
|
+
arg.arg not in old_names
|
|
1219
|
+
or (arg.arg not in old_kw_required and arg.arg not in old_pos_required)
|
|
1220
|
+
):
|
|
1221
|
+
return f"new required keyword parameter '{arg.arg}'"
|
|
1222
|
+
return None
|
|
1223
|
+
|
|
1224
|
+
|
|
1225
|
+
def _private_module(path: str) -> bool:
|
|
1226
|
+
parts = _path_parts(path)
|
|
1227
|
+
return any(p.startswith("_") and p not in ("__init__.py", "__main__.py") for p in parts)
|
|
1228
|
+
|
|
1229
|
+
|
|
1230
|
+
@rule(
|
|
1231
|
+
id="python/signature-break",
|
|
1232
|
+
severity="warning",
|
|
1233
|
+
title="Public function signature breaks callers",
|
|
1234
|
+
languages={"python"},
|
|
1235
|
+
classes={"source", "agent-config"},
|
|
1236
|
+
introduced_only=False,
|
|
1237
|
+
rationale=(
|
|
1238
|
+
"Removing, renaming or reordering a required parameter of a public function, or "
|
|
1239
|
+
"adding a new required one, breaks every existing caller, including code outside "
|
|
1240
|
+
"this repository."
|
|
1241
|
+
),
|
|
1242
|
+
hint="Keep the old parameters (with defaults or a deprecation path) or update every caller.",
|
|
1243
|
+
tags={"python", "api"},
|
|
1244
|
+
)
|
|
1245
|
+
def signature_break(ctx: FileContext) -> Iterator[Hit]:
|
|
1246
|
+
"""Old and new AST compared for module functions and methods of module-level
|
|
1247
|
+
classes whose names have no leading underscore (``__init__``, ``__new__`` and
|
|
1248
|
+
``__call__`` count as public: they are the class's call signature).
|
|
1249
|
+
|
|
1250
|
+
Ignored: private names, test files, modules under a ``_private`` path segment,
|
|
1251
|
+
names defined twice on one side, properties and ``@overload`` stubs, and a
|
|
1252
|
+
change between plain, ``staticmethod`` and ``classmethod``. A new ``*args`` or
|
|
1253
|
+
``**kwargs`` absorbs removed and renamed parameters. Removing an optional
|
|
1254
|
+
parameter is not reported (the catalogue targets required ones).
|
|
1255
|
+
"""
|
|
1256
|
+
src = _source(ctx)
|
|
1257
|
+
old_tree = ctx.old_python_ast
|
|
1258
|
+
if src is None or old_tree is None or _private_module(ctx.path):
|
|
1259
|
+
return
|
|
1260
|
+
old_api = _api(old_tree)
|
|
1261
|
+
for key, new in _api(src.tree).items():
|
|
1262
|
+
old = old_api.get(key)
|
|
1263
|
+
if new is None or old is None:
|
|
1264
|
+
continue
|
|
1265
|
+
new_decos, old_decos = _decorator_names(new), _decorator_names(old)
|
|
1266
|
+
if (new_decos | old_decos) & _ACCESSOR_DECORATORS:
|
|
1267
|
+
continue
|
|
1268
|
+
binding = {"staticmethod", "classmethod"}
|
|
1269
|
+
if new_decos & binding != old_decos & binding:
|
|
1270
|
+
continue
|
|
1271
|
+
reason = _signature_break(old, new)
|
|
1272
|
+
if reason is not None:
|
|
1273
|
+
kind = "method" if "." in key else "function"
|
|
1274
|
+
yield src.hit(new, message=f"public {kind} '{key}': {reason}", end=_header_end(new))
|
|
1275
|
+
|
|
1276
|
+
|
|
1277
|
+
# --- loop-closure ------------------------------------------------------------------
|
|
1278
|
+
|
|
1279
|
+
_DEFERRED_CALLS = frozenset(
|
|
1280
|
+
{
|
|
1281
|
+
"append",
|
|
1282
|
+
"appendleft",
|
|
1283
|
+
"add",
|
|
1284
|
+
"insert",
|
|
1285
|
+
"extend",
|
|
1286
|
+
"setdefault",
|
|
1287
|
+
"register",
|
|
1288
|
+
"connect",
|
|
1289
|
+
"submit",
|
|
1290
|
+
"Thread",
|
|
1291
|
+
"Timer",
|
|
1292
|
+
"Process",
|
|
1293
|
+
"call_soon",
|
|
1294
|
+
"call_soon_threadsafe",
|
|
1295
|
+
"call_later",
|
|
1296
|
+
"call_at",
|
|
1297
|
+
"add_done_callback",
|
|
1298
|
+
"after",
|
|
1299
|
+
"after_idle",
|
|
1300
|
+
"bind",
|
|
1301
|
+
"subscribe",
|
|
1302
|
+
"add_listener",
|
|
1303
|
+
"add_callback",
|
|
1304
|
+
"add_handler",
|
|
1305
|
+
"on",
|
|
1306
|
+
"schedule",
|
|
1307
|
+
}
|
|
1308
|
+
)
|
|
1309
|
+
_DEFERRED_KEYWORDS = frozenset({"target", "callback", "command", "handler", "on_click"})
|
|
1310
|
+
|
|
1311
|
+
|
|
1312
|
+
def _escapes(src: _Source, node: ast.AST) -> bool:
|
|
1313
|
+
"""Does the value ``node`` outlive the current iteration (stored, registered, yielded)?"""
|
|
1314
|
+
parent = src.parent(node)
|
|
1315
|
+
if isinstance(parent, ast.keyword):
|
|
1316
|
+
call = src.parent(parent)
|
|
1317
|
+
if parent.arg in _DEFERRED_KEYWORDS:
|
|
1318
|
+
return True
|
|
1319
|
+
return isinstance(call, ast.Call) and _final_name(call.func) in _DEFERRED_CALLS
|
|
1320
|
+
if isinstance(parent, ast.Call):
|
|
1321
|
+
return node is not parent.func and _final_name(parent.func) in _DEFERRED_CALLS
|
|
1322
|
+
if isinstance(parent, (ast.List, ast.Tuple, ast.Set, ast.Dict)):
|
|
1323
|
+
return True
|
|
1324
|
+
if isinstance(parent, (ast.Yield, ast.YieldFrom)):
|
|
1325
|
+
return True
|
|
1326
|
+
if isinstance(parent, (ast.Assign, ast.AnnAssign)) and node is parent.value:
|
|
1327
|
+
targets = parent.targets if isinstance(parent, ast.Assign) else [parent.target]
|
|
1328
|
+
return any(isinstance(t, (ast.Subscript, ast.Attribute)) for t in targets)
|
|
1329
|
+
return False
|
|
1330
|
+
|
|
1331
|
+
|
|
1332
|
+
def _free_reads(func: ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda) -> set[str]:
|
|
1333
|
+
"""Names ``func`` reads but does not bind itself (parameters or local stores)."""
|
|
1334
|
+
args = func.args
|
|
1335
|
+
params = {a.arg for a in [*args.posonlyargs, *args.args, *args.kwonlyargs]}
|
|
1336
|
+
if args.vararg:
|
|
1337
|
+
params.add(args.vararg.arg)
|
|
1338
|
+
if args.kwarg:
|
|
1339
|
+
params.add(args.kwarg.arg)
|
|
1340
|
+
body: list[ast.AST] = [func.body] if isinstance(func, ast.Lambda) else list(func.body)
|
|
1341
|
+
loads: set[str] = set()
|
|
1342
|
+
stores: set[str] = set()
|
|
1343
|
+
for root in body:
|
|
1344
|
+
for node in ast.walk(root):
|
|
1345
|
+
if isinstance(node, ast.Name):
|
|
1346
|
+
(loads if isinstance(node.ctx, ast.Load) else stores).add(node.id)
|
|
1347
|
+
return loads - params - stores
|
|
1348
|
+
|
|
1349
|
+
|
|
1350
|
+
def _target_names(target: ast.expr) -> set[str]:
|
|
1351
|
+
return {n.id for n in ast.walk(target) if isinstance(n, ast.Name)}
|
|
1352
|
+
|
|
1353
|
+
|
|
1354
|
+
@rule(
|
|
1355
|
+
id="python/loop-closure",
|
|
1356
|
+
severity="warning",
|
|
1357
|
+
title="Closure captures a loop variable late",
|
|
1358
|
+
languages={"python"},
|
|
1359
|
+
rationale=(
|
|
1360
|
+
"A lambda or nested def reads the loop variable when it is called, not when it "
|
|
1361
|
+
"is created, so every closure made in the loop sees the last value."
|
|
1362
|
+
),
|
|
1363
|
+
hint="Bind the value as a default argument (lambda i=i: ...) or use functools.partial.",
|
|
1364
|
+
tags={"python", "correctness"},
|
|
1365
|
+
)
|
|
1366
|
+
def loop_closure(ctx: FileContext) -> Iterator[Hit]:
|
|
1367
|
+
"""A lambda or nested def created in a ``for`` body (or a comprehension element)
|
|
1368
|
+
that reads the loop variable without binding it as a default, and that outlives
|
|
1369
|
+
the iteration: stored in a container, subscript or attribute, passed to a
|
|
1370
|
+
registering call (``append``, ``submit``, ``Thread``, ``connect``,
|
|
1371
|
+
``call_later``, ``target=``/``callback=``...), yielded, or decorated.
|
|
1372
|
+
|
|
1373
|
+
A closure used at once (``sorted(..., key=lambda x: x[i])``) is correct and
|
|
1374
|
+
stays silent; ``while`` loops have no loop variable and are not checked.
|
|
1375
|
+
"""
|
|
1376
|
+
src = _source(ctx)
|
|
1377
|
+
if src is None:
|
|
1378
|
+
return
|
|
1379
|
+
for loop in ast.walk(src.tree):
|
|
1380
|
+
if isinstance(loop, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)):
|
|
1381
|
+
names = set().union(*(_target_names(g.target) for g in loop.generators))
|
|
1382
|
+
elts = [loop.key, loop.value] if isinstance(loop, ast.DictComp) else [loop.elt]
|
|
1383
|
+
for elt in elts:
|
|
1384
|
+
items = elt.elts if isinstance(elt, (ast.Tuple, ast.List)) else [elt]
|
|
1385
|
+
for item in items:
|
|
1386
|
+
if isinstance(item, ast.Lambda):
|
|
1387
|
+
captured = sorted(_free_reads(item) & names)
|
|
1388
|
+
if captured:
|
|
1389
|
+
yield _closure_hit(src, item, captured[0])
|
|
1390
|
+
continue
|
|
1391
|
+
if not isinstance(loop, (ast.For, ast.AsyncFor)):
|
|
1392
|
+
continue
|
|
1393
|
+
names = _target_names(loop.target)
|
|
1394
|
+
body = list(_scoped(loop.body))
|
|
1395
|
+
for node in body:
|
|
1396
|
+
if not isinstance(node, (*_FUNCS, ast.Lambda)):
|
|
1397
|
+
continue
|
|
1398
|
+
captured = sorted(_free_reads(node) & names)
|
|
1399
|
+
if not captured:
|
|
1400
|
+
continue
|
|
1401
|
+
if isinstance(node, ast.Lambda):
|
|
1402
|
+
escaped = _escapes(src, node)
|
|
1403
|
+
parent = src.parent(node)
|
|
1404
|
+
if not escaped and isinstance(parent, ast.Assign) and node is parent.value:
|
|
1405
|
+
local = {t.id for t in parent.targets if isinstance(t, ast.Name)}
|
|
1406
|
+
escaped = _name_escapes(src, body, local)
|
|
1407
|
+
else:
|
|
1408
|
+
escaped = bool(node.decorator_list) or _name_escapes(src, body, {node.name})
|
|
1409
|
+
if escaped:
|
|
1410
|
+
yield _closure_hit(src, node, captured[0])
|
|
1411
|
+
|
|
1412
|
+
|
|
1413
|
+
def _name_escapes(src: _Source, body: list[ast.AST], names: set[str]) -> bool:
|
|
1414
|
+
return any(
|
|
1415
|
+
isinstance(n, ast.Name)
|
|
1416
|
+
and isinstance(n.ctx, ast.Load)
|
|
1417
|
+
and n.id in names
|
|
1418
|
+
and _escapes(src, n)
|
|
1419
|
+
for n in body
|
|
1420
|
+
)
|
|
1421
|
+
|
|
1422
|
+
|
|
1423
|
+
def _closure_hit(src: _Source, node: ast.AST, name: str) -> Hit:
|
|
1424
|
+
kind = "lambda" if isinstance(node, ast.Lambda) else "nested function"
|
|
1425
|
+
end = None if isinstance(node, ast.Lambda) else _header_end(node)
|
|
1426
|
+
return src.hit(
|
|
1427
|
+
node,
|
|
1428
|
+
message=f"{kind} reads loop variable '{name}' late; it sees the last value",
|
|
1429
|
+
evidence=f"{kind} reads loop variable {name}",
|
|
1430
|
+
end=end,
|
|
1431
|
+
)
|
|
1432
|
+
|
|
1433
|
+
|
|
1434
|
+
# --- Notes -------------------------------------------------------------------------
|
|
1435
|
+
|
|
1436
|
+
|
|
1437
|
+
@rule(
|
|
1438
|
+
id="python/raise-without-from",
|
|
1439
|
+
severity="note",
|
|
1440
|
+
title="Exception re-raised without 'from'",
|
|
1441
|
+
languages={"python"},
|
|
1442
|
+
rationale=(
|
|
1443
|
+
"Raising a new exception inside 'except' without 'from' reports the original as "
|
|
1444
|
+
"'During handling ... another exception occurred', which reads like a second bug."
|
|
1445
|
+
),
|
|
1446
|
+
hint="Write 'raise NewError(...) from exc' (or 'from None' to hide the cause).",
|
|
1447
|
+
tags={"python", "error-handling"},
|
|
1448
|
+
)
|
|
1449
|
+
def raise_without_from(ctx: FileContext) -> Iterator[Hit]:
|
|
1450
|
+
"""``raise X(...)`` or ``raise X`` (a CamelCase class) inside an ``except`` body of
|
|
1451
|
+
the same function, without ``from``. Re-raising the caught name, a bare ``raise``,
|
|
1452
|
+
``.with_traceback(...)`` and ``SystemExit``/``KeyboardInterrupt`` (an exit, not a
|
|
1453
|
+
translated error) stay silent."""
|
|
1454
|
+
src = _source(ctx)
|
|
1455
|
+
if src is None:
|
|
1456
|
+
return
|
|
1457
|
+
for handler in ast.walk(src.tree):
|
|
1458
|
+
if not isinstance(handler, ast.ExceptHandler):
|
|
1459
|
+
continue
|
|
1460
|
+
for node in _scoped(handler.body):
|
|
1461
|
+
if not isinstance(node, ast.Raise) or node.exc is None or node.cause is not None:
|
|
1462
|
+
continue
|
|
1463
|
+
exc = node.exc
|
|
1464
|
+
target = exc.func if isinstance(exc, ast.Call) else exc
|
|
1465
|
+
name = _final_name(target)
|
|
1466
|
+
if (
|
|
1467
|
+
name is None
|
|
1468
|
+
or not name[:1].isupper()
|
|
1469
|
+
or name in ("SystemExit", "KeyboardInterrupt")
|
|
1470
|
+
or not isinstance(target, (ast.Name, ast.Attribute))
|
|
1471
|
+
):
|
|
1472
|
+
continue
|
|
1473
|
+
yield src.hit(
|
|
1474
|
+
node,
|
|
1475
|
+
message="exception raised in 'except' without 'from'",
|
|
1476
|
+
evidence=f"raise {_short(target, 80)}",
|
|
1477
|
+
)
|
|
1478
|
+
|
|
1479
|
+
|
|
1480
|
+
_QUERY_CALLS = frozenset(
|
|
1481
|
+
{"filter", "where", "filter_by", "having", "join", "outerjoin", "case", "and_", "or_", "not_"}
|
|
1482
|
+
)
|
|
1483
|
+
|
|
1484
|
+
|
|
1485
|
+
@rule(
|
|
1486
|
+
id="python/eq-none",
|
|
1487
|
+
severity="note",
|
|
1488
|
+
title="Comparison to None with == or !=",
|
|
1489
|
+
languages={"python"},
|
|
1490
|
+
rationale=(
|
|
1491
|
+
"== None calls the operand's __eq__, which may be overridden (NumPy, pandas); "
|
|
1492
|
+
"'is None' is the exact, idiomatic test."
|
|
1493
|
+
),
|
|
1494
|
+
hint="Use 'is None' or 'is not None'.",
|
|
1495
|
+
tags={"python", "style"},
|
|
1496
|
+
)
|
|
1497
|
+
def eq_none(ctx: FileContext) -> Iterator[Hit]:
|
|
1498
|
+
"""Silent inside query-builder calls (``filter``, ``where``, ``and_``...), where
|
|
1499
|
+
SQLAlchemy and similar libraries need ``== None`` to build ``IS NULL``."""
|
|
1500
|
+
src = _source(ctx)
|
|
1501
|
+
if src is None:
|
|
1502
|
+
return
|
|
1503
|
+
for node in ast.walk(src.tree):
|
|
1504
|
+
if not isinstance(node, ast.Compare):
|
|
1505
|
+
continue
|
|
1506
|
+
operands = [node.left, *node.comparators]
|
|
1507
|
+
if not any(
|
|
1508
|
+
isinstance(op, (ast.Eq, ast.NotEq))
|
|
1509
|
+
and any(
|
|
1510
|
+
isinstance(x, ast.Constant) and x.value is None
|
|
1511
|
+
for x in (operands[i], operands[i + 1])
|
|
1512
|
+
)
|
|
1513
|
+
for i, op in enumerate(node.ops)
|
|
1514
|
+
):
|
|
1515
|
+
continue
|
|
1516
|
+
if _in_query_call(src, node):
|
|
1517
|
+
continue
|
|
1518
|
+
yield src.hit(node, message="compare with None using 'is'", evidence=_short(node))
|
|
1519
|
+
|
|
1520
|
+
|
|
1521
|
+
def _in_query_call(src: _Source, node: ast.AST) -> bool:
|
|
1522
|
+
current: ast.AST | None = src.parent(node)
|
|
1523
|
+
while current is not None and not isinstance(current, ast.stmt):
|
|
1524
|
+
if isinstance(current, ast.Call) and _final_name(current.func) in _QUERY_CALLS:
|
|
1525
|
+
return True
|
|
1526
|
+
current = src.parent(current)
|
|
1527
|
+
return False
|
|
1528
|
+
|
|
1529
|
+
|
|
1530
|
+
@rule(
|
|
1531
|
+
id="python/utcnow",
|
|
1532
|
+
severity="note",
|
|
1533
|
+
title="Naive UTC datetime",
|
|
1534
|
+
languages={"python"},
|
|
1535
|
+
rationale=(
|
|
1536
|
+
"datetime.utcnow() and utcfromtimestamp() return naive datetimes that later code "
|
|
1537
|
+
"takes for local time; both are deprecated since Python 3.12."
|
|
1538
|
+
),
|
|
1539
|
+
hint="Use datetime.now(timezone.utc) or datetime.fromtimestamp(ts, timezone.utc).",
|
|
1540
|
+
tags={"python", "correctness"},
|
|
1541
|
+
)
|
|
1542
|
+
def utcnow(ctx: FileContext) -> Iterator[Hit]:
|
|
1543
|
+
"""On ``datetime``, ``datetime.datetime`` or a name imported as the datetime class
|
|
1544
|
+
(``arrow.utcnow()`` and similar aware APIs stay silent)."""
|
|
1545
|
+
src = _source(ctx)
|
|
1546
|
+
if src is None:
|
|
1547
|
+
return
|
|
1548
|
+
classes = {"datetime"}
|
|
1549
|
+
for node in ast.walk(src.tree):
|
|
1550
|
+
if isinstance(node, ast.ImportFrom) and node.module == "datetime":
|
|
1551
|
+
for alias in node.names:
|
|
1552
|
+
if alias.name == "datetime":
|
|
1553
|
+
classes.add(alias.asname or alias.name)
|
|
1554
|
+
for node in ast.walk(src.tree):
|
|
1555
|
+
if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
|
|
1556
|
+
continue
|
|
1557
|
+
func = node.func
|
|
1558
|
+
if func.attr not in ("utcnow", "utcfromtimestamp"):
|
|
1559
|
+
continue
|
|
1560
|
+
base = func.value
|
|
1561
|
+
if (isinstance(base, ast.Name) and base.id in classes) or (
|
|
1562
|
+
isinstance(base, ast.Attribute) and base.attr == "datetime"
|
|
1563
|
+
):
|
|
1564
|
+
yield src.hit(
|
|
1565
|
+
node,
|
|
1566
|
+
message=f"{func.attr}() returns a naive datetime",
|
|
1567
|
+
evidence=f"datetime.{func.attr}",
|
|
1568
|
+
)
|
|
1569
|
+
|
|
1570
|
+
|
|
1571
|
+
_CLI_IMPORTS = frozenset({"argparse", "click", "typer", "fire", "docopt"})
|
|
1572
|
+
_CLI_DIRS = frozenset({"scripts", "bin", "cli"})
|
|
1573
|
+
|
|
1574
|
+
|
|
1575
|
+
def _cli_file(path: str, tree: ast.Module, first_line: str) -> bool:
|
|
1576
|
+
"""A script or command-line module, where printing is the interface."""
|
|
1577
|
+
parts = _path_parts(path)
|
|
1578
|
+
name = parts[-1] if parts else ""
|
|
1579
|
+
if any(p in _CLI_DIRS for p in parts[:-1]):
|
|
1580
|
+
return True
|
|
1581
|
+
stem = name.removesuffix(".py")
|
|
1582
|
+
if name in ("__main__.py", "manage.py", "setup.py", "noxfile.py") or stem == "cli":
|
|
1583
|
+
return True
|
|
1584
|
+
if stem.startswith("cli_") or stem.endswith("_cli"):
|
|
1585
|
+
return True
|
|
1586
|
+
if first_line.lstrip("").startswith("#!"):
|
|
1587
|
+
return True
|
|
1588
|
+
for stmt in tree.body:
|
|
1589
|
+
if (
|
|
1590
|
+
isinstance(stmt, ast.If)
|
|
1591
|
+
and isinstance(stmt.test, ast.Compare)
|
|
1592
|
+
and isinstance(stmt.test.left, ast.Name)
|
|
1593
|
+
and stmt.test.left.id == "__name__"
|
|
1594
|
+
):
|
|
1595
|
+
return True
|
|
1596
|
+
if isinstance(stmt, (ast.Import, ast.ImportFrom)):
|
|
1597
|
+
modules = (
|
|
1598
|
+
[a.name for a in stmt.names] if isinstance(stmt, ast.Import) else [stmt.module]
|
|
1599
|
+
)
|
|
1600
|
+
if any(m and m.split(".")[0] in _CLI_IMPORTS for m in modules):
|
|
1601
|
+
return True
|
|
1602
|
+
return False
|
|
1603
|
+
|
|
1604
|
+
|
|
1605
|
+
@rule(
|
|
1606
|
+
id="python/print-call",
|
|
1607
|
+
severity="note",
|
|
1608
|
+
title="print() in library code",
|
|
1609
|
+
languages={"python"},
|
|
1610
|
+
classes={"source", "agent-config"},
|
|
1611
|
+
default_enabled=False,
|
|
1612
|
+
rationale=(
|
|
1613
|
+
"print() in library or service code writes to stdout that nobody reads and "
|
|
1614
|
+
"bypasses logging levels and handlers; often a debugging leftover."
|
|
1615
|
+
),
|
|
1616
|
+
hint="Use the logging module, or remove the leftover.",
|
|
1617
|
+
tags={"python", "debug"},
|
|
1618
|
+
)
|
|
1619
|
+
def print_call(ctx: FileContext) -> Iterator[Hit]:
|
|
1620
|
+
"""Opt-in. Never in tests or in scripts and CLI modules, which are: files under a
|
|
1621
|
+
``scripts/``, ``bin/`` or ``cli/`` directory; ``__main__.py``, ``manage.py``,
|
|
1622
|
+
``setup.py``, ``noxfile.py``, ``cli.py``, ``cli_*.py`` and ``*_cli.py``; files
|
|
1623
|
+
with a shebang; and modules with a top-level ``if __name__ == "__main__":`` or a
|
|
1624
|
+
top-level import of argparse, click, typer, fire or docopt.
|
|
1625
|
+
|
|
1626
|
+
Silent for ``print(..., file=...)`` (a deliberate stream) and when the module
|
|
1627
|
+
binds ``print`` itself (``from rich import print``).
|
|
1628
|
+
"""
|
|
1629
|
+
src = _source(ctx)
|
|
1630
|
+
if src is None:
|
|
1631
|
+
return
|
|
1632
|
+
first = src.lines[0] if src.lines else ""
|
|
1633
|
+
if _cli_file(ctx.path, src.tree, first) or "print" in _bound_names(src.tree):
|
|
1634
|
+
return
|
|
1635
|
+
for node in ast.walk(src.tree):
|
|
1636
|
+
if (
|
|
1637
|
+
isinstance(node, ast.Call)
|
|
1638
|
+
and isinstance(node.func, ast.Name)
|
|
1639
|
+
and node.func.id == "print"
|
|
1640
|
+
and not any(kw.arg == "file" for kw in node.keywords)
|
|
1641
|
+
):
|
|
1642
|
+
yield src.hit(node, message="print() in library code", evidence=_short(node, 80))
|