Snippet parsing for FasterEditHighlightedCodeStep

This commit is contained in:
Nate Sesti 2023-05-29 15:47:36 -04:00
parent 30d83f19da
commit 8c00cddb93
2 changed files with 25 additions and 1 deletions

View file

@ -191,7 +191,7 @@ class FasterEditHighlightedCodeStep(Step):
replace_me = edit["replace_me"]
replace_with = edit["replace_with"]
file_edits.append(
FileEdit(filepath=filepath, range=Range.from_snippet_in_file(content=rif_dict[filepath], snippet=replace_me), replacement=replace_with))
FileEdit(filepath=filepath, range=Range.from_lines_snippet_in_file(content=rif_dict[filepath], snippet=replace_me), replacement=replace_with))
# ------------------------------
self._edit_diffs = []

View file

@ -93,6 +93,30 @@ class Range(BaseModel):
end_index = start_index + len(snippet)
return Range.from_indices(content, start_index, end_index)
@staticmethod
def from_lines_snippet_in_file(content: str, snippet: str) -> "Range":
# lines is a substring of the content modulo whitespace on each line
content_lines = content.splitlines()
snippet_lines = snippet.splitlines()
start_line = -1
end_line = -1
looking_for_line = 0
for i in range(len(content_lines)):
if content_lines[i].strip() == snippet_lines[looking_for_line].strip():
if looking_for_line == len(snippet_lines) - 1:
start_line = i - len(snippet_lines) + 1
end_line = i
break
looking_for_line += 1
else:
looking_for_line = 0
if start_line == -1 or end_line == -1:
raise ValueError("Snippet not found in content")
return Range.from_shorthand(start_line, 0, end_line, len(content_lines[end_line]) - 1)
class AbstractModel(ABC, BaseModel):
@root_validator(pre=True)