fix(tools): preserve authorized document link search
This commit is contained in:
1 parent
d2e03d23a0
commit
66b8c447dc
5 files changed
+90
-56
No files matched your search
@@ -634,7 +634,7 @@ class GrepTool(_SearchTool):
|
||||
|
||||
@staticmethod
|
||||
def _open_source(source: ReadableFile, pages: str | None, max_bytes: int) -> DocumentLineSource | None:
|
||||
if source.path.suffix.lower() in _DOCUMENT_EXTENSIONS:
|
||||
if source.suffix in _DOCUMENT_EXTENSIONS:
|
||||
return source.document_lines(pages=pages)
|
||||
with source.open() as (file, size):
|
||||
if size > max_bytes:
|
||||
@@ -770,7 +770,7 @@ class GrepTool(_SearchTool):
|
||||
skipped_large += 1
|
||||
continue
|
||||
source_iterator: Iterator[LocatedDocumentLine] | None = None
|
||||
is_document = file.path.suffix.lower() in _DOCUMENT_EXTENSIONS
|
||||
is_document = file.suffix in _DOCUMENT_EXTENSIONS
|
||||
try:
|
||||
source = self._open_source(file, pages, max_file_bytes)
|
||||
if source is None:
|
||||
|
||||
+10
-12
@@ -73,6 +73,7 @@ class ReadableFile:
|
||||
path: Path
|
||||
size: int
|
||||
modified: float
|
||||
suffix: str
|
||||
|
||||
def open(self) -> AbstractContextManager[tuple[BinaryIO, int]]:
|
||||
return _open_regular_file(self.path)
|
||||
@@ -89,7 +90,7 @@ class ReadableFile:
|
||||
def document_lines(self, *, pages: str | None = None) -> DocumentLineSource | None:
|
||||
from nanobot.utils.document import open_document_line_source
|
||||
|
||||
return open_document_line_source(self.path, pages=pages)
|
||||
return open_document_line_source(self.path, pages=pages, suffix=self.suffix)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -218,15 +219,15 @@ class FileSearch:
|
||||
return self._candidate(path).stat().st_mtime
|
||||
|
||||
def read_file(self, path: Path) -> ReadableFile:
|
||||
return _regular_file(self._candidate(path))
|
||||
return _regular_file(self._candidate(path), suffix=path.suffix.lower())
|
||||
|
||||
|
||||
def _regular_file(target: Path) -> ReadableFile:
|
||||
def _regular_file(target: Path, *, suffix: str | None = None) -> ReadableFile:
|
||||
_reject_device(target, resolved=True)
|
||||
info = target.stat()
|
||||
if not stat.S_ISREG(info.st_mode):
|
||||
raise NotRegularFileError
|
||||
return ReadableFile(target, info.st_size, info.st_mtime)
|
||||
return ReadableFile(target, info.st_size, info.st_mtime, target.suffix.lower() if suffix is None else suffix)
|
||||
|
||||
|
||||
class WorkspaceFiles:
|
||||
@@ -305,7 +306,7 @@ class WorkspaceFiles:
|
||||
)
|
||||
return access.project_path, self._allowed_root(access.allowed_root)
|
||||
|
||||
def _read_path(self, path: str | Path, *, directory: bool = False) -> Path:
|
||||
def _read_path(self, path: str | Path) -> Path:
|
||||
workspace, root = self._roots()
|
||||
extra_roots: list[Path] = []
|
||||
if root is not None:
|
||||
@@ -320,7 +321,7 @@ class WorkspaceFiles:
|
||||
workspace=workspace,
|
||||
allowed_root=root,
|
||||
extra_allowed_roots=extra_roots,
|
||||
extra_allowed_files=self._read_files if root is not None and not directory else (),
|
||||
extra_allowed_files=self._read_files if root is not None else (),
|
||||
)
|
||||
|
||||
def edit_target(self, path: str) -> WritableFile:
|
||||
@@ -352,7 +353,7 @@ class WorkspaceFiles:
|
||||
def list_directory(
|
||||
self, path: str, *, recursive: bool, ignored: set[str], limit: int,
|
||||
) -> DirectoryListing:
|
||||
directory = self._read_path(path, directory=True)
|
||||
directory = self._read_path(path)
|
||||
if not directory.exists():
|
||||
raise FileNotFoundError(path)
|
||||
if not directory.is_dir():
|
||||
@@ -379,7 +380,7 @@ class WorkspaceFiles:
|
||||
def sibling_files(self, target: WritableFile) -> list[str]:
|
||||
"""Suggest names only when the caller can read the directory itself."""
|
||||
try:
|
||||
parent = self._read_path(target.path.parent, directory=True)
|
||||
parent = self._read_path(target.path.parent)
|
||||
except PermissionError:
|
||||
return []
|
||||
return [item.name for item in parent.iterdir() if item.is_file()] if parent.is_dir() else []
|
||||
@@ -389,7 +390,4 @@ class WorkspaceFiles:
|
||||
mode = target.stat().st_mode
|
||||
if not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)):
|
||||
raise NotRegularFileError
|
||||
is_directory = stat.S_ISDIR(mode)
|
||||
if is_directory:
|
||||
target = self._read_path(path, directory=True)
|
||||
return FileSearch(target, is_directory, self._read_path)
|
||||
return FileSearch(target, stat.S_ISDIR(mode), self._read_path)
|
||||
@@ -70,7 +70,9 @@ def _is_path_exactly_allowed(
|
||||
except (OSError, RuntimeError, TypeError, ValueError):
|
||||
continue
|
||||
if _path_key(allowed_file) == logical_key:
|
||||
return True
|
||||
# A missing file can be created, but an exact file grant cannot
|
||||
# become a directory grant if the path now refers to a directory.
|
||||
return not resolved_path.is_dir()
|
||||
return False
|
||||
|
||||
|
||||
|
||||
+44
-41
@@ -136,6 +136,7 @@ def open_document_line_source(
|
||||
path: str | Path,
|
||||
*,
|
||||
pages: str | None = None,
|
||||
suffix: str | None = None,
|
||||
) -> DocumentLineSource | None:
|
||||
"""Open a document as an incremental stream of extracted lines.
|
||||
|
||||
@@ -145,8 +146,9 @@ def open_document_line_source(
|
||||
blank separators) have ``searchable=False`` so range reads can retain them
|
||||
without making grep match synthetic text.
|
||||
"""
|
||||
# Format can come from a displayed name; all I/O uses the supplied path.
|
||||
path = Path(path)
|
||||
ext = path.suffix.lower()
|
||||
ext = (path.suffix if suffix is None else suffix).lower()
|
||||
if ext not in {".pdf", ".docx", ".xlsx", ".pptx"}:
|
||||
return None
|
||||
if error := _extraction_path_error(path):
|
||||
@@ -241,54 +243,55 @@ def _open_xlsx_line_source(path: Path) -> DocumentLineSource:
|
||||
from openpyxl import load_workbook
|
||||
except ImportError as e:
|
||||
raise DocumentExtractionError("openpyxl not installed") from e
|
||||
try:
|
||||
workbook = load_workbook(path, read_only=True, data_only=True)
|
||||
except Exception as e:
|
||||
raise DocumentExtractionError(f"failed to open XLSX: {e!s}") from e
|
||||
|
||||
def iter_lines() -> Iterator[LocatedDocumentLine]:
|
||||
extracted_line = 0
|
||||
wrote_document_content = False
|
||||
try:
|
||||
for worksheet in workbook.worksheets:
|
||||
sheet_name = worksheet.title
|
||||
# Producer-supplied dimensions can omit cells that are present in the XML.
|
||||
worksheet.reset_dimensions()
|
||||
wrote_header = False
|
||||
for row_index, row in enumerate(worksheet.iter_rows(values_only=True), 1):
|
||||
cells = [str(cell) if cell is not None else "" for cell in row]
|
||||
row_text = "\t".join(cells)
|
||||
if not row_text.strip():
|
||||
continue
|
||||
column_starts: list[int] = []
|
||||
offset = 0
|
||||
for cell in cells:
|
||||
column_starts.append(offset)
|
||||
offset += len(cell) + 1
|
||||
if not wrote_header:
|
||||
if wrote_document_content:
|
||||
# Let openpyxl parse the authorized file even if its real name has no suffix.
|
||||
with path.open("rb") as source:
|
||||
try:
|
||||
workbook = load_workbook(source, read_only=True, data_only=True)
|
||||
except Exception as e:
|
||||
raise DocumentExtractionError(f"failed to open XLSX: {e!s}") from e
|
||||
extracted_line = 0
|
||||
wrote_document_content = False
|
||||
try:
|
||||
for worksheet in workbook.worksheets:
|
||||
sheet_name = worksheet.title
|
||||
# Producer-supplied dimensions can omit cells that are present in the XML.
|
||||
worksheet.reset_dimensions()
|
||||
wrote_header = False
|
||||
for row_index, row in enumerate(worksheet.iter_rows(values_only=True), 1):
|
||||
cells = [str(cell) if cell is not None else "" for cell in row]
|
||||
row_text = "\t".join(cells)
|
||||
if not row_text.strip():
|
||||
continue
|
||||
column_starts: list[int] = []
|
||||
offset = 0
|
||||
for cell in cells:
|
||||
column_starts.append(offset)
|
||||
offset += len(cell) + 1
|
||||
if not wrote_header:
|
||||
if wrote_document_content:
|
||||
extracted_line += 1
|
||||
yield LocatedDocumentLine(
|
||||
"", extracted_line, "", searchable=False
|
||||
)
|
||||
extracted_line += 1
|
||||
yield LocatedDocumentLine(
|
||||
"", extracted_line, "", searchable=False
|
||||
f"--- Sheet: {sheet_name} ---",
|
||||
extracted_line,
|
||||
"",
|
||||
searchable=False,
|
||||
)
|
||||
wrote_header = True
|
||||
wrote_document_content = True
|
||||
extracted_line += 1
|
||||
yield LocatedDocumentLine(
|
||||
f"--- Sheet: {sheet_name} ---",
|
||||
row_text,
|
||||
extracted_line,
|
||||
"",
|
||||
searchable=False,
|
||||
f"sheet={sheet_name!r},row={row_index}",
|
||||
column_starts=tuple(column_starts),
|
||||
)
|
||||
wrote_header = True
|
||||
wrote_document_content = True
|
||||
extracted_line += 1
|
||||
yield LocatedDocumentLine(
|
||||
row_text,
|
||||
extracted_line,
|
||||
f"sheet={sheet_name!r},row={row_index}",
|
||||
column_starts=tuple(column_starts),
|
||||
)
|
||||
finally:
|
||||
workbook.close()
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
return DocumentLineSource(iter_lines())
|
||||
|
||||
|
||||
@@ -484,6 +484,37 @@ async def test_grep_searches_pdf_with_page_locator(tmp_path: Path) -> None:
|
||||
assert "pdf needle" in result
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("suffix", "locator"), [
|
||||
(".pdf", "[page=1,line=1]"),
|
||||
(".xlsx", "[sheet='Sheet',row=1,cell=A1]"),
|
||||
])
|
||||
async def test_grep_uses_document_link_name_for_format(tmp_path: Path, suffix: str, locator: str) -> None:
|
||||
target = tmp_path / "stored-content"
|
||||
link = tmp_path / f"manual{suffix}"
|
||||
if suffix == ".pdf":
|
||||
import fitz
|
||||
|
||||
with fitz.open() as document:
|
||||
document.new_page().insert_text((72, 72), "document needle")
|
||||
document.save(target)
|
||||
else:
|
||||
from openpyxl import Workbook
|
||||
|
||||
workbook = Workbook()
|
||||
workbook["Sheet"]["A1"] = "document needle"
|
||||
workbook.save(target)
|
||||
workbook.close()
|
||||
try:
|
||||
link.symlink_to(target)
|
||||
except (NotImplementedError, OSError):
|
||||
pytest.skip("symlinks unavailable")
|
||||
|
||||
tool = GrepTool(workspace=tmp_path, allowed_dir=tmp_path)
|
||||
result = await tool.execute(pattern="document needle", path=".", glob=f"*{suffix}", fixed_strings=True)
|
||||
assert f"{link.name}:2 {locator}" in result
|
||||
assert "document needle" in result
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_grep_searches_xlsx_beyond_attachment_preview_limit(
|
||||
tmp_path: Path,
|
||||
|
||||
Reference in new issue
Block a user