-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (78 loc) · 1.81 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
package gen
import (
"io"
"io/ioutil"
"log"
"os"
"strings"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
)
// Generator ...
type Generator interface {
Generate(in *plugin.CodeGeneratorRequest) *plugin.CodeGeneratorResponse
}
// Main ...
func Main(g Generator) {
req := readGenRequest()
resp := g.Generate(req)
writeResponse(os.Stdout, resp)
}
// FilesToGenerate ...
func FilesToGenerate(req *plugin.CodeGeneratorRequest) []*descriptor.FileDescriptorProto {
genFiles := make([]*descriptor.FileDescriptorProto, 0)
Outer:
for _, name := range req.FileToGenerate {
for _, f := range req.ProtoFile {
if f.GetName() == name {
genFiles = append(genFiles, f)
continue Outer
}
}
Fail("could not find file named", name)
}
return genFiles
}
func readGenRequest() *plugin.CodeGeneratorRequest {
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
Error(err, "reading input")
}
req := new(plugin.CodeGeneratorRequest)
if err = proto.Unmarshal(data, req); err != nil {
Error(err, "parsing input proto")
}
if len(req.FileToGenerate) == 0 {
Fail("no files to generate")
}
return req
}
func writeResponse(w io.Writer, resp *plugin.CodeGeneratorResponse) {
data, err := proto.Marshal(resp)
if err != nil {
Error(err, "marshaling response")
}
_, err = w.Write(data)
if err != nil {
Error(err, "writing response")
}
}
// Fail log and exit
func Fail(msgs ...string) {
s := strings.Join(msgs, " ")
log.Print("error:", s)
os.Exit(1)
}
// Fail log and exit
func Info(msgs ...string) {
s := strings.Join(msgs, " ")
log.Print("info:", s)
os.Exit(1)
}
// Error log and exit
func Error(err error, msgs ...string) {
s := strings.Join(msgs, " ") + ":" + err.Error()
log.Print("error:", s)
os.Exit(1)
}