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 collections.abc import Iterator, Mapping
from copy import deepcopy from copy import deepcopy
from dataclasses import dataclass from dataclasses import dataclass
from itertools import accumulate
from pathlib import Path from pathlib import Path
from typing import Any, BinaryIO 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) 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] = [] matches: list[_MatchSpan] = []
start = 0 start = previous = 0
while True: line = 1
idx = content.find(old_text, start) size = len(needle)
if idx == -1: step = size or 1
break while (idx := search_text.find(needle, start)) != -1:
matches.append( line += content.count("\n", previous, idx)
_MatchSpan( end = idx + size
start=idx, matches.append(_MatchSpan(idx, end, content[idx:end], line))
end=idx + len(old_text), previous = idx
text=content[idx : idx + len(old_text)], start = idx + step
line=content.count("\n", 0, idx) + 1,
)
)
start = idx + max(1, len(old_text))
return matches return matches
@@ -747,17 +745,11 @@ def _find_trim_matches(content: str, old_text: str, *, normalize_quotes: bool =
if not old_lines: if not old_lines:
return [] return []
content_lines = content.splitlines() content_lines = content.splitlines(keepends=True)
content_lines_keepends = content.splitlines(keepends=True)
if len(content_lines) < len(old_lines): if len(content_lines) < len(old_lines):
return [] return []
offsets: list[int] = [] offsets = list(accumulate(map(len, content_lines), initial=0))
pos = 0
for line in content_lines_keepends:
offsets.append(pos)
pos += len(line)
offsets.append(pos)
if normalize_quotes: if normalize_quotes:
stripped_old = [_normalize_quotes(line.strip()) for line in old_lines] 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. # Include the line terminator only when the requested match includes it.
if ( if (
not old_text.endswith("\n") 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 end -= 1
matches.append( matches.append(
@@ -794,38 +786,13 @@ def _find_trim_matches(content: str, old_text: str, *, normalize_quotes: bool =
return matches 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]: def _find_matches(content: str, old_text: str) -> list[_MatchSpan]:
for matcher in ( return (
lambda: _find_exact_matches(content, old_text), _find_literal_matches(content, content, old_text)
lambda: _find_trim_matches(content, old_text), or _find_trim_matches(content, old_text)
lambda: _find_trim_matches(content, old_text, normalize_quotes=True), or _find_trim_matches(content, old_text, normalize_quotes=True)
lambda: _find_quote_matches(content, old_text), or _find_literal_matches(content, _normalize_quotes(content), _normalize_quotes(old_text))
): )
matches = matcher()
if matches:
return matches
return []
def _collapse_internal_whitespace(text: str) -> str: 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 contextlib import suppress
from dataclasses import dataclass from dataclasses import dataclass
from functools import lru_cache from functools import lru_cache
from itertools import islice from itertools import count, islice
from pathlib import Path, PurePosixPath from pathlib import Path, PurePosixPath
from typing import Any, Iterable, Iterator, TypeVar from typing import Any, Iterable, Iterator, TypeVar
@@ -348,21 +348,6 @@ class FindFilesTool(_SearchTool):
# to propagate from the explicit checkpoints above. # to propagate from the explicit checkpoints above.
pass 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( def _iter_paths(
self, self,
tree: FileSearch, tree: FileSearch,
@@ -380,22 +365,23 @@ class FindFilesTool(_SearchTool):
if include_dirs: if include_dirs:
yield self._entry(root, root, is_dir=True) yield self._entry(root, root, is_dir=True)
frontier: list[tuple[str, int, _FindFilesEntry]] = [] sequence = count()
sequence = self._push_directory_entries(tree, root, root, frontier, 0, budget)
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: while frontier:
budget.checkpoint() budget.checkpoint()
_, _, entry = heapq.heappop(frontier) _, _, entry = heapq.heappop(frontier)
if entry.is_dir: if entry.is_dir:
if include_dirs: if include_dirs:
yield entry yield entry
sequence = self._push_directory_entries( for item in queue(entry.path):
tree, heapq.heappush(frontier, item)
entry.path,
root,
frontier,
sequence,
budget,
)
else: else:
yield entry 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): def test_edit_file_line_hint_can_cover_multiline_match(tmp_path):
target = tmp_path / "block.txt" 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) tool = EditFileTool(workspace=tmp_path)
result = asyncio.run(tool.execute( result = asyncio.run(tool.execute(
path=str(target), path=str(target),
old_text="start\nmiddle\nend", old_text="start\nmiddle\nend",
new_text="start\nchanged\nend", new_text="start\nchanged\nend",
line_hint=3, line_hint=7,
)) ))
assert "Patch applied:" in result 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): def test_edit_file_multiple_match_hint_mentions_occurrence(tmp_path):