Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(health): reject extractions that lose local imports (#3410)

nightcityblade3845f81227e5
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
index eb757d6e6..2d325c20b 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py
@@ -183,6 +183,7 @@ def find_extractions(
max_slice_nloc = _MAX_BODY_SHARE * _stmts_nloc(body_container.named_children, lines)
def_lines, use_lines = _var_lines(analysis.def_use)
+ import_reads = _import_reads(analysis)
declared_first = _declared_before_read(analysis.def_use)
# Built on the first span that clears the cheap gates.
reads: dict[str, list[tuple[int, frozenset[int]]]] | None = None
@@ -238,6 +239,8 @@ def find_extractions(
span = stmts[i : j + 1]
s = span[0].start_point[0] + 1
e = span[-1].end_point[0] + 1
+ if any(import_line < s <= use_line <= e for import_line, use_line in import_reads):
+ continue
if reads is None:
reads = _reads_observing(analysis, def_lines)
params, returns = _infer_in_out(
@@ -579,6 +582,27 @@ def _var_lines(def_use: FunctionDefUse) -> tuple[dict[str, list[int]], dict[str,
return def_lines, use_lines
+def _import_reads(analysis: FunctionAnalysis) -> tuple[tuple[int, int], ...]:
+ """Function-local import lines paired with the reads they reach."""
+ imports = {
+ (definition.var, definition.line)
+ for definition in analysis.reaching.definitions
+ if definition.imports
+ }
+ if not imports:
+ return ()
+ import_lines: dict[str, list[int]] = defaultdict(list)
+ for name, line in sorted(imports):
+ import_lines[name].append(line)
+ return tuple(
+ (definition_line, use_line)
+ for name, reads in _reads_observing(analysis, import_lines).items()
+ for use_line, seen in reads
+ for definition_line in seen
+ if (name, definition_line) in imports
+ )
+
+
def _declared_before_read(def_use: FunctionDefUse) -> dict[str, frozenset[int]]:
"""Per variable, the lines where a declaration of it comes before its first
read on the same line.
diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.py
index c4cadf501..aa40f2b0b 100644
--- a/tests/unit/health/test_refactoring_extract_method.py
+++ b/tests/unit/health/test_refactoring_extract_method.py
@@ -1274,4 +1274,26 @@ def test_a_span_holding_an_import_read_after_it_is_refused():
spans = find_extractions(_first(src), get_language_map("python"))
found = {(x.start_line, x.end_line): (x.params, x.returns) for x in spans}
assert (3, 5) not in found
- assert found[(4, 6)] == (("a", "c"), ("t",))
+ assert (4, 6) not in found
+ assert found[(3, 6)] == (("a", "c"), ("t",))
+
+
+ ("prefix", "inside", "floor", "offered"),
+ [("import json\n", "", 0, True), ("", " import json\n", 2, False)],
+)
+def test_import_scope_controls_extractability(prefix, inside, floor, offered):
+ src = f"""{prefix}def f(v):
+{inside} n = 0
+ dump = lambda x: json.dumps(x)
+ if v: n += len(dump(v))
+ if n: n += len(dump(n))
+ return n
+"""
+ with pytest.MonkeyPatch.context() as mp:
+ from repowise.core.analysis.health.dataflow import slice as slicer
+
+ mp.setattr(slicer, "_MAX_BODY_SHARE", float("inf"))
+ mp.setattr(slicer, "_MIN_SLICE_NLOC", 1)
+ spans = find_extractions(_first(src), get_language_map("python"))
+ assert any(floor < x.start_line <= 4 <= x.end_line for x in spans) is offered