-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
198 lines (172 loc) · 5.67 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
package main
import (
"errors"
"fmt"
"strings"
"google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/pluginpb"
entitypb "github.com/utilitywarehouse/protoc-gen-uwentity/gen/uw/entity/v1"
)
var (
errIdentifierNotFound = errors.New("identifier not found")
errUnsupportedField = errors.New("unsupported field type")
)
var tmpl = `
// GetEntityIdentifier returns the value from the field marked as the identifier
func (m *%s) GetEntityIdentifier() string {
return %s
}
`
// If set, then only these directories will raise errors for messages that do not set an identifier
// By default all messages are checked with the `Event` suffix
var paramEnforceDirs []string
type identifier struct {
// the Message that the GetEntityIdentifier method will be added to
message string
// the Field on the message which should be used as the identifier
identifier string
converter string
}
func main() {
protogen.Options{
ParamFunc: func(name, value string) error {
switch name {
case "enforce-dir":
paramEnforceDirs = append(paramEnforceDirs, value)
default:
return fmt.Errorf("invalid param: %s", name)
}
return nil
},
}.Run(func(gen *protogen.Plugin) error {
for _, file := range gen.Files {
if !file.Generate {
continue
}
if len(file.Messages) == 0 {
continue
}
gen.SupportedFeatures |= uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
output := gen.NewGeneratedFile(file.GeneratedFilenamePrefix+".pb.uwentity.go", file.GoImportPath)
output.P("// Code generated by protoc-gen-uwentity. DO NOT EDIT.")
output.P("// source: ", file.Desc.Path())
output.P("package ", file.GoPackageName)
var idents []identifier
for _, msg := range file.Messages {
// Ingore messages with `uw.entity.v1.ignore = true`
msgopts := msg.Desc.Options().(*descriptorpb.MessageOptions)
if proto.GetExtension(msgopts, entitypb.E_Ignore).(bool) {
continue
}
messageIdentifier, err := getMessageIdentifier(msg.GoIdent.GoName, msg)
switch {
default:
return err
case errors.Is(err, nil):
idents = append(idents, messageIdentifier)
case errors.Is(err, errIdentifierNotFound):
// Check that each event has set the identifier
// Pass `enforce-dir=<path>` to only check these directories & skip others
// Set message option `(uw.entity.v1.ignore) = true` to skip an individual message
if strings.HasSuffix(msg.GoIdent.GoName, "Event") {
if len(paramEnforceDirs) > 0 {
var skipEnforce bool
for _, dir := range paramEnforceDirs {
if !strings.HasPrefix(file.Desc.Path(), dir) {
skipEnforce = true
break
}
}
if skipEnforce {
continue
}
}
return fmt.Errorf(
"%s/%s: `uw.entity.v1.identifier` not set on event",
file.Desc.Path(),
msg.GoIdent.GoName,
)
}
}
}
if len(idents) == 0 {
// file contains no identifiers
output.Skip()
continue
}
var needsStrconv bool
for _, ident := range idents {
if ident.converter != "" {
needsStrconv = true
break
}
}
if needsStrconv {
output.P()
output.P("import \"strconv\"")
}
// output identifier accessing methods, checking that we support the field type
for _, ident := range idents {
if ident.converter != "" {
output.P(fmt.Sprintf(tmpl, ident.message, fmt.Sprintf(ident.converter, "m."+ident.identifier)))
} else {
output.P(fmt.Sprintf(tmpl, ident.message, "m."+ident.identifier))
}
}
}
return nil
})
}
func getMessageIdentifier(entity string, msg *protogen.Message, fields ...string) (identifier, error) {
for _, field := range msg.Fields {
// Skip field that don't have `uw.entity.v1.identifer = true`
fieldopts := field.Desc.Options().(*descriptorpb.FieldOptions)
if !proto.GetExtension(fieldopts, entitypb.E_Identifier).(bool) {
continue
}
if field.Desc.Cardinality() == protoreflect.Repeated {
return identifier{}, fmt.Errorf("repeated fields are not supported on %s: %s: %w", entity, field.Desc.Kind(), errUnsupportedField)
}
var value, converter string
switch field.Desc.Kind() {
case protoreflect.Int64Kind:
value = fmt.Sprintf("Get%s()", field.GoName)
converter = `strconv.FormatInt(%s, 10)`
case protoreflect.Int32Kind:
value = fmt.Sprintf("Get%s()", field.GoName)
converter = `strconv.FormatInt(int64(%s), 10)`
case protoreflect.StringKind:
value = fmt.Sprintf("Get%s()", field.GoName)
case protoreflect.EnumKind:
value = fmt.Sprintf("Get%s().String()", field.GoName)
case protoreflect.MessageKind:
nestedIdentifier := false
// check if the nested message has an identifier
for _, f := range field.Message.Fields {
if proto.GetExtension(f.Desc.Options().(*descriptorpb.FieldOptions), entitypb.E_Identifier).(bool) {
nestedIdentifier = true
}
}
if !nestedIdentifier {
return identifier{}, fmt.Errorf("nested messages must have an identifier on %s: %s: %w", entity, field.Desc.Kind(), errUnsupportedField)
}
value = fmt.Sprintf("Get%s().GetEntityIdentifier()", field.GoName)
return identifier{
message: entity,
identifier: strings.Join(append(fields, value), "."),
converter: converter,
}, nil
default:
return identifier{}, fmt.Errorf("unsupported field type on %s: %s: %w", entity, field.Desc.Kind(), errUnsupportedField)
}
return identifier{
message: entity,
identifier: strings.Join(append(fields, value), "."),
converter: converter,
}, nil
}
return identifier{}, errIdentifierNotFound
}