Skip to content

Commit 751b069

Browse files
committed
Skip redundant leading empty lines when applying diffs to empty files
1 parent d59d6b0 commit 751b069

5 files changed

Lines changed: 38 additions & 3 deletions

File tree

‎apps/editor/src/commands/apply-chat-response-command/utils/edit-formats/diffs/diff-processor.spec.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,5 +236,19 @@ describe('diff-processor', () => {
236236

237237
expect(result).toBe(expected)
238238
})
239+
it('applies diff with a redundant new empty line correctly', async () => {
240+
const test_case = 'redundant-new-empty-line'
241+
const original = load_test_case_file('', test_case, 'original.txt')
242+
const diff = load_test_case_file('', test_case, 'diff.txt')
243+
const expected = load_test_case_file('', test_case, 'expected.txt')
244+
245+
const result = apply_diff({
246+
original_code: original,
247+
diff_patch: diff
248+
})
249+
250+
expect(result).toBe(expected)
251+
})
252+
239253
})
240254
})

‎apps/editor/src/commands/apply-chat-response-command/utils/edit-formats/diffs/diff-processor.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export const apply_diff = (params: {
2525
let has_additions = false
2626
let in_hunk = false
2727
const result_lines: string[] = []
28+
let seen_content = false
2829

2930
for (const line of patch_lines) {
3031
if (line.startsWith('@@')) {
@@ -33,13 +34,27 @@ export const apply_diff = (params: {
3334
}
3435
if (!in_hunk) continue
3536

37+
let line_to_add: string | null = null
38+
let is_addition = false
39+
3640
if (line.startsWith('+')) {
37-
result_lines.push(line.substring(1))
41+
line_to_add = line.substring(1)
42+
is_addition = true
3843
has_additions = true
3944
} else if (line.startsWith(' ')) {
40-
result_lines.push(line.substring(1))
45+
line_to_add = line.substring(1)
4146
} else if (line == '') {
42-
result_lines.push('')
47+
line_to_add = ''
48+
}
49+
50+
if (line_to_add !== null) {
51+
if (!seen_content) {
52+
if (!is_addition && line_to_add.trim() == '') {
53+
continue
54+
}
55+
seen_content = true
56+
}
57+
result_lines.push(line_to_add)
4358
}
4459
}
4560

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
--- a/index.ts
2+
+++ b/index.ts
3+
@@ -1,2 +1,2 @@
4+
5+
+export * from './b'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './b'

‎apps/editor/src/commands/apply-chat-response-command/utils/edit-formats/diffs/test-cases/redundant-new-empty-line/original.txt‎

Whitespace-only changes.

0 commit comments

Comments
 (0)