github.com/stackb/rules_proto@v0.0.0-20240221195024-5428336c51f1/pkg/plugin/grpcecosystem/grpcgateway/protoc-gen-grpc-gateway.go (about)

     1  package grpcgateway
     2  
     3  import (
     4  	"path"
     5  
     6  	"github.com/bazelbuild/bazel-gazelle/label"
     7  	"github.com/stackb/rules_proto/pkg/protoc"
     8  )
     9  
    10  func init() {
    11  	protoc.Plugins().MustRegisterPlugin(&protocGenGrpcGatewayPlugin{})
    12  }
    13  
    14  // protocGenGrpcGatewayPlugin implements Plugin for protoc-gen-grpc-gateway.
    15  type protocGenGrpcGatewayPlugin struct{}
    16  
    17  // Name implements part of the Plugin interface.
    18  func (p *protocGenGrpcGatewayPlugin) Name() string {
    19  	return "grpc-ecosystem:grpc-gateway:protoc-gen-grpc-gateway"
    20  }
    21  
    22  // Configure implements part of the Plugin interface.
    23  func (p *protocGenGrpcGatewayPlugin) Configure(ctx *protoc.PluginContext) *protoc.PluginConfiguration {
    24  	generateUnbound := ctx.PluginConfig.Options["generate_unbound_methods=true"]
    25  	if !p.shouldApply(ctx.ProtoLibrary, generateUnbound) {
    26  		return nil
    27  	}
    28  	return &protoc.PluginConfiguration{
    29  		Label:   label.New("build_stack_rules_proto", "plugin/grpc-ecosystem/grpc-gateway", "protoc-gen-grpc-gateway"),
    30  		Outputs: p.outputs(ctx.Rel, ctx.ProtoLibrary, generateUnbound),
    31  		Options: ctx.PluginConfig.GetOptions(),
    32  	}
    33  }
    34  
    35  func (p *protocGenGrpcGatewayPlugin) shouldApply(lib protoc.ProtoLibrary, generateUnbound bool) bool {
    36  	for _, f := range lib.Files() {
    37  		if p.shouldOutputForFile(f, generateUnbound) {
    38  			return true
    39  		}
    40  	}
    41  	return false
    42  }
    43  
    44  func (p *protocGenGrpcGatewayPlugin) outputs(rel string, lib protoc.ProtoLibrary, generateUnbound bool) []string {
    45  	srcs := make([]string, 0)
    46  	for _, f := range lib.Files() {
    47  		if !p.shouldOutputForFile(f, generateUnbound) {
    48  			continue
    49  		}
    50  		base := f.Name
    51  		if rel != "" {
    52  			base = path.Join(rel, base)
    53  		}
    54  		srcs = append(srcs, base+".pb.gw.go")
    55  	}
    56  	return srcs
    57  }
    58  
    59  func (p *protocGenGrpcGatewayPlugin) shouldOutputForFile(f *protoc.File, generateUnbound bool) bool {
    60  	return f.HasRPCs() && (generateUnbound || f.HasRPCOption("(google.api.http)"))
    61  }