Skip to content

Commit 9140021

Browse files
authored
fix(diff): implement offset tracking for sequential hunk application (#1493)
- Adjust hunk start positions by cumulative offset to match patch utility behavior - Add comprehensive tests for offset logic (additions, deletions, mixed, context) - Ensure unified diff application is robust for multi-hunk scenarios
1 parent be3291c commit 9140021

File tree

2 files changed

+440
-1
lines changed

2 files changed

+440
-1
lines changed

lua/CopilotChat/utils/diff.lua

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,10 +143,21 @@ function M.apply_unified_diff(diff_text, original_content)
143143
local hunks = parse_hunks(diff_text)
144144
local new_content = original_content
145145
local applied = false
146+
local offset = 0 -- Track cumulative line offset from previous hunks
147+
146148
for _, hunk in ipairs(hunks) do
147-
local patched, ok = apply_hunk(hunk, new_content)
149+
-- Adjust hunk start position based on accumulated offset
150+
local adjusted_hunk = vim.deepcopy(hunk)
151+
if adjusted_hunk.start_old then
152+
adjusted_hunk.start_old = hunk.start_old + offset
153+
end
154+
155+
local patched, ok = apply_hunk(adjusted_hunk, new_content)
148156
new_content = patched
149157
applied = applied or ok
158+
159+
-- Update offset: (new lines added) - (old lines removed)
160+
offset = offset + (#hunk.new_snippet - #hunk.old_snippet)
150161
end
151162

152163
local new_lines = vim.split(new_content, '\n', { trimempty = true })

0 commit comments

Comments
 (0)