refactor(files): remove redundant edit and snapshot state
This commit is contained in:
1 parent
721cc4e23f
commit
51884a244e
6 files changed
+47
-61
No files matched your search
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterator, Mapping
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
from nanobot.agent.tools.base import ToolResult, tool_parameters
|
||||
@@ -102,8 +103,7 @@ class ApplyPatchTool(_WritableFsTool):
|
||||
raise _PatchError("must provide edits")
|
||||
|
||||
writes: dict[WritableFile, str] = {}
|
||||
originals: dict[WritableFile, str] = {}
|
||||
actions: dict[WritableFile, str] = {}
|
||||
originals: dict[WritableFile, str | None] = {}
|
||||
|
||||
for edit_value in edits:
|
||||
if not isinstance(edit_value, dict):
|
||||
@@ -124,21 +124,20 @@ class ApplyPatchTool(_WritableFsTool):
|
||||
raise _PatchError(f"new_text required for {action}: {path}")
|
||||
new_text = cast(str, new_text)
|
||||
|
||||
pending = writes.get(source)
|
||||
content = pending
|
||||
if content is None and source.exists():
|
||||
try:
|
||||
content = source.read_bytes().decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
raise _PatchError(f"file is not UTF-8 text: {path}")
|
||||
created = content is None
|
||||
content = writes.get(source)
|
||||
if content is None:
|
||||
if action == "replace":
|
||||
if source.exists():
|
||||
try:
|
||||
content = source.read_bytes().decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
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":
|
||||
raise _PatchError(f"file to update does not exist: {path}")
|
||||
content = ""
|
||||
|
||||
if action == "replace" and pending is None and not source.is_file():
|
||||
raise _PatchError(f"path to update is not a file: {path}")
|
||||
originals[source] = content
|
||||
if content is None:
|
||||
content = ""
|
||||
|
||||
norm_content = content.replace("\r\n", "\n")
|
||||
if action == "add":
|
||||
@@ -164,16 +163,14 @@ class ApplyPatchTool(_WritableFsTool):
|
||||
if updated and not updated.endswith("\n"):
|
||||
updated += "\n"
|
||||
writes[source] = updated.replace("\n", "\r\n") if "\r\n" in content else updated
|
||||
originals.setdefault(source, content)
|
||||
actions.setdefault(source, "add" if created else "update")
|
||||
|
||||
diffs = {
|
||||
source: FileDiff.from_text(originals[source], content)
|
||||
for source, content in writes.items()
|
||||
}
|
||||
diffs: dict[Path, FileDiff] = {}
|
||||
summaries: list[str] = []
|
||||
for source, diff in diffs.items():
|
||||
action_name = actions[source]
|
||||
for source, content in writes.items():
|
||||
original = originals[source]
|
||||
action_name = "add" if original is None else "update"
|
||||
diff = FileDiff.from_text(original or "", content)
|
||||
diffs[source.path] = diff
|
||||
path = display_file_edit_path(source.path, self._files.display_workspace)
|
||||
added, deleted = diff.added, diff.deleted
|
||||
stats = f" (+{added}/-{deleted})" if added or deleted else ""
|
||||
@@ -187,7 +184,7 @@ class ApplyPatchTool(_WritableFsTool):
|
||||
self._file_states.record_write(target.path)
|
||||
return FileEditResult(
|
||||
"Patch applied:\n" + "\n".join(summaries),
|
||||
{target.path: diff for target, diff in diffs.items()},
|
||||
diffs,
|
||||
)
|
||||
except PermissionError as exc:
|
||||
return ToolResult.error(f"Error: {exc}")
|
||||
|
||||
@@ -8,6 +8,7 @@ import heapq
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from collections import Counter
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
@@ -749,7 +750,7 @@ class GrepTool(_SearchTool):
|
||||
skipped_large = 0
|
||||
document_error: str | None = None
|
||||
document_continuations: list[str] = []
|
||||
counts: dict[str, int] = {}
|
||||
counts: Counter[str] = Counter()
|
||||
file_mtimes: dict[str, float] = {}
|
||||
root = tree.root if tree.is_directory else tree.root.parent
|
||||
max_file_bytes = (
|
||||
@@ -835,7 +836,7 @@ class GrepTool(_SearchTool):
|
||||
# A document can fail after yielding matches. Keep the count
|
||||
# of those lines even though the failed file is not ranked.
|
||||
if file_matches and output_mode == "count":
|
||||
counts[display_path] = counts.get(display_path, 0) + file_matches
|
||||
counts[display_path] += file_matches
|
||||
if file_matches:
|
||||
file_mtimes[display_path] = mtime
|
||||
if content_page.stopped:
|
||||
|
||||
@@ -99,15 +99,10 @@ class ReadableFile:
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class FileSnapshot:
|
||||
"""Text for the edit preview: empty for missing files, None if unavailable."""
|
||||
|
||||
exists: bool
|
||||
text: str | None
|
||||
unreadable: bool = False
|
||||
binary: bool = False
|
||||
oversized: bool = False
|
||||
|
||||
@property
|
||||
def countable(self) -> bool:
|
||||
return self.text is not None and not (self.binary or self.oversized or self.unreadable)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -140,18 +135,16 @@ class WritableFile:
|
||||
return FileSnapshot(exists=False, text="")
|
||||
with _open_regular_file(self.path) as (stream, size):
|
||||
if size > max_bytes:
|
||||
return FileSnapshot(exists=True, text=None, oversized=True)
|
||||
return FileSnapshot(exists=True, text=None)
|
||||
raw = stream.read(max_bytes + 1)
|
||||
except OSError:
|
||||
return FileSnapshot(exists=self.exists(), text=None, unreadable=True)
|
||||
if len(raw) > max_bytes:
|
||||
return FileSnapshot(exists=True, text=None, oversized=True)
|
||||
if b"\x00" in raw:
|
||||
return FileSnapshot(exists=True, text=None, binary=True)
|
||||
return FileSnapshot(exists=self.exists(), text=None)
|
||||
if len(raw) > max_bytes or b"\x00" in raw:
|
||||
return FileSnapshot(exists=True, text=None)
|
||||
try:
|
||||
text = raw.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
return FileSnapshot(exists=True, text=None, binary=True)
|
||||
return FileSnapshot(exists=True, text=None)
|
||||
return FileSnapshot(exists=True, text=text.replace("\r\n", "\n"))
|
||||
|
||||
|
||||
|
||||
@@ -248,10 +248,7 @@ def build_file_edit_end_event(
|
||||
) -> dict[str, Any]:
|
||||
after = tracker.target.snapshot(_MAX_SNAPSHOT_BYTES)
|
||||
diff_payload: dict[str, Any] | None = None
|
||||
if (
|
||||
tracker.before.countable and after.countable
|
||||
and tracker.before.text is not None and after.text is not None
|
||||
):
|
||||
if tracker.before.text is not None and after.text is not None:
|
||||
if diff is None or not diff.matches(tracker.before.text, after.text):
|
||||
diff = FileDiff.from_text(tracker.before.text, after.text)
|
||||
added, deleted = diff.added, diff.deleted
|
||||
@@ -265,14 +262,7 @@ def build_file_edit_end_event(
|
||||
binary = False
|
||||
else:
|
||||
added, deleted = 0, 0
|
||||
binary = (
|
||||
tracker.before.binary
|
||||
or tracker.before.oversized
|
||||
or tracker.before.unreadable
|
||||
or after.binary
|
||||
or after.oversized
|
||||
or after.unreadable
|
||||
)
|
||||
binary = True
|
||||
payload = _event_payload(
|
||||
tracker,
|
||||
phase="end",
|
||||
|
||||
Reference in new issue
Block a user