This repository has been archived by the owner on Jun 17, 2023. It is now read-only.
forked from stackb/rules_proto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protoc-gen-grpc-web.go
71 lines (61 loc) · 1.94 KB
/
protoc-gen-grpc-web.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package grpcnode
import (
"fmt"
"path"
"strings"
"github.com/bazelbuild/bazel-gazelle/label"
"github.com/stackb/rules_proto/pkg/protoc"
)
func init() {
protoc.Plugins().MustRegisterPlugin(&ProtocGenGrpcWeb{})
}
// ProtocGenGrpcWeb implements Plugin for grpc_web_plugin in the
// grpc/grpc-web repo.
type ProtocGenGrpcWeb struct{}
// Name implements part of the Plugin interface.
func (p *ProtocGenGrpcWeb) Name() string {
return "grpc:grpc-web:protoc-gen-grpc-web"
}
// Configure implements part of the Plugin interface.
func (p *ProtocGenGrpcWeb) Configure(ctx *protoc.PluginContext) *protoc.PluginConfiguration {
if !protoc.HasServices(ctx.ProtoLibrary.Files()...) {
return nil
}
return &protoc.PluginConfiguration{
Label: label.New("build_stack_rules_proto", "plugin/grpc/grpc-web", "protoc-gen-grpc-web"),
Outputs: protoc.FlatMapFiles(
grpcGeneratedFileName(ctx.Rel, ctx.PluginConfig.GetOptions()),
protoc.HasService,
ctx.ProtoLibrary.Files()...,
),
Options: ctx.PluginConfig.GetOptions(),
}
}
// grpcGeneratedFileName is a utility function that returns a function that
// computes the name of a predicted generated file having the given extension(s)
// relative to the given dir.
func grpcGeneratedFileName(reldir string, options []string) func(f *protoc.File) []string {
isTypescript := false
for _, option := range options {
if option == "import_style=typescript" {
isTypescript = true
}
}
return func(f *protoc.File) []string {
name := strings.ReplaceAll(f.Name, "-", "_")
if reldir != "" {
name = path.Join(reldir, name)
}
var filename string
if isTypescript {
segments := strings.Split(name, "/")
lastSegment := segments[len(segments)-1]
capitalized := strings.Title(lastSegment)
segments[len(segments)-1] = capitalized
filename = fmt.Sprintf("%sServiceClientPb.ts", strings.Join(segments, "/"))
} else {
filename = fmt.Sprintf("%s_grpc_web_pb.js", name)
}
return []string{filename}
}
}