perf(files): retain only the requested directory prefix
This commit is contained in:
1 parent
150f0dfced
commit
f61d52439c
3 files changed
+61
-62
No files matched your search
@@ -12,6 +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 pathlib import Path, PurePosixPath
|
from pathlib import Path, PurePosixPath
|
||||||
from typing import Any, Iterable, Iterator, TypeVar
|
from typing import Any, Iterable, Iterator, TypeVar
|
||||||
|
|
||||||
@@ -200,14 +201,6 @@ def _matches_type(name: str, file_type: str | None) -> bool:
|
|||||||
return any(fnmatch.fnmatch(name.lower(), pattern.lower()) for pattern in patterns)
|
return any(fnmatch.fnmatch(name.lower(), pattern.lower()) for pattern in patterns)
|
||||||
|
|
||||||
|
|
||||||
def _matches_query(rel_path: str, query: str | None) -> bool:
|
|
||||||
if not query:
|
|
||||||
return True
|
|
||||||
haystack = rel_path.lower()
|
|
||||||
terms = [part for part in query.lower().split() if part]
|
|
||||||
return all(term in haystack for term in terms)
|
|
||||||
|
|
||||||
|
|
||||||
class _SearchTool(_FsTool):
|
class _SearchTool(_FsTool):
|
||||||
_IGNORE_DIRS = ListDirTool._IGNORE_DIRS | {".worktrees", ".worktree", ".nanobot"}
|
_IGNORE_DIRS = ListDirTool._IGNORE_DIRS | {".worktrees", ".worktree", ".nanobot"}
|
||||||
_MAX_SCAN_PATHS = 500_000
|
_MAX_SCAN_PATHS = 500_000
|
||||||
@@ -438,23 +431,6 @@ class FindFilesTool(_SearchTool):
|
|||||||
for entry, mtime in zip(selected, times, strict=True):
|
for entry, mtime in zip(selected, times, strict=True):
|
||||||
yield entry.display_path + ("/" if entry.is_dir else ""), mtime
|
yield entry.display_path + ("/" if entry.is_dir else ""), mtime
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _matches_entry(
|
|
||||||
entry: _FindFilesEntry,
|
|
||||||
*,
|
|
||||||
query: str | None,
|
|
||||||
glob: str | None,
|
|
||||||
file_type: str | None,
|
|
||||||
) -> bool:
|
|
||||||
if glob and not _match_glob(entry.rel_path, entry.name, glob):
|
|
||||||
return False
|
|
||||||
if entry.is_dir:
|
|
||||||
if file_type:
|
|
||||||
return False
|
|
||||||
elif not _matches_type(entry.name, file_type):
|
|
||||||
return False
|
|
||||||
return _matches_query(entry.display_path, query)
|
|
||||||
|
|
||||||
async def execute(
|
async def execute(
|
||||||
self,
|
self,
|
||||||
path: str = ".",
|
path: str = ".",
|
||||||
@@ -529,40 +505,40 @@ class FindFilesTool(_SearchTool):
|
|||||||
max_paths=self._MAX_SCAN_PATHS,
|
max_paths=self._MAX_SCAN_PATHS,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
terms = query.lower().split() if query else []
|
||||||
|
|
||||||
def matches_entry(entry: _FindFilesEntry) -> bool:
|
def matches_entry(entry: _FindFilesEntry) -> bool:
|
||||||
return self._matches_entry(entry, query=query, glob=glob, file_type=file_type)
|
if glob and not _match_glob(entry.rel_path, entry.name, glob):
|
||||||
|
return False
|
||||||
|
if file_type and (entry.is_dir or not _matches_type(entry.name, file_type)):
|
||||||
|
return False
|
||||||
|
if not terms:
|
||||||
|
return True
|
||||||
|
haystack = entry.display_path.lower()
|
||||||
|
return all(term in haystack for term in terms)
|
||||||
|
|
||||||
def matching_paths() -> Iterator[tuple[str, float]]:
|
selection_size = None if limit is None else offset + limit + 1
|
||||||
for entry in self._iter_paths(
|
|
||||||
tree,
|
|
||||||
include_dirs=include_dirs,
|
|
||||||
budget=budget,
|
|
||||||
):
|
|
||||||
if matches_entry(entry):
|
|
||||||
yield entry.display_path + ("/" if entry.is_dir else ""), 0.0
|
|
||||||
|
|
||||||
matches: list[tuple[str, float]]
|
|
||||||
try:
|
try:
|
||||||
if sort == "modified":
|
if sort == "modified":
|
||||||
by_modified = self._iter_modified(
|
by_modified = self._iter_modified(
|
||||||
tree, include_dirs=include_dirs, matches=matches_entry, budget=budget,
|
tree, include_dirs=include_dirs, matches=matches_entry, budget=budget,
|
||||||
)
|
)
|
||||||
if limit is None:
|
if selection_size is None:
|
||||||
matches = sorted(by_modified, key=lambda item: (-item[1], item[0]))
|
matches = sorted(by_modified, key=lambda item: (-item[1], item[0]))
|
||||||
else:
|
else:
|
||||||
selection_size = offset + limit + 1
|
|
||||||
matches = heapq.nsmallest(
|
matches = heapq.nsmallest(
|
||||||
selection_size,
|
selection_size,
|
||||||
by_modified,
|
by_modified,
|
||||||
key=lambda item: (-item[1], item[0]),
|
key=lambda item: (-item[1], item[0]),
|
||||||
)
|
)
|
||||||
|
paths = [item[0] for item in matches]
|
||||||
else:
|
else:
|
||||||
selection_size = None if limit is None else offset + limit + 1
|
matching_paths = (
|
||||||
matches = []
|
entry.display_path + ("/" if entry.is_dir else "")
|
||||||
for match in matching_paths():
|
for entry in self._iter_paths(tree, include_dirs=include_dirs, budget=budget)
|
||||||
matches.append(match)
|
if matches_entry(entry)
|
||||||
if selection_size is not None and len(matches) >= selection_size:
|
)
|
||||||
break
|
paths = list(islice(matching_paths, selection_size))
|
||||||
budget.checkpoint()
|
budget.checkpoint()
|
||||||
except _SearchBudgetExceededError as exc:
|
except _SearchBudgetExceededError as exc:
|
||||||
if str(exc) == "paths":
|
if str(exc) == "paths":
|
||||||
@@ -574,7 +550,6 @@ class FindFilesTool(_SearchTool):
|
|||||||
"narrow path, query, glob, or type and retry."
|
"narrow path, query, glob, or type and retry."
|
||||||
)
|
)
|
||||||
|
|
||||||
paths = [item[0] for item in matches]
|
|
||||||
paged, truncated = _text_page(paths, limit, offset, self._MAX_RESULT_CHARS)
|
paged, truncated = _text_page(paths, limit, offset, self._MAX_RESULT_CHARS)
|
||||||
if not paged:
|
if not paged:
|
||||||
return "No files found"
|
return "No files found"
|
||||||
|
|||||||
+25
-17
@@ -8,6 +8,8 @@ import stat
|
|||||||
from collections.abc import Callable, Generator, Iterable
|
from collections.abc import Callable, Generator, Iterable
|
||||||
from contextlib import AbstractContextManager, ExitStack, contextmanager
|
from contextlib import AbstractContextManager, ExitStack, contextmanager
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
from heapq import nsmallest
|
||||||
|
from operator import itemgetter
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import TYPE_CHECKING, BinaryIO
|
from typing import TYPE_CHECKING, BinaryIO
|
||||||
|
|
||||||
@@ -491,23 +493,29 @@ class WorkspaceFiles:
|
|||||||
if not directory.is_dir():
|
if not directory.is_dir():
|
||||||
raise NotADirectoryError(path)
|
raise NotADirectoryError(path)
|
||||||
tree = FileSearch(directory, True, self._read_path)
|
tree = FileSearch(directory, True, self._read_path)
|
||||||
pending = [directory]
|
total = 0
|
||||||
entries: list[tuple[Path, bool]] = []
|
|
||||||
while pending:
|
def walk() -> Generator[tuple[Path, bool]]:
|
||||||
parent = pending.pop()
|
nonlocal total
|
||||||
try:
|
pending = [directory]
|
||||||
for entry in tree.entries(parent):
|
while pending:
|
||||||
if entry.name in ignored:
|
parent = pending.pop()
|
||||||
continue
|
try:
|
||||||
child = parent / entry.name
|
for entry in tree.entries(parent):
|
||||||
entries.append((child.relative_to(directory), entry.is_directory))
|
if entry.name in ignored:
|
||||||
if recursive and entry.is_directory and not entry.is_directory_link:
|
continue
|
||||||
pending.append(child)
|
child = parent / entry.name
|
||||||
except PermissionError:
|
if recursive and entry.is_directory and not entry.is_directory_link:
|
||||||
if not recursive:
|
pending.append(child)
|
||||||
raise
|
total += 1
|
||||||
entries.sort(key=lambda entry: entry[0])
|
yield child.relative_to(directory), entry.is_directory
|
||||||
return DirectoryListing(entries[:max(0, limit)], len(entries))
|
except PermissionError:
|
||||||
|
if not recursive:
|
||||||
|
raise
|
||||||
|
|
||||||
|
# Scan all entries for the exact total, but retain only the requested prefix.
|
||||||
|
entries = nsmallest(max(1, limit), walk(), key=itemgetter(0))
|
||||||
|
return DirectoryListing(entries if limit > 0 else [], total)
|
||||||
|
|
||||||
def sibling_files(self, target: WritableFile) -> list[str]:
|
def sibling_files(self, target: WritableFile) -> list[str]:
|
||||||
"""Suggest names only when the caller can read the directory itself."""
|
"""Suggest names only when the caller can read the directory itself."""
|
||||||
|
|||||||
@@ -385,6 +385,22 @@ class TestListDirTool:
|
|||||||
assert "truncated" in result
|
assert "truncated" in result
|
||||||
assert "3 of 10" in result
|
assert "3 of 10" in result
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_recursive_limit_preserves_sorted_prefix_and_exact_total(self, tool, tmp_path):
|
||||||
|
(tmp_path / "z").mkdir()
|
||||||
|
(tmp_path / "z" / "a.txt").touch()
|
||||||
|
(tmp_path / "a").mkdir()
|
||||||
|
(tmp_path / "a" / "z.txt").touch()
|
||||||
|
(tmp_path / "b.txt").touch()
|
||||||
|
(tmp_path / ".git").mkdir()
|
||||||
|
(tmp_path / ".git" / "ignored").touch()
|
||||||
|
|
||||||
|
result = await tool.execute(path=".", recursive=True, max_entries=3)
|
||||||
|
|
||||||
|
assert result.replace("\\", "/").splitlines() == [
|
||||||
|
"a/", "a/z.txt", "b.txt", "", "(truncated, showing first 3 of 5 entries)",
|
||||||
|
]
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_empty_dir(self, tool, tmp_path):
|
async def test_empty_dir(self, tool, tmp_path):
|
||||||
d = tmp_path / "empty"
|
d = tmp_path / "empty"
|
||||||
|
|||||||
Reference in new issue
Block a user