-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
210 lines (157 loc) · 5.22 KB
/
main.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package main
import (
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"log"
"os"
"path/filepath"
"regexp"
"strings"
)
// tagExp will find a single tag expressions
var tagExp = regexp.MustCompile(`[_a-z][_\w]*:".+?"`)
// commentTagExp will find tag expressions in comments which match the syntax
// "// `tagName:"tagValues"`"
// "// `tagName:"tagValues" secondTagName:"secondTagValues"`"
// tag expressions must be placed on a separate line however
// "// `tagName:"tagValue"` additional information" will not be matched
var commentTagExp = regexp.MustCompile("^//\\s*`(([_a-z][_\\w]*:\"[^\"]+\")(\\s+[_a-z][_\\w]*:\"[^\"]+\")*)`$")
func main() {
var directory string
flag.StringVar(&directory, "dir", ".", "directory to search for pb files or single file")
flag.Parse()
fileinfo, err := os.Stat(directory)
if err != nil {
log.Printf("could not open file or directory: %s, %v\n", directory, err)
return
}
var parseError error
// enable parsing of single files or directories
switch fileinfo.IsDir() {
case false:
// handle single files
parseError = applyStructTags(directory)
case true:
// handle all files in the given directory
parseError = filepath.Walk(directory, walker)
}
if parseError != nil {
log.Printf("error while parsing files: %s, %v\n", directory, err)
}
}
// walker will be executed recusrively on every file in the target directory
func walker(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// ignore all files that have not been generated by pb
if strings.HasSuffix(path, ".pb.go") == false {
return nil
}
err = applyStructTags(path)
if err != nil {
log.Printf("%s: %v\n", path, err)
}
return err
}
// applyStructTags will add specifically defined tags to the go protobuf structs
func applyStructTags(path string) error {
fileSet := token.NewFileSet()
astFile, err := parser.ParseFile(fileSet, path, nil, parser.ParseComments)
if err != nil {
return fmt.Errorf("could not parse go file: %v", err)
}
var visitor visitor
ast.Walk(visitor, astFile)
file, err := os.Create(path)
if err != nil {
return fmt.Errorf("could not open output file: %v", err)
}
defer file.Close() // nolint: errcheck
err = format.Node(file, fileSet, astFile)
if err != nil {
return fmt.Errorf("could not write output file: %v", err)
}
return nil
}
// define a visitor struct to handle every ast node
type visitor struct{}
// Visit will find all fields in the code and add tags that are placed
// in the comment above the field as struct tags to the field
func (v visitor) Visit(node ast.Node) ast.Visitor {
if node == nil {
return nil
}
switch node.(type) {
// we are only interested in field types
case *ast.Field:
// comments after the field are stripped away by the grpc protoc-generator
// therefore we need to check the lines above the field which are
// contained in the comment that is part of the field
var commentTags []string
// iterate through the sub-nodes of the field
ast.Inspect(node, func(child ast.Node) bool {
// handle each comment line separately
// note: commentGroup could be used to handle all comments at once
switch comment := child.(type) {
case *ast.Comment:
// we are only interested in comments which matches our specific syntax
match := commentTagExp.FindStringSubmatch(comment.Text)
// the match must return exactly for items
// the first one contains the complete comment tag
if len(match) == 4 {
commentTags = append(commentTags, match[1])
}
}
return true
})
// continue with the next node if there are no comment tags
if len(commentTags) == 0 {
break
}
// tags are stored as child nodes of type ast.BasicLit
ast.Inspect(node, func(child ast.Node) bool {
switch basicLit := child.(type) {
case *ast.BasicLit:
// combine the current tag list with our new comment tags
basicLit.Value = combineTags(basicLit.Value, commentTags)
}
return true
})
}
return v
}
// combineTags will combine the given tags with the existing tags
// the order will be kept as is with existing tags first and new tags after.
// new tags will replace existing tags. if a tag is repeated, only the last
// version will be kept
func combineTags(tagList string, commentTags []string) string {
// remove ticks from the current tag list
tagList = strings.Trim(tagList, "`")
// commentTags may contain multiple struct tags i.e. db:"smthing" json:"test"
// therefore we combine all comment tags and split them into separate
// tags again
commentTagList := strings.Join(commentTags, " ")
// use a regular expression to split all comments into tags
tags := tagExp.FindAllString(commentTagList, -1)
for _, tag := range tags {
// get the tag name from the complete tag
tagName := strings.Split(tag, ":")[0]
// define the tag that should be matched
tagMatch := fmt.Sprintf(`%s:".+?"`, tagName)
// create a custom tag matcher based on the tag name
matcher := regexp.MustCompile(tagMatch)
// replace any matching existing tags in the taglist
if matcher.MatchString(tagList) {
tagList = matcher.ReplaceAllString(tagList, tag)
continue
}
// append the tag to the list of tags
tagList = fmt.Sprintf("%s %s", tagList, tag)
}
return fmt.Sprintf("`%s`", tagList)
}