Skip to content

Commit 2e08a3a

Browse files
authored
feat: support placeholders in patches (#114)
* fix: support placeholders in patches * Apply suggestions from code review
1 parent 527ce5a commit 2e08a3a

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

gptme/tools/patch.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,29 @@ def apply(codeblock: str, content: str) -> str:
104104

105105
# TODO: maybe allow modified chunk to contain "// ..." to refer to chunks in the original,
106106
# and then replace these with the original chunks?
107+
re_placeholder = re.compile(r"^[ \t]*(#|//) \.\.\. ?.*$", re.MULTILINE)
108+
if re_placeholder.search(original) or re_placeholder.search(modified):
109+
# raise ValueError("placeholders in modified chunk")
110+
# split them by lines starting with "# ..."
111+
originals = re_placeholder.split(original)
112+
modifieds = re_placeholder.split(modified)
113+
if len(originals) != len(modifieds):
114+
raise ValueError(
115+
"different number of placeholders in original and modified chunks"
116+
f"\n{originals}\n{modifieds}"
117+
)
118+
new = content
119+
for orig, mod in zip(originals, modifieds):
120+
if orig == mod:
121+
continue
122+
new = new.replace(orig, mod)
123+
else:
124+
if original not in content: # pragma: no cover
125+
raise ValueError("original chunk not found in file", original)
126+
127+
# replace the original chunk with the modified chunk
128+
new = content.replace(original, modified)
107129

108-
# replace the original chunk with the modified chunk
109-
new = content.replace(original, modified)
110130
if new == content: # pragma: no cover
111131
raise ValueError("patch did not change the file")
112132

0 commit comments

Comments
 (0)