Skip to content

Commit

Permalink
Fix buggy get_code_region_containing_code
Browse files Browse the repository at this point in the history
  • Loading branch information
Marti2203 committed Oct 20, 2024
1 parent 290aebb commit fd13430
Showing 1 changed file with 9 additions and 27 deletions.
36 changes: 9 additions & 27 deletions app/search/search_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,36 +233,18 @@ def get_code_region_containing_code(
pattern = re.compile(re.escape(code_str))
# each occurrence is a tuple of (line_no, code_snippet) (1-based line number)
occurrences: list[tuple[int, str]] = []
file_content_lines = file_content.splitlines()
for match in pattern.finditer(file_content):
matched_start_pos = match.start()
# first, find the line number of the matched start position (1-based)
matched_line_no = file_content.count("\n", 0, matched_start_pos) + 1
# next, get a few surrounding lines as context
search_start = match.start() - 1
search_end = match.end() + 1
# from the matched position, go left to find 5 new lines.
for _ in range(context_size):
# find the \n to the left
left_newline = file_content.rfind("\n", 0, search_start)
if left_newline == -1:
# no more new line to the left
search_start = 0
break
else:
search_start = left_newline
# go right to fine 5 new lines
for _ in range(context_size):
right_newline = file_content.find("\n", search_end + 1)
if right_newline == -1:
# no more new line to the right
search_end = len(file_content)
break
else:
search_end = right_newline
# first, find the line number of the matched start position (0-based)
matched_line_no = file_content.count("\n", 0, matched_start_pos)

window_start_index = max(0, matched_line_no - context_size)
window_end_index = min(
len(file_content_lines), matched_line_no + context_size + 1
)

start = max(0, search_start)
end = min(len(file_content), search_end)
context = file_content[start:end]
context = "\n".join(file_content_lines[window_start_index:window_end_index])
occurrences.append((matched_line_no, context))

return occurrences
Expand Down

0 comments on commit fd13430

Please sign in to comment.