-
Notifications
You must be signed in to change notification settings - Fork 0
/
comment_annotation.go
97 lines (87 loc) · 2.14 KB
/
comment_annotation.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 protokit
import (
"strings"
"github.com/sandwich-go/boost/misc/annotation"
"github.com/sandwich-go/boost/xstrings"
"google.golang.org/protobuf/types/descriptorpb"
)
const AnnotationService = "service"
const AnnotationGlobal = "global"
type Comment struct {
Content string
Tags map[string]string
Annotations []annotation.Annotation
}
func CommentLines(loc *descriptorpb.SourceCodeInfo_Location) []string {
var lines []string
for _, str := range loc.GetLeadingDetachedComments() {
if s := strings.TrimSpace(str); s != "" {
lines = append(lines, s)
}
}
arr := strings.Split(loc.GetLeadingComments(), "\n")
for _, v := range arr {
if s := strings.TrimSpace(v); s != "" {
lines = append(lines, s)
}
}
if s := strings.TrimSpace(loc.GetTrailingComments()); s != "" {
lines = append(lines, s)
}
return lines
}
func GetAnnotation(c *Comment, name string) annotation.Annotation {
if c == nil {
return nil
}
return c.Annotation(name)
}
func (c *Comment) Annotation(name ...string) annotation.Annotation {
annotationName := AnnotationGlobal
if len(name) != 0 {
annotationName = name[0]
}
for _, v := range c.Annotations {
if v.Name() == annotationName {
return v
}
}
return annotation.EmptyAnnotation
}
func NewComment(lines []string) *Comment {
comment := &Comment{
Tags: make(map[string]string),
}
if len(lines) == 0 {
return comment
}
comment.Content = strings.Join(lines, "\n")
comment.Annotations, _ = annotation.New().ResolveMany(lines...)
for _, l := range lines {
l = xstrings.Trim(l)
arr := strings.Split(l, "@")
if len(arr) <= 1 {
continue
}
for _, v := range arr {
if len(v) == 0 {
continue
}
// todo,目前的stamp只支持最多一个参数
kv := strings.Split(v, "=")
key := strings.Trim(strings.ToLower(kv[0]), " ")
if len(kv) > 1 {
comment.Tags[key] = kv[1]
} else {
comment.Tags[key] = "true"
}
}
}
var attributes = make(map[string]string)
for k, v := range comment.Tags {
attributes[k] = v
}
global := annotation.NewAnnotation(AnnotationGlobal, attributes)
comment.Annotations = append(comment.Annotations, global)
return comment
}