fix(tools): preserve separator whitespace in inline replacements
This commit is contained in:
1 parent
9d7cc0204c
commit
e36a016b6f
2 files changed
+59
-8
No files matched your search
@@ -894,9 +894,13 @@ class EditFileTool(_FsTool):
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _strip_trailing_ws(text: str) -> str:
|
||||
"""Strip trailing whitespace from each line."""
|
||||
return "\n".join(line.rstrip() for line in text.split("\n"))
|
||||
def _strip_trailing_ws(text: str, *, preserve_last_line: bool = False) -> str:
|
||||
"""Strip line-ending whitespace, except a final fragment that continues inline."""
|
||||
lines = text.split("\n")
|
||||
return "\n".join(
|
||||
line if preserve_last_line and i == len(lines) - 1 else line.rstrip()
|
||||
for i, line in enumerate(lines)
|
||||
)
|
||||
|
||||
def _format_summary(
|
||||
self, resolved_path: Path, before: str, after: str, *,
|
||||
@@ -996,10 +1000,6 @@ class EditFileTool(_FsTool):
|
||||
|
||||
norm_new = new_text.replace("\r\n", "\n")
|
||||
|
||||
# Trailing whitespace stripping (skip markdown to preserve double-space line breaks)
|
||||
if fp.suffix.lower() not in self._MARKDOWN_EXTS:
|
||||
norm_new = self._strip_trailing_ws(norm_new)
|
||||
|
||||
if replace_all:
|
||||
selected = matches
|
||||
elif occurrence is not None:
|
||||
@@ -1030,7 +1030,18 @@ class EditFileTool(_FsTool):
|
||||
)
|
||||
new_content = content
|
||||
for match in reversed(selected):
|
||||
replacement = _preserve_quote_style(norm_old, match.text, norm_new)
|
||||
replacement = norm_new
|
||||
# Preserve separator whitespace when the remaining line has content.
|
||||
# Markdown keeps all trailing whitespace for hard line breaks.
|
||||
if fp.suffix.lower() not in self._MARKDOWN_EXTS:
|
||||
line_end = content.find("\n", match.end)
|
||||
if line_end == -1:
|
||||
line_end = len(content)
|
||||
replacement = self._strip_trailing_ws(
|
||||
replacement,
|
||||
preserve_last_line=bool(content[match.end:line_end].strip()),
|
||||
)
|
||||
replacement = _preserve_quote_style(norm_old, match.text, replacement)
|
||||
replacement = _reindent_like_match(norm_old, match.text, replacement)
|
||||
|
||||
# Only consume the trailing newline when deleting complete lines;
|
||||
|
||||
@@ -275,6 +275,46 @@ class TestTrailingWhitespaceStrip:
|
||||
content = f.read_text()
|
||||
assert "x = 2\ny = 3\n" == content
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("newline", ["\n", "\r\n"], ids=["lf", "crlf"])
|
||||
@pytest.mark.parametrize(
|
||||
"before,old_text,new_text,expected",
|
||||
[
|
||||
("return value\n", "return ", "yield ", "yield value\n"),
|
||||
("return value\n", "return ", "yield\t", "yield\tvalue\n"),
|
||||
("hello-world\n", "-", " ", "hello world\n"),
|
||||
(
|
||||
"return value\n", "return ", "ready = True \nyield ",
|
||||
"ready = True\nyield value\n",
|
||||
),
|
||||
],
|
||||
ids=["space", "tab", "whitespace-only", "multiline"],
|
||||
)
|
||||
async def test_inline_replacement_preserves_separator(
|
||||
self, tool, tmp_path, newline, before, old_text, new_text, expected,
|
||||
):
|
||||
f = tmp_path / "inline.py"
|
||||
f.write_bytes(before.replace("\n", newline).encode("utf-8"))
|
||||
result = await tool.execute(
|
||||
path=str(f), old_text=old_text.replace("\n", newline),
|
||||
new_text=new_text.replace("\n", newline),
|
||||
)
|
||||
assert "Patch applied:" in result
|
||||
assert f.read_bytes() == expected.replace("\n", newline).encode("utf-8")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("newline", ["\n", "\r\n"], ids=["lf", "crlf"])
|
||||
async def test_replace_all_cleans_only_actual_line_endings(self, tool, tmp_path, newline):
|
||||
f = tmp_path / "mixed.txt"
|
||||
f.write_bytes("old value\nold \nold \nold ".replace("\n", newline).encode("utf-8"))
|
||||
result = await tool.execute(
|
||||
path=str(f), old_text="old ", new_text="new ", replace_all=True,
|
||||
)
|
||||
assert "Patch applied:" in result
|
||||
# Preserve existing suffix whitespace; only clean the replacement's line endings.
|
||||
expected = "new value\nnew\nnew \nnew"
|
||||
assert f.read_bytes() == expected.replace("\n", newline).encode("utf-8")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_preserves_trailing_whitespace_in_markdown(self, tool, tmp_path):
|
||||
f = tmp_path / "doc.md"
|
||||
|
||||
Reference in new issue
Block a user