main.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2018 Twitch Interactive, Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"). You may not
  4. // use this file except in compliance with the License. A copy of the License is
  5. // located at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // or in the "license" file accompanying this file. This file is distributed on
  10. // an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  11. // express or implied. See the License for the specific language governing
  12. // permissions and limitations under the License.
  13. package gen
  14. import (
  15. "io"
  16. "io/ioutil"
  17. "os"
  18. "github.com/golang/protobuf/proto"
  19. "github.com/golang/protobuf/protoc-gen-go/descriptor"
  20. plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
  21. )
  22. // Generator ...
  23. type Generator interface {
  24. Generate(in *plugin.CodeGeneratorRequest) *plugin.CodeGeneratorResponse
  25. }
  26. // Main ...
  27. func Main(g Generator) {
  28. req := readGenRequest()
  29. resp := g.Generate(req)
  30. writeResponse(os.Stdout, resp)
  31. }
  32. // FilesToGenerate ...
  33. func FilesToGenerate(req *plugin.CodeGeneratorRequest) []*descriptor.FileDescriptorProto {
  34. genFiles := make([]*descriptor.FileDescriptorProto, 0)
  35. Outer:
  36. for _, name := range req.FileToGenerate {
  37. for _, f := range req.ProtoFile {
  38. if f.GetName() == name {
  39. genFiles = append(genFiles, f)
  40. continue Outer
  41. }
  42. }
  43. Fail("could not find file named", name)
  44. }
  45. return genFiles
  46. }
  47. func readGenRequest() *plugin.CodeGeneratorRequest {
  48. data, err := ioutil.ReadAll(os.Stdin)
  49. if err != nil {
  50. Error(err, "reading input")
  51. }
  52. req := new(plugin.CodeGeneratorRequest)
  53. if err = proto.Unmarshal(data, req); err != nil {
  54. Error(err, "parsing input proto")
  55. }
  56. if len(req.FileToGenerate) == 0 {
  57. Fail("no files to generate")
  58. }
  59. return req
  60. }
  61. func writeResponse(w io.Writer, resp *plugin.CodeGeneratorResponse) {
  62. data, err := proto.Marshal(resp)
  63. if err != nil {
  64. Error(err, "marshaling response")
  65. }
  66. _, err = w.Write(data)
  67. if err != nil {
  68. Error(err, "writing response")
  69. }
  70. }