-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathannotationParser.go
92 lines (85 loc) · 2.67 KB
/
annotationParser.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
package go_annotation
import (
"strconv"
"strings"
)
type AnnotationParser interface {
Parse(comments []string) map[string]*Annotation
}
func getAnnotationParser(mode AnnotationMode) AnnotationParser {
switch mode {
case AnnotationModeMap:
return &MapAnnotationParser{}
default:
return &ArrayAnnotationParser{}
}
}
type ArrayAnnotationParser struct{}
func (a *ArrayAnnotationParser) Parse(comments []string) map[string]*Annotation {
annotations := make(map[string]*Annotation)
for _, comment := range comments {
commentSlice := splitComment(comment)
if len(commentSlice) == 0 {
continue
}
name := commentSlice[0]
attribute := make(map[string]string)
for i := 1; i < len(commentSlice); i++ {
attribute[strconv.Itoa(i-1)] = commentSlice[i]
}
if _, ok := annotations[name]; ok {
if len(attribute) > 0 {
annotations[name].Attributes = append(annotations[name].Attributes, attribute)
}
} else {
annotation := &Annotation{Name: name, Attributes: []map[string]string{}}
if len(attribute) > 0 {
annotation.Attributes = append(annotation.Attributes, attribute)
}
annotations[name] = annotation
}
}
return annotations
}
type MapAnnotationParser struct{}
func (a *MapAnnotationParser) Parse(comments []string) map[string]*Annotation {
annotations := make(map[string]*Annotation)
for _, comment := range comments {
if strings.Contains(comment, "(") {
// get annotation name
name := comment[:strings.Index(comment, "(")]
// get attribute
attributeStr := comment[strings.Index(comment, "(")+1 : strings.LastIndex(comment, ")")]
attributeSlice := strings.Split(attributeStr, ",")
attribute := make(map[string]string)
for _, item := range attributeSlice {
// get attribute name and value
itemSlice := strings.Split(item, "=")
if len(itemSlice) != 2 {
continue
}
attributeName := strings.TrimSpace(itemSlice[0])
attributeValue := strings.TrimSpace(itemSlice[1])
if strings.HasPrefix(attributeValue, "\"") && strings.HasSuffix(attributeValue, "\"") {
attributeValue = attributeValue[1 : len(attributeValue)-1]
}
attribute[attributeName] = attributeValue
}
if _, ok := annotations[name]; ok {
if len(attribute) > 0 {
annotations[name].Attributes = append(annotations[name].Attributes, attribute)
}
} else {
annotation := &Annotation{Name: name, Attributes: []map[string]string{}}
if len(attribute) > 0 {
annotation.Attributes = append(annotation.Attributes, attribute)
}
annotations[name] = annotation
}
} else {
annotation := &Annotation{Name: comment, Attributes: []map[string]string{}}
annotations[comment] = annotation
}
}
return annotations
}