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): gate Extract Method plans on span share, size and docstring start (#3252)

Raghav Chamadiyab6c0b9cf279a
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index 5f58944a9..39e24904b 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -160,6 +160,11 @@ Most plans answer a health finding, so per-path marker rules in
- Extract Method skips spans too small to matter and spans that would carry the
original finding into the helper. A component whose branching is mostly in its
markup gets no extraction.
+- An Extract Method span must remove at least two decision points, hold at least
+ 8 code lines, cover at most 60% of the function's lines, and not start on the
+ docstring. When the best span misses one of these, only a span that does not
+ overlap it is offered, never a slightly smaller copy of it. Estimated gain
+ never exceeds the share of decision points removed.
- Move Method never targets a class the method only instantiates, or an ancestor of
its own class.
- Split File works on any language with call resolution and suggests a split only
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/file_scan.py b/packages/core/src/repowise/core/analysis/health/complexity/file_scan.py
index 48655d8d3..f5f970531 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/file_scan.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/file_scan.py
@@ -20,7 +20,7 @@ from ..perf.io_boundaries import _finish_io_names, _io_visit
from .error_handling import _eh_node_kinds, _eh_rust_attr_is_test, _eh_visit
from .languages import LanguageNodeMap
from .models import ErrorHandlingHit
-from .nloc import CodeLineIndex, _is_docstring_stmt, _source_lines
+from .nloc import CodeLineIndex, _source_lines, is_docstring_stmt
if TYPE_CHECKING:
from tree_sitter import Node
@@ -127,7 +127,7 @@ def scan_file(
if "comment" in t:
ctx |= _IN_COMMENT | _IN_DOCSTRING
excluded.append((node.start_byte, node.end_byte))
- elif t == "expression_statement" and _is_docstring_stmt(node):
+ elif t == "expression_statement" and is_docstring_stmt(node):
ctx |= _IN_DOCSTRING
excluded.append((node.start_byte, node.end_byte))
elif not ctx & _IN_COMMENT and "comment" in t:
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/nloc.py b/packages/core/src/repowise/core/analysis/health/complexity/nloc.py
index 3a25fed9a..4265c56ea 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/nloc.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/nloc.py
@@ -34,7 +34,15 @@ def _source_lines(source: bytes) -> list[str]:
return lines
-def _is_docstring_stmt(node: Node) -> bool:
+def is_string_stmt(node: Node) -> bool:
+ """True for a bare string-literal statement (a docstring wherever it sits)."""
+ if node.type != "expression_statement":
+ return False
+ named = [c for c in node.children if c.is_named]
+ return len(named) == 1 and "string" in named[0].type
+
+
+def is_docstring_stmt(node: Node) -> bool:
"""True for a docstring: a bare string statement opening a function/class.
A Python docstring is an ``expression_statement`` whose sole child is a
@@ -42,10 +50,7 @@ def _is_docstring_stmt(node: Node) -> bool:
the leading position keeps a mid-body bare string (a rare no-op, but real
source) counted, while the documentation block is excluded from NLOC.
"""
- if node.type != "expression_statement":
- return False
- named = [c for c in node.children if c.is_named]
- if len(named) != 1 or "string" not in named[0].type:
+ if not is_string_stmt(node):
return False
parent = node.parent
if parent is None:
@@ -69,7 +74,7 @@ def _code_line_numbers(node: Node, lines: list[str], *, drop_docstrings: bool) -
cur = stack.pop()
if "comment" in cur.type:
continue
- if drop_docstrings and _is_docstring_stmt(cur):
+ if drop_docstrings and is_docstring_stmt(cur):
continue
if not cur.children and cur.start_byte < cur.end_byte:
for line in range(cur.start_point[0], cur.end_point[0] + 1):
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
index 0f785d1f4..cbdcac93e 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/extract_method.py
@@ -10,20 +10,24 @@ OUT return). This detector turns the best such span into one structured
``impact_delta`` is the share of the finding the extraction itself removes,
not the whole finding: the share of what the finding measures that moves into
the helper, applied to the finding's ``health_impact``. That is
-``ccn_removed / ccn`` for ``complex_method``, ``slice_nloc / nloc`` for
-``large_method`` and the larger of the two for ``brain_method``, capped at 1
+``ccn_removed / ccn`` for ``complex_method`` and ``brain_method``, and the
+smaller of ``slice_nloc / nloc`` and that for ``large_method``
(:func:`recovered_share`). Both line counts follow the walker's NLOC rule, so
comments credit nothing. Crediting the whole finding whenever the residual and
the helper both fell under the biomarker's bar let a two-line span in a
function barely over the bar claim all of it, and rank first on the repo.
A span is only offered when it is worth doing (:func:`_worth_extracting`): it
-removes at least two decision points, or, for a ``large_method`` finding, lifts
-at least 12 code lines, and the helper it creates would not carry the finding
-at the function's own severity or worse (lifting nearly the whole body moves
-the smell, it does not split it).
-When the best span misses that floor the next-best one that clears it is
-offered instead.
+removes at least two decision points and the helper it creates would not carry
+the finding at the function's own severity or worse (lifting nearly the whole
+body moves the smell, it does not split it). When the best span misses that
+floor the next-best one that clears it is offered instead.
+
+That span is then offered only when it is a split a reviewer would make
+(:func:`_offerable`): at most 60% of the function's lines, at least 8 code
+lines, and not opening on the docstring. A miss falls through only to a span
+that does not overlap it: an overlapping one is the same block minus a
+statement, just under the cut.
A JSX function component whose decision points sit mostly in its markup
(conditional spreads, ``&&`` and ternaries in attributes or children, template
@@ -66,6 +70,7 @@ from ..biomarkers.complex_method import ComplexMethodDetector
from ..biomarkers.large_method import LargeMethodDetector
from ..complexity.cyclomatic import _is_boolean_operator
from ..complexity.languages import get_language_map
+from ..complexity.nloc import is_string_stmt
from ..dataflow import find_extractions
from ..scoring import severity_deduction
from .models import RefactoringContext, RefactoringSuggestion
@@ -113,14 +118,18 @@ _SEVERITY_RULE: dict[str, Callable[[int, int], Severity | None]] = {
"complex_method": ComplexMethodDetector.severity_for,
}
-# Minimum worth. Census of the 1,162 stored plans on this repo's index: the best
-# span of 408 missed this floor (2 code lines lifting 2 decision points out of
-# ``walk_file`` was the #1 plan), 187 of those had a next-best span that clears
-# it and 221 were dropped. A size-only bar for ``large_method`` keeps big
-# low-branching spans that do shrink the finding. Table in the commit that set
-# it.
-_MIN_CCN_REMOVED = 2
-_MIN_LARGE_SPAN_NLOC = 12
+# Minimum worth: a helper lifting one decision point is a renamed ``if``, not
+# a split, however many straight lines come with it.
+_MIN_OFFER_CCN_REMOVED = 2
+
+# A span over three fifths of the function leaves a shell (a guard, a wrapper,
+# the final ``return``) behind; the smell moved instead of splitting. Inclusive,
+# since a span at exactly 0.60 still leaves real work. This is a stricter
+# offer-time gate on the function's physical lines, distinct from slice.py's
+# candidate-time ``_MAX_BODY_SHARE`` on the body's code lines.
+_MAX_SPAN_SHARE = 0.60
+# Below 8 code lines the helper's call and signature cost about what it saves.
+_MIN_OFFER_NLOC = 8
# ``high`` confidence also needs the helper to take a real share of the
# function: below a tenth (a 2-point span out of a CCN 249 function) the step
@@ -149,15 +158,7 @@ class ExtractMethodDetector(RefactoringDetector):
if jsx_plumbing_dominates(analysis.fn_node, lmap):
continue
markers = {getattr(f, "biomarker_type", "") for f in matched}
- # Best-first, so the first span worth doing is the strongest one.
- best = next(
- (
- c
- for c in find_extractions(analysis, lmap)
- if _worth_extracting(analysis, c, markers)
- ),
- None,
- )
+ best = _choose(analysis, find_extractions(analysis, lmap), markers)
if best is None:
continue
impact, share, source = self._impact_for(analysis, best, matched)
@@ -271,15 +272,11 @@ class ExtractMethodDetector(RefactoringDetector):
@staticmethod
def _confidence(extraction: Extraction, share: float) -> str:
- """High when the extraction is unambiguous and worth handing off: it
- removes several decision points with a clean signature and takes a real
- share of the function. Medium otherwise. (Every emitted span is
- single-exit with at most one return by construction.)"""
- if (
- extraction.ccn_removed >= _MIN_CCN_REMOVED
- and len(extraction.params) <= 4
- and share >= _HIGH_MIN_SHARE
- ):
+ """High when the extraction is unambiguous and worth handing off: a
+ clean signature and a real share of the function. Medium otherwise.
+ (Every emitted span is single-exit with at most one return and removes
+ at least two decision points by construction.)"""
+ if len(extraction.params) <= 4 and share >= _HIGH_MIN_SHARE:
return "high"
return "medium"
@@ -289,25 +286,25 @@ def recovered_share(
) -> float:
"""Share of what *biomarker* measures that *extraction* moves into the helper.
- Decision points for ``complex_method``, code lines for ``large_method``
- (the walker's NLOC rule on both sides), the larger of the two for
- ``brain_method``, capped at 1. Per biomarker because the plain maximum let
- 2 decision points out of a CCN 3, 292-line method claim two thirds of a
- size finding.
+ Decision points for every biomarker except ``large_method``, the only one
+ *biomarker* changes: code lines there (the walker's NLOC rule on both
+ sides), capped at 1. Per biomarker because
+ the plain maximum let 2 decision points out of a CCN 3, 292-line method
+ claim two thirds of a size finding. Never more than the decision-point
+ share, ``brain_method`` included: a long flat span claimed most of a size
+ finding for moving straight-line code.
"""
ccn_share = extraction.ccn_removed / analysis.ccn if analysis.ccn > 0 else 0.0
- nloc_share = extraction.slice_nloc / analysis.nloc if analysis.nloc > 0 else 0.0
- if biomarker == "complex_method":
- return min(1.0, ccn_share)
if biomarker == "large_method":
- return min(1.0, nloc_share)
- return min(1.0, max(ccn_share, nloc_share))
+ nloc_share = extraction.slice_nloc / analysis.nloc if analysis.nloc > 0 else 0.0
+ return min(1.0, nloc_share, ccn_share)
+ return min(1.0, ccn_share)
def _worth_extracting(
analysis: FunctionAnalysis, extraction: Extraction, markers: set[str]
) -> bool:
- """The minimum-worth floor (the slicer already demands 5 code lines)."""
+ """The minimum-worth floor, applied while choosing among candidates."""
for marker in markers:
rule = _SEVERITY_RULE[marker]
helper = rule(extraction.ccn_removed + 1, extraction.slice_nloc)
@@ -317,9 +314,54 @@ def _worth_extracting(
before is None or severity_deduction(helper) >= severity_deduction(before)
):
return False
- if extraction.ccn_removed >= _MIN_CCN_REMOVED:
- return True
- return "large_method" in markers and extraction.slice_nloc >= _MIN_LARGE_SPAN_NLOC
+ return extraction.ccn_removed >= _MIN_OFFER_CCN_REMOVED
+
+
+def _choose(
+ analysis: FunctionAnalysis, candidates: list[Extraction], markers: set[str]
+) -> Extraction | None:
+ """The strongest span worth doing and offerable, best-first.
+
+ Once the strongest worth-doing span is refused, only spans disjoint from it
+ stay eligible: one overlapping it is a shrunken copy of the refused plan.
+ """
+ refused: Extraction | None = None
+ for c in candidates:
+ if not _worth_extracting(analysis, c, markers):
+ continue
+ if refused is not None and not (
+ c.end_line < refused.start_line or c.start_line > refused.end_line
+ ):
+ continue
+ if _offerable(analysis, c):
+ return c
+ refused = refused or c
+ return None
+
+
+def _offerable(analysis: FunctionAnalysis, extraction: Extraction) -> bool:
+ """Whether a span is a split worth offering (share of physical lines)."""
+ fn_lines = max(analysis.end_line - analysis.start_line + 1, 1)
+ span_lines = extraction.end_line - extraction.start_line + 1
+ if span_lines / fn_lines > _MAX_SPAN_SHARE or extraction.slice_nloc < _MIN_OFFER_NLOC:
+ return False
+ return not _starts_on_docstring(analysis.fn_node, extraction.start_line)
+
+
+def _starts_on_docstring(fn_node: Any, start_line: int) -> bool:
+ """True when the span opens on the body's docstring (or a JS/TS directive
+ such as ``"use strict"``): lifting it strips the function of it. Comments
+ before it are skipped, as they are not statements."""
+ body = fn_node.child_by_field_name("body") if fn_node is not None else None
+ if body is None:
+ return False
+ first = next((c for c in body.named_children if "comment" not in c.type), None)
+ # Only bodies holding bare string statements (Python, JS/TS) can match.
+ return (
+ first is not None
+ and is_string_stmt(first)
+ and start_line <= first.start_point[0] + 1
+ )
def jsx_plumbing_dominates(fn_node: Any, lmap: LanguageNodeMap) -> bool:
diff --git a/tests/fixtures/refactoring_corpus/golden_opportunities.json b/tests/fixtures/refactoring_corpus/golden_opportunities.json
index 99f067d3f..6ba0a071d 100644
--- a/tests/fixtures/refactoring_corpus/golden_opportunities.json
+++ b/tests/fixtures/refactoring_corpus/golden_opportunities.json
@@ -216,30 +216,30 @@
"effort_bucket": "S",
"evidence": [
{
- "plan_id": "refac4_aa609dc289a6e9572306",
+ "plan_id": "refac4_4e1bab0813290d0fa647",
"refactoring_type": "extract_helper",
"source_biomarker": "dry_violation",
"summary": {
"co_change_count": 0,
- "duplicated_lines": 21,
+ "duplicated_lines": 23,
"is_intra_file": true,
"occurrence_count": 3,
- "token_count": 14000
+ "token_count": 16200
},
- "target_symbol": "handlers.py:25-45"
+ "target_symbol": "handlers.py:25-47"
},
{
- "plan_id": "refac4_8ea65569516929f43f5b",
+ "plan_id": "refac4_401e3a6f4aaa43d4f4c9",
"refactoring_type": "extract_helper",
"source_biomarker": "dry_violation",
"summary": {
"co_change_count": 0,
- "duplicated_lines": 21,
+ "duplicated_lines": 23,
"is_intra_file": true,
"occurrence_count": 2,
- "token_count": 7050
+ "token_count": 8150
},
- "target_symbol": "handlers.py:87-107"
+ "target_symbol": "handlers.py:89-111"
}
],
"file_path": "handlers.py",
@@ -247,7 +247,7 @@
"lead_biomarker": "complex_method",
"lead_refactoring_type": "extract_method",
"mechanical_steps": 3,
- "opportunity_id": "refop4_2b1f7e87189e7adb819c",
+ "opportunity_id": "refop4_147d3fb92ab4fa10d95a",
"rank_factors": {
"benefit": 0.249,
"cost": 3.0,
@@ -279,7 +279,7 @@
"effort_bucket": "S",
"file_path": "handlers.py",
"impact_delta": 0.083,
- "plan_id": "refac4_cdc5177783ea57d763e5",
+ "plan_id": "refac4_3bb7e47b918d8f2f87b0",
"refactoring_type": "extract_method",
"relocated_by": null,
"source_biomarker": "complex_method",
@@ -304,7 +304,7 @@
"effort_bucket": "S",
"file_path": "handlers.py",
"impact_delta": 0.083,
- "plan_id": "refac4_48c888afc5af0d975522",
+ "plan_id": "refac4_431988e94554e6ba35d2",
"refactoring_type": "extract_method",
"relocated_by": null,
"source_biomarker": "complex_method",
@@ -329,7 +329,7 @@
"effort_bucket": "S",
"file_path": "handlers.py",
"impact_delta": 0.083,
- "plan_id": "refac4_4ecbf32a9c6419829a56",
+ "plan_id": "refac4_9ff9f92beaaa4041f2fa",
"refactoring_type": "extract_method",
"relocated_by": null,
"source_biomarker": "complex_method",
diff --git a/tests/fixtures/refactoring_corpus/trees/web/handlers.py b/tests/fixtures/refactoring_corpus/trees/web/handlers.py
index 6bfd24638..d292cbf9f 100644
--- a/tests/fixtures/refactoring_corpus/trees/web/handlers.py
+++ b/tests/fixtures/refactoring_corpus/trees/web/handlers.py
@@ -42,6 +42,8 @@ def read_account(account_id: str, expand: str = "") -> dict[str, object]:
for name in sorted(wanted):
if name not in normalized:
normalized[name] = None
+ normalized["expanded"] = sorted(wanted)
+ normalized["expanded_count"] = len(wanted)
normalized["links"] = {"self": f"/accounts/{account_id}"}
return normalized
@@ -104,6 +106,8 @@ def read_workspace(workspace_id: str, expand: str = "") -> dict[str, object]:
for name in sorted(wanted):
if name not in normalized:
normalized[name] = None
+ normalized["expanded"] = sorted(wanted)
+ normalized["expanded_count"] = len(wanted)
normalized["links"] = {"self": f"/workspaces/{workspace_id}"}
return normalized
@@ -166,6 +170,8 @@ def read_project(project_id: str, expand: str = "") -> dict[str, object]:
for name in sorted(wanted):
if name not in normalized:
normalized[name] = None
+ normalized["expanded"] = sorted(wanted)
+ normalized["expanded_count"] = len(wanted)
normalized["links"] = {"self": f"/projects/{project_id}"}
return normalized
diff --git a/tests/unit/health/test_refactoring_extract_method.py b/tests/unit/health/test_refactoring_extract_method.py
index 3d85c26a6..fe522badb 100644
--- a/tests/unit/health/test_refactoring_extract_method.py
+++ b/tests/unit/health/test_refactoring_extract_method.py
@@ -744,7 +744,15 @@ def test_share_follows_what_the_biomarker_measures():
assert recovered_share("large_method", fn, span) == 0.25
assert recovered_share("brain_method", fn, span) == 0.5
# Capped: a span cannot recover more than the whole finding.
- assert recovered_share("large_method", _Shape(3, 10), _Span(2, 20)) == 1.0
+ assert recovered_share("large_method", _Shape(2, 10), _Span(2, 20)) == 1.0
+
+
+def test_no_biomarker_credits_more_than_the_decision_point_share():
+ # A long flat span (137 code lines, 2 decision points out of 40) moves
+ # straight-line code: the size share must not stand in for the split.
+ fn, span = _Shape(40, 200), _Span(2, 137)
+ assert recovered_share("large_method", fn, span) == pytest.approx(2 / 40)
+ assert recovered_share("brain_method", fn, span) == pytest.approx(2 / 40)
def test_two_decision_points_out_of_a_tiny_size_finding_claim_little():
@@ -754,12 +762,13 @@ def test_two_decision_points_out_of_a_tiny_size_finding_claim_little():
assert share == pytest.approx(16 / 292)
-def test_floor_drops_a_one_point_span_unless_it_is_a_large_size_lift():
+def test_floor_drops_a_one_point_span_whatever_its_size():
fn = _Shape(12, 80)
assert not _worth_extracting(fn, _Span(1, 8), {"complex_method"})
assert _worth_extracting(fn, _Span(2, 5), {"complex_method"})
- assert not _worth_extracting(fn, _Span(1, 11), {"large_method"})
- assert _worth_extracting(fn, _Span(1, 12), {"large_method"})
+ # A 137-line span lifting one decision point out of a large method
+ # (registerChannelsCli) is no longer a size lift worth a plan.
+ assert not _worth_extracting(_Shape(30, 180), _Span(1, 137), {"large_method"})
def test_a_helper_inheriting_the_finding_undiminished_is_not_worth_it():
@@ -906,7 +915,7 @@ def test_a_best_span_below_the_floor_yields_to_the_next_one(monkeypatch):
from repowise.core.analysis.health.refactoring import extract_method
trivial = Extraction(10, 17, ("a",), (), slice_nloc=8, ccn_removed=1)
- worth = Extraction(20, 25, ("b",), (), slice_nloc=6, ccn_removed=3)
+ worth = Extraction(20, 27, ("b",), (), slice_nloc=8, ccn_removed=3)
monkeypatch.setattr(extract_method, "find_extractions", lambda _a, _l: [trivial, worth])
fn = _Shape(12, 40)
analysis = type(
@@ -922,7 +931,7 @@ def test_a_best_span_below_the_floor_yields_to_the_next_one(monkeypatch):
function_analyses=[analysis],
)
(s,) = ExtractMethodDetector().detect(ctx)
- assert s.plan["span"] == {"start": 20, "end": 25}
+ assert s.plan["span"] == {"start": 20, "end": 27}
assert s.impact_delta == round(1.2 * 3 / 12, 3)
@@ -996,3 +1005,142 @@ def test_a_span_leaving_real_work_behind_is_still_offered():
(best, *_) = find_extractions(fn, lmap)
assert "average" in best.returns
assert best.end_line < fn.end_line
+
+
+# -- offer gates (span share, size, docstring start) ---------------------------------
+
+
+def _fn_lines(start: int, end: int):
+ return type("A", (), {"start_line": start, "end_line": end, "fn_node": None})()
+
+
+def _offer(fn_span: tuple[int, int], span: tuple[int, int], nloc: int, ccn: int = 9) -> bool:
+ from repowise.core.analysis.health.dataflow import Extraction
+ from repowise.core.analysis.health.refactoring.extract_method import _offerable
+
+ return _offerable(_fn_lines(*fn_span), Extraction(*span, (), (), nloc, ccn))
+
+
+ ("fn_span", "span", "nloc"),
+ [
+ ((31, 313), (108, 311), 183), # parseLineDirectives, share 0.72
+ ((1601, 1827), (1665, 1826), 151), # cmd_migrate, share 0.71
+ ((18, 63), (29, 57), 23), # buildConformanceOverlay, share 0.63
+ ],
+)
+def test_a_span_over_three_fifths_of_the_function_is_not_offered(fn_span, span, nloc):
+ assert not _offer(fn_span, span, nloc)
+
+
+def test_a_six_line_span_is_not_offered():
+ # bulk_update: 6 code lines out of a 132-line function.
+ assert not _offer((1304, 1435), (1349, 1354), 6, ccn=3)
+ assert _offer((1304, 1435), (1349, 1356), 8, ccn=3)
+
+
+ ("fn_span", "span", "nloc"),
+ [
+ ((171, 210), (186, 209), 24), # extract_include_dirs, share exactly 0.600
+ ((1699, 2208), (1769, 1786), 12), # compute_order_by_sql
+ ((273, 367), (326, 366), 37), # _start_multiplex
+ ((170, 216), (183, 204), 21), # parallel provider search
+ ((20, 78), (38, 59), 22), # qwen-oauth prepare_messages
+ ],
+)
+def test_calibration_shapes_are_still_offered(fn_span, span, nloc):
+ assert _offer(fn_span, span, nloc)
+
+
+# uninstall_gui: the slicer's best span ties with the one a line lower and wins
+# on the earlier start, so it opens on the docstring.
+_DOCSTRING_FIRST = """
+def uninstall(home, packaged, keep):
+ \"\"\"Remove the built artifacts and the packaged app.
+
+ Never touches user data. Returns the paths removed.
+ \"\"\"
+ removed = []
+ for path in home:
+ if path.exists() and path.is_dir():
+ removed.append(path)
+ for path in packaged:
+ if path.exists() or path.is_symlink():
+ removed.append(path)
+ print(len(removed))
+ if not removed:
+ print("nothing to remove")
+ return []
+ if keep:
+ print("kept user data")
+ return removed
+ print("removed user data")
+ print("done")
+ print("bye")
+ return removed
+"""
+
+
+def test_a_span_opening_on_the_docstring_is_not_offered():
+ fn = _first(_DOCSTRING_FIRST)
+ (best, *_) = find_extractions(fn, get_language_map("python"))
+ assert best.start_line == fn.start_line + 1 # the docstring line
+ findings = [_Finding("complex_method", "uninstall", fn.start_line, 1.5)]
+ assert ExtractMethodDetector().detect(_ctx(_DOCSTRING_FIRST, findings)) == []
+
+
+def test_a_leading_comment_is_not_a_docstring():
+ from repowise.core.analysis.health.refactoring.extract_method import _starts_on_docstring
+
+ node = _parse(
+ "typescript",
+ """
+ function f(a: number[]) {
+ /** Totals the positive values. */
+ let total = 0;
+ return total;
+ }
+ """,
+ )
+ assert not _starts_on_docstring(node, node.start_point[0] + 2)
+ assert not _starts_on_docstring(node, node.start_point[0] + 3)
+ strict = _parse("typescript", 'function g() {\n "use strict";\n let x = 1;\n return x;\n}\n')
+ assert _starts_on_docstring(strict, strict.start_point[0] + 2)
+
+
+def test_a_comment_before_the_docstring_does_not_hide_it():
+ src = _DOCSTRING_FIRST.replace(
+ "def uninstall(home, packaged, keep):\n",
+ "def uninstall(home, packaged, keep):\n # kept in sync with the installer\n",
+ )
+ fn = _first(src)
+ (best, *_) = find_extractions(fn, get_language_map("python"))
+ assert best.start_line == fn.start_line + 2 # the docstring, under the comment
+ findings = [_Finding("complex_method", "uninstall", fn.start_line, 1.5)]
+ assert ExtractMethodDetector().detect(_ctx(src, findings)) == []
+
+
+def test_a_refused_span_yields_only_to_a_disjoint_one(monkeypatch):
+ from repowise.core.analysis.health.dataflow import Extraction
+ from repowise.core.analysis.health.refactoring import extract_method
+
+ whole = Extraction(2, 80, ("a",), (), slice_nloc=60, ccn_removed=9) # share 0.79
+ shrunk = Extraction(2, 55, ("a",), (), slice_nloc=40, ccn_removed=8) # overlaps it
+ disjoint = Extraction(85, 95, ("b",), (), slice_nloc=10, ccn_removed=3)
+ monkeypatch.setattr(
+ extract_method, "find_extractions", lambda _a, _l: [whole, shrunk, disjoint]
+ )
+ analysis = type(
+ "A", (), {"name": "f", "start_line": 1, "end_line": 100, "ccn": 30, "nloc": 90,
+ "fn_node": None}
+ )()
+ ctx = RefactoringContext(
+ file_path="m.py",
+ language="python",
+ nloc=100,
+ findings=[_Finding("complex_method", "f", 1, 1.2)],
+ function_analyses=[analysis],
+ )
+ (s,) = ExtractMethodDetector().detect(ctx)
+ assert s.plan["span"] == {"start": 85, "end": 95}