main.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // protoc-gen-go is a plugin for the Google protocol buffer compiler to generate
  5. // Go code. Install it by building this program and making it accessible within
  6. // your PATH with the name:
  7. // protoc-gen-go
  8. //
  9. // The 'go' suffix becomes part of the argument for the protocol compiler,
  10. // such that it can be invoked as:
  11. // protoc --go_out=paths=source_relative:. path/to/file.proto
  12. //
  13. // This generates Go bindings for the protocol buffer defined by file.proto.
  14. // With that input, the output will be written to:
  15. // path/to/file.pb.go
  16. //
  17. // See the README and documentation for protocol buffers to learn more:
  18. // https://developers.google.com/protocol-buffers/
  19. package main
  20. import (
  21. "flag"
  22. "fmt"
  23. "strings"
  24. gengogrpc "google.golang.org/protobuf/cmd/protoc-gen-go-grpc/internal_gengogrpc"
  25. gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo"
  26. "google.golang.org/protobuf/compiler/protogen"
  27. )
  28. func main() {
  29. var (
  30. flags flag.FlagSet
  31. plugins = flags.String("plugins", "", "list of plugins to enable (supported values: grpc)")
  32. importPrefix = flags.String("import_prefix", "", "prefix to prepend to import paths")
  33. )
  34. importRewriteFunc := func(importPath protogen.GoImportPath) protogen.GoImportPath {
  35. switch importPath {
  36. case "context", "fmt", "math":
  37. return importPath
  38. }
  39. if *importPrefix != "" {
  40. return protogen.GoImportPath(*importPrefix) + importPath
  41. }
  42. return importPath
  43. }
  44. opts := &protogen.Options{
  45. ParamFunc: flags.Set,
  46. ImportRewriteFunc: importRewriteFunc,
  47. }
  48. protogen.Run(opts, func(gen *protogen.Plugin) error {
  49. grpc := false
  50. for _, plugin := range strings.Split(*plugins, ",") {
  51. switch plugin {
  52. case "grpc":
  53. grpc = true
  54. case "":
  55. default:
  56. return fmt.Errorf("protoc-gen-go: unknown plugin %q", plugin)
  57. }
  58. }
  59. for _, f := range gen.Files {
  60. if !f.Generate {
  61. continue
  62. }
  63. g := gengo.GenerateFile(gen, f)
  64. if grpc {
  65. gengogrpc.GenerateFileContent(gen, f, g)
  66. }
  67. }
  68. return nil
  69. })
  70. }