MCPcopy Create free account
hub / github.com/alibaba/open-code-review / ComputeLineDiff

Function ComputeLineDiff

internal/suggestdiff/diff.go:30–80  ·  view source on GitHub ↗

ComputeLineDiff returns a line-level diff between oldLines and newLines. Uses Myers-style LCS to find common subsequences, then emits context/added/deleted lines.

(oldLines, newLines []string)

Source from the content-addressed store, hash-verified

28// ComputeLineDiff returns a line-level diff between oldLines and newLines.
29// Uses Myers-style LCS to find common subsequences, then emits context/added/deleted lines.
30func ComputeLineDiff(oldLines, newLines []string) []DiffLine {
31 m, n := len(oldLines), len(newLines)
32 if m == 0 && n == 0 {
33 return nil
34 }
35
36 // LCS DP table
37 lcs := make([][]int, m+1)
38 for i := range lcs {
39 lcs[i] = make([]int, n+1)
40 }
41 for i := 1; i <= m; i++ {
42 for j := 1; j <= n; j++ {
43 if strings.EqualFold(strings.TrimSpace(oldLines[i-1]), strings.TrimSpace(newLines[j-1])) {
44 lcs[i][j] = lcs[i-1][j-1] + 1
45 } else {
46 lcs[i][j] = max(lcs[i-1][j], lcs[i][j-1])
47 }
48 }
49 }
50
51 // Backtrack to produce diff
52 var result []DiffLine
53 i, j := m, n
54 back := make([]DiffLine, 0, max(m, n)*2)
55 for i > 0 || j > 0 {
56 if i > 0 && j > 0 && strings.EqualFold(strings.TrimSpace(oldLines[i-1]), strings.TrimSpace(newLines[j-1])) {
57 if oldLines[i-1] == newLines[j-1] {
58 back = append(back, DiffLine{Type: DiffContext, Content: oldLines[i-1]})
59 } else {
60 // Fuzzy equality is only for alignment; preserve raw changes in the rendered diff.
61 back = append(back, DiffLine{Type: DiffAdded, Content: newLines[j-1]})
62 back = append(back, DiffLine{Type: DiffDeleted, Content: oldLines[i-1]})
63 }
64 i--
65 j--
66 } else if j > 0 && (i == 0 || lcs[i][j-1] >= lcs[i-1][j]) {
67 back = append(back, DiffLine{Type: DiffAdded, Content: newLines[j-1]})
68 j--
69 } else {
70 back = append(back, DiffLine{Type: DiffDeleted, Content: oldLines[i-1]})
71 i--
72 }
73 }
74
75 // Reverse
76 for _, b := range slices.Backward(back) {
77 result = append(result, b)
78 }
79 return result
80}

Calls

no outgoing calls