Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bazel's select isn't interpreted

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?

like image 856
GlinesMome Avatar asked Dec 12 '25 22:12

GlinesMome


1 Answers

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:

  1. The loading phase produces a graph of targets and transitions between them. These targets tie a rule to a set of attribute values, which includes unevaluated selects.
  2. This graph is combined with command-line flags to produce one or more configurations for each target.
  3. Each target is evaluated with each configuration that applies to it, with selects resolved as appropriate for that configuration. Effectively, the implementation functions are run with the attribute values from the target, after evaluating selects. This produces configured targets.
like image 144
Brian Silverman Avatar answered Dec 14 '25 23:12

Brian Silverman