I'm trying to set a conditional (in Bazel 4.2.2) over the current operating system:
is_darwin = select({
"@bazel_tools//src/conditions:darwin": True,
"//conditions:default": False,
})
if is_darwin:
# a
else:
# b
However I fall into a, even if I'm on Linux.
I've tried to print it, but it seems to not be evaluated:
DEBUG: WORKSPACE:65:6: select({"@bazel_tools//src/conditions:darwin": True, "//conditions:default": False})
How should I check it correctly?
Select is only evaluated in rule implementation functions, not macros like you're using. You'll need to use attr.bool to create an attribute, pass the select to it, and then perform your logic based on that.
You can also use ctx.target_platform_has_constraint to do this directly, without select:
def _impl(ctx):
darwin_constraint = ctx.attr._darwin_constraint[platform_common.ConstraintValueInfo]
if ctx.target_platform_has_constraint(darwin_constraint):
print('on darwin')
else:
print('not darwin')
my_rule = rule(
implementation = _impl,
attrs = {
...
'_darwin_constraint': attr.label(default = '@bazel_platforms//os:darwin'),
},
)
Another way to look at the difference is that loading BUILD files and running macros happens in the loading phase, but evaluating selects happens between the loading and analysis phases. The relevant steps are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With