Skip to content

Commit 120233c

Browse files
committed
fix: fixed issues with applying patches
1 parent 74e4b18 commit 120233c

File tree

2 files changed

+40
-10
lines changed

2 files changed

+40
-10
lines changed

gptme/tools/patch.py

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,9 @@
5555
```
5656
""".strip()
5757

58-
ORIGINAL = "\n<<<<<<< ORIGINAL\n"
58+
ORIGINAL = "<<<<<<< ORIGINAL\n"
5959
DIVIDER = "\n=======\n"
60-
UPDATED = ">>>>>>> UPDATED\n"
60+
UPDATED = "\n>>>>>>> UPDATED"
6161

6262

6363
def apply(codeblock: str, content: str) -> str:
@@ -77,9 +77,9 @@ def apply(codeblock: str, content: str) -> str:
7777
raise ValueError(f"invalid patch, no `{DIVIDER.strip()}`", codeblock)
7878
original, modified = re.split(DIVIDER, original)
7979

80-
if UPDATED not in modified: # pragma: no cover
80+
if UPDATED not in "\n" + modified: # pragma: no cover
8181
raise ValueError(f"invalid patch, no `{UPDATED.strip()}`", codeblock)
82-
modified = re.split(UPDATED, modified)[0].rstrip("\n")
82+
modified = re.split(UPDATED, modified)[0]
8383

8484
# TODO: maybe allow modified chunk to contain "// ..." to refer to chunks in the original,
8585
# and then replace these with the original chunks?
@@ -93,12 +93,6 @@ def apply(codeblock: str, content: str) -> str:
9393

9494

9595
def apply_file(codeblock, filename):
96-
codeblock = codeblock.strip()
97-
_patch, filename = codeblock.splitlines()[0].split()
98-
if not _patch == "```patch":
99-
raise ValueError(
100-
"invalid patch, codeblock is missing leading ```patch", codeblock
101-
)
10296
if not Path(filename).exists():
10397
raise FileNotFoundError(filename)
10498

tests/test_tools_patch.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,25 @@ def hello(name="world"):
4747
"""
4848
)
4949

50+
51+
def test_clear_file():
5052
# only remove code in patch
53+
content = """
54+
def hello():
55+
print("hello")
56+
57+
if __name__ == "__main__":
58+
hello()
59+
"""
60+
61+
# NOTE: test fails if UPDATED block doesn't have an empty line
5162
codeblock = """
5263
```patch test.py
5364
<<<<<<< ORIGINAL
5465
def hello():
5566
print("hello")
5667
=======
68+
5769
>>>>>>> UPDATED
5870
```
5971
"""
@@ -64,3 +76,27 @@ def hello():
6476
assert result.startswith(
6577
"\n\n"
6678
), f"result: {result.replace(newline, newline_escape)}"
79+
80+
81+
def test_apply_empty_lines():
82+
# a test where it replaces a empty line with 3 empty lines
83+
# checks that whitespace is preserved
84+
content = """
85+
def hello():
86+
print("hello")
87+
88+
if __name__ == "__main__":
89+
hello()
90+
"""
91+
codeblock = """
92+
```patch test.py
93+
<<<<<<< ORIGINAL
94+
95+
=======
96+
97+
98+
>>>>>>> UPDATED
99+
```
100+
"""
101+
result = apply(codeblock, content)
102+
assert "\n\n\n" in result

0 commit comments

Comments
 (0)