Merge pull request #921: fix(tools): provide diff hint when edit_file old_text not found
This commit is contained in:
@@ -172,30 +172,21 @@ class EditFileTool(Tool):
|
|||||||
"""Build a helpful error when old_text is not found."""
|
"""Build a helpful error when old_text is not found."""
|
||||||
lines = content.splitlines(keepends=True)
|
lines = content.splitlines(keepends=True)
|
||||||
old_lines = old_text.splitlines(keepends=True)
|
old_lines = old_text.splitlines(keepends=True)
|
||||||
|
|
||||||
best_ratio = 0.0
|
|
||||||
best_start = 0
|
|
||||||
window = len(old_lines)
|
window = len(old_lines)
|
||||||
|
|
||||||
|
best_ratio, best_start = 0.0, 0
|
||||||
for i in range(max(1, len(lines) - window + 1)):
|
for i in range(max(1, len(lines) - window + 1)):
|
||||||
chunk = lines[i : i + window]
|
ratio = difflib.SequenceMatcher(None, old_lines, lines[i : i + window]).ratio()
|
||||||
ratio = difflib.SequenceMatcher(None, old_lines, chunk).ratio()
|
|
||||||
if ratio > best_ratio:
|
if ratio > best_ratio:
|
||||||
best_ratio = ratio
|
best_ratio, best_start = ratio, i
|
||||||
best_start = i
|
|
||||||
|
|
||||||
if best_ratio > 0.5:
|
if best_ratio > 0.5:
|
||||||
best_chunk = lines[best_start : best_start + window]
|
diff = "\n".join(difflib.unified_diff(
|
||||||
diff = difflib.unified_diff(
|
old_lines, lines[best_start : best_start + window],
|
||||||
old_lines, best_chunk,
|
|
||||||
fromfile="old_text (provided)", tofile=f"{path} (actual, line {best_start + 1})",
|
fromfile="old_text (provided)", tofile=f"{path} (actual, line {best_start + 1})",
|
||||||
lineterm="",
|
lineterm="",
|
||||||
)
|
))
|
||||||
diff_str = "\n".join(diff)
|
return f"Error: old_text not found in {path}.\nBest match ({best_ratio:.0%} similar) at line {best_start + 1}:\n{diff}"
|
||||||
return (
|
|
||||||
f"Error: old_text not found in {path}.\n"
|
|
||||||
f"Best match ({best_ratio:.0%} similar) at line {best_start + 1}:\n{diff_str}"
|
|
||||||
)
|
|
||||||
return f"Error: old_text not found in {path}. No similar text found. Verify the file content."
|
return f"Error: old_text not found in {path}. No similar text found. Verify the file content."
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user