-
Notifications
You must be signed in to change notification settings - Fork 4
/
calc.go
88 lines (76 loc) · 1.84 KB
/
calc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package diff
import (
"fmt"
"strings"
"github.com/hexops/gotextdiff"
"github.com/hexops/gotextdiff/myers"
"github.com/hexops/gotextdiff/span"
)
const (
addedKey = "added"
deletedKey = "deleted"
contextKey = "context"
)
type Result struct {
Filename string `json:"filename"`
Src string `json:"src"`
Tgt string `json:"tgt"`
Edits Edits `json:"edits"`
Changes Changes `json:"changes"`
Patch string `json:"patch"`
}
type Results []*Result
type Line struct {
T string `json:"t"`
V string `json:"v"`
}
type Lines []*Line
func (l Line) String() string {
switch l.T {
case addedKey:
return " + " + l.V
case deletedKey:
return " - " + l.V
case contextKey:
return " . " + l.V
default:
return " ? " + l.V
}
}
type Change struct {
From int `json:"from"`
To int `json:"to"`
Lines Lines
}
type Changes []*Change
func Calc(fn string, src string, tgt string) *Result {
edits := myers.ComputeEdits(span.URIFromPath(""), tgt, src)
p, c := changes(tgt, edits)
return &Result{Filename: fn, Src: src, Tgt: tgt, Edits: edits, Changes: c, Patch: p}
}
func changes(src string, edits []gotextdiff.TextEdit) (string, Changes) {
u := gotextdiff.ToUnified("", "", src, edits)
ret := make(Changes, 0, len(u.Hunks))
for _, h := range u.Hunks {
lines := make(Lines, 0, len(h.Lines))
for _, l := range h.Lines {
t := "unknown"
switch l.Kind {
case gotextdiff.Delete:
t = deletedKey
case gotextdiff.Insert:
t = addedKey
case gotextdiff.Equal:
t = contextKey
}
lines = append(lines, &Line{T: t, V: l.Content})
}
ret = append(ret, &Change{From: h.FromLine, To: h.ToLine, Lines: lines})
}
patch := fmt.Sprint(u)
patch = strings.TrimPrefix(patch, "--- ")
patch = strings.TrimPrefix(patch, "\n")
patch = strings.TrimPrefix(patch, "+++ ")
patch = strings.TrimPrefix(patch, "\n")
return patch, ret
}