protoc-gen-go: move gengogrpc into v1 repo

The eventual home of this is the gRPC repo, but extract it from the
APIv2 repo for now.

Change-Id: I0d88659945e17887da117ab6511e478598e70f02
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/220354
Reviewed-by: Joe Tsai <thebrokentoaster@gmail.com>
This commit is contained in:
Damien Neil 2020-02-20 17:08:18 -08:00
Родитель 0fd14f9610
Коммит cea45d6ceb
10 изменённых файлов: 1614 добавлений и 2 удалений

398
internal/gengogrpc/grpc.go Normal file
Просмотреть файл

@ -0,0 +1,398 @@
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package gengogrpc contains the gRPC code generator.
package gengogrpc
import (
"fmt"
"strconv"
"strings"
"google.golang.org/protobuf/compiler/protogen"
"google.golang.org/protobuf/types/descriptorpb"
)
const (
contextPackage = protogen.GoImportPath("context")
grpcPackage = protogen.GoImportPath("google.golang.org/grpc")
codesPackage = protogen.GoImportPath("google.golang.org/grpc/codes")
statusPackage = protogen.GoImportPath("google.golang.org/grpc/status")
)
// GenerateFile generates a _grpc.pb.go file containing gRPC service definitions.
func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile {
if len(file.Services) == 0 {
return nil
}
filename := file.GeneratedFilenamePrefix + "_grpc.pb.go"
g := gen.NewGeneratedFile(filename, file.GoImportPath)
g.P("// Code generated by protoc-gen-go-grpc. DO NOT EDIT.")
g.P()
g.P("package ", file.GoPackageName)
g.P()
GenerateFileContent(gen, file, g)
return g
}
// GenerateFileContent generates the gRPC service definitions, excluding the package statement.
func GenerateFileContent(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) {
if len(file.Services) == 0 {
return
}
// TODO: Remove this. We don't need to include these references any more.
g.P("// Reference imports to suppress errors if they are not otherwise used.")
g.P("var _ ", contextPackage.Ident("Context"))
g.P("var _ ", grpcPackage.Ident("ClientConnInterface"))
g.P()
g.P("// This is a compile-time assertion to ensure that this generated file")
g.P("// is compatible with the grpc package it is being compiled against.")
g.P("const _ = ", grpcPackage.Ident("SupportPackageIsVersion6"))
g.P()
for _, service := range file.Services {
genService(gen, file, g, service)
}
}
func genService(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) {
clientName := service.GoName + "Client"
g.P("// ", clientName, " is the client API for ", service.GoName, " service.")
g.P("//")
g.P("// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.")
// Client interface.
if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
g.P("//")
g.P(deprecationComment)
}
g.Annotate(clientName, service.Location)
g.P("type ", clientName, " interface {")
for _, method := range service.Methods {
g.Annotate(clientName+"."+method.GoName, method.Location)
if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() {
g.P(deprecationComment)
}
g.P(method.Comments.Leading,
clientSignature(g, method))
}
g.P("}")
g.P()
// Client structure.
g.P("type ", unexport(clientName), " struct {")
g.P("cc ", grpcPackage.Ident("ClientConnInterface"))
g.P("}")
g.P()
// NewClient factory.
if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
g.P(deprecationComment)
}
g.P("func New", clientName, " (cc ", grpcPackage.Ident("ClientConnInterface"), ") ", clientName, " {")
g.P("return &", unexport(clientName), "{cc}")
g.P("}")
g.P()
var methodIndex, streamIndex int
// Client method implementations.
for _, method := range service.Methods {
if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() {
// Unary RPC method
genClientMethod(gen, file, g, method, methodIndex)
methodIndex++
} else {
// Streaming RPC method
genClientMethod(gen, file, g, method, streamIndex)
streamIndex++
}
}
// Server interface.
serverType := service.GoName + "Server"
g.P("// ", serverType, " is the server API for ", service.GoName, " service.")
if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
g.P("//")
g.P(deprecationComment)
}
g.Annotate(serverType, service.Location)
g.P("type ", serverType, " interface {")
for _, method := range service.Methods {
g.Annotate(serverType+"."+method.GoName, method.Location)
if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() {
g.P(deprecationComment)
}
g.P(method.Comments.Leading,
serverSignature(g, method))
}
g.P("}")
g.P()
// Server Unimplemented struct for forward compatibility.
g.P("// Unimplemented", serverType, " can be embedded to have forward compatible implementations.")
g.P("type Unimplemented", serverType, " struct {")
g.P("}")
g.P()
for _, method := range service.Methods {
nilArg := ""
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
nilArg = "nil,"
}
g.P("func (*Unimplemented", serverType, ") ", serverSignature(g, method), "{")
g.P("return ", nilArg, statusPackage.Ident("Errorf"), "(", codesPackage.Ident("Unimplemented"), `, "method `, method.GoName, ` not implemented")`)
g.P("}")
}
g.P()
// Server registration.
if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() {
g.P(deprecationComment)
}
serviceDescVar := "_" + service.GoName + "_serviceDesc"
g.P("func Register", service.GoName, "Server(s *", grpcPackage.Ident("Server"), ", srv ", serverType, ") {")
g.P("s.RegisterService(&", serviceDescVar, `, srv)`)
g.P("}")
g.P()
// Server handler implementations.
var handlerNames []string
for _, method := range service.Methods {
hname := genServerMethod(gen, file, g, method)
handlerNames = append(handlerNames, hname)
}
// Service descriptor.
g.P("var ", serviceDescVar, " = ", grpcPackage.Ident("ServiceDesc"), " {")
g.P("ServiceName: ", strconv.Quote(string(service.Desc.FullName())), ",")
g.P("HandlerType: (*", serverType, ")(nil),")
g.P("Methods: []", grpcPackage.Ident("MethodDesc"), "{")
for i, method := range service.Methods {
if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
continue
}
g.P("{")
g.P("MethodName: ", strconv.Quote(string(method.Desc.Name())), ",")
g.P("Handler: ", handlerNames[i], ",")
g.P("},")
}
g.P("},")
g.P("Streams: []", grpcPackage.Ident("StreamDesc"), "{")
for i, method := range service.Methods {
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
continue
}
g.P("{")
g.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",")
g.P("Handler: ", handlerNames[i], ",")
if method.Desc.IsStreamingServer() {
g.P("ServerStreams: true,")
}
if method.Desc.IsStreamingClient() {
g.P("ClientStreams: true,")
}
g.P("},")
}
g.P("},")
g.P("Metadata: \"", file.Desc.Path(), "\",")
g.P("}")
g.P()
}
func clientSignature(g *protogen.GeneratedFile, method *protogen.Method) string {
s := method.GoName + "(ctx " + g.QualifiedGoIdent(contextPackage.Ident("Context"))
if !method.Desc.IsStreamingClient() {
s += ", in *" + g.QualifiedGoIdent(method.Input.GoIdent)
}
s += ", opts ..." + g.QualifiedGoIdent(grpcPackage.Ident("CallOption")) + ") ("
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
s += "*" + g.QualifiedGoIdent(method.Output.GoIdent)
} else {
s += method.Parent.GoName + "_" + method.GoName + "Client"
}
s += ", error)"
return s
}
func genClientMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method, index int) {
service := method.Parent
sname := fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.Desc.Name())
if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() {
g.P(deprecationComment)
}
g.P("func (c *", unexport(service.GoName), "Client) ", clientSignature(g, method), "{")
if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() {
g.P("out := new(", method.Output.GoIdent, ")")
g.P(`err := c.cc.Invoke(ctx, "`, sname, `", in, out, opts...)`)
g.P("if err != nil { return nil, err }")
g.P("return out, nil")
g.P("}")
g.P()
return
}
streamType := unexport(service.GoName) + method.GoName + "Client"
serviceDescVar := "_" + service.GoName + "_serviceDesc"
g.P("stream, err := c.cc.NewStream(ctx, &", serviceDescVar, ".Streams[", index, `], "`, sname, `", opts...)`)
g.P("if err != nil { return nil, err }")
g.P("x := &", streamType, "{stream}")
if !method.Desc.IsStreamingClient() {
g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }")
g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
}
g.P("return x, nil")
g.P("}")
g.P()
genSend := method.Desc.IsStreamingClient()
genRecv := method.Desc.IsStreamingServer()
genCloseAndRecv := !method.Desc.IsStreamingServer()
// Stream auxiliary types and methods.
g.P("type ", service.GoName, "_", method.GoName, "Client interface {")
if genSend {
g.P("Send(*", method.Input.GoIdent, ") error")
}
if genRecv {
g.P("Recv() (*", method.Output.GoIdent, ", error)")
}
if genCloseAndRecv {
g.P("CloseAndRecv() (*", method.Output.GoIdent, ", error)")
}
g.P(grpcPackage.Ident("ClientStream"))
g.P("}")
g.P()
g.P("type ", streamType, " struct {")
g.P(grpcPackage.Ident("ClientStream"))
g.P("}")
g.P()
if genSend {
g.P("func (x *", streamType, ") Send(m *", method.Input.GoIdent, ") error {")
g.P("return x.ClientStream.SendMsg(m)")
g.P("}")
g.P()
}
if genRecv {
g.P("func (x *", streamType, ") Recv() (*", method.Output.GoIdent, ", error) {")
g.P("m := new(", method.Output.GoIdent, ")")
g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
g.P("return m, nil")
g.P("}")
g.P()
}
if genCloseAndRecv {
g.P("func (x *", streamType, ") CloseAndRecv() (*", method.Output.GoIdent, ", error) {")
g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
g.P("m := new(", method.Output.GoIdent, ")")
g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
g.P("return m, nil")
g.P("}")
g.P()
}
}
func serverSignature(g *protogen.GeneratedFile, method *protogen.Method) string {
var reqArgs []string
ret := "error"
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
reqArgs = append(reqArgs, g.QualifiedGoIdent(contextPackage.Ident("Context")))
ret = "(*" + g.QualifiedGoIdent(method.Output.GoIdent) + ", error)"
}
if !method.Desc.IsStreamingClient() {
reqArgs = append(reqArgs, "*"+g.QualifiedGoIdent(method.Input.GoIdent))
}
if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() {
reqArgs = append(reqArgs, method.Parent.GoName+"_"+method.GoName+"Server")
}
return method.GoName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
}
func genServerMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method) string {
service := method.Parent
hname := fmt.Sprintf("_%s_%s_Handler", service.GoName, method.GoName)
if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() {
g.P("func ", hname, "(srv interface{}, ctx ", contextPackage.Ident("Context"), ", dec func(interface{}) error, interceptor ", grpcPackage.Ident("UnaryServerInterceptor"), ") (interface{}, error) {")
g.P("in := new(", method.Input.GoIdent, ")")
g.P("if err := dec(in); err != nil { return nil, err }")
g.P("if interceptor == nil { return srv.(", service.GoName, "Server).", method.GoName, "(ctx, in) }")
g.P("info := &", grpcPackage.Ident("UnaryServerInfo"), "{")
g.P("Server: srv,")
g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.GoName)), ",")
g.P("}")
g.P("handler := func(ctx ", contextPackage.Ident("Context"), ", req interface{}) (interface{}, error) {")
g.P("return srv.(", service.GoName, "Server).", method.GoName, "(ctx, req.(*", method.Input.GoIdent, "))")
g.P("}")
g.P("return interceptor(ctx, in, info, handler)")
g.P("}")
g.P()
return hname
}
streamType := unexport(service.GoName) + method.GoName + "Server"
g.P("func ", hname, "(srv interface{}, stream ", grpcPackage.Ident("ServerStream"), ") error {")
if !method.Desc.IsStreamingClient() {
g.P("m := new(", method.Input.GoIdent, ")")
g.P("if err := stream.RecvMsg(m); err != nil { return err }")
g.P("return srv.(", service.GoName, "Server).", method.GoName, "(m, &", streamType, "{stream})")
} else {
g.P("return srv.(", service.GoName, "Server).", method.GoName, "(&", streamType, "{stream})")
}
g.P("}")
g.P()
genSend := method.Desc.IsStreamingServer()
genSendAndClose := !method.Desc.IsStreamingServer()
genRecv := method.Desc.IsStreamingClient()
// Stream auxiliary types and methods.
g.P("type ", service.GoName, "_", method.GoName, "Server interface {")
if genSend {
g.P("Send(*", method.Output.GoIdent, ") error")
}
if genSendAndClose {
g.P("SendAndClose(*", method.Output.GoIdent, ") error")
}
if genRecv {
g.P("Recv() (*", method.Input.GoIdent, ", error)")
}
g.P(grpcPackage.Ident("ServerStream"))
g.P("}")
g.P()
g.P("type ", streamType, " struct {")
g.P(grpcPackage.Ident("ServerStream"))
g.P("}")
g.P()
if genSend {
g.P("func (x *", streamType, ") Send(m *", method.Output.GoIdent, ") error {")
g.P("return x.ServerStream.SendMsg(m)")
g.P("}")
g.P()
}
if genSendAndClose {
g.P("func (x *", streamType, ") SendAndClose(m *", method.Output.GoIdent, ") error {")
g.P("return x.ServerStream.SendMsg(m)")
g.P("}")
g.P()
}
if genRecv {
g.P("func (x *", streamType, ") Recv() (*", method.Input.GoIdent, ", error) {")
g.P("m := new(", method.Input.GoIdent, ")")
g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }")
g.P("return m, nil")
g.P("}")
g.P()
}
return hname
}
const deprecationComment = "// Deprecated: Do not use."
func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] }

Просмотреть файл

@ -0,0 +1,367 @@
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"flag"
"go/build"
"go/parser"
"go/token"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"testing"
)
// Set --regenerate to regenerate the golden files.
var regenerate = flag.Bool("regenerate", false, "regenerate golden files")
// When the environment variable RUN_AS_PROTOC_GEN_GO is set, we skip running
// tests and instead act as protoc-gen-go. This allows the test binary to
// pass itself to protoc.
func init() {
if os.Getenv("RUN_AS_PROTOC_GEN_GO") != "" {
main()
os.Exit(0)
}
}
func TestGolden(t *testing.T) {
workdir, err := ioutil.TempDir("", "proto-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(workdir)
// Find all the proto files we need to compile. We assume that each directory
// contains the files for a single package.
supportTypeAliases := hasReleaseTag("go1.9")
packages := map[string][]string{}
err = filepath.Walk("testdata", func(path string, info os.FileInfo, err error) error {
if filepath.Base(path) == "import_public" && !supportTypeAliases {
// Public imports require type alias support.
return filepath.SkipDir
}
if !strings.HasSuffix(path, ".proto") {
return nil
}
dir := filepath.Dir(path)
packages[dir] = append(packages[dir], path)
return nil
})
if err != nil {
t.Fatal(err)
}
// Compile each package, using this binary as protoc-gen-go.
for _, sources := range packages {
args := []string{"-Itestdata", "--go_out=plugins=grpc,paths=source_relative:" + workdir}
args = append(args, sources...)
protoc(t, args)
}
// Compare each generated file to the golden version.
filepath.Walk(workdir, func(genPath string, info os.FileInfo, _ error) error {
if info.IsDir() {
return nil
}
// For each generated file, figure out the path to the corresponding
// golden file in the testdata directory.
relPath, err := filepath.Rel(workdir, genPath)
if err != nil {
t.Errorf("filepath.Rel(%q, %q): %v", workdir, genPath, err)
return nil
}
if filepath.SplitList(relPath)[0] == ".." {
t.Errorf("generated file %q is not relative to %q", genPath, workdir)
}
goldenPath := filepath.Join("testdata", relPath)
got, err := ioutil.ReadFile(genPath)
if err != nil {
t.Error(err)
return nil
}
if *regenerate {
// If --regenerate set, just rewrite the golden files.
err := ioutil.WriteFile(goldenPath, got, 0666)
if err != nil {
t.Error(err)
}
return nil
}
want, err := ioutil.ReadFile(goldenPath)
if err != nil {
t.Error(err)
return nil
}
want = fdescRE.ReplaceAll(want, nil)
got = fdescRE.ReplaceAll(got, nil)
if bytes.Equal(got, want) {
return nil
}
cmd := exec.Command("diff", "-u", goldenPath, genPath)
out, _ := cmd.CombinedOutput()
t.Errorf("golden file differs: %v\n%v", relPath, string(out))
return nil
})
}
var fdescRE = regexp.MustCompile(`(?ms)^var fileDescriptor.*}`)
// Source files used by TestParameters.
const (
aProto = `
syntax = "proto3";
package test.alpha;
option go_package = "package/alpha";
import "beta/b.proto";
message M { test.beta.M field = 1; }`
bProto = `
syntax = "proto3";
package test.beta;
// no go_package option
message M {}`
)
func TestParameters(t *testing.T) {
for _, test := range []struct {
parameters string
wantFiles map[string]bool
wantImportsA map[string]bool
wantPackageA string
wantPackageB string
}{{
parameters: "",
wantFiles: map[string]bool{
"package/alpha/a.pb.go": true,
"beta/b.pb.go": true,
},
wantPackageA: "alpha",
wantPackageB: "test_beta",
wantImportsA: map[string]bool{
"google.golang.org/protobuf/runtime/protoimpl": true,
"beta": true,
},
}, {
parameters: "import_prefix=prefix",
wantFiles: map[string]bool{
"package/alpha/a.pb.go": true,
"beta/b.pb.go": true,
},
wantPackageA: "alpha",
wantPackageB: "test_beta",
wantImportsA: map[string]bool{
// This really doesn't seem like useful behavior.
"prefixgoogle.golang.org/protobuf/runtime/protoimpl": true,
"prefixbeta": true,
},
}, {
// import_path only affects the 'package' line.
parameters: "import_path=import/path/of/pkg",
wantPackageA: "alpha",
wantPackageB: "pkg",
wantFiles: map[string]bool{
"package/alpha/a.pb.go": true,
"beta/b.pb.go": true,
},
}, {
parameters: "Mbeta/b.proto=package/gamma",
wantFiles: map[string]bool{
"package/alpha/a.pb.go": true,
"beta/b.pb.go": true,
},
wantPackageA: "alpha",
wantPackageB: "test_beta",
wantImportsA: map[string]bool{
"google.golang.org/protobuf/runtime/protoimpl": true,
// Rewritten by the M parameter.
"package/gamma": true,
},
}, {
parameters: "import_prefix=prefix,Mbeta/b.proto=package/gamma",
wantFiles: map[string]bool{
"package/alpha/a.pb.go": true,
"beta/b.pb.go": true,
},
wantPackageA: "alpha",
wantPackageB: "test_beta",
wantImportsA: map[string]bool{
// import_prefix applies after M.
"prefixpackage/gamma": true,
},
}, {
parameters: "paths=source_relative",
wantFiles: map[string]bool{
"alpha/a.pb.go": true,
"beta/b.pb.go": true,
},
wantPackageA: "alpha",
wantPackageB: "test_beta",
}, {
parameters: "paths=source_relative,import_prefix=prefix",
wantFiles: map[string]bool{
// import_prefix doesn't affect filenames.
"alpha/a.pb.go": true,
"beta/b.pb.go": true,
},
wantPackageA: "alpha",
wantPackageB: "test_beta",
}} {
name := test.parameters
if name == "" {
name = "defaults"
}
// TODO: Switch to t.Run when we no longer support Go 1.6.
t.Logf("TEST: %v", name)
workdir, err := ioutil.TempDir("", "proto-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(workdir)
for _, dir := range []string{"alpha", "beta", "out"} {
if err := os.MkdirAll(filepath.Join(workdir, dir), 0777); err != nil {
t.Fatal(err)
}
}
if err := ioutil.WriteFile(filepath.Join(workdir, "alpha", "a.proto"), []byte(aProto), 0666); err != nil {
t.Fatal(err)
}
if err := ioutil.WriteFile(filepath.Join(workdir, "beta", "b.proto"), []byte(bProto), 0666); err != nil {
t.Fatal(err)
}
protoc(t, []string{
"-I" + workdir,
"--go_out=" + test.parameters + ":" + filepath.Join(workdir, "out"),
filepath.Join(workdir, "alpha", "a.proto"),
})
protoc(t, []string{
"-I" + workdir,
"--go_out=" + test.parameters + ":" + filepath.Join(workdir, "out"),
filepath.Join(workdir, "beta", "b.proto"),
})
contents := make(map[string]string)
gotFiles := make(map[string]bool)
outdir := filepath.Join(workdir, "out")
filepath.Walk(outdir, func(p string, info os.FileInfo, _ error) error {
if info.IsDir() {
return nil
}
base := filepath.Base(p)
if base == "a.pb.go" || base == "b.pb.go" {
b, err := ioutil.ReadFile(p)
if err != nil {
t.Fatal(err)
}
contents[base] = string(b)
}
relPath, _ := filepath.Rel(outdir, p)
gotFiles[relPath] = true
return nil
})
for got := range gotFiles {
if runtime.GOOS == "windows" {
got = filepath.ToSlash(got)
}
if !test.wantFiles[got] {
t.Errorf("unexpected output file: %v", got)
}
}
for want := range test.wantFiles {
if runtime.GOOS == "windows" {
want = filepath.FromSlash(want)
}
if !gotFiles[want] {
t.Errorf("missing output file: %v", want)
}
}
gotPackageA, gotImports, err := parseFile(contents["a.pb.go"])
if err != nil {
t.Fatal(err)
}
gotPackageB, _, err := parseFile(contents["b.pb.go"])
if err != nil {
t.Fatal(err)
}
if got, want := gotPackageA, test.wantPackageA; want != got {
t.Errorf("output file a.pb.go is package %q, want %q", got, want)
}
if got, want := gotPackageB, test.wantPackageB; want != got {
t.Errorf("output file b.pb.go is package %q, want %q", got, want)
}
missingImport := false
WantImport:
for want := range test.wantImportsA {
for _, imp := range gotImports {
if `"`+want+`"` == imp {
continue WantImport
}
}
t.Errorf("output file a.pb.go does not contain expected import %q", want)
missingImport = true
}
if missingImport {
t.Error("got imports:")
for _, imp := range gotImports {
t.Errorf(" %v", imp)
}
}
}
}
// parseFile returns a file's package name and a list of all packages it imports.
func parseFile(source string) (packageName string, imports []string, err error) {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "<source>", source, parser.ImportsOnly)
if err != nil {
return "", nil, err
}
for _, imp := range f.Imports {
imports = append(imports, imp.Path.Value)
}
return f.Name.Name, imports, nil
}
func protoc(t *testing.T, args []string) {
cmd := exec.Command("protoc", "--plugin=protoc-gen-go="+os.Args[0])
cmd.Args = append(cmd.Args, args...)
// We set the RUN_AS_PROTOC_GEN_GO environment variable to indicate that
// the subprocess should act as a proto compiler rather than a test.
cmd.Env = append(os.Environ(), "RUN_AS_PROTOC_GEN_GO=1")
out, err := cmd.CombinedOutput()
if len(out) > 0 || err != nil {
t.Log("RUNNING: ", strings.Join(cmd.Args, " "))
}
if len(out) > 0 {
t.Log(string(out))
}
if err != nil {
t.Fatalf("protoc: %v", err)
}
}
func hasReleaseTag(want string) bool {
for _, tag := range build.Default.ReleaseTags {
if tag == want {
return true
}
}
return false
}

Просмотреть файл

@ -24,7 +24,7 @@ import (
"fmt"
"strings"
gengogrpc "google.golang.org/protobuf/cmd/protoc-gen-go-grpc/internal_gengogrpc"
"github.com/golang/protobuf/internal/gengogrpc"
gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo"
"google.golang.org/protobuf/compiler/protogen"
)

11
protoc-gen-go/testdata/grpc/go.mod поставляемый Normal file
Просмотреть файл

@ -0,0 +1,11 @@
module github.com/golang/protobuf/protoc-gen-go/testdata/grpc
go 1.9
require (
github.com/golang/protobuf v1.3.2
google.golang.org/grpc v1.27.0-pre.0.20200124224931-7afcfdd66b12
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd
)
replace github.com/golang/protobuf => ../../..

50
protoc-gen-go/testdata/grpc/go.sum поставляемый Normal file
Просмотреть файл

@ -0,0 +1,50 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.27.0-pre.0.20200124224931-7afcfdd66b12 h1:Xr+lKA5ySDBoca3aMs7eOexQcsEkNin70xNPcILZITc=
google.golang.org/grpc v1.27.0-pre.0.20200124224931-7afcfdd66b12/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd h1:zSMqFwpTkfj+1nNFgmgu4B+Qv5Kpf4jpd11lCmHKuwQ=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

613
protoc-gen-go/testdata/grpc/grpc.pb.go поставляемый Normal file
Просмотреть файл

@ -0,0 +1,613 @@
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.19.0-devel
// protoc v3.11.3
// source: grpc/grpc.proto
package testing
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(19 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 19)
)
type SimpleRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *SimpleRequest) Reset() {
*x = SimpleRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_grpc_grpc_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SimpleRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SimpleRequest) ProtoMessage() {}
func (x *SimpleRequest) ProtoReflect() protoreflect.Message {
mi := &file_grpc_grpc_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SimpleRequest.ProtoReflect.Descriptor instead.
func (*SimpleRequest) Descriptor() ([]byte, []int) {
return file_grpc_grpc_proto_rawDescGZIP(), []int{0}
}
type SimpleResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *SimpleResponse) Reset() {
*x = SimpleResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_grpc_grpc_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *SimpleResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SimpleResponse) ProtoMessage() {}
func (x *SimpleResponse) ProtoReflect() protoreflect.Message {
mi := &file_grpc_grpc_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SimpleResponse.ProtoReflect.Descriptor instead.
func (*SimpleResponse) Descriptor() ([]byte, []int) {
return file_grpc_grpc_proto_rawDescGZIP(), []int{1}
}
type StreamMsg struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *StreamMsg) Reset() {
*x = StreamMsg{}
if protoimpl.UnsafeEnabled {
mi := &file_grpc_grpc_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *StreamMsg) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StreamMsg) ProtoMessage() {}
func (x *StreamMsg) ProtoReflect() protoreflect.Message {
mi := &file_grpc_grpc_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use StreamMsg.ProtoReflect.Descriptor instead.
func (*StreamMsg) Descriptor() ([]byte, []int) {
return file_grpc_grpc_proto_rawDescGZIP(), []int{2}
}
type StreamMsg2 struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *StreamMsg2) Reset() {
*x = StreamMsg2{}
if protoimpl.UnsafeEnabled {
mi := &file_grpc_grpc_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *StreamMsg2) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StreamMsg2) ProtoMessage() {}
func (x *StreamMsg2) ProtoReflect() protoreflect.Message {
mi := &file_grpc_grpc_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use StreamMsg2.ProtoReflect.Descriptor instead.
func (*StreamMsg2) Descriptor() ([]byte, []int) {
return file_grpc_grpc_proto_rawDescGZIP(), []int{3}
}
var File_grpc_grpc_proto protoreflect.FileDescriptor
var file_grpc_grpc_proto_rawDesc = []byte{
0x0a, 0x0f, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x12, 0x0c, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x22,
0x0f, 0x0a, 0x0d, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
0x22, 0x10, 0x0a, 0x0e, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
0x73, 0x65, 0x22, 0x0b, 0x0a, 0x09, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x4d, 0x73, 0x67, 0x22,
0x0c, 0x0a, 0x0a, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x4d, 0x73, 0x67, 0x32, 0x32, 0x98, 0x02,
0x0a, 0x04, 0x54, 0x65, 0x73, 0x74, 0x12, 0x46, 0x0a, 0x09, 0x55, 0x6e, 0x61, 0x72, 0x79, 0x43,
0x61, 0x6c, 0x6c, 0x12, 0x1b, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x69,
0x6e, 0x67, 0x2e, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
0x1a, 0x1c, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e,
0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x44,
0x0a, 0x0a, 0x44, 0x6f, 0x77, 0x6e, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x1b, 0x2e, 0x67,
0x72, 0x70, 0x63, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x53, 0x69, 0x6d, 0x70,
0x6c, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x17, 0x2e, 0x67, 0x72, 0x70, 0x63,
0x2e, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x4d,
0x73, 0x67, 0x30, 0x01, 0x12, 0x43, 0x0a, 0x08, 0x55, 0x70, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d,
0x12, 0x17, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e,
0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x4d, 0x73, 0x67, 0x1a, 0x1c, 0x2e, 0x67, 0x72, 0x70, 0x63,
0x2e, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x53, 0x69, 0x6d, 0x70, 0x6c, 0x65, 0x52,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x28, 0x01, 0x12, 0x3d, 0x0a, 0x04, 0x42, 0x69, 0x64,
0x69, 0x12, 0x17, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67,
0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x4d, 0x73, 0x67, 0x1a, 0x18, 0x2e, 0x67, 0x72, 0x70,
0x63, 0x2e, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d,
0x4d, 0x73, 0x67, 0x32, 0x28, 0x01, 0x30, 0x01, 0x42, 0x40, 0x5a, 0x3e, 0x67, 0x69, 0x74, 0x68,
0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65,
0x6e, 0x2d, 0x67, 0x6f, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x64, 0x61, 0x74, 0x61, 0x2f, 0x67, 0x72,
0x70, 0x63, 0x3b, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74,
0x6f, 0x33,
}
var (
file_grpc_grpc_proto_rawDescOnce sync.Once
file_grpc_grpc_proto_rawDescData = file_grpc_grpc_proto_rawDesc
)
func file_grpc_grpc_proto_rawDescGZIP() []byte {
file_grpc_grpc_proto_rawDescOnce.Do(func() {
file_grpc_grpc_proto_rawDescData = protoimpl.X.CompressGZIP(file_grpc_grpc_proto_rawDescData)
})
return file_grpc_grpc_proto_rawDescData
}
var file_grpc_grpc_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_grpc_grpc_proto_goTypes = []interface{}{
(*SimpleRequest)(nil), // 0: grpc.testing.SimpleRequest
(*SimpleResponse)(nil), // 1: grpc.testing.SimpleResponse
(*StreamMsg)(nil), // 2: grpc.testing.StreamMsg
(*StreamMsg2)(nil), // 3: grpc.testing.StreamMsg2
}
var file_grpc_grpc_proto_depIdxs = []int32{
0, // 0: grpc.testing.Test.UnaryCall:input_type -> grpc.testing.SimpleRequest
0, // 1: grpc.testing.Test.Downstream:input_type -> grpc.testing.SimpleRequest
2, // 2: grpc.testing.Test.Upstream:input_type -> grpc.testing.StreamMsg
2, // 3: grpc.testing.Test.Bidi:input_type -> grpc.testing.StreamMsg
1, // 4: grpc.testing.Test.UnaryCall:output_type -> grpc.testing.SimpleResponse
2, // 5: grpc.testing.Test.Downstream:output_type -> grpc.testing.StreamMsg
1, // 6: grpc.testing.Test.Upstream:output_type -> grpc.testing.SimpleResponse
3, // 7: grpc.testing.Test.Bidi:output_type -> grpc.testing.StreamMsg2
4, // [4:8] is the sub-list for method output_type
0, // [0:4] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_grpc_grpc_proto_init() }
func file_grpc_grpc_proto_init() {
if File_grpc_grpc_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_grpc_grpc_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SimpleRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_grpc_grpc_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*SimpleResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_grpc_grpc_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*StreamMsg); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_grpc_grpc_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*StreamMsg2); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_grpc_grpc_proto_rawDesc,
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_grpc_grpc_proto_goTypes,
DependencyIndexes: file_grpc_grpc_proto_depIdxs,
MessageInfos: file_grpc_grpc_proto_msgTypes,
}.Build()
File_grpc_grpc_proto = out.File
file_grpc_grpc_proto_rawDesc = nil
file_grpc_grpc_proto_goTypes = nil
file_grpc_grpc_proto_depIdxs = nil
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// TestClient is the client API for Test service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type TestClient interface {
UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error)
// This RPC streams from the server only.
Downstream(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (Test_DownstreamClient, error)
// This RPC streams from the client.
Upstream(ctx context.Context, opts ...grpc.CallOption) (Test_UpstreamClient, error)
// This one streams in both directions.
Bidi(ctx context.Context, opts ...grpc.CallOption) (Test_BidiClient, error)
}
type testClient struct {
cc grpc.ClientConnInterface
}
func NewTestClient(cc grpc.ClientConnInterface) TestClient {
return &testClient{cc}
}
func (c *testClient) UnaryCall(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (*SimpleResponse, error) {
out := new(SimpleResponse)
err := c.cc.Invoke(ctx, "/grpc.testing.Test/UnaryCall", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *testClient) Downstream(ctx context.Context, in *SimpleRequest, opts ...grpc.CallOption) (Test_DownstreamClient, error) {
stream, err := c.cc.NewStream(ctx, &_Test_serviceDesc.Streams[0], "/grpc.testing.Test/Downstream", opts...)
if err != nil {
return nil, err
}
x := &testDownstreamClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type Test_DownstreamClient interface {
Recv() (*StreamMsg, error)
grpc.ClientStream
}
type testDownstreamClient struct {
grpc.ClientStream
}
func (x *testDownstreamClient) Recv() (*StreamMsg, error) {
m := new(StreamMsg)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *testClient) Upstream(ctx context.Context, opts ...grpc.CallOption) (Test_UpstreamClient, error) {
stream, err := c.cc.NewStream(ctx, &_Test_serviceDesc.Streams[1], "/grpc.testing.Test/Upstream", opts...)
if err != nil {
return nil, err
}
x := &testUpstreamClient{stream}
return x, nil
}
type Test_UpstreamClient interface {
Send(*StreamMsg) error
CloseAndRecv() (*SimpleResponse, error)
grpc.ClientStream
}
type testUpstreamClient struct {
grpc.ClientStream
}
func (x *testUpstreamClient) Send(m *StreamMsg) error {
return x.ClientStream.SendMsg(m)
}
func (x *testUpstreamClient) CloseAndRecv() (*SimpleResponse, error) {
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
m := new(SimpleResponse)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func (c *testClient) Bidi(ctx context.Context, opts ...grpc.CallOption) (Test_BidiClient, error) {
stream, err := c.cc.NewStream(ctx, &_Test_serviceDesc.Streams[2], "/grpc.testing.Test/Bidi", opts...)
if err != nil {
return nil, err
}
x := &testBidiClient{stream}
return x, nil
}
type Test_BidiClient interface {
Send(*StreamMsg) error
Recv() (*StreamMsg2, error)
grpc.ClientStream
}
type testBidiClient struct {
grpc.ClientStream
}
func (x *testBidiClient) Send(m *StreamMsg) error {
return x.ClientStream.SendMsg(m)
}
func (x *testBidiClient) Recv() (*StreamMsg2, error) {
m := new(StreamMsg2)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
// TestServer is the server API for Test service.
type TestServer interface {
UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error)
// This RPC streams from the server only.
Downstream(*SimpleRequest, Test_DownstreamServer) error
// This RPC streams from the client.
Upstream(Test_UpstreamServer) error
// This one streams in both directions.
Bidi(Test_BidiServer) error
}
// UnimplementedTestServer can be embedded to have forward compatible implementations.
type UnimplementedTestServer struct {
}
func (*UnimplementedTestServer) UnaryCall(context.Context, *SimpleRequest) (*SimpleResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UnaryCall not implemented")
}
func (*UnimplementedTestServer) Downstream(*SimpleRequest, Test_DownstreamServer) error {
return status.Errorf(codes.Unimplemented, "method Downstream not implemented")
}
func (*UnimplementedTestServer) Upstream(Test_UpstreamServer) error {
return status.Errorf(codes.Unimplemented, "method Upstream not implemented")
}
func (*UnimplementedTestServer) Bidi(Test_BidiServer) error {
return status.Errorf(codes.Unimplemented, "method Bidi not implemented")
}
func RegisterTestServer(s *grpc.Server, srv TestServer) {
s.RegisterService(&_Test_serviceDesc, srv)
}
func _Test_UnaryCall_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SimpleRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(TestServer).UnaryCall(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpc.testing.Test/UnaryCall",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TestServer).UnaryCall(ctx, req.(*SimpleRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Test_Downstream_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(SimpleRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(TestServer).Downstream(m, &testDownstreamServer{stream})
}
type Test_DownstreamServer interface {
Send(*StreamMsg) error
grpc.ServerStream
}
type testDownstreamServer struct {
grpc.ServerStream
}
func (x *testDownstreamServer) Send(m *StreamMsg) error {
return x.ServerStream.SendMsg(m)
}
func _Test_Upstream_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(TestServer).Upstream(&testUpstreamServer{stream})
}
type Test_UpstreamServer interface {
SendAndClose(*SimpleResponse) error
Recv() (*StreamMsg, error)
grpc.ServerStream
}
type testUpstreamServer struct {
grpc.ServerStream
}
func (x *testUpstreamServer) SendAndClose(m *SimpleResponse) error {
return x.ServerStream.SendMsg(m)
}
func (x *testUpstreamServer) Recv() (*StreamMsg, error) {
m := new(StreamMsg)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
func _Test_Bidi_Handler(srv interface{}, stream grpc.ServerStream) error {
return srv.(TestServer).Bidi(&testBidiServer{stream})
}
type Test_BidiServer interface {
Send(*StreamMsg2) error
Recv() (*StreamMsg, error)
grpc.ServerStream
}
type testBidiServer struct {
grpc.ServerStream
}
func (x *testBidiServer) Send(m *StreamMsg2) error {
return x.ServerStream.SendMsg(m)
}
func (x *testBidiServer) Recv() (*StreamMsg, error) {
m := new(StreamMsg)
if err := x.ServerStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
var _Test_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.testing.Test",
HandlerType: (*TestServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "UnaryCall",
Handler: _Test_UnaryCall_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "Downstream",
Handler: _Test_Downstream_Handler,
ServerStreams: true,
},
{
StreamName: "Upstream",
Handler: _Test_Upstream_Handler,
ClientStreams: true,
},
{
StreamName: "Bidi",
Handler: _Test_Bidi_Handler,
ServerStreams: true,
ClientStreams: true,
},
},
Metadata: "grpc/grpc.proto",
}

34
protoc-gen-go/testdata/grpc/grpc.proto поставляемый Normal file
Просмотреть файл

@ -0,0 +1,34 @@
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
syntax = "proto3";
package grpc.testing;
option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/grpc;testing";
message SimpleRequest {
}
message SimpleResponse {
}
message StreamMsg {
}
message StreamMsg2 {
}
service Test {
rpc UnaryCall(SimpleRequest) returns (SimpleResponse);
// This RPC streams from the server only.
rpc Downstream(SimpleRequest) returns (stream StreamMsg);
// This RPC streams from the client.
rpc Upstream(stream StreamMsg) returns (SimpleResponse);
// This one streams in both directions.
rpc Bidi(stream StreamMsg) returns (stream StreamMsg2);
}

127
protoc-gen-go/testdata/grpc/grpc_empty.pb.go поставляемый Normal file
Просмотреть файл

@ -0,0 +1,127 @@
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.19.0-devel
// protoc v3.11.3
// source: grpc/grpc_empty.proto
package testing
import (
context "context"
grpc "google.golang.org/grpc"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(19 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 19)
)
var File_grpc_grpc_empty_proto protoreflect.FileDescriptor
var file_grpc_grpc_empty_proto_rawDesc = []byte{
0x0a, 0x15, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x5f, 0x65, 0x6d, 0x70, 0x74,
0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0c, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x74, 0x65,
0x73, 0x74, 0x69, 0x6e, 0x67, 0x32, 0x0e, 0x0a, 0x0c, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x53, 0x65,
0x72, 0x76, 0x69, 0x63, 0x65, 0x42, 0x40, 0x5a, 0x3e, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e,
0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x62, 0x75, 0x66, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x63, 0x2d, 0x67, 0x65, 0x6e, 0x2d, 0x67,
0x6f, 0x2f, 0x74, 0x65, 0x73, 0x74, 0x64, 0x61, 0x74, 0x61, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x3b,
0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_grpc_grpc_empty_proto_rawDescOnce sync.Once
file_grpc_grpc_empty_proto_rawDescData = file_grpc_grpc_empty_proto_rawDesc
)
func file_grpc_grpc_empty_proto_rawDescGZIP() []byte {
file_grpc_grpc_empty_proto_rawDescOnce.Do(func() {
file_grpc_grpc_empty_proto_rawDescData = protoimpl.X.CompressGZIP(file_grpc_grpc_empty_proto_rawDescData)
})
return file_grpc_grpc_empty_proto_rawDescData
}
var file_grpc_grpc_empty_proto_goTypes = []interface{}{}
var file_grpc_grpc_empty_proto_depIdxs = []int32{
0, // [0:0] is the sub-list for method output_type
0, // [0:0] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_grpc_grpc_empty_proto_init() }
func file_grpc_grpc_empty_proto_init() {
if File_grpc_grpc_empty_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_grpc_grpc_empty_proto_rawDesc,
NumEnums: 0,
NumMessages: 0,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_grpc_grpc_empty_proto_goTypes,
DependencyIndexes: file_grpc_grpc_empty_proto_depIdxs,
}.Build()
File_grpc_grpc_empty_proto = out.File
file_grpc_grpc_empty_proto_rawDesc = nil
file_grpc_grpc_empty_proto_goTypes = nil
file_grpc_grpc_empty_proto_depIdxs = nil
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// EmptyServiceClient is the client API for EmptyService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type EmptyServiceClient interface {
}
type emptyServiceClient struct {
cc grpc.ClientConnInterface
}
func NewEmptyServiceClient(cc grpc.ClientConnInterface) EmptyServiceClient {
return &emptyServiceClient{cc}
}
// EmptyServiceServer is the server API for EmptyService service.
type EmptyServiceServer interface {
}
// UnimplementedEmptyServiceServer can be embedded to have forward compatible implementations.
type UnimplementedEmptyServiceServer struct {
}
func RegisterEmptyServiceServer(s *grpc.Server, srv EmptyServiceServer) {
s.RegisterService(&_EmptyService_serviceDesc, srv)
}
var _EmptyService_serviceDesc = grpc.ServiceDesc{
ServiceName: "grpc.testing.EmptyService",
HandlerType: (*EmptyServiceServer)(nil),
Methods: []grpc.MethodDesc{},
Streams: []grpc.StreamDesc{},
Metadata: "grpc/grpc_empty.proto",
}

11
protoc-gen-go/testdata/grpc/grpc_empty.proto поставляемый Normal file
Просмотреть файл

@ -0,0 +1,11 @@
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
syntax = "proto3";
package grpc.testing;
option go_package = "github.com/golang/protobuf/protoc-gen-go/testdata/grpc;testing";
service EmptyService {}

Просмотреть файл

@ -4,5 +4,6 @@
# license that can be found in the LICENSE file.
cd "$(git rev-parse --show-toplevel)"
set -e
go run ./internal/cmd/generate-alias -execute
exit $?
go test ./protoc-gen-go -regenerate