-
Notifications
You must be signed in to change notification settings - Fork 148
/
parse.go
97 lines (86 loc) · 2.46 KB
/
parse.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
89
90
91
92
93
94
95
96
97
package main
import (
"fmt"
"strings"
)
func tagFromComment(comment string) (tag string) {
match := rComment.FindStringSubmatch(comment)
if len(match) == 2 {
tag = match[1]
}
return
}
type tagItem struct {
key string
value string
}
type tagItems []tagItem
func (ti tagItems) format() string {
tags := []string{}
for _, item := range ti {
tags = append(tags, fmt.Sprintf(`%s:%s`, item.key, item.value))
}
return strings.Join(tags, " ")
}
func (ti tagItems) override(nti tagItems) tagItems {
overrided := []tagItem{}
for i := range ti {
dup := -1
for j := range nti {
if ti[i].key == nti[j].key {
dup = j
break
}
}
if dup == -1 {
overrided = append(overrided, ti[i])
} else {
overrided = append(overrided, nti[dup])
nti = append(nti[:dup], nti[dup+1:]...)
}
}
return append(overrided, nti...)
}
func newTagItems(tag string) tagItems {
items := []tagItem{}
splitted := rTags.FindAllString(tag, -1)
for _, t := range splitted {
sepPos := strings.Index(t, ":")
items = append(items, tagItem{
key: t[:sepPos],
value: t[sepPos+1:],
})
}
return items
}
func injectTag(contents []byte, area textArea, removeTagComment bool) (injected []byte) {
expr := make([]byte, area.End-area.Start)
copy(expr, contents[area.Start-1:area.End-1])
cti := newTagItems(area.CurrentTag)
iti := newTagItems(area.InjectTag)
ti := cti.override(iti)
expr = rInject.ReplaceAll(expr, []byte(fmt.Sprintf("`%s`", ti.format())))
if removeTagComment {
strippedComment := make([]byte, area.CommentEnd-area.CommentStart)
copy(strippedComment, contents[area.CommentStart-1:area.CommentEnd-1])
strippedComment = rAll.ReplaceAll(expr, []byte(" "))
if area.CommentStart < area.Start {
injected = append(injected, contents[:area.CommentStart-1]...)
injected = append(injected, strippedComment...)
injected = append(injected, contents[area.CommentEnd-1:area.Start-1]...)
injected = append(injected, expr...)
injected = append(injected, contents[area.End-1:]...)
} else {
injected = append(injected, contents[:area.Start-1]...)
injected = append(injected, expr...)
injected = append(injected, contents[area.End-1:area.CommentStart-1]...)
injected = append(injected, strippedComment...)
injected = append(injected, contents[area.CommentEnd-1:]...)
}
} else {
injected = append(injected, contents[:area.Start-1]...)
injected = append(injected, expr...)
injected = append(injected, contents[area.End-1:]...)
}
return
}