refactor(files): reuse native matching and heap primitives

This commit is contained in:
Xubin Ren committed 2026-11-14 22:09:21 +08:00
1 parent 63209dab1d
commit 721cc4e23f
3 files changed
+37 -84

No files matched your search

+22 -55
View File
@@ -7,6 +7,7 @@ import mimetypes
from collections.abc import Iterator, Mapping
from copy import deepcopy
from dataclasses import dataclass
from itertools import accumulate
from pathlib import Path
from typing import Any, BinaryIO
@@ -723,22 +724,19 @@ def _match_covers_line(match: _MatchSpan, line: int) -> bool:
return match.line <= line <= _match_end_line(match)
def _find_exact_matches(content: str, old_text: str) -> list[_MatchSpan]:
def _find_literal_matches(content: str, search_text: str, needle: str) -> list[_MatchSpan]:
"""Locate matches in original text or its length-preserving quote normalization."""
matches: list[_MatchSpan] = []
start = 0
while True:
idx = content.find(old_text, start)
if idx == -1:
break
matches.append(
_MatchSpan(
start=idx,
end=idx + len(old_text),
text=content[idx : idx + len(old_text)],
line=content.count("\n", 0, idx) + 1,
)
)
start = idx + max(1, len(old_text))
start = previous = 0
line = 1
size = len(needle)
step = size or 1
while (idx := search_text.find(needle, start)) != -1:
line += content.count("\n", previous, idx)
end = idx + size
matches.append(_MatchSpan(idx, end, content[idx:end], line))
previous = idx
start = idx + step
return matches
@@ -747,17 +745,11 @@ def _find_trim_matches(content: str, old_text: str, *, normalize_quotes: bool =
if not old_lines:
return []
content_lines = content.splitlines()
content_lines_keepends = content.splitlines(keepends=True)
content_lines = content.splitlines(keepends=True)
if len(content_lines) < len(old_lines):
return []
offsets: list[int] = []
pos = 0
for line in content_lines_keepends:
offsets.append(pos)
pos += len(line)
offsets.append(pos)
offsets = list(accumulate(map(len, content_lines), initial=0))
if normalize_quotes:
stripped_old = [_normalize_quotes(line.strip()) for line in old_lines]
@@ -780,7 +772,7 @@ def _find_trim_matches(content: str, old_text: str, *, normalize_quotes: bool =
# Include the line terminator only when the requested match includes it.
if (
not old_text.endswith("\n")
and content_lines_keepends[i + window_size - 1].endswith("\n")
and content_lines[i + window_size - 1].endswith("\n")
):
end -= 1
matches.append(
@@ -794,38 +786,13 @@ def _find_trim_matches(content: str, old_text: str, *, normalize_quotes: bool =
return matches
def _find_quote_matches(content: str, old_text: str) -> list[_MatchSpan]:
norm_content = _normalize_quotes(content)
norm_old = _normalize_quotes(old_text)
matches: list[_MatchSpan] = []
start = 0
while True:
idx = norm_content.find(norm_old, start)
if idx == -1:
break
matches.append(
_MatchSpan(
start=idx,
end=idx + len(old_text),
text=content[idx : idx + len(old_text)],
line=content.count("\n", 0, idx) + 1,
)
)
start = idx + max(1, len(norm_old))
return matches
def _find_matches(content: str, old_text: str) -> list[_MatchSpan]:
for matcher in (
lambda: _find_exact_matches(content, old_text),
lambda: _find_trim_matches(content, old_text),
lambda: _find_trim_matches(content, old_text, normalize_quotes=True),
lambda: _find_quote_matches(content, old_text),
):
matches = matcher()
if matches:
return matches
return []
return (
_find_literal_matches(content, content, old_text)
or _find_trim_matches(content, old_text)
or _find_trim_matches(content, old_text, normalize_quotes=True)
or _find_literal_matches(content, _normalize_quotes(content), _normalize_quotes(old_text))
)
def _collapse_internal_whitespace(text: str) -> str:
+12 -26
View File
@@ -12,7 +12,7 @@ from collections.abc import Callable
from contextlib import suppress
from dataclasses import dataclass
from functools import lru_cache
from itertools import islice
from itertools import count, islice
from pathlib import Path, PurePosixPath
from typing import Any, Iterable, Iterator, TypeVar
@@ -348,21 +348,6 @@ class FindFilesTool(_SearchTool):
# to propagate from the explicit checkpoints above.
pass
def _push_directory_entries(
self,
tree: FileSearch,
directory: Path,
root: Path,
frontier: list[tuple[str, int, _FindFilesEntry]],
sequence: int,
budget: _SearchBudget,
) -> int:
for entry in self._directory_entries(tree, directory, root, budget):
sort_path = entry.display_path + ("/" if entry.is_dir else "")
heapq.heappush(frontier, (sort_path, sequence, entry))
sequence += 1
return sequence
def _iter_paths(
self,
tree: FileSearch,
@@ -380,22 +365,23 @@ class FindFilesTool(_SearchTool):
if include_dirs:
yield self._entry(root, root, is_dir=True)
frontier: list[tuple[str, int, _FindFilesEntry]] = []
sequence = self._push_directory_entries(tree, root, root, frontier, 0, budget)
sequence = count()
def queue(directory: Path) -> Iterator[tuple[str, int, _FindFilesEntry]]:
for entry in self._directory_entries(tree, directory, root, budget):
sort_path = entry.display_path + ("/" if entry.is_dir else "")
yield sort_path, next(sequence), entry
frontier = list(queue(root))
heapq.heapify(frontier)
while frontier:
budget.checkpoint()
_, _, entry = heapq.heappop(frontier)
if entry.is_dir:
if include_dirs:
yield entry
sequence = self._push_directory_entries(
tree,
entry.path,
root,
frontier,
sequence,
budget,
)
for item in queue(entry.path):
heapq.heappush(frontier, item)
else:
yield entry
@@ -108,18 +108,18 @@ def test_edit_file_rejects_unique_match_outside_line_hint(tmp_path):
def test_edit_file_line_hint_can_cover_multiline_match(tmp_path):
target = tmp_path / "block.txt"
target.write_text("before\nstart\nmiddle\nend\nafter\n")
target.write_text("before\nstart\nmiddle\nend\nbetween\nstart\nmiddle\nend\nafter\n")
tool = EditFileTool(workspace=tmp_path)
result = asyncio.run(tool.execute(
path=str(target),
old_text="start\nmiddle\nend",
new_text="start\nchanged\nend",
line_hint=3,
line_hint=7,
))
assert "Patch applied:" in result
assert target.read_text() == "before\nstart\nchanged\nend\nafter\n"
assert target.read_text() == "before\nstart\nmiddle\nend\nbetween\nstart\nchanged\nend\nafter\n"
def test_edit_file_multiple_match_hint_mentions_occurrence(tmp_path):