-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
93 lines (75 loc) · 1.88 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
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/golang/protobuf/proto"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"github.com/pkg/errors"
)
// Version is the release version of the python server twirp generator
var Version = "1.0.0"
func main() {
var err error
versionFlag := flag.Bool("version", false, "print version and exit")
flag.Parse()
if *versionFlag {
fmt.Println(Version)
os.Exit(0)
}
// protoc pipes the information about what needs generating into os.Stdin.
// Read the request and return it.
req, err := readCodeGeneratorRequest(os.Stdin)
if err != nil {
fmt.Println("error:", err)
os.Exit(1)
}
// Validate the request
if len(req.FileToGenerate) == 0 {
fmt.Println("no files to generate")
os.Exit(1)
}
// Generate the code
gen := &generator{}
resp, err := gen.Generate(req)
if err != nil {
fmt.Fprintln(os.Stderr, err)
fmt.Println("error:", err)
os.Exit(1)
}
// Write response to os.Stdout
err = writeCodeGeneratorResponse(os.Stdout, resp)
if err != nil {
fmt.Println("error:", err)
os.Exit(1)
}
}
func readCodeGeneratorRequest(in io.Reader) (*plugin.CodeGeneratorRequest, error) {
var err error
// Read the full request before trying to parse it
data, err := ioutil.ReadAll(in)
if err != nil {
return nil, errors.Wrap(err, "reading CodeGeneratorRequest")
}
// Unmarshal the request
req := &plugin.CodeGeneratorRequest{}
err = proto.Unmarshal(data, req)
if err != nil {
return nil, errors.Wrap(err, "unmarshaling CodeGeneratorRequest")
}
return req, nil
}
func writeCodeGeneratorResponse(out io.Writer, resp *plugin.CodeGeneratorResponse) error {
var err error
data, err := proto.Marshal(resp)
if err != nil {
return errors.Wrap(err, "marshaling CodeGeneratorResponse")
}
_, err = out.Write(data)
if err != nil {
return errors.Wrap(err, "writing CodeGeneratorResponse")
}
return nil
}