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
5// protoc-gen-go is a plugin for the Google protocol buffer compiler to generate
6// Go code. Install it by building this program and making it accessible within
7// your PATH with the name:
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//	protoc --go_out=paths=source_relative:. path/to/file.proto
13//
14// This generates Go bindings for the protocol buffer defined by file.proto.
15// With that input, the output will be written to:
16//	path/to/file.pb.go
17//
18// See the README and documentation for protocol buffers to learn more:
19//	https://developers.google.com/protocol-buffers/
20package main
21
22import (
23	"flag"
24	"fmt"
25	"strings"
26
27	"github.com/golang/protobuf/internal/gengogrpc"
28	gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo"
29	"google.golang.org/protobuf/compiler/protogen"
30)
31
32func 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}
75