Guard file handles and streamline scoped search
This commit is contained in:
1 parent
51884a244e
commit
5c7ff5b796
6 files changed
+137
-78
No files matched your search
@@ -131,8 +131,6 @@ class ApplyPatchTool(_WritableFsTool):
|
|||||||
content = source.read_bytes().decode("utf-8")
|
content = source.read_bytes().decode("utf-8")
|
||||||
except UnicodeDecodeError:
|
except UnicodeDecodeError:
|
||||||
raise _PatchError(f"file is not UTF-8 text: {path}")
|
raise _PatchError(f"file is not UTF-8 text: {path}")
|
||||||
if action == "replace" and not source.is_file():
|
|
||||||
raise _PatchError(f"path to update is not a file: {path}")
|
|
||||||
elif action == "replace":
|
elif action == "replace":
|
||||||
raise _PatchError(f"file to update does not exist: {path}")
|
raise _PatchError(f"file to update does not exist: {path}")
|
||||||
originals[source] = content
|
originals[source] = content
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import threading
|
|||||||
import time
|
import time
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
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 count, islice
|
from itertools import count, islice
|
||||||
@@ -61,7 +60,6 @@ class _FindFilesEntry:
|
|||||||
path: Path
|
path: Path
|
||||||
rel_path: str
|
rel_path: str
|
||||||
display_path: str
|
display_path: str
|
||||||
name: str
|
|
||||||
is_dir: bool
|
is_dir: bool
|
||||||
|
|
||||||
|
|
||||||
@@ -218,13 +216,6 @@ class _SearchTool(_FsTool):
|
|||||||
def _ignore_directory(cls, name: str) -> bool:
|
def _ignore_directory(cls, name: str) -> bool:
|
||||||
return name in cls._IGNORE_DIRS or name.startswith(".verify-")
|
return name in cls._IGNORE_DIRS or name.startswith(".verify-")
|
||||||
|
|
||||||
def _display_path(self, target: Path, root: Path) -> str:
|
|
||||||
workspace = self._files.display_workspace
|
|
||||||
if workspace:
|
|
||||||
with suppress(ValueError):
|
|
||||||
return target.relative_to(workspace).as_posix()
|
|
||||||
return target.relative_to(root).as_posix()
|
|
||||||
|
|
||||||
def _iter_files(self, tree: FileSearch, budget: _SearchBudget) -> Iterable[Path]:
|
def _iter_files(self, tree: FileSearch, budget: _SearchBudget) -> Iterable[Path]:
|
||||||
if not tree.is_directory:
|
if not tree.is_directory:
|
||||||
budget.visit_path()
|
budget.visit_path()
|
||||||
@@ -318,21 +309,11 @@ class FindFilesTool(_SearchTool):
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
def _entry(self, path: Path, root: Path, *, is_dir: bool) -> _FindFilesEntry:
|
|
||||||
display_path = self._display_path(path, root)
|
|
||||||
return _FindFilesEntry(
|
|
||||||
path=path,
|
|
||||||
rel_path=path.relative_to(root).as_posix(),
|
|
||||||
display_path=display_path,
|
|
||||||
name=path.name,
|
|
||||||
is_dir=is_dir,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _directory_entries(
|
def _directory_entries(
|
||||||
self,
|
self,
|
||||||
tree: FileSearch,
|
tree: FileSearch,
|
||||||
directory: Path,
|
directory: Path,
|
||||||
root: Path,
|
entry_for: Callable[[Path, bool], _FindFilesEntry],
|
||||||
budget: _SearchBudget,
|
budget: _SearchBudget,
|
||||||
) -> Iterator[_FindFilesEntry]:
|
) -> Iterator[_FindFilesEntry]:
|
||||||
budget.checkpoint()
|
budget.checkpoint()
|
||||||
@@ -342,7 +323,7 @@ class FindFilesTool(_SearchTool):
|
|||||||
is_dir = raw_entry.is_directory
|
is_dir = raw_entry.is_directory
|
||||||
if raw_entry.is_directory_link or (is_dir and self._ignore_directory(raw_entry.name)):
|
if raw_entry.is_directory_link or (is_dir and self._ignore_directory(raw_entry.name)):
|
||||||
continue
|
continue
|
||||||
yield self._entry(directory / raw_entry.name, root, is_dir=is_dir)
|
yield entry_for(directory / raw_entry.name, is_dir)
|
||||||
except OSError:
|
except OSError:
|
||||||
# os.walk silently skips directories that cannot be listed. Preserve
|
# os.walk silently skips directories that cannot be listed. Preserve
|
||||||
# that behavior while still allowing cancellation and budget errors
|
# that behavior while still allowing cancellation and budget errors
|
||||||
@@ -354,22 +335,23 @@ class FindFilesTool(_SearchTool):
|
|||||||
tree: FileSearch,
|
tree: FileSearch,
|
||||||
*,
|
*,
|
||||||
include_dirs: bool,
|
include_dirs: bool,
|
||||||
|
entry_for: Callable[[Path, bool], _FindFilesEntry],
|
||||||
budget: _SearchBudget,
|
budget: _SearchBudget,
|
||||||
) -> Iterable[_FindFilesEntry]:
|
) -> Iterable[_FindFilesEntry]:
|
||||||
budget.checkpoint()
|
budget.checkpoint()
|
||||||
root = tree.root
|
root = tree.root
|
||||||
if not tree.is_directory:
|
if not tree.is_directory:
|
||||||
budget.visit_path()
|
budget.visit_path()
|
||||||
yield self._entry(root, root.parent, is_dir=False)
|
yield entry_for(root, False)
|
||||||
return
|
return
|
||||||
|
|
||||||
if include_dirs:
|
if include_dirs:
|
||||||
yield self._entry(root, root, is_dir=True)
|
yield entry_for(root, True)
|
||||||
|
|
||||||
sequence = count()
|
sequence = count()
|
||||||
|
|
||||||
def queue(directory: Path) -> Iterator[tuple[str, int, _FindFilesEntry]]:
|
def queue(directory: Path) -> Iterator[tuple[str, int, _FindFilesEntry]]:
|
||||||
for entry in self._directory_entries(tree, directory, root, budget):
|
for entry in self._directory_entries(tree, directory, entry_for, budget):
|
||||||
sort_path = entry.display_path + ("/" if entry.is_dir else "")
|
sort_path = entry.display_path + ("/" if entry.is_dir else "")
|
||||||
yield sort_path, next(sequence), entry
|
yield sort_path, next(sequence), entry
|
||||||
|
|
||||||
@@ -391,6 +373,7 @@ class FindFilesTool(_SearchTool):
|
|||||||
tree: FileSearch,
|
tree: FileSearch,
|
||||||
*,
|
*,
|
||||||
include_dirs: bool,
|
include_dirs: bool,
|
||||||
|
entry_for: Callable[[Path, bool], _FindFilesEntry],
|
||||||
matches: Callable[[_FindFilesEntry], bool],
|
matches: Callable[[_FindFilesEntry], bool],
|
||||||
budget: _SearchBudget,
|
budget: _SearchBudget,
|
||||||
) -> Iterator[tuple[str, float]]:
|
) -> Iterator[tuple[str, float]]:
|
||||||
@@ -399,7 +382,7 @@ class FindFilesTool(_SearchTool):
|
|||||||
if not tree.is_directory or include_dirs:
|
if not tree.is_directory or include_dirs:
|
||||||
if not tree.is_directory:
|
if not tree.is_directory:
|
||||||
budget.visit_path()
|
budget.visit_path()
|
||||||
entry = self._entry(root, root if tree.is_directory else root.parent, is_dir=tree.is_directory)
|
entry = entry_for(root, tree.is_directory)
|
||||||
if matches(entry):
|
if matches(entry):
|
||||||
yield entry.display_path + ("/" if entry.is_dir else ""), tree.modified(root)
|
yield entry.display_path + ("/" if entry.is_dir else ""), tree.modified(root)
|
||||||
if not tree.is_directory:
|
if not tree.is_directory:
|
||||||
@@ -410,7 +393,7 @@ class FindFilesTool(_SearchTool):
|
|||||||
while pending:
|
while pending:
|
||||||
directory = pending.pop()
|
directory = pending.pop()
|
||||||
selected: list[_FindFilesEntry] = []
|
selected: list[_FindFilesEntry] = []
|
||||||
for entry in self._directory_entries(tree, directory, root, budget):
|
for entry in self._directory_entries(tree, directory, entry_for, budget):
|
||||||
if entry.is_dir:
|
if entry.is_dir:
|
||||||
pending.append(entry.path)
|
pending.append(entry.path)
|
||||||
if not include_dirs:
|
if not include_dirs:
|
||||||
@@ -419,7 +402,7 @@ class FindFilesTool(_SearchTool):
|
|||||||
selected.append(entry)
|
selected.append(entry)
|
||||||
if selected:
|
if selected:
|
||||||
times = tree.modified_children(
|
times = tree.modified_children(
|
||||||
directory, [entry.name for entry in selected], checkpoint=budget.checkpoint,
|
directory, [entry.path.name for entry in selected], checkpoint=budget.checkpoint,
|
||||||
)
|
)
|
||||||
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
|
||||||
@@ -499,11 +482,19 @@ class FindFilesTool(_SearchTool):
|
|||||||
)
|
)
|
||||||
|
|
||||||
terms = query.lower().split() if query else []
|
terms = query.lower().split() if query else []
|
||||||
|
root = tree.root if tree.is_directory else tree.root.parent
|
||||||
|
workspace = self._files.display_workspace
|
||||||
|
display_root = workspace if workspace and root.is_relative_to(workspace) else root
|
||||||
|
|
||||||
|
def entry_for(path: Path, is_dir: bool) -> _FindFilesEntry:
|
||||||
|
rel_path = path.relative_to(root).as_posix()
|
||||||
|
displayed = rel_path if display_root == root else path.relative_to(display_root).as_posix()
|
||||||
|
return _FindFilesEntry(path, rel_path, displayed, is_dir)
|
||||||
|
|
||||||
def matches_entry(entry: _FindFilesEntry) -> bool:
|
def matches_entry(entry: _FindFilesEntry) -> bool:
|
||||||
if glob and not _match_glob(entry.rel_path, entry.name, glob):
|
if glob and not _match_glob(entry.rel_path, entry.path.name, glob):
|
||||||
return False
|
return False
|
||||||
if file_type and (entry.is_dir or not _matches_type(entry.name, file_type)):
|
if file_type and (entry.is_dir or not _matches_type(entry.path.name, file_type)):
|
||||||
return False
|
return False
|
||||||
if not terms:
|
if not terms:
|
||||||
return True
|
return True
|
||||||
@@ -514,14 +505,14 @@ class FindFilesTool(_SearchTool):
|
|||||||
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, entry_for=entry_for, matches=matches_entry, budget=budget,
|
||||||
)
|
)
|
||||||
matches = _ordered_prefix(by_modified, selection_size, key=lambda item: (-item[1], item[0]))
|
matches = _ordered_prefix(by_modified, selection_size, key=lambda item: (-item[1], item[0]))
|
||||||
paths = [item[0] for item in matches]
|
paths = [item[0] for item in matches]
|
||||||
else:
|
else:
|
||||||
matching_paths = (
|
matching_paths = (
|
||||||
entry.display_path + ("/" if entry.is_dir else "")
|
entry.display_path + ("/" if entry.is_dir else "")
|
||||||
for entry in self._iter_paths(tree, include_dirs=include_dirs, budget=budget)
|
for entry in self._iter_paths(tree, include_dirs=include_dirs, entry_for=entry_for, budget=budget)
|
||||||
if matches_entry(entry)
|
if matches_entry(entry)
|
||||||
)
|
)
|
||||||
paths = list(islice(matching_paths, selection_size))
|
paths = list(islice(matching_paths, selection_size))
|
||||||
@@ -643,8 +634,8 @@ class GrepTool(_SearchTool):
|
|||||||
}
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _text_source(raw: bytes, max_bytes: int) -> DocumentLineSource | None:
|
def _text_source(raw: bytes) -> DocumentLineSource | None:
|
||||||
if len(raw) > max_bytes or _is_binary(raw):
|
if _is_binary(raw):
|
||||||
return None
|
return None
|
||||||
try:
|
try:
|
||||||
content = raw.decode("utf-8")
|
content = raw.decode("utf-8")
|
||||||
@@ -758,6 +749,7 @@ class GrepTool(_SearchTool):
|
|||||||
)
|
)
|
||||||
|
|
||||||
workspace = self._files.display_workspace
|
workspace = self._files.display_workspace
|
||||||
|
display_root = workspace if workspace and root.is_relative_to(workspace) else root
|
||||||
with tree.search_bytes_reader() as read_bytes:
|
with tree.search_bytes_reader() as read_bytes:
|
||||||
for file_path in self._iter_files(tree, budget):
|
for file_path in self._iter_files(tree, budget):
|
||||||
rel_path = file_path.relative_to(root).as_posix()
|
rel_path = file_path.relative_to(root).as_posix()
|
||||||
@@ -765,10 +757,7 @@ class GrepTool(_SearchTool):
|
|||||||
continue
|
continue
|
||||||
if not _matches_type(file_path.name, type):
|
if not _matches_type(file_path.name, type):
|
||||||
continue
|
continue
|
||||||
display_path = rel_path
|
display_path = rel_path if display_root == root else file_path.relative_to(display_root).as_posix()
|
||||||
if workspace is not None and workspace != root:
|
|
||||||
with suppress(ValueError):
|
|
||||||
display_path = file_path.relative_to(workspace).as_posix()
|
|
||||||
|
|
||||||
source: DocumentLineSource | None = None
|
source: DocumentLineSource | None = None
|
||||||
is_document = file_path.suffix.lower() in _DOCUMENT_EXTENSIONS
|
is_document = file_path.suffix.lower() in _DOCUMENT_EXTENSIONS
|
||||||
@@ -794,7 +783,7 @@ class GrepTool(_SearchTool):
|
|||||||
skipped_large += 1
|
skipped_large += 1
|
||||||
continue
|
continue
|
||||||
mtime = contents.modified
|
mtime = contents.modified
|
||||||
source = self._text_source(contents.data, max_file_bytes)
|
source = self._text_source(contents.data)
|
||||||
if source is None:
|
if source is None:
|
||||||
skipped_binary += 1
|
skipped_binary += 1
|
||||||
continue
|
continue
|
||||||
|
|||||||
+43
-29
@@ -6,7 +6,7 @@ import os
|
|||||||
import re
|
import re
|
||||||
import stat
|
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, suppress
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from heapq import nsmallest
|
from heapq import nsmallest
|
||||||
from operator import itemgetter
|
from operator import itemgetter
|
||||||
@@ -27,17 +27,17 @@ class NotRegularFileError(OSError):
|
|||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def _open_regular_file(
|
def _open_regular_file(
|
||||||
resolved_path: Path | str, *, dir_fd: int | None = None,
|
resolved_path: Path | str, *, dir_fd: int | None = None, write: bool = False,
|
||||||
) -> Generator[tuple[BinaryIO, int]]:
|
) -> Generator[tuple[BinaryIO, int]]:
|
||||||
"""Own one descriptor for the entire read and report its initial size.
|
"""Own one descriptor and check its type before reading or truncating it.
|
||||||
|
|
||||||
Callers must supply an authorized path or a child of an authorized directory handle.
|
Callers must supply an authorized path or a child of an authorized directory handle.
|
||||||
Where supported, refuse a swapped-in final symlink and avoid waiting on
|
Where supported, refuse a swapped-in final symlink and avoid waiting on
|
||||||
a swapped-in FIFO. This does not protect ancestor path components.
|
a swapped-in FIFO. This does not protect ancestor path components.
|
||||||
"""
|
"""
|
||||||
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
|
flags = (os.O_WRONLY | os.O_CREAT) if write else os.O_RDONLY
|
||||||
flags |= getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)
|
flags |= getattr(os, "O_BINARY", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)
|
||||||
with os.fdopen(os.open(resolved_path, flags, dir_fd=dir_fd), "rb") as stream:
|
with os.fdopen(os.open(resolved_path, flags, 0o666, dir_fd=dir_fd), "wb" if write else "rb") as stream:
|
||||||
opened = os.fstat(stream.fileno())
|
opened = os.fstat(stream.fileno())
|
||||||
if not stat.S_ISREG(opened.st_mode):
|
if not stat.S_ISREG(opened.st_mode):
|
||||||
raise NotRegularFileError
|
raise NotRegularFileError
|
||||||
@@ -114,24 +114,22 @@ class WritableFile:
|
|||||||
def exists(self) -> bool:
|
def exists(self) -> bool:
|
||||||
return self.path.exists()
|
return self.path.exists()
|
||||||
|
|
||||||
def is_file(self) -> bool:
|
|
||||||
return self.path.is_file()
|
|
||||||
|
|
||||||
def size(self) -> int:
|
def size(self) -> int:
|
||||||
return self.path.stat().st_size
|
return self.path.stat().st_size
|
||||||
|
|
||||||
def read_bytes(self) -> bytes:
|
def read_bytes(self) -> bytes:
|
||||||
return self.path.read_bytes()
|
with _open_regular_file(self.path) as (stream, _):
|
||||||
|
return stream.read()
|
||||||
|
|
||||||
def write(self, content: str, *, create_parents: bool = False) -> None:
|
def write(self, content: str, *, create_parents: bool = False) -> None:
|
||||||
if create_parents:
|
if create_parents:
|
||||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
self.path.write_text(content, encoding="utf-8", newline="")
|
_write_regular_file(self.path, content.encode("utf-8"))
|
||||||
|
|
||||||
def snapshot(self, max_bytes: int) -> FileSnapshot:
|
def snapshot(self, max_bytes: int) -> FileSnapshot:
|
||||||
"""Read a bounded edit preview, not an independent path grant."""
|
"""Read a bounded edit preview, not an independent path grant."""
|
||||||
try:
|
try:
|
||||||
if not self.is_file():
|
if not self.path.is_file():
|
||||||
return FileSnapshot(exists=False, text="")
|
return FileSnapshot(exists=False, text="")
|
||||||
with _open_regular_file(self.path) as (stream, size):
|
with _open_regular_file(self.path) as (stream, size):
|
||||||
if size > max_bytes:
|
if size > max_bytes:
|
||||||
@@ -148,6 +146,12 @@ class WritableFile:
|
|||||||
return FileSnapshot(exists=True, text=text.replace("\r\n", "\n"))
|
return FileSnapshot(exists=True, text=text.replace("\r\n", "\n"))
|
||||||
|
|
||||||
|
|
||||||
|
def _write_regular_file(path: Path, data: bytes) -> None:
|
||||||
|
with _open_regular_file(path, write=True) as (stream, _):
|
||||||
|
stream.truncate(0)
|
||||||
|
stream.write(data)
|
||||||
|
|
||||||
|
|
||||||
def commit_file_edits(writes: dict[WritableFile, str]) -> None:
|
def commit_file_edits(writes: dict[WritableFile, str]) -> None:
|
||||||
"""Write validated patch targets; restore their previous bytes on failure."""
|
"""Write validated patch targets; restore their previous bytes on failure."""
|
||||||
backups = {target: target.read_bytes() if target.exists() else None for target in writes}
|
backups = {target: target.read_bytes() if target.exists() else None for target in writes}
|
||||||
@@ -159,11 +163,13 @@ def commit_file_edits(writes: dict[WritableFile, str]) -> None:
|
|||||||
except Exception:
|
except Exception:
|
||||||
for target in attempted:
|
for target in attempted:
|
||||||
data = backups[target]
|
data = backups[target]
|
||||||
if data is None:
|
# A replaced target can reject rollback. Continue restoring the
|
||||||
target.path.unlink(missing_ok=True)
|
# other targets without replacing the original write error.
|
||||||
else:
|
with suppress(OSError):
|
||||||
target.path.parent.mkdir(parents=True, exist_ok=True)
|
if data is None:
|
||||||
target.path.write_bytes(data)
|
target.path.unlink(missing_ok=True)
|
||||||
|
else:
|
||||||
|
_write_regular_file(target.path, data)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
@@ -326,15 +332,20 @@ class FileSearch:
|
|||||||
opened_path = path.name
|
opened_path = path.name
|
||||||
if size > limit:
|
if size > limit:
|
||||||
return SearchBytes(None, modified)
|
return SearchBytes(None, modified)
|
||||||
with _open_regular_file(opened_path, dir_fd=fd) as (stream, opened_size):
|
try:
|
||||||
if opened_size > limit:
|
with _open_regular_file(opened_path, dir_fd=fd) as (stream, opened_size):
|
||||||
return None
|
if opened_size > limit:
|
||||||
# Avoid allocating the full scan limit for each small file. The
|
return SearchBytes(None, modified)
|
||||||
# extra byte detects growth (including streams with a reported size of zero).
|
# The extra byte detects growth without allocating the full
|
||||||
data = stream.read(opened_size + 1)
|
# scan limit for every small file.
|
||||||
if len(data) > opened_size:
|
data = stream.read(opened_size + 1)
|
||||||
data += stream.read(limit + 1 - len(data))
|
if len(data) > opened_size:
|
||||||
return SearchBytes(data, modified)
|
data += stream.read(limit + 1 - len(data))
|
||||||
|
return SearchBytes(data if len(data) <= limit else None, modified)
|
||||||
|
except OSError:
|
||||||
|
if not self.is_directory:
|
||||||
|
raise
|
||||||
|
return None # The file disappeared, changed type, or became unreadable.
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def search_bytes_reader(self) -> Generator[Callable[[Path, int], SearchBytes | None]]:
|
def search_bytes_reader(self) -> Generator[Callable[[Path, int], SearchBytes | None]]:
|
||||||
@@ -430,7 +441,7 @@ class WorkspaceFiles:
|
|||||||
)
|
)
|
||||||
return access.project_path, self._allowed_root(access.allowed_root)
|
return access.project_path, self._allowed_root(access.allowed_root)
|
||||||
|
|
||||||
def _read_path(self, path: str | Path) -> Path:
|
def _read_path(self, path: str | Path, *, include_file_grants: bool = True) -> Path:
|
||||||
workspace, root = self._roots()
|
workspace, root = self._roots()
|
||||||
extra_roots: list[Path] = []
|
extra_roots: list[Path] = []
|
||||||
if root is not None:
|
if root is not None:
|
||||||
@@ -445,7 +456,7 @@ class WorkspaceFiles:
|
|||||||
workspace=workspace,
|
workspace=workspace,
|
||||||
allowed_root=root,
|
allowed_root=root,
|
||||||
extra_allowed_roots=extra_roots,
|
extra_allowed_roots=extra_roots,
|
||||||
extra_allowed_files=self._read_files if root is not None else (),
|
extra_allowed_files=self._read_files if root is not None and include_file_grants else (),
|
||||||
)
|
)
|
||||||
|
|
||||||
def edit_target(self, path: str) -> WritableFile:
|
def edit_target(self, path: str) -> WritableFile:
|
||||||
@@ -490,6 +501,7 @@ class WorkspaceFiles:
|
|||||||
raise FileNotFoundError(path)
|
raise FileNotFoundError(path)
|
||||||
if not directory.is_dir():
|
if not directory.is_dir():
|
||||||
raise NotADirectoryError(path)
|
raise NotADirectoryError(path)
|
||||||
|
directory = self._read_path(directory, include_file_grants=False)
|
||||||
tree = FileSearch(directory, True, self._read_path)
|
tree = FileSearch(directory, True, self._read_path)
|
||||||
total = 0
|
total = 0
|
||||||
|
|
||||||
@@ -526,6 +538,8 @@ class WorkspaceFiles:
|
|||||||
def search_tree(self, path: str) -> FileSearch:
|
def search_tree(self, path: str) -> FileSearch:
|
||||||
target = self._read_path(path)
|
target = self._read_path(path)
|
||||||
mode = target.stat().st_mode
|
mode = target.stat().st_mode
|
||||||
if not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)):
|
if stat.S_ISDIR(mode):
|
||||||
|
target = self._read_path(target, include_file_grants=False)
|
||||||
|
elif not stat.S_ISREG(mode):
|
||||||
raise NotRegularFileError
|
raise NotRegularFileError
|
||||||
return FileSearch(target, stat.S_ISDIR(mode), self._read_path)
|
return FileSearch(target, stat.S_ISDIR(mode), self._read_path)
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from nanobot.agent.tools.apply_patch import ApplyPatchTool
|
from nanobot.agent.tools.apply_patch import ApplyPatchTool
|
||||||
|
from nanobot.execution.files import WritableFile
|
||||||
|
|
||||||
|
|
||||||
def test_apply_patch_edits_replace(tmp_path):
|
def test_apply_patch_edits_replace(tmp_path):
|
||||||
@@ -472,18 +472,17 @@ def test_apply_patch_edits_rolls_back_when_later_write_fails(tmp_path, monkeypat
|
|||||||
second_original = b"before\r\nsecond tail"
|
second_original = b"before\r\nsecond tail"
|
||||||
second.write_bytes(second_original)
|
second.write_bytes(second_original)
|
||||||
tool = ApplyPatchTool(workspace=tmp_path)
|
tool = ApplyPatchTool(workspace=tmp_path)
|
||||||
write_text = Path.write_text
|
write = WritableFile.write
|
||||||
failed = False
|
failed = False
|
||||||
|
|
||||||
def _fail_second_write(path, *args, **kwargs):
|
def _fail_second_write(target, *args, **kwargs):
|
||||||
nonlocal failed
|
nonlocal failed
|
||||||
written = write_text(path, *args, **kwargs)
|
write(target, *args, **kwargs)
|
||||||
if path == second and not failed:
|
if target.path == second.resolve() and not failed:
|
||||||
failed = True
|
failed = True
|
||||||
raise OSError("injected second write failure")
|
raise OSError("injected second write failure")
|
||||||
return written
|
|
||||||
|
|
||||||
monkeypatch.setattr(Path, "write_text", _fail_second_write)
|
monkeypatch.setattr(WritableFile, "write", _fail_second_write)
|
||||||
|
|
||||||
result = asyncio.run(
|
result = asyncio.run(
|
||||||
tool.execute(
|
tool.execute(
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ from nanobot.agent.tools.filesystem import (
|
|||||||
ReadFileTool,
|
ReadFileTool,
|
||||||
WriteFileTool,
|
WriteFileTool,
|
||||||
)
|
)
|
||||||
|
from nanobot.execution.files import WorkspaceFiles
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="requires a POSIX named pipe")
|
@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="requires a POSIX named pipe")
|
||||||
@@ -39,6 +40,39 @@ async def test_file_mutation_rejects_named_pipe_without_opening_it(tmp_path, mon
|
|||||||
assert "Not a regular file: pipe" in result
|
assert "Not a regular file: pipe" in result
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.skipif(not hasattr(os, "O_NOFOLLOW"), reason="requires no-follow file opens")
|
||||||
|
@pytest.mark.parametrize("operation", ["write", "patch"])
|
||||||
|
async def test_file_mutation_does_not_follow_a_symlink_swapped_in_after_authorization(
|
||||||
|
tmp_path, monkeypatch, operation,
|
||||||
|
):
|
||||||
|
workspace = (tmp_path / "workspace").resolve()
|
||||||
|
workspace.mkdir()
|
||||||
|
inside = workspace / "inside.txt"
|
||||||
|
outside = tmp_path / "private.txt"
|
||||||
|
inside.write_text("before", encoding="utf-8")
|
||||||
|
outside.write_text("private", encoding="utf-8")
|
||||||
|
authorize = WorkspaceFiles.edit_target
|
||||||
|
|
||||||
|
def swap_after_authorize(files, path):
|
||||||
|
target = authorize(files, path)
|
||||||
|
inside.unlink()
|
||||||
|
inside.symlink_to(outside)
|
||||||
|
return target
|
||||||
|
|
||||||
|
monkeypatch.setattr(WorkspaceFiles, "edit_target", swap_after_authorize)
|
||||||
|
if operation == "write":
|
||||||
|
result = await WriteFileTool(workspace=workspace, allowed_dir=workspace).execute(
|
||||||
|
path="inside.txt", content="changed",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
result = await ApplyPatchTool(workspace=workspace, allowed_dir=workspace).execute(
|
||||||
|
edits=[{"path": "inside.txt", "action": "add", "new_text": "changed"}],
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.is_error
|
||||||
|
assert outside.read_text(encoding="utf-8") == "private"
|
||||||
|
|
||||||
|
|
||||||
async def test_exact_edit_grant_does_not_list_sibling_files(tmp_path):
|
async def test_exact_edit_grant_does_not_list_sibling_files(tmp_path):
|
||||||
workspace = tmp_path / "workspace"
|
workspace = tmp_path / "workspace"
|
||||||
workspace.mkdir()
|
workspace.mkdir()
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ from nanobot.agent.tools.search import FindFilesTool, GrepTool
|
|||||||
from nanobot.agent.tools.web import WebSearchTool
|
from nanobot.agent.tools.web import WebSearchTool
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
from nanobot.config.schema import WebSearchConfig
|
from nanobot.config.schema import WebSearchConfig
|
||||||
from nanobot.execution.files import FileSearch
|
from nanobot.execution.files import FileSearch, WorkspaceFiles
|
||||||
from nanobot.providers.base import GenerationSettings
|
from nanobot.providers.base import GenerationSettings
|
||||||
from nanobot.security.workspace_access import (
|
from nanobot.security.workspace_access import (
|
||||||
bind_workspace_scope,
|
bind_workspace_scope,
|
||||||
@@ -363,6 +363,31 @@ async def test_exact_read_grant_does_not_authorize_a_directory_tree(tmp_path: Pa
|
|||||||
assert "needle private" not in result
|
assert "needle private" not in result
|
||||||
|
|
||||||
|
|
||||||
|
async def test_search_cannot_expand_exact_file_grant_after_file_becomes_directory(
|
||||||
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
|
||||||
|
) -> None:
|
||||||
|
workspace = tmp_path / "workspace"
|
||||||
|
workspace.mkdir()
|
||||||
|
grant = tmp_path / "history.jsonl"
|
||||||
|
grant.write_text("needle history", encoding="utf-8")
|
||||||
|
resolve_read = WorkspaceFiles._read_path
|
||||||
|
|
||||||
|
def replace_after_grant(files, path, **kwargs):
|
||||||
|
target = resolve_read(files, path, **kwargs)
|
||||||
|
if target == grant.resolve() and target.is_file():
|
||||||
|
target.unlink()
|
||||||
|
target.mkdir()
|
||||||
|
(target / "private.txt").write_text("needle private", encoding="utf-8")
|
||||||
|
return target
|
||||||
|
|
||||||
|
monkeypatch.setattr(WorkspaceFiles, "_read_path", replace_after_grant)
|
||||||
|
tool = GrepTool(workspace=workspace, allowed_dir=workspace, extra_read_allowed_files=[grant])
|
||||||
|
result = await tool.execute(pattern="needle", path=str(grant))
|
||||||
|
assert is_tool_error_result(result)
|
||||||
|
assert "outside allowed directory" in result
|
||||||
|
assert "needle private" not in result
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_find_files_cancellation_stops_worker_scan(
|
async def test_find_files_cancellation_stops_worker_scan(
|
||||||
tmp_path: Path,
|
tmp_path: Path,
|
||||||
@@ -962,7 +987,7 @@ async def test_grep_keeps_read_limit_when_an_open_file_grows(tmp_path, monkeypat
|
|||||||
|
|
||||||
if exceeds_limit:
|
if exceeds_limit:
|
||||||
assert result.startswith("No matches found")
|
assert result.startswith("No matches found")
|
||||||
assert "skipped 1 binary/unreadable files" in result
|
assert "skipped 1 large files" in result
|
||||||
else:
|
else:
|
||||||
assert result == "growing.log"
|
assert result == "growing.log"
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user