-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
192 lines (160 loc) · 5.29 KB
/
plugin.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
package plugin
import (
"fmt"
"io"
"log"
"os"
"path"
"strings"
"github.com/golang/protobuf/proto"
plugingo "github.com/golang/protobuf/protoc-gen-go/plugin"
generatorpkg "github.com/cjp2600/protoc-gen-structify/plugin/generator"
helperpkg "github.com/cjp2600/protoc-gen-structify/plugin/pkg/helper"
"github.com/cjp2600/protoc-gen-structify/plugin/provider"
statepkg "github.com/cjp2600/protoc-gen-structify/plugin/state"
)
// Plugin handles generation of code based on protobuf.
type Plugin struct {
req *plugingo.CodeGeneratorRequest
res *plugingo.CodeGeneratorResponse
state *statepkg.State
pathType pathType
param map[string]string
}
// NewPlugin creates a new Plugin.
func NewPlugin() *Plugin {
return &Plugin{
req: &plugingo.CodeGeneratorRequest{},
res: &plugingo.CodeGeneratorResponse{},
}
}
// Run handles the input/output of the plugin.
// It reads the request from stdin and writes the response to stdout.
func (p *Plugin) Run() {
// read from stdin
data, err := io.ReadAll(os.Stdin)
if err != nil {
log.Fatalf("Failed to read from stdin: %v", err)
}
// unmarshal protobuf from stdin to request struct and check for errors
if err := proto.Unmarshal(data, p.req); err != nil {
log.Fatalf("Failed to unmarshal protobuf: %v", err)
}
// check protobuf version
if err := p.checkProtobufVersion(); err != nil {
log.Fatalf("Failed to check protobuf version: %v", err)
}
// check if there are any proto files
if len(helperpkg.GetUserProtoFiles(p.req)) == 0 {
log.Fatalf("No proto file is supported: %d", len(helperpkg.GetUserProtoFiles(p.req)))
}
// only one proto file is supported
if len(helperpkg.GetUserProtoFiles(p.req)) > 1 {
log.Fatalf("Only one proto file is supported: %d", len(helperpkg.GetUserProtoFiles(p.req)))
}
// parse command line parameters
{
p.parseCommandLineParameters(p.req.GetParameter())
}
// get default plugin state
p.state = statepkg.NewState(p.req)
{
// set additional state parameters
p.state.IncludeConnection = p.parseIncludeConnectionParam()
}
// get provider template builder based on command line parameter
templBuilder, err := provider.GetTemplateBuilder(p.req)
if err != nil {
log.Fatalf("Failed to get template builder: %v", err)
}
// generate main content
// - package name
// - imports
// - init block
// - messages block
// - conditions block
//
generator := generatorpkg.NewContentGenerator(p.state, templBuilder, &generatorpkg.Request{
BaseFileName: p.state.FileName,
FilePath: p.fileName,
})
files, err := generator.Files()
if err != nil {
log.Fatalf("Failed to generate content: %v", err)
}
p.res.File = append(p.res.File, files...)
// set supported features
p.res.SupportedFeatures = proto.Uint64(uint64(plugingo.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL))
// format Go code and marshal protobuf
//
if err := helperpkg.GoFmt(p.res); err != nil {
log.Fatalf("Failed to format Go code: %v", err)
}
// marshal protobuf and write to stdout
data, err = proto.Marshal(p.res)
if err != nil {
log.Fatalf("Failed to marshal protobuf: %v", err)
}
// write to stdout
if _, err := os.Stdout.Write(data); err != nil {
log.Fatalf("Failed to write to stdout: %v", err)
}
}
// parseCommandLineParameters parses the command line parameters into the param map.
func (p *Plugin) parseCommandLineParameters(parameter string) {
p.param = make(map[string]string)
params := strings.Split(parameter, ",")
for _, param := range params {
if i := strings.Index(param, "="); i < 0 {
p.param[param] = ""
} else {
p.param[param[:i]] = param[i+1:]
}
}
p.parsePathType()
}
func (p *Plugin) parseIncludeConnectionParam() bool {
return p.param["include_connection"] == "true"
}
// parsePathType parses the path type from the parameters.
func (p *Plugin) parsePathType() {
switch p.param["paths"] {
case "import":
p.pathType = PathTypeImport
case "source_relative":
p.pathType = PathTypeSourceRelative
default:
log.Fatalf(`Unknown path type %q: want "import" or "source_relative".`, p.param["paths"])
}
}
// fileName create file name ...
func (p *Plugin) fileName(name string) string {
generatedBaseName := name + GeneratedFilePostfix
if p.pathType == PathTypeSourceRelative {
// The generated file will have the same base as the source file, and it will be located in the same directory.
fileDir := path.Dir(p.req.GetFileToGenerate()[0])
return path.Join(fileDir, generatedBaseName)
}
return generatedBaseName
}
// checkProtobufVersion checks that the protobuf version is supported.
func (p *Plugin) checkProtobufVersion() error {
ver := p.req.GetCompilerVersion()
// check protobuf version is supported (3.12.0 or later)
if ver.GetMajor() < 3 || (ver.GetMajor() == 3 && ver.GetMinor() < 12) {
return fmt.Errorf("unsupported protobuf version: %s, please upgrade to 3.12.0 or later", ver.String())
}
// check protobuf syntax is supported (proto3)
if err := helperpkg.CheckProtoSyntax(helperpkg.GetUserProtoFile(p.req)); err != nil {
return fmt.Errorf("unsupported protobuf syntax: %s, only 'proto3' is supported", helperpkg.GetUserProtoFile(p.req).GetSyntax())
}
return nil
}
// pathType is a type for how to generate output filenames.
type pathType int
// Available path singleTypes.
const (
PathTypeImport pathType = iota
PathTypeSourceRelative
)
const GeneratedFilePostfix = ".db.go"