Skip to content

Commit f588cfa

Browse files
authored
Merge pull request #6 from 255BITS/codex/create-test-case-for-patch-parsing-issue
Handle diffs missing context prefixes
2 parents 139283c + f5764ef commit f588cfa

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

gptdiff/applydiff.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,19 @@ def apply_patch_to_file(file_path, patch):
9696
# Addition line: add to new_lines.
9797
new_lines.append(pline[1:] + "\n")
9898
else:
99-
print("Unexpected line in hunk:", pline)
100-
return False
99+
# Some diffs (especially LLM-generated) omit the leading space on
100+
# context lines. Treat bare lines as context when they match the
101+
# original file to make patch application more forgiving.
102+
expected = pline
103+
if current_index >= len(original_lines):
104+
print("Context line expected but file ended")
105+
return False
106+
orig_line = original_lines[current_index].rstrip("\n")
107+
if orig_line != expected:
108+
print("Context line mismatch. Expected:", expected, "Got:", orig_line)
109+
return False
110+
new_lines.append(original_lines[current_index])
111+
current_index += 1
101112
i += 1
102113
else:
103114
# Skip non-hunk header lines.

tests/test_applydiff_edgecases.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,30 @@ def test_diff_with_whitespace_changes(tmp_project_dir):
141141
assert "line2 " in content, "Whitespace change should be reflected in the file"
142142

143143

144+
def test_diff_without_context_prefixes(tmp_project_dir):
145+
"""
146+
Diffs generated by LLMs sometimes omit the leading space on context lines.
147+
Ensure we still treat those lines as context when they match the file.
148+
"""
149+
file = tmp_project_dir / "example.txt"
150+
file.write_text("line1\nline2\nline3\n")
151+
diff_text = (
152+
"diff --git a/example.txt b/example.txt\n"
153+
"--- a/example.txt\n"
154+
"+++ a/example.txt\n"
155+
"@@ -1,3 +1,3 @@\n"
156+
"line1\n"
157+
"-line2\n"
158+
"+line2 updated\n"
159+
"line3\n"
160+
)
161+
162+
result = apply_diff(str(tmp_project_dir), diff_text)
163+
164+
assert result is True, "Diff without context prefixes should still apply"
165+
assert file.read_text() == "line1\nline2 updated\nline3\n"
166+
167+
144168
def test_diff_file_deletion_edge(tmp_project_dir):
145169
"""
146170
Test deletion diff for a file with minimal content.

0 commit comments

Comments
 (0)