MCPcopy Create free account
hub / github.com/PerpetualSoftware/pad / FormatLineDiff

Function FormatLineDiff

internal/cli/builtin_format.go:16–79  ·  view source on GitHub ↗

FormatLineDiff renders old -> new as lines prefixed "-", "+" or " ", keeping at most context unchanged lines around each change and eliding the rest with "…" (TASK-3462 U3c). Empty when the two are equal.

(oldText, newText string, context int)

Source from the content-addressed store, hash-verified

14// keeping at most context unchanged lines around each change and eliding the
15// rest with "…" (TASK-3462 U3c). Empty when the two are equal.
16func FormatLineDiff(oldText, newText string, context int) string {
17 if oldText == newText {
18 return ""
19 }
20 // A change to the final newline alone renders as two identical-looking
21 // lines, so it is named, as diff does.
22 oldNL, newNL := strings.HasSuffix(oldText, "\n"), strings.HasSuffix(newText, "\n")
23 dmp := diffmatchpatch.New()
24 a, b, lines := dmp.DiffLinesToChars(oldText, newText)
25 diffs := dmp.DiffCharsToLines(dmp.DiffMain(a, b, false), lines)
26
27 type line struct {
28 op diffmatchpatch.Operation
29 text string
30 }
31 var all []line
32 for _, d := range diffs {
33 text := strings.TrimSuffix(d.Text, "\n")
34 for _, l := range strings.Split(text, "\n") {
35 all = append(all, line{d.Type, l})
36 }
37 }
38 keep := make([]bool, len(all))
39 for i, l := range all {
40 if l.op == diffmatchpatch.DiffEqual {
41 continue
42 }
43 for j := i - context; j <= i+context; j++ {
44 if j >= 0 && j < len(all) {
45 keep[j] = true
46 }
47 }
48 }
49 var out strings.Builder
50 elided := false
51 for i, l := range all {
52 if !keep[i] {
53 if !elided {
54 out.WriteString(" …\n")
55 elided = true
56 }
57 continue
58 }
59 elided = false
60 switch l.op {
61 case diffmatchpatch.DiffInsert:
62 out.WriteString("+")
63 case diffmatchpatch.DiffDelete:
64 out.WriteString("-")
65 default:
66 out.WriteString(" ")
67 }
68 out.WriteString(l.text)
69 out.WriteString("\n")
70 }
71 if oldNL != newNL {
72 side := "new"
73 if !oldNL {

Calls 3

appendFunction · 0.85
makeFunction · 0.50
StringMethod · 0.45