Skip to content

Commit 68352a9

Browse files
committed
Replace createTwoFilesPatch with diffLines in get_diff_stats to improve diff accuracy
1 parent 3c5f7ec commit 68352a9

1 file changed

Lines changed: 14 additions & 25 deletions

File tree

  • apps/editor/src/commands/apply-chat-response-command/utils/preview

‎apps/editor/src/commands/apply-chat-response-command/utils/preview/diff-utils.ts‎

Lines changed: 14 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,29 @@
1-
import { createTwoFilesPatch } from 'diff'
1+
import { diffLines } from 'diff'
22

33
export const get_diff_stats = (params: {
44
original_content: string
55
new_content: string
66
}): { lines_added: number; lines_removed: number } => {
7-
const original_content_processed = params.original_content
8-
.split(/\r?\n/)
9-
.map((line) => line.trim())
10-
.join('\n')
11-
const new_content_processed = params.new_content
12-
.split(/\r?\n/)
13-
.map((line) => line.trim())
14-
.join('\n')
15-
if (original_content_processed === new_content_processed) {
7+
const original_content_processed = params.original_content.replace(
8+
/\r\n/g,
9+
'\n'
10+
)
11+
const new_content_processed = params.new_content.replace(/\r\n/g, '\n')
12+
13+
if (original_content_processed == new_content_processed) {
1614
return { lines_added: 0, lines_removed: 0 }
1715
}
1816

19-
const patch = createTwoFilesPatch(
20-
'original',
21-
'modified',
22-
original_content_processed,
23-
new_content_processed,
24-
undefined,
25-
undefined,
26-
{ context: 0 }
27-
)
17+
const changes = diffLines(original_content_processed, new_content_processed)
2818

2919
let lines_added = 0
3020
let lines_removed = 0
3121

32-
const lines = patch.split('\n')
33-
for (const line of lines) {
34-
if (line.startsWith('+') && !line.startsWith('+++')) {
35-
lines_added++
36-
} else if (line.startsWith('-') && !line.startsWith('---')) {
37-
lines_removed++
22+
for (const change of changes) {
23+
if (change.added) {
24+
lines_added += change.count || 0
25+
} else if (change.removed) {
26+
lines_removed += change.count || 0
3827
}
3928
}
4029

0 commit comments

Comments
 (0)