Skip to content

The agent that grows with you

fix(code-health): report every independent import-time capture (F19)

Tekniuma52a7f829b9c
diff --git a/scripts/code_health/py_rules.py b/scripts/code_health/py_rules.py
index 97d3e4bcaa8..f0f4ed1ead4 100644
--- a/scripts/code_health/py_rules.py
+++ b/scripts/code_health/py_rules.py
@@ -346,18 +346,29 @@ def unscoped_secret_fallback(tree: ast.Module, ctx: Ctx) -> Iterable[int]:
break
+def _is_capture(node: ast.AST) -> bool:
+ if isinstance(node, ast.Call):
+ name = _call_name(node)
+ if name.rsplit(".", 1)[-1] in _CAPTURE_CALLS or name.endswith("Path.home"):
+ return True
+ return bool(_env_read_name(node))
+
+
def _capture_lines(expr: ast.AST) -> Iterator[int]:
- # Deferred bodies (lambda, def, generator element) read at call time: that is the fix.
- for node in _eager(expr):
- if isinstance(node, ast.Call):
- name = _call_name(node)
- leaf = name.rsplit(".", 1)[-1]
- if leaf in _CAPTURE_CALLS or name.endswith("Path.home"):
- yield node.lineno
- return
- if _env_read_name(node):
+ """Every independent capture ``expr`` evaluates: each dict entry or list item is its own
+ occurrence, so one added next to an existing one is new debt. A capture nested inside
+ another (``expanduser(getenv(...))``) is the same occurrence and is not entered.
+ Deferred bodies (lambda, def, generator element) read at call time: that is the fix."""
+ stack = [expr]
+ while stack:
+ node = stack.pop()
+ parts = _deferred_parts(node)
+ if parts is not None:
+ stack.extend(parts)
+ elif _is_capture(node):
yield getattr(node, "lineno", 0)
- return
+ else:
+ stack.extend(ast.iter_child_nodes(node))
def _main_guard(stmt: ast.stmt) -> str | None:
diff --git a/tests/scripts/test_code_health_rules.py b/tests/scripts/test_code_health_rules.py
index 7724d8e50f5..f1887fe2d2a 100644
--- a/tests/scripts/test_code_health_rules.py
+++ b/tests/scripts/test_code_health_rules.py
@@ -53,3 +53,39 @@ def test_import_alias_with_unrelated_parameter_blocks_through_the_verdict(tmp_pa
head = {"pkg/c.py": _ALIAS.format("def identity(execute):\n return execute", "")}
code, out = _judge(tmp_path, capsys, {}, head)
assert code == 1 and "HX006" in out, out
+
+
+# --- F19: every independent eager capture is its own occurrence ---
+
+_DICT = 'import os\n\nCACHE = {{\n{} "old": os.getenv("PATH"),\n}}\n'
+_LIST = "import os\n\nPATHS = [\n{} os.getenv(\"PATH\"),\n]\n"
+_DEFAULT = "import os\n\n\ndef f(\n{} a=os.getenv(\"PATH\"),\n):\n return a\n"
+
+
[email protected]("shape, added, blocks", [
+ (_DICT, ' "new": os.getenv("HOME"),\n', True),
+ (_LIST, ' os.getenv("HOME"),\n', True),
+ (_DEFAULT, ' b=os.getenv("HOME"),\n', True),
+ (_DICT, ' "new": lambda: os.getenv("HOME"),\n', False), # deferred read: the fix
+ (_DICT, ' "new": "literal",\n', False), # unchanged debt stays grandfathered
+])
+def test_added_capture_inside_an_existing_expression_is_new(tmp_path, capsys, shape, added, blocks):
+ code, out = _judge(tmp_path, capsys, {"pkg/c.py": shape.format("")},
+ {"pkg/c.py": shape.format(added)})
+ assert code == (1 if blocks else 0), out
+ assert ("HX005" in out) is blocks, out
+
+
+def test_added_capture_in_its_own_assignment_is_new(tmp_path, capsys):
+ base = _DICT.format("")
+ code, out = _judge(tmp_path, capsys, {"pkg/c.py": base},
+ {"pkg/c.py": base + 'NEW = os.getenv("HOME")\n'})
+ assert code == 1 and "HX005" in out, out
+
+
+def test_capture_lines_reports_each_independent_capture_once():
+ two = 'import os\n\nCACHE = {\n "a": os.getenv("A"),\n "b": os.getenv("B"),\n}\n'
+ assert _hits("HX005", two) == [4, 5]
+ # a capture nested inside another is the same occurrence
+ nested = 'import os\n\nHOME = os.path.expanduser(\n os.getenv("A", "~")\n)\n'
+ assert _hits("HX005", nested) == [3]