Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 26 additions & 13 deletions openhands-tools/openhands/tools/file_editor/editor.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import base64
import mimetypes
import os
import re
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager
Expand Down Expand Up @@ -53,6 +52,21 @@ def _is_encodable(text: str, encoding: str) -> bool:
return True


def _occurrence_starts(text: str, needle: str) -> list[int]:
"""Every start offset where ``needle`` occurs in ``text``, overlaps included.

``str.find`` keeps the engine on its fast literal search; a regex
lookahead would report the same offsets but only by attempting a match at
every position.
"""
starts: list[int] = []
index = text.find(needle)
while index != -1:
starts.append(index)
index = text.find(needle, index + 1)
return starts


class FileEditor:
"""
An filesystem editor tool that allows the agent to
Expand Down Expand Up @@ -199,16 +213,16 @@ def str_replace(
# replacements
file_content = self.read_file(path)

# Find all occurrences using regex
# Escape special regex characters in old_str to match it literally
pattern = re.escape(old_str)
# Find every occurrence, including overlapping ones ("aa" occurs twice
# in "aaa"), so an ambiguous old_str is refused instead of silently
# replacing its first match.
occurrences = [
(
file_content.count("\n", 0, match.start()) + 1, # line number
match.group(), # matched text
match.start(), # start position
file_content.count("\n", 0, start) + 1, # line number
old_str, # matched text
start, # start position
)
for match in re.finditer(pattern, file_content)
for start in _occurrence_starts(file_content, old_str)
]

if not occurrences:
Expand All @@ -219,14 +233,13 @@ def str_replace(
# meaningful leading/trailing whitespace (e.g. a Markdown hard line
# break or intentional indentation) the caller asked to write.
old_str = old_str.strip()
pattern = re.escape(old_str)
occurrences = [
(
file_content.count("\n", 0, match.start()) + 1, # line number
match.group(), # matched text
match.start(), # start position
file_content.count("\n", 0, start) + 1, # line number
old_str, # matched text
start, # start position
)
for match in re.finditer(pattern, file_content)
for start in _occurrence_starts(file_content, old_str)
]
if not occurrences:
raise ToolError(
Expand Down
13 changes: 13 additions & 0 deletions tests/tools/file_editor/test_basic_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,6 +509,19 @@ def test_str_replace_error_multiple_multiline_occurrences(editor):
assert "[1, 7]" in error_msg # Should show correct starting line numbers


def test_str_replace_rejects_overlapping_occurrences(editor, tmp_path):
editor, _ = editor
# "aa" occurs at offsets 0 and 1 of "aaa", so it does not identify a single
# location and the replacement must be refused.
path = tmp_path / "overlap.txt"
path.write_text("aaa\n")

with pytest.raises(ToolError, match="Multiple occurrences"):
editor(command="str_replace", path=str(path), old_str="aa", new_str="b")

assert path.read_text() == "aaa\n"


def test_str_replace_nonexistent_string(editor):
editor, test_file = editor
with pytest.raises(ToolError) as exc_info:
Expand Down
Loading