Skip to content

Commit

Permalink
fix: completed diff_minimal
Browse files Browse the repository at this point in the history
  • Loading branch information
ErikBjare committed Oct 2, 2024
1 parent e2b2d6a commit df9d83c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
16 changes: 15 additions & 1 deletion gptme/tools/patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,10 @@ class Patch:
def apply(self, content: str) -> str:
return content.replace(self.original, self.updated, 1)

def diff_minimal(self) -> str:
def diff_minimal(self, strip_context=False) -> str:
"""
Show a minimal diff of the patch.
Note that a minimal diff isn't necessarily a unique diff.
"""
# TODO: write tests, actually check the implementation
# TODO: show this when previewing the patch
Expand All @@ -82,6 +83,19 @@ def diff_minimal(self) -> str:
fromfile="original",
tofile="updated",
)
diff = list(diff)[3:]
if strip_context:
# find first and last lines with changes
markers = [l[0] for l in diff]
start = min(
markers.index("+") if "+" in markers else len(markers),
markers.index("-") if "-" in markers else len(markers),
)
end = min(
markers[::-1].index("+") if "+" in markers else len(markers),
markers[::-1].index("-") if "-" in markers else len(markers),
)
diff = diff[start : len(diff) - end]
return "\n".join(diff)

@classmethod
Expand Down
23 changes: 22 additions & 1 deletion tests/test_tools_patch.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from gptme.tools.patch import apply
from gptme.tools.patch import Patch, apply

example_patch = """
<<<<<<< ORIGINAL
Expand Down Expand Up @@ -139,3 +139,24 @@ def hello_world():
"""
result = apply(codeblock, content)
assert "hello_world()" in result


def test_patch_minimal():
p = Patch(
"""1
2
3
""",
"""1
0
3
""",
)
assert (
p.diff_minimal()
== """ 1
-2
+0
3"""
)
assert p.diff_minimal(strip_context=True) == "-2\n+0"

0 comments on commit df9d83c

Please sign in to comment.