This repository has been archived by the owner on Jan 13, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
108 lines (87 loc) · 2.01 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
package main
import (
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"github.com/gobuffalo/packr"
"github.com/golang/protobuf/proto"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
"github.com/pkg/errors"
"github.com/twirphp/protoc-gen-twirp_php/internal/gen"
)
// Provisioned by ldflags
var (
Version string
)
func main() {
version := flag.Bool("version", false, "print version and exit")
flag.Parse()
if *version {
fmt.Println(Version)
os.Exit(0)
}
err := Main(os.Stdin, os.Stdout, "./templates")
if err != nil {
log.Fatal(err)
}
}
// Main does the hard work. It is called by the main func.
func Main(in io.Reader, out io.Writer, templates string) error {
req, err := readCodeGeneratorRequest(in)
if err != nil {
return err
}
box := packr.NewBox(templates)
g := gen.New(box)
greq := &gen.Request{
CodeGeneratorRequest: req,
GlobalFiles: []string{
"global/Server.php",
"global/TwirpClient.php",
"global/TwirpError.php",
"global/TwirpServer.php",
},
ServiceFiles: []string{
"service/_Service_.php",
"service/Client.php",
"service/Server.php",
},
}
resp, err := g.Generate(greq)
if err != nil {
return err
}
err = writeCodeGeneratorResponse(out, resp)
if err != nil {
return err
}
return nil
}
func readCodeGeneratorRequest(in io.Reader) (*plugin.CodeGeneratorRequest, error) {
data, err := ioutil.ReadAll(in)
if err != nil {
return nil, errors.Wrap(err, "cannot read input")
}
req := new(plugin.CodeGeneratorRequest)
if err = proto.Unmarshal(data, req); err != nil {
return nil, errors.Wrap(err, "cannot parse input proto")
}
if len(req.FileToGenerate) == 0 {
return nil, errors.Wrap(err, "no files to generate")
}
return req, nil
}
func writeCodeGeneratorResponse(out io.Writer, resp *plugin.CodeGeneratorResponse) error {
data, err := proto.Marshal(resp)
if err != nil {
return errors.Wrap(err, "cannot serialize output proto")
}
_, err = out.Write(data)
if err != nil {
return errors.Wrap(err, "cannot write output")
}
return nil
}