This repository has been archived by the owner on Oct 29, 2023. It is now read-only.
/
protogen.go
84 lines (71 loc) · 2.25 KB
/
protogen.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
package ent
import (
"fmt"
"strings"
"github.com/nokamoto/2pf23/internal/protogen/core"
v1 "github.com/nokamoto/2pf23/pkg/api/inhouse/v1"
optionv1 "github.com/nokamoto/2pf23/pkg/api/option/v1"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/pluginpb"
)
// Plugin is a protoc plugin to generate ent code.
type Plugin struct {
core.Plugin
}
// NewPlugin returns a new Plugin with stdin and stdout.
func NewPlugin() *Plugin {
var p *Plugin
p = &Plugin{
*core.NewPlugin(func(req *pluginpb.CodeGeneratorRequest) (*pluginpb.CodeGeneratorResponse, error) {
m := map[string]*v1.Ent{}
for _, file := range req.GetProtoFile() {
for _, msg := range file.GetMessageType() {
if !proto.HasExtension(msg.GetOptions(), optionv1.E_Resource_EntQuery) {
continue
}
entQuery := proto.GetExtension(msg.GetOptions(), optionv1.E_Resource_EntQuery).(bool)
if !entQuery {
continue
}
filename := fmt.Sprintf("%s.json", strings.ToLower(msg.GetName()))
ent := &v1.Ent{
Name: msg.GetName(),
ImportPath: core.NewAPIDescriptor(file).ImportPath(),
}
for _, field := range msg.GetField() {
if field.GetName() == "name" {
continue
}
goName := cases.Title(language.English, cases.NoLower).String(field.GetJsonName())
switch field.GetType() {
case descriptorpb.FieldDescriptorProto_TYPE_ENUM:
ent.EnumFields = append(ent.EnumFields, &v1.EnumField{
Name: goName,
Type: core.GoTypeNameFromFullyQualified(field.GetTypeName()),
})
case descriptorpb.FieldDescriptorProto_TYPE_STRING, descriptorpb.FieldDescriptorProto_TYPE_INT32:
ent.Fields = append(ent.Fields, goName)
}
}
m[filename] = ent
}
}
var resp pluginpb.CodeGeneratorResponse
for file, ent := range m {
content, err := p.MarshalJsonProto(ent)
if err != nil {
return nil, fmt.Errorf("failed to marshal json: %w", err)
}
resp.File = append(resp.File, &pluginpb.CodeGeneratorResponse_File{
Name: proto.String(file),
Content: proto.String(string(content)),
})
}
return &resp, nil
}),
}
return p
}