main.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. //
  8. // protoc-gen-go
  9. //
  10. // The 'go' suffix becomes part of the argument for the protocol compiler,
  11. // such that it can be invoked as:
  12. //
  13. // protoc --go_out=paths=source_relative:. path/to/file.proto
  14. //
  15. // This generates Go bindings for the protocol buffer defined by file.proto.
  16. // With that input, the output will be written to:
  17. //
  18. // path/to/file.pb.go
  19. //
  20. // See the README and documentation for protocol buffers to learn more:
  21. //
  22. // https://developers.google.com/protocol-buffers/
  23. package main
  24. import (
  25. "flag"
  26. "fmt"
  27. "strings"
  28. "github.com/golang/protobuf/internal/gengogrpc"
  29. gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo"
  30. "google.golang.org/protobuf/compiler/protogen"
  31. )
  32. func main() {
  33. var (
  34. flags flag.FlagSet
  35. plugins = flags.String("plugins", "", "list of plugins to enable (supported values: grpc)")
  36. importPrefix = flags.String("import_prefix", "", "prefix to prepend to import paths")
  37. )
  38. importRewriteFunc := func(importPath protogen.GoImportPath) protogen.GoImportPath {
  39. switch importPath {
  40. case "context", "fmt", "math":
  41. return importPath
  42. }
  43. if *importPrefix != "" {
  44. return protogen.GoImportPath(*importPrefix) + importPath
  45. }
  46. return importPath
  47. }
  48. protogen.Options{
  49. ParamFunc: flags.Set,
  50. ImportRewriteFunc: importRewriteFunc,
  51. }.Run(func(gen *protogen.Plugin) error {
  52. grpc := false
  53. for _, plugin := range strings.Split(*plugins, ",") {
  54. switch plugin {
  55. case "grpc":
  56. grpc = true
  57. case "":
  58. default:
  59. return fmt.Errorf("protoc-gen-go: unknown plugin %q", plugin)
  60. }
  61. }
  62. for _, f := range gen.Files {
  63. if !f.Generate {
  64. continue
  65. }
  66. g := gengo.GenerateFile(gen, f)
  67. if grpc {
  68. gengogrpc.GenerateFileContent(gen, f, g)
  69. }
  70. }
  71. gen.SupportedFeatures = gengo.SupportedFeatures
  72. return nil
  73. })
  74. }