forked from bazel-contrib/rules_python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrule_builders.bzl
695 lines (573 loc) · 20.4 KB
/
rule_builders.bzl
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
# Copyright 2025 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Builders for creating rules, aspects et al.
When defining rules, Bazel only allows creating *immutable* objects that can't
be introspected. This makes it difficult to perform arbitrary customizations of
how a rule is defined, which makes extending a rule implementation prone to
copy/paste issues and version skew.
These builders are, essentially, mutable and inspectable wrappers for those
Bazel objects. This allows defining a rule where the values are mutable and
callers can customize them to derive their own variant of the rule while still
inheriting everything else about the rule.
To that end, the builders are not strict in how they handle values. They
generally assume that the values provided are valid and provide ways to
override their logic and force particular values to be used when they are
eventually converted to the args for calling e.g. `rule()`.
:::{important}
When using builders, most lists, dicts, et al passed into them **must** be
locally created values, otherwise they won't be mutable. This is due to Bazel's
implicit immutability rules: after evaluating a `.bzl` file, its global
variables are frozen.
:::
:::{tip}
To aid defining reusable pieces, many APIs accept no-arg callable functions
that create a builder. For example, common attributes can be stored
in a `dict[str, lambda]`, e.g. `ATTRS = {"srcs": lambda: LabelList(...)}`.
:::
Example usage:
```
load(":rule_builders.bzl", "ruleb")
load(":attr_builders.bzl", "attrb")
# File: foo_binary.bzl
_COMMON_ATTRS = {
"srcs": lambda: attrb.LabelList(...),
}
def create_foo_binary_builder():
foo = ruleb.Rule(
executable = True,
)
foo.implementation.set(_foo_binary_impl)
foo.attrs.update(COMMON_ATTRS)
return foo
def create_foo_test_builder():
foo = create_foo_binary_build()
binary_impl = foo.implementation.get()
def foo_test_impl(ctx):
binary_impl(ctx)
...
foo.implementation.set(foo_test_impl)
foo.executable.set(False)
foo.test.test(True)
foo.attrs.update(
_coverage = attrb.Label(default="//:coverage")
)
return foo
foo_binary = create_foo_binary_builder().build()
foo_test = create_foo_test_builder().build()
# File: custom_foo_binary.bzl
load(":foo_binary.bzl", "create_foo_binary_builder")
def create_custom_foo_binary():
r = create_foo_binary_builder()
r.attrs["srcs"].default.append("whatever.txt")
return r.build()
custom_foo_binary = create_custom_foo_binary()
```
:::{versionadded} 1.3.0
:::
"""
load("@bazel_skylib//lib:types.bzl", "types")
load(
":builders_util.bzl",
"kwargs_getter",
"kwargs_getter_doc",
"kwargs_set_default_dict",
"kwargs_set_default_doc",
"kwargs_set_default_ignore_none",
"kwargs_set_default_list",
"kwargs_setter",
"kwargs_setter_doc",
"list_add_unique",
)
# Various string constants for kwarg key names used across two or more
# functions, or in contexts with optional lookups (e.g. dict.dict, key in dict).
# Constants are used to reduce the chance of typos.
# NOTE: These keys are often part of function signature via `**kwargs`; they
# are not simply internal names.
_ATTRS = "attrs"
_CFG = "cfg"
_EXEC_COMPATIBLE_WITH = "exec_compatible_with"
_EXEC_GROUPS = "exec_groups"
_IMPLEMENTATION = "implementation"
_INPUTS = "inputs"
_OUTPUTS = "outputs"
_TOOLCHAINS = "toolchains"
def _is_builder(obj):
return hasattr(obj, "build")
def _ExecGroup_typedef():
"""Builder for {external:bzl:obj}`exec_group`
:::{function} toolchains() -> list[ToolchainType]
:::
:::{function} exec_compatible_with() -> list[str | Label]
:::
:::{include} /_includes/field_kwargs_doc.md
:::
"""
def _ExecGroup_new(**kwargs):
"""Creates a builder for {external:bzl:obj}`exec_group`.
Args:
**kwargs: Same as {external:bzl:obj}`exec_group`
Returns:
{type}`ExecGroup`
"""
kwargs_set_default_list(kwargs, _TOOLCHAINS)
kwargs_set_default_list(kwargs, _EXEC_COMPATIBLE_WITH)
for i, value in enumerate(kwargs[_TOOLCHAINS]):
kwargs[_TOOLCHAINS][i] = _ToolchainType_maybe_from(value)
# buildifier: disable=uninitialized
self = struct(
toolchains = kwargs_getter(kwargs, _TOOLCHAINS),
exec_compatible_with = kwargs_getter(kwargs, _EXEC_COMPATIBLE_WITH),
kwargs = kwargs,
build = lambda: _ExecGroup_build(self),
)
return self
def _ExecGroup_maybe_from(obj):
if types.is_function(obj):
return obj()
else:
return obj
def _ExecGroup_build(self):
kwargs = dict(self.kwargs)
if kwargs.get(_TOOLCHAINS):
kwargs[_TOOLCHAINS] = [
v.build() if _is_builder(v) else v
for v in kwargs[_TOOLCHAINS]
]
if kwargs.get(_EXEC_COMPATIBLE_WITH):
kwargs[_EXEC_COMPATIBLE_WITH] = [
v.build() if _is_builder(v) else v
for v in kwargs[_EXEC_COMPATIBLE_WITH]
]
return exec_group(**kwargs)
# buildifier: disable=name-conventions
ExecGroup = struct(
TYPEDEF = _ExecGroup_typedef,
new = _ExecGroup_new,
build = _ExecGroup_build,
)
def _ToolchainType_typedef():
"""Builder for {obj}`config_common.toolchain_type()`
:::{include} /_includes/field_kwargs_doc.md
:::
:::{function} mandatory() -> bool
:::
:::{function} name() -> str | Label | None
:::
:::{function} set_name(v: str)
:::
:::{function} set_mandatory(v: bool)
:::
"""
def _ToolchainType_new(name = None, **kwargs):
"""Creates a builder for `config_common.toolchain_type`.
Args:
name: {type}`str | Label | None` the toolchain type target.
**kwargs: Same as {obj}`config_common.toolchain_type`
Returns:
{type}`ToolchainType`
"""
kwargs["name"] = name
kwargs_set_default_ignore_none(kwargs, "mandatory", True)
# buildifier: disable=uninitialized
self = struct(
# keep sorted
build = lambda: _ToolchainType_build(self),
kwargs = kwargs,
mandatory = kwargs_getter(kwargs, "mandatory"),
name = kwargs_getter(kwargs, "name"),
set_mandatory = kwargs_setter(kwargs, "mandatory"),
set_name = kwargs_setter(kwargs, "name"),
)
return self
def _ToolchainType_maybe_from(obj):
if types.is_string(obj) or type(obj) == "Label":
return ToolchainType.new(name = obj)
elif types.is_function(obj):
# A lambda to create a builder
return obj()
else:
# For lack of another option, return it as-is.
# Presumably it's already a builder or other valid object.
return obj
def _ToolchainType_build(self):
"""Builds a `config_common.toolchain_type`
Args:
self: implicitly added
Returns:
{type}`config_common.toolchain_type`
"""
kwargs = dict(self.kwargs)
name = kwargs.pop("name") # Name must be positional
return config_common.toolchain_type(name, **kwargs)
# buildifier: disable=name-conventions
ToolchainType = struct(
TYPEDEF = _ToolchainType_typedef,
new = _ToolchainType_new,
build = _ToolchainType_build,
)
def _RuleCfg_typedef():
"""Wrapper for `rule.cfg` arg.
:::{function} implementation() -> str | callable | None | config.target | config.none
:::
::::{function} inputs() -> list[Label]
:::{seealso}
The {obj}`add_inputs()` and {obj}`update_inputs` methods for adding unique
values.
:::
::::
:::{function} outputs() -> list[Label]
:::{seealso}
The {obj}`add_outputs()` and {obj}`update_outputs` methods for adding unique
values.
:::
:::
:::{function} set_implementation(v: str | callable | None | config.target | config.none)
The string values "target" and "none" are supported.
:::
"""
def _RuleCfg_new(rule_cfg_arg):
"""Creates a builder for the `rule.cfg` arg.
Args:
rule_cfg_arg: {type}`str | dict | None` The `cfg` arg passed to Rule().
Returns:
{type}`RuleCfg`
"""
state = {}
if types.is_dict(rule_cfg_arg):
state.update(rule_cfg_arg)
else:
# Assume its a string, config.target, config.none, or other
# valid object.
state[_IMPLEMENTATION] = rule_cfg_arg
kwargs_set_default_list(state, _INPUTS)
kwargs_set_default_list(state, _OUTPUTS)
# buildifier: disable=uninitialized
self = struct(
add_inputs = lambda *a, **k: _RuleCfg_add_inputs(self, *a, **k),
add_outputs = lambda *a, **k: _RuleCfg_add_outputs(self, *a, **k),
_state = state,
build = lambda: _RuleCfg_build(self),
implementation = kwargs_getter(state, _IMPLEMENTATION),
inputs = kwargs_getter(state, _INPUTS),
outputs = kwargs_getter(state, _OUTPUTS),
set_implementation = kwargs_setter(state, _IMPLEMENTATION),
update_inputs = lambda *a, **k: _RuleCfg_update_inputs(self, *a, **k),
update_outputs = lambda *a, **k: _RuleCfg_update_outputs(self, *a, **k),
)
return self
def _RuleCfg_add_inputs(self, *inputs):
"""Adds an input to the list of inputs, if not present already.
:::{seealso}
The {obj}`update_inputs()` method for adding a collection of
values.
:::
Args:
self: implicitly arg.
*inputs: {type}`Label` the inputs to add. Note that a `Label`,
not `str`, should be passed to ensure different apparent labels
can be properly de-duplicated.
"""
self.update_inputs(inputs)
def _RuleCfg_add_outputs(self, *outputs):
"""Adds an output to the list of outputs, if not present already.
:::{seealso}
The {obj}`update_outputs()` method for adding a collection of
values.
:::
Args:
self: implicitly arg.
*outputs: {type}`Label` the outputs to add. Note that a `Label`,
not `str`, should be passed to ensure different apparent labels
can be properly de-duplicated.
"""
self.update_outputs(outputs)
def _RuleCfg_build(self):
"""Builds the rule cfg into the value rule.cfg arg value.
Returns:
{type}`transition` the transition object to apply to the rule.
"""
impl = self._state[_IMPLEMENTATION]
if impl == "target" or impl == None:
# config.target is Bazel 8+
if hasattr(config, "target"):
return config.target()
else:
return None
elif impl == "none":
return config.none()
elif types.is_function(impl):
return transition(
implementation = impl,
# Transitions only accept unique lists of strings.
inputs = {str(v): None for v in self._state[_INPUTS]}.keys(),
outputs = {str(v): None for v in self._state[_OUTPUTS]}.keys(),
)
else:
# Assume its valid. Probably an `config.XXX` object or manually
# set transition object.
return impl
def _RuleCfg_update_inputs(self, *others):
"""Add a collection of values to inputs.
Args:
self: implicitly added
*others: {type}`collection[Label]` collection of labels to add to
inputs. Only values not already present are added. Note that a
`Label`, not `str`, should be passed to ensure different apparent
labels can be properly de-duplicated.
"""
list_add_unique(self._state[_INPUTS], others)
def _RuleCfg_update_outputs(self, *others):
"""Add a collection of values to outputs.
Args:
self: implicitly added
*others: {type}`collection[Label]` collection of labels to add to
outputs. Only values not already present are added. Note that a
`Label`, not `str`, should be passed to ensure different apparent
labels can be properly de-duplicated.
"""
list_add_unique(self._state[_OUTPUTS], others)
# buildifier: disable=name-conventions
RuleCfg = struct(
TYPEDEF = _RuleCfg_typedef,
new = _RuleCfg_new,
# keep sorted
add_inputs = _RuleCfg_add_inputs,
add_outputs = _RuleCfg_add_outputs,
build = _RuleCfg_build,
update_inputs = _RuleCfg_update_inputs,
update_outputs = _RuleCfg_update_outputs,
)
def _Rule_typedef():
"""A builder to accumulate state for constructing a `rule` object.
:::{field} attrs
:type: AttrsDict
:::
:::{field} cfg
:type: RuleCfg
:::
:::{function} doc() -> str
:::
:::{function} exec_groups() -> dict[str, ExecGroup]
:::
:::{function} executable() -> bool
:::
:::{include} /_includes/field_kwargs_doc.md
:::
:::{function} fragments() -> list[str]
:::
:::{function} implementation() -> callable | None
:::
:::{function} provides() -> list[provider | list[provider]]
:::
:::{function} set_doc(v: str)
:::
:::{function} set_executable(v: bool)
:::
:::{function} set_implementation(v: callable)
:::
:::{function} set_test(v: bool)
:::
:::{function} test() -> bool
:::
:::{function} toolchains() -> list[ToolchainType]
:::
"""
def _Rule_new(**kwargs):
"""Builder for creating rules.
Args:
**kwargs: The same as the `rule()` function, but using builders or
dicts to specify sub-objects instead of the immutable Bazel
objects.
"""
kwargs.setdefault(_IMPLEMENTATION, None)
kwargs_set_default_doc(kwargs)
kwargs_set_default_dict(kwargs, _EXEC_GROUPS)
kwargs_set_default_ignore_none(kwargs, "executable", False)
kwargs_set_default_list(kwargs, "fragments")
kwargs_set_default_list(kwargs, "provides")
kwargs_set_default_ignore_none(kwargs, "test", False)
kwargs_set_default_list(kwargs, _TOOLCHAINS)
for name, value in kwargs[_EXEC_GROUPS].items():
kwargs[_EXEC_GROUPS][name] = _ExecGroup_maybe_from(value)
for i, value in enumerate(kwargs[_TOOLCHAINS]):
kwargs[_TOOLCHAINS][i] = _ToolchainType_maybe_from(value)
# buildifier: disable=uninitialized
self = struct(
attrs = _AttrsDict_new(kwargs.pop(_ATTRS, None)),
build = lambda *a, **k: _Rule_build(self, *a, **k),
cfg = _RuleCfg_new(kwargs.pop(_CFG, None)),
doc = kwargs_getter_doc(kwargs),
exec_groups = kwargs_getter(kwargs, _EXEC_GROUPS),
executable = kwargs_getter(kwargs, "executable"),
fragments = kwargs_getter(kwargs, "fragments"),
implementation = kwargs_getter(kwargs, _IMPLEMENTATION),
kwargs = kwargs,
provides = kwargs_getter(kwargs, "provides"),
set_doc = kwargs_setter_doc(kwargs),
set_executable = kwargs_setter(kwargs, "executable"),
set_implementation = kwargs_setter(kwargs, _IMPLEMENTATION),
set_test = kwargs_setter(kwargs, "test"),
test = kwargs_getter(kwargs, "test"),
to_kwargs = lambda: _Rule_to_kwargs(self),
toolchains = kwargs_getter(kwargs, _TOOLCHAINS),
)
return self
def _Rule_build(self, debug = ""):
"""Builds a `rule` object
Args:
self: implicitly added
debug: {type}`str` If set, prints the args used to create the rule.
Returns:
{type}`rule`
"""
kwargs = self.to_kwargs()
if debug:
lines = ["=" * 80, "rule kwargs: {}:".format(debug)]
for k, v in sorted(kwargs.items()):
if types.is_dict(v):
lines.append(" %s={" % k)
for k2, v2 in sorted(v.items()):
lines.append(" {}: {}".format(k2, v2))
lines.append(" }")
elif types.is_list(v):
lines.append(" {}=[".format(k))
for i, v2 in enumerate(v):
lines.append(" [{}] {}".format(i, v2))
lines.append(" ]")
else:
lines.append(" {}={}".format(k, v))
print("\n".join(lines)) # buildifier: disable=print
return rule(**kwargs)
def _Rule_to_kwargs(self):
"""Builds the arguments for calling `rule()`.
This is added as an escape hatch to construct the final values `rule()`
kwarg values in case callers want to manually change them.
Args:
self: implicitly added.
Returns:
{type}`dict`
"""
kwargs = dict(self.kwargs)
if _EXEC_GROUPS in kwargs:
kwargs[_EXEC_GROUPS] = {
k: v.build() if _is_builder(v) else v
for k, v in kwargs[_EXEC_GROUPS].items()
}
if _TOOLCHAINS in kwargs:
kwargs[_TOOLCHAINS] = [
v.build() if _is_builder(v) else v
for v in kwargs[_TOOLCHAINS]
]
if _ATTRS not in kwargs:
kwargs[_ATTRS] = self.attrs.build()
if _CFG not in kwargs:
kwargs[_CFG] = self.cfg.build()
return kwargs
# buildifier: disable=name-conventions
Rule = struct(
TYPEDEF = _Rule_typedef,
new = _Rule_new,
build = _Rule_build,
to_kwargs = _Rule_to_kwargs,
)
def _AttrsDict_typedef():
"""Builder for the dictionary of rule attributes.
:::{field} map
:type: dict[str, AttributeBuilder]
The underlying dict of attributes. Directly accessible so that regular
dict operations (e.g. `x in y`) can be performed, if necessary.
:::
:::{function} get(key, default=None)
Get an entry from the dict. Convenience wrapper for `.map.get(...)`
:::
:::{function} items() -> list[tuple[str, object]]
Returns a list of key-value tuples. Convenience wrapper for `.map.items()`
:::
:::{function} pop(key, default) -> object
Removes a key from the attr dict
:::
"""
def _AttrsDict_new(initial):
"""Creates a builder for the `rule.attrs` dict.
Args:
initial: {type}`dict[str, callable | AttributeBuilder] | None` dict of
initial values to populate the attributes dict with.
Returns:
{type}`AttrsDict`
"""
# buildifier: disable=uninitialized
self = struct(
# keep sorted
build = lambda: _AttrsDict_build(self),
get = lambda *a, **k: self.map.get(*a, **k),
items = lambda: self.map.items(),
map = {},
put = lambda key, value: _AttrsDict_put(self, key, value),
update = lambda *a, **k: _AttrsDict_update(self, *a, **k),
pop = lambda *a, **k: self.map.pop(*a, **k),
)
if initial:
_AttrsDict_update(self, initial)
return self
def _AttrsDict_put(self, name, value):
"""Sets a value in the attrs dict.
Args:
self: implicitly added
name: {type}`str` the attribute name to set in the dict
value: {type}`AttributeBuilder | callable` the value for the
attribute. If a callable, then it is treated as an
attribute builder factory (no-arg callable that returns an
attribute builder) and is called immediately.
"""
if types.is_function(value):
# Convert factory function to builder
value = value()
self.map[name] = value
def _AttrsDict_update(self, other):
"""Merge `other` into this object.
Args:
self: implicitly added
other: {type}`dict[str, callable | AttributeBuilder]` the values to
merge into this object. If the value a function, it is called
with no args and expected to return an attribute builder. This
allows defining dicts of common attributes (where the values are
functions that create a builder) and merge them into the rule.
"""
for k, v in other.items():
# Handle factory functions that create builders
if types.is_function(v):
self.map[k] = v()
else:
self.map[k] = v
def _AttrsDict_build(self):
"""Build an attribute dict for passing to `rule()`.
Returns:
{type}`dict[str, attribute]` where the values are `attr.XXX` objects
"""
attrs = {}
for k, v in self.map.items():
attrs[k] = v.build() if _is_builder(v) else v
return attrs
# buildifier: disable=name-conventions
AttrsDict = struct(
TYPEDEF = _AttrsDict_typedef,
new = _AttrsDict_new,
update = _AttrsDict_update,
build = _AttrsDict_build,
)
ruleb = struct(
Rule = _Rule_new,
ToolchainType = _ToolchainType_new,
ExecGroup = _ExecGroup_new,
)