-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathproto_compile.go
More file actions
257 lines (223 loc) · 6.95 KB
/
proto_compile.go
File metadata and controls
257 lines (223 loc) · 6.95 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package protoc
import (
"fmt"
"log"
"path"
"sort"
"strings"
"github.com/bazelbuild/bazel-gazelle/config"
"github.com/bazelbuild/bazel-gazelle/label"
"github.com/bazelbuild/bazel-gazelle/resolve"
"github.com/bazelbuild/bazel-gazelle/rule"
)
const (
// ProtoLibraryKey stores the ProtoLibrary implementation for a rule.
ProtoLibraryKey = "_proto_library"
)
func init() {
Rules().MustRegisterRule("stackb:rules_proto:proto_compile", &protoCompile{})
}
// protoCompile implements LanguageRule for the 'proto_compile' rule.
type protoCompile struct{}
// KindInfo implements part of the LanguageRule interface.
func (s *protoCompile) KindInfo() rule.KindInfo {
return rule.KindInfo{
NonEmptyAttrs: map[string]bool{
"outputs": true,
},
MergeableAttrs: map[string]bool{
"outputs": true,
"plugins": true,
"output_mappings": true,
"options": true,
"protos": true,
},
SubstituteAttrs: map[string]bool{
"out": true,
},
}
}
// Name implements part of the LanguageRule interface.
func (s *protoCompile) Name() string {
return "proto_compile"
}
// LoadInfo implements part of the LanguageRule interface.
func (s *protoCompile) LoadInfo() rule.LoadInfo {
return rule.LoadInfo{
Name: "@build_stack_rules_proto//rules:proto_compile.bzl",
Symbols: []string{"proto_compile"},
}
}
// ProvideRule implements part of the LanguageRule interface.
func (s *protoCompile) ProvideRule(cfg *LanguageRuleConfig, config *ProtocConfiguration) RuleProvider {
if len(config.Outputs) == 0 {
return nil
}
return &protoCompileRule{
kind: "proto_compile",
nameSuffix: "compile",
outputsAttrName: "outputs",
config: config,
ruleConfig: cfg,
}
}
// protoCompile implements RuleProvider for the 'proto_compile' rule.
type protoCompileRule struct {
kind string
nameSuffix string
outputsAttrName string
config *ProtocConfiguration
ruleConfig *LanguageRuleConfig
}
// Kind implements part of the ruleProvider interface.
func (s *protoCompileRule) Kind() string {
return s.kind
}
// Name implements part of the ruleProvider interface.
func (s *protoCompileRule) Name() string {
return fmt.Sprintf("%s_%s_%s", s.config.Library.BaseName(), s.config.Prefix, s.nameSuffix)
}
// Visibility provides visibility labels.
func (s *protoCompileRule) Visibility() []string {
return s.ruleConfig.GetVisibility()
}
func (s *protoCompileRule) Outputs() []string {
outputs := s.config.Outputs
sort.Strings(outputs)
return outputs
}
// Rule implements part of the ruleProvider interface.
func (s *protoCompileRule) Rule(otherGen ...*rule.Rule) *rule.Rule {
outputs := s.Outputs()
// Check for output overlap with existing proto_compile rules of the same
// kind. When a package-level plugin (e.g. protoc-gen-prost) produces the
// same output file from multiple proto_library rules, merge them into a
// single proto_compile rule using the "protos" attribute.
for _, other := range otherGen {
if other.Kind() != s.Kind() {
continue
}
otherOutputs := other.AttrStrings(s.outputsAttrName)
if !hasOverlap(outputs, otherOutputs) {
continue
}
// Merge outputs
other.SetAttr(s.outputsAttrName, DeduplicateAndSort(append(otherOutputs, outputs...)))
// Convert singular "proto" to list "protos" if needed, then append
existingProtos := other.AttrStrings("protos")
if len(existingProtos) == 0 {
if p := other.AttrString("proto"); p != "" {
existingProtos = []string{p}
other.DelAttr("proto")
}
}
existingProtos = append(existingProtos, s.config.Library.Name())
other.SetAttr("protos", DeduplicateAndSort(existingProtos))
// Merge plugins
otherPlugins := other.AttrStrings("plugins")
otherPlugins = append(otherPlugins, GetPluginLabels(s.config.Plugins)...)
other.SetAttr("plugins", DeduplicateAndSort(otherPlugins))
// Merge output_mappings
if len(s.config.Mappings) > 0 {
existing := other.AttrStrings("output_mappings")
for k, v := range s.config.Mappings {
existing = append(existing, k+"="+v)
}
other.SetAttr("output_mappings", DeduplicateAndSort(existing))
}
// Rename merged rule based on output content (proto package) rather
// than the first library's arbitrary name.
mergedOutputs := DeduplicateAndSort(append(otherOutputs, outputs...))
if name := mergedRuleName(mergedOutputs, s.config.Prefix, s.nameSuffix); name != "" {
other.SetName(name)
}
return other
}
// No overlap found — create new rule
newRule := rule.NewRule(s.Kind(), s.Name())
newRule.SetAttr(s.outputsAttrName, outputs)
newRule.SetAttr("plugins", GetPluginLabels(s.config.Plugins))
newRule.SetAttr("proto", s.config.Library.Name())
if s.config.LanguageConfig.Protoc != "" {
newRule.SetAttr("protoc", s.config.LanguageConfig.Protoc)
}
if len(s.config.Mappings) > 0 {
mappings := make([]string, len(s.config.Mappings))
var i int
for k, v := range s.config.Mappings {
mappings[i] = k + "=" + v
i++
}
sort.Strings(mappings)
newRule.SetAttr("output_mappings", mappings)
}
outs := GetPluginOuts(s.config.Plugins)
if len(outs) > 0 {
newRule.SetAttr("outs", MakeStringDict(outs))
}
visibility := s.Visibility()
if len(visibility) > 0 {
newRule.SetAttr("visibility", visibility)
}
for _, name := range s.ruleConfig.GetAttrNames() {
vals := s.ruleConfig.GetAttr(name)
if len(vals) == 0 {
continue
}
switch name {
case "verbose":
val := vals[0]
switch val {
case "True", "true":
newRule.SetAttr("verbose", true)
case "False", "false":
newRule.SetAttr("verbose", false)
default:
log.Printf("bad attr 'verbose' value: %q", val)
}
default:
newRule.SetAttr(name, vals)
}
}
return newRule
}
// mergedRuleName derives a rule name from the output filenames for a merged
// proto_compile rule. It takes the first output (sorted), strips the file
// extension, replaces dots with underscores, and formats as
// {sanitized}_{prefix}_{suffix}.
func mergedRuleName(outputs []string, prefix, suffix string) string {
if len(outputs) == 0 {
return ""
}
base := outputs[0]
ext := path.Ext(base)
if ext != "" {
base = base[:len(base)-len(ext)]
}
sanitized := strings.ReplaceAll(base, ".", "_")
return fmt.Sprintf("%s_%s_%s", sanitized, prefix, suffix)
}
// hasOverlap returns true if two string slices share any common element.
func hasOverlap(a, b []string) bool {
set := make(map[string]bool, len(a))
for _, s := range a {
set[s] = true
}
for _, s := range b {
if set[s] {
return true
}
}
return false
}
// Imports implements part of the RuleProvider interface.
func (s *protoCompileRule) Imports(c *config.Config, r *rule.Rule, file *rule.File) []resolve.ImportSpec {
return nil
}
// Resolve implements part of the RuleProvider interface.
func (s *protoCompileRule) Resolve(c *config.Config, ix *resolve.RuleIndex, r *rule.Rule, imports []string, from label.Label) {
options := GetPluginOptions(s.config.Plugins, r, from)
if len(options) > 0 {
r.SetAttr("options", MakeStringListDict(options))
}
}