-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrunner.go
214 lines (176 loc) · 4.74 KB
/
runner.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
211
212
213
214
package main
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"io"
"os"
"strings"
"github.com/samber/lo"
gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo"
"google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/pluginpb"
)
// run executes a function as a protoc plugin.
//
// It reads a [pluginpb.CodeGeneratorRequest] message from [os.Stdin], invokes the plugin
// function, and writes a [pluginpb.CodeGeneratorResponse] message to [os.Stdout].
//
// If a failure occurs while reading or writing, Run prints an error to
// [os.Stderr] and calls [os.Exit](1).
func run(reader io.Reader, opts *protogen.Options) error {
if len(os.Args) > 1 {
return fmt.Errorf("unknown argument %q (this program should be run by protoc, not directly)", os.Args[1])
}
in, err := io.ReadAll(reader)
if err != nil {
return err
}
// err = os.WriteFile("testdata/message.desc", in, 0644)
// if err == nil {
// return err
// }
req := &pluginpb.CodeGeneratorRequest{}
if err := proto.Unmarshal(in, req); err != nil {
return err
}
gen, err := opts.New(req)
if err != nil {
return err
}
descs, err := parseCommentaryDeclarations(gen.Files)
if err != nil {
return err
}
gen.SupportedFeatures = gengo.SupportedFeatures
gen.SupportedEditionsMinimum = gengo.SupportedEditionsMinimum
gen.SupportedEditionsMaximum = gengo.SupportedEditionsMaximum
for _, f := range gen.Files {
if f.Generate {
gengo.GenerateFile(gen, f)
}
}
resp := gen.Response()
if err = regenerateGoSources(descs, resp.File); err != nil {
return err
}
out, err := proto.Marshal(resp)
if err != nil {
return err
}
if _, err := os.Stdout.Write(out); err != nil {
return err
}
return nil
}
func parseCommentaryDeclarations(files []*protogen.File) (descs []*FileDescriptor, err error) {
descs = make([]*FileDescriptor, 0, len(files))
for _, file := range files {
if !file.Generate || file.Desc == nil {
continue
}
desc := &FileDescriptor{
ProtoPath: file.Desc.Path(),
GoPath: strings.Replace(file.Desc.Path(), ".proto", ".pb.go", 1),
Models: make(map[string]*Model),
}
if err = desc.parse(file); err != nil {
return
}
if len(desc.Models) > 0 {
descs = append(descs, desc)
}
}
return
}
func regenerateGoSources(descs []*FileDescriptor, sources []*pluginpb.CodeGeneratorResponse_File) (err error) {
if len(descs) == 0 || len(sources) == 0 {
return
}
for _, source := range sources {
desc, ok := lo.Find(descs, func(desc *FileDescriptor) bool {
return desc.GoPath == *source.Name
})
if !ok || desc == nil {
continue
}
var newSource string
if newSource, err = generate(*source.Content, desc); err != nil {
return
}
if len(newSource) > 0 {
source.Content = &newSource
}
}
return
}
func generate(source string, desc *FileDescriptor) (string, error) {
fileSet := token.NewFileSet()
file, err := parser.ParseFile(fileSet, "", source, parser.ParseComments)
if err != nil {
return "", err
}
ast.Inspect(file, func(node ast.Node) bool {
switch spec := node.(type) {
case *ast.TypeSpec:
if spec.Name == nil {
break
}
model, ok := desc.Models[spec.Name.Name]
if !ok || model == nil {
break
}
if stype, ok := spec.Type.(*ast.StructType); ok && stype != nil {
for _, field := range stype.Fields.List {
if len(field.Names) != 1 || field.Tag == nil {
continue
}
fdesc, ok := model.Fields[field.Names[0].String()]
if !ok || fdesc == nil || len(fdesc.Tags) == 0 {
continue
}
var value bytes.Buffer
value.WriteString(field.Tag.Value[:len(field.Tag.Value)-1])
for _, tag := range fdesc.Tags {
switch strings.ToLower(tag.Kind) {
case "json":
if !strings.Contains(tag.Value, "omitempty") {
tag.Value += ",omitempty"
}
newTag := "json:\"" + tag.Value + "\""
original := value.String()
if begin := strings.Index(original, "json:\""); begin >= 0 {
if end := strings.Index(original[begin+7:], "\""); end > 0 {
original = strings.Replace(original, original[begin:begin+7+end+1], newTag, 1)
value.Reset()
value.WriteString(original)
}
} else {
value.WriteByte(' ')
value.WriteString(newTag)
}
default:
value.WriteByte(' ')
value.WriteString(tag.Kind)
value.WriteString(":\"")
value.WriteString(tag.Value)
value.WriteString("\"")
}
}
value.WriteByte('`')
field.Tag.Value = value.String()
}
}
}
return true
})
buf := bytes.NewBuffer(make([]byte, 0, len(source)*2))
if err = format.Node(buf, fileSet, file); err != nil {
return "", err
}
return buf.String(), err
}