forked from favadi/protoc-go-inject-tag
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
162 lines (141 loc) · 3.76 KB
/
file.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
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"os"
"regexp"
"strings"
)
var (
rComment = regexp.MustCompile(`^//.*?@(?i:gotags?|inject_tags?):\s*(.*)$`)
rInject = regexp.MustCompile("`.+`$")
rTags = regexp.MustCompile(`[\w_]+:"[^"]+"`)
rAll = regexp.MustCompile(".*")
)
type textArea struct {
Start int
End int
CurrentTag string
InjectTag string
CommentStart int
CommentEnd int
}
func parseFile(inputPath string, src interface{}, xxxSkip []string) (areas []textArea, err error) {
logf("parsing file %q for inject tag comments", inputPath)
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, inputPath, src, parser.ParseComments)
if err != nil {
return
}
for _, decl := range f.Decls {
// check if is generic declaration
genDecl, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
var typeSpec *ast.TypeSpec
for _, spec := range genDecl.Specs {
if ts, tsOK := spec.(*ast.TypeSpec); tsOK {
typeSpec = ts
break
}
}
// skip if can't get type spec
if typeSpec == nil {
continue
}
// not a struct, skip
structDecl, ok := typeSpec.Type.(*ast.StructType)
if !ok {
continue
}
builder := strings.Builder{}
if len(xxxSkip) > 0 {
for i, skip := range xxxSkip {
builder.WriteString(fmt.Sprintf("%s:\"-\"", skip))
if i > 0 {
builder.WriteString(",")
}
}
}
for _, field := range structDecl.Fields.List {
// skip if field has no doc
if len(field.Names) > 0 {
name := field.Names[0].Name
if len(xxxSkip) > 0 && strings.HasPrefix(name, "XXX") {
currentTag := field.Tag.Value
area := textArea{
Start: int(field.Pos()),
End: int(field.End()),
CurrentTag: currentTag[1 : len(currentTag)-1],
InjectTag: builder.String(),
}
areas = append(areas, area)
}
}
comments := []*ast.Comment{}
if field.Doc != nil {
comments = append(comments, field.Doc.List...)
}
// The "doc" field (above comment) is more commonly "free-form"
// due to the ability to have a much larger comment without it
// being unwieldy. As such, the "comment" field (trailing comment),
// should take precedence if there happen to be multiple tags
// specified, both in the field doc, and the field line. Whichever
// comes last, will take precedence.
if field.Comment != nil {
comments = append(comments, field.Comment.List...)
}
for _, comment := range comments {
tag := tagFromComment(comment.Text)
if tag == "" {
continue
}
if strings.Contains(comment.Text, "inject_tag") {
logf("warn: deprecated 'inject_tag' used")
}
currentTag := field.Tag.Value
area := textArea{
Start: int(field.Pos()),
End: int(field.End()),
CurrentTag: currentTag[1 : len(currentTag)-1],
InjectTag: tag,
CommentStart: int(comment.Pos()),
CommentEnd: int(comment.End()),
}
areas = append(areas, area)
}
}
}
logf("parsed file %q, number of fields to inject custom tags: %d", inputPath, len(areas))
return
}
func writeFile(inputPath string, areas []textArea, removeTagComment bool) (err error) {
f, err := os.Open(inputPath)
if err != nil {
return
}
contents, err := io.ReadAll(f)
if err != nil {
return
}
if err = f.Close(); err != nil {
return
}
// inject custom tags from tail of file first to preserve order
for i := range areas {
area := areas[len(areas)-i-1]
logf("inject custom tag %q to expression %q", area.InjectTag, string(contents[area.Start-1:area.End-1]))
contents = injectTag(contents, area, removeTagComment)
}
if err = os.WriteFile(inputPath, contents, 0o644); err != nil {
return
}
if len(areas) > 0 {
logf("file %q is injected with custom tags", inputPath)
}
return
}