refactor(files): simplify patch staging and bounded diff rendering

This commit is contained in:
Xubin Ren committed 2026-11-14 22:09:21 +08:00
1 parent f24383771d
commit 150f0dfced
4 files changed
+119 -229

No files matched your search

+35 -83
View File
@@ -31,17 +31,6 @@ def _validate_patch_path(path: object) -> str:
return normalized return normalized
def _append_text(content: str, addition: str) -> str:
base = content.replace("\r\n", "\n")
extra = addition.replace("\r\n", "\n")
if base and extra and not base.endswith("\n") and not extra.startswith("\n"):
base += "\n"
combined = base + extra
if combined and not combined.endswith("\n"):
combined += "\n"
return combined
@tool_parameters( @tool_parameters(
tool_parameters_schema( tool_parameters_schema(
edits=ArraySchema( edits=ArraySchema(
@@ -125,70 +114,40 @@ class ApplyPatchTool(_WritableFsTool):
if not isinstance(action, str): if not isinstance(action, str):
raise _PatchError(f"action required for edit: {path}") raise _PatchError(f"action required for edit: {path}")
source = self._files.edit_target(path) source = self._files.edit_target(path)
if action not in ("add", "replace"):
raise _PatchError(f"unknown action: {action}")
old_text = edit.get("old_text") or ""
if action == "replace" and not old_text:
raise _PatchError(f"old_text required for replace: {path}")
new_text = edit.get("new_text")
if new_text is None:
raise _PatchError(f"new_text required for {action}: {path}")
new_text = cast(str, new_text)
if action == "add": pending = writes.get(source)
new_text = edit.get("new_text") content = pending
if new_text is None: if content is None and source.exists():
raise _PatchError(f"new_text required for add: {path}") try:
new_text = cast(str, new_text) content = source.read_bytes().decode("utf-8")
except UnicodeDecodeError:
pending = writes.get(source) raise _PatchError(f"file is not UTF-8 text: {path}")
if pending is not None: created = content is None
content = pending if content is None:
exists = True if action == "replace":
elif source.exists():
raw = source.read_bytes()
try:
content = raw.decode("utf-8")
except UnicodeDecodeError:
raise _PatchError(f"file is not UTF-8 text: {path}")
exists = True
else:
content = ""
exists = False
if exists:
uses_crlf = "\r\n" in content
new_norm = _append_text(content, new_text)
if uses_crlf:
new_norm = new_norm.replace("\n", "\r\n")
writes[source] = new_norm
action_name = "update"
else:
new_norm = new_text.replace("\r\n", "\n")
if new_norm and not new_norm.endswith("\n"):
new_norm += "\n"
writes[source] = new_norm
action_name = "add"
elif action == "replace":
old_text = edit.get("old_text") or ""
if not old_text:
raise _PatchError(f"old_text required for replace: {path}")
old_text = cast(str, old_text)
new_text = edit.get("new_text")
if new_text is None:
raise _PatchError(f"new_text required for replace: {path}")
new_text = cast(str, new_text)
pending = writes.get(source)
if pending is not None:
content = pending
elif source.exists():
raw = source.read_bytes()
try:
content = raw.decode("utf-8")
except UnicodeDecodeError:
raise _PatchError(f"file is not UTF-8 text: {path}")
else:
raise _PatchError(f"file to update does not exist: {path}") raise _PatchError(f"file to update does not exist: {path}")
content = ""
if pending is None and not source.is_file(): if action == "replace" and pending is None and not source.is_file():
raise _PatchError(f"path to update is not a file: {path}") raise _PatchError(f"path to update is not a file: {path}")
uses_crlf = "\r\n" in content norm_content = content.replace("\r\n", "\n")
norm_content = content.replace("\r\n", "\n") if action == "add":
norm_old = old_text.replace("\r\n", "\n") norm_new = new_text.replace("\r\n", "\n")
if norm_content and norm_new and not norm_content.endswith("\n") and not norm_new.startswith("\n"):
norm_content += "\n"
updated = norm_content + norm_new
else:
norm_old = cast(str, old_text).replace("\r\n", "\n")
pos = norm_content.find(norm_old) pos = norm_content.find(norm_old)
if pos < 0: if pos < 0:
@@ -196,24 +155,17 @@ class ApplyPatchTool(_WritableFsTool):
if norm_content.find(norm_old, pos + 1) >= 0: if norm_content.find(norm_old, pos + 1) >= 0:
raise _PatchError(f"old_text appears multiple times in {path}") raise _PatchError(f"old_text appears multiple times in {path}")
new_norm = ( updated = (
norm_content[:pos] norm_content[:pos]
+ new_text.replace("\r\n", "\n") + new_text.replace("\r\n", "\n")
+ norm_content[pos + len(norm_old) :] + norm_content[pos + len(norm_old) :]
) )
if new_norm and not new_norm.endswith("\n"):
new_norm += "\n"
if uses_crlf:
new_norm = new_norm.replace("\n", "\r\n")
writes[source] = new_norm
action_name = "update"
else:
raise _PatchError(f"unknown action: {action}")
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) originals.setdefault(source, content)
actions.setdefault(source, action_name) actions.setdefault(source, "add" if created else "update")
diffs = { diffs = {
source: FileDiff.from_text(originals[source], content) source: FileDiff.from_text(originals[source], content)
+54 -146
View File
@@ -1,9 +1,8 @@
from __future__ import annotations from __future__ import annotations
import re
from collections.abc import Iterable, Iterator, Mapping from collections.abc import Iterable, Iterator, Mapping
from dataclasses import dataclass from dataclasses import dataclass
from itertools import groupby, islice from itertools import islice
from pathlib import Path from pathlib import Path
from typing import Any, Protocol, cast, runtime_checkable from typing import Any, Protocol, cast, runtime_checkable
@@ -100,34 +99,58 @@ class FileDiff:
if any(code.tag != "equal" for code in group): if any(code.tag != "equal" for code in group):
yield group yield group
def unified_lines(self, fromfile: str, tofile: str, context: int) -> Iterator[str]: def _hunk_lines(self, group: list[Opcode]) -> Iterator[str]:
if not self.added and not self.deleted: for code in group:
return if code.tag != "insert":
yield f"--- {fromfile}" marker = " " if code.tag == "equal" else "-"
yield f"+++ {tofile}" yield from (
for group in self._groups(context): marker + self.before_lines[index]
for index in range(code.src_start, code.src_end)
)
if code.tag in ("replace", "insert"):
yield from (
"+" + self.after_lines[index]
for index in range(code.dest_start, code.dest_end)
)
def unified_payload(
self, fromfile: str, tofile: str, *, context_lines: int, max_lines: int, max_line_chars: int,
) -> dict[str, Any] | None:
remaining = max(0, int(max_lines))
line_width = max(0, int(max_line_chars))
lines = [f"--- {fromfile}", f"+++ {tofile}"]
truncated = False
for group in self._groups(max(0, int(context_lines))):
if not remaining:
truncated = True
break
body = list(islice(self._hunk_lines(group), remaining + 1))
if len(body) > remaining:
body.pop()
truncated = True
first, last = group[0], group[-1] first, last = group[0], group[-1]
old_count = last.src_end - first.src_start # Clipping changes the displayed line counts, not the original hunk starts.
new_count = last.dest_end - first.dest_start old_start = first.src_start + (last.src_end > first.src_start)
old_range = _format_hunk_range(first.src_start + bool(old_count), old_count) new_start = first.dest_start + (last.dest_end > first.dest_start)
new_range = _format_hunk_range(first.dest_start + bool(new_count), new_count) old_range = _format_hunk_range(old_start, sum(line[0] != "+" for line in body))
yield f"@@ -{old_range} +{new_range} @@" new_range = _format_hunk_range(new_start, sum(line[0] != "-" for line in body))
for code in group: lines.append(f"@@ -{old_range} +{new_range} @@")
if code.tag == "equal": for line in body:
yield from ( if line_width and len(line) > line_width + 1:
" " + self.before_lines[index] line = line[:line_width + 1] # The diff marker is not part of the content.
for index in range(code.src_start, code.src_end) truncated = True
) lines.append(line)
if code.tag in ("replace", "delete"): remaining -= len(body)
yield from (
"-" + self.before_lines[index] if len(lines) == 2:
for index in range(code.src_start, code.src_end) return None
) return {
if code.tag in ("replace", "insert"): "format": "unified",
yield from ( "context": context_lines,
"+" + self.after_lines[index] "truncated": truncated,
for index in range(code.dest_start, code.dest_end) "text": "\n".join(lines),
) }
class FileEditResult(str): class FileEditResult(str):
@@ -154,8 +177,6 @@ def display_file_edit_path(path: Path, workspace: Path | None) -> str:
return path.as_posix() return path.as_posix()
def build_unified_diff_payload( def build_unified_diff_payload(
before: str | None, before: str | None,
after: str | None, after: str | None,
@@ -172,123 +193,10 @@ def build_unified_diff_payload(
return None return None
if diff is None: if diff is None:
diff = FileDiff.from_text(before, after) diff = FileDiff.from_text(before, after)
limited_lines, truncated, emitted_body_lines = _limit_unified_diff_lines( return diff.unified_payload(
diff.unified_lines(fromfile, tofile, max(0, int(context_lines))), fromfile, tofile, context_lines=context_lines, max_lines=max_lines,
max_lines=max_lines,
max_line_chars=max_line_chars, max_line_chars=max_line_chars,
) )
if emitted_body_lines == 0:
return None
return {
"format": "unified",
"context": context_lines,
"truncated": truncated,
"text": "\n".join(limited_lines),
}
def _limit_unified_diff_lines(
diff_lines: Iterable[str],
*,
max_lines: int,
max_line_chars: int,
) -> tuple[list[str], bool, int]:
body_limit = max(0, int(max_lines))
line_char_limit = max(0, int(max_line_chars))
limited: list[str] = []
emitted_body_lines = 0
truncated = False
line_groups = groupby(diff_lines, key=lambda line: line.startswith("@@ "))
for is_hunk_header, lines in line_groups:
if not is_hunk_header:
limited.extend(lines)
continue
hunk_header = next(lines)
remaining = body_limit - emitted_body_lines
if remaining <= 0:
truncated = True
break
_, hunk_lines = next(line_groups)
hunk_body = list(islice(hunk_lines, remaining + 1))
selected_body = hunk_body[:remaining]
if len(selected_body) < len(hunk_body):
truncated = True
selected_body, truncated_line = _limit_unified_diff_line_chars(
selected_body,
max_line_chars=line_char_limit,
)
truncated = truncated or truncated_line
limited.append(
hunk_header
if len(selected_body) == len(hunk_body)
else _rewrite_hunk_header_for_body(hunk_header, selected_body)
)
limited.extend(selected_body)
emitted_body_lines += len(selected_body)
if truncated and emitted_body_lines >= body_limit:
break
return limited, truncated, emitted_body_lines
def _limit_unified_diff_line_chars(
lines: list[str],
*,
max_line_chars: int,
) -> tuple[list[str], bool]:
if max_line_chars <= 0:
return lines, False
limited: list[str] = []
truncated = False
for line in lines:
if not line or line[0] not in (" ", "+", "-"):
limited.append(line)
continue
marker = line[0]
content = line[1:]
if len(content) > max_line_chars:
limited.append(f"{marker}{content[:max_line_chars]}")
truncated = True
else:
limited.append(line)
return limited, truncated
_HUNK_HEADER_RE = re.compile(
r"^@@ -(?P<old_start>\d+)(?:,(?P<old_lines>\d+))? "
r"\+(?P<new_start>\d+)(?:,(?P<new_lines>\d+))? @@(?P<section>.*)$"
)
def _rewrite_hunk_header_for_body(header: str, body: list[str]) -> str:
match = _HUNK_HEADER_RE.match(header)
if match is None:
return header
old_lines = 0
new_lines = 0
for line in body:
if not line:
continue
marker = line[0]
if marker in (" ", "-"):
old_lines += 1
if marker in (" ", "+"):
new_lines += 1
old_start = int(match.group("old_start"))
new_start = int(match.group("new_start"))
section = match.group("section")
return (
f"@@ -{_format_hunk_range(old_start, old_lines)} "
f"+{_format_hunk_range(new_start, new_lines)} @@{section}"
)
def _format_hunk_range(start: int, line_count: int) -> str: def _format_hunk_range(start: int, line_count: int) -> str:
+18
View File
@@ -141,6 +141,24 @@ def test_apply_patch_edits_add_to_existing_crlf_file_without_final_newline(tmp_p
assert target.read_bytes() == b"alpha\r\nbravo\r\ncharlie\r\n" assert target.read_bytes() == b"alpha\r\nbravo\r\ncharlie\r\n"
@pytest.mark.parametrize("existing", [False, True], ids=["new-file", "existing-crlf"])
def test_apply_patch_replaces_text_from_an_earlier_edit_in_the_batch(tmp_path, existing):
target = tmp_path / "notes.txt"
if existing:
target.write_bytes(b"alpha\r\nbravo")
tool = ApplyPatchTool(workspace=tmp_path)
result = asyncio.run(tool.execute(edits=[
{"path": "notes.txt", "action": "add", "new_text": "charlie"},
{"path": "./notes.txt", "action": "replace", "old_text": "charlie", "new_text": "delta"},
]))
assert result.startswith("Patch applied:\n")
assert result.count("notes.txt") == 1
assert f"{'update' if existing else 'add'} notes.txt" in result
assert target.read_bytes() == (b"alpha\r\nbravo\r\ndelta\r\n" if existing else b"delta\n")
def test_apply_patch_rejects_delete_action(tmp_path): def test_apply_patch_rejects_delete_action(tmp_path):
target = tmp_path / "utils.py" target = tmp_path / "utils.py"
target.write_text("def unused():\n pass\ndef used():\n return 1\n") target.write_text("def unused():\n pass\ndef used():\n return 1\n")
+12
View File
@@ -210,6 +210,18 @@ def test_unified_diff_payload_truncates_large_diffs() -> None:
assert len(body_lines) == 5 assert len(body_lines) == 5
def test_unified_diff_clips_long_content_without_changing_header_counts() -> None:
payload = build_unified_diff_payload(
"old line\nkeep this\n", "new line\nkeep this\n", max_line_chars=3,
)
assert payload == {
"format": "unified",
"context": 3,
"truncated": True,
"text": "--- before\n+++ after\n@@ -1,2 +1,2 @@\n+new\n-old\n kee",
}
@pytest.mark.parametrize(("max_lines", "expected_tail", "truncated"), [ @pytest.mark.parametrize(("max_lines", "expected_tail", "truncated"), [
(2, "", True), (2, "", True),
(3, "\n@@ -3,0 +3 @@\n+new last", True), (3, "\n@@ -3,0 +3 @@\n+new last", True),