Skip to content

The agent that grows with you

fix(tools): narrow mid-line reindent guard

Elisa Martinez Abad395e1cd7b137
diff --git a/tests/tools/test_fuzzy_match.py b/tests/tools/test_fuzzy_match.py
index fb74ac0c99c..2fbe2b2ce7d 100644
--- a/tests/tools/test_fuzzy_match.py
+++ b/tests/tools/test_fuzzy_match.py
@@ -1,5 +1,7 @@
"""Tests for the fuzzy matching module."""
+import pytest
+
from tools.fuzzy_match import IDENTICAL_STRINGS_ERROR, fuzzy_find_and_replace
@@ -146,27 +148,32 @@ class TestIndentationPreservation:
assert lines[1] == ""
assert lines[2] == " b = 99"
- def test_mid_line_anchor_keeps_new_string_indentation(self):
- # Replacing an expression, not a whole line: old_string's first line has no
- # indentation because the text before it on that line was never part of it.
+ @pytest.mark.parametrize("anchor_indent", ["", " ", "\t"])
+ def test_mid_line_anchor_keeps_new_string_indentation(self, anchor_indent):
+ # Whitespace-bearing anchors match the separator after '='. Their indentation
+ # differs from that separator, so the old re-anchoring shifts continuation lines.
content = "def f():\n total = compute(a, b)\n"
- old = "compute(a, b)"
- new = "compute(\n a, b)"
+ old = anchor_indent + "compute(a, b)"
+ new = anchor_indent + "compute(\n a, b)"
out, count, strategy, err = fuzzy_find_and_replace(content, old, new)
assert err is None and count == 1 and strategy != "exact"
- assert out == "def f():\n total = compute(\n a, b)\n"
+ assert out.splitlines()[-1] == new.splitlines()[-1]
+ compile(out, "<patched>", "exec")
- def test_match_starting_with_line_break_is_reindented(self):
+ @pytest.mark.parametrize("leading_breaks", ["\n", "\n\n", "\n \t\n", "\r\n", "\r\n\r\n"])
+ @pytest.mark.parametrize("anchor_indent", [" ", "\t"])
+ def test_match_starting_with_line_break_is_reindented(self, leading_breaks, anchor_indent):
# old_string starts with the line break that ends the previous line, so the
# match starts at the end of a line, but every code line in it is whole.
- content = "class A:\n def f(self):\n x = 1\n return x\n"
- old = "\n return x"
- new = "\n return x + 1"
+ line_break = "\r\n" if leading_breaks.startswith("\r\n") else "\n"
+ prefix = line_break.join(("class A:", " def f(self):", " x = 1"))
+ content = prefix + leading_breaks + " return x" + line_break
+ old = leading_breaks + anchor_indent + "return x"
+ new = leading_breaks + anchor_indent + "return x + 1"
out, count, strategy, err = fuzzy_find_and_replace(content, old, new)
assert err is None and count == 1 and strategy != "exact"
- assert "\n return x + 1\n" in out
- import ast
- ast.parse(out)
+ assert out == prefix + leading_breaks + " return x + 1" + line_break
+ compile(out, "<patched>", "exec")
class TestReplaceAll:
diff --git a/tools/fuzzy_match.py b/tools/fuzzy_match.py
index f67d47e10e2..f06c1659043 100644
--- a/tools/fuzzy_match.py
+++ b/tools/fuzzy_match.py
@@ -525,22 +525,32 @@ def _first_meaningful_line(text: str) -> Optional[str]:
return next((line for line in text.split("\n") if line.strip()), None)
+def _match_starts_mid_line(content: str, start: int, end: int) -> bool:
+ """Whether text outside the match precedes its first non-blank line.
+
+ Leading newlines and blank lines do not make an anchor partial-line: the first
+ code line can still be captured in full and need indentation adjustment.
+ """
+ first_line_start = start
+ for line in content[start:end].split("\n"):
+ if line.strip():
+ line_start = content.rfind("\n", 0, first_line_start) + 1
+ return bool(content[line_start:first_line_start].strip(" \t\r"))
+ first_line_start += len(line) + 1
+ return False
+
+
def _reindent_replacement(file_region: str, old_string: str, new_string: str, *,
- match_starts_at_line_start: bool) -> str:
+ match_starts_mid_line: bool) -> str:
"""Re-anchor ``new_string``'s indentation onto the file's actual base indent after a
non-exact match: swap the LLM base prefix (first non-blank old_string line) for the
file's, preserving relative nesting; shallower lines anchor to the file base.
- Skips entirely when the match does not begin at column 0 of a line in the file
- (``match_starts_at_line_start`` False). Anchoring mid-line is normal when the model
- replaces an expression rather than a whole statement -- old_string never captured
- whatever precedes it on that line, so its own first-line leading whitespace is not a
- real "base indent" to re-anchor onto; treating it as one (the old behavior) silently
- prepends the file's indentation onto lines that already carry their own. A genuine
- whole-line anchor whose old_string happens to start with no indentation is unaffected:
- match_starts_at_line_start is still True there, so it re-anchors exactly as before.
+ Preserve the supplied indentation when non-whitespace text precedes the match's
+ first non-blank line: a partial-line expression has no reliable base indent.
+ Leading line breaks and blank lines still allow whole-line re-anchoring.
"""
- if not new_string or not match_starts_at_line_start:
+ if not new_string or match_starts_mid_line:
return new_string
old_first = _first_meaningful_line(old_string)
file_first = _first_meaningful_line(file_region)
@@ -607,9 +617,10 @@ def _apply_replacements(content: str, matches: list[Span],
# Each occurrence may use different typographic characters even
# though all normalize to the same old_string.
adjusted = _preserve_unicode_in_replacement(region, adjusted, unicode_plan)
- match_starts_at_line_start = start == 0 or content[start - 1] == "\n"
- adjusted = _reindent_replacement(region, old_string, adjusted,
- match_starts_at_line_start=match_starts_at_line_start)
+ adjusted = _reindent_replacement(
+ region, old_string, adjusted,
+ match_starts_mid_line=_match_starts_mid_line(content, start, end),
+ )
result = result[:start] + adjusted + result[end:]
return result