'How to query sibling rules from a Bazel rule

I would like to be able to do the following in a Bazel BUILD file:

alpha(
  name = "hello world",
  color = "blue"
)

beta(
  name = "hello again"
)

Where alpha and beta are custom rules. I want beta to be able to access the color attribute of the alpha rule, without adding a label attribute. In Bazel query, I can do something like this:

bazel query 'kind(beta, siblings(kind(alpha, //...)))'

which gives me the beta which is side by side to alpha. Can I achieve the same somehow from within the implementation function of the beta rule?

def _beta_rule_impl(ctx):
  # This does not exist, I wish it did: ctx.siblings(kind='alpha')

I've seen this been done with a label like this

beta(
  name = "hello again",
  alpha_link = ":hello world" # explicitly linking
)

but I find this a bit verbose, especially since there is a sibling query support.



Solution 1:[1]

The way the question is formulated, the answer is no. It is not possible.

Bazel design philosophy is to be explicit about target dependencies. Providers mechanism is meant to provide the access to the dependency graph information during the analysis phase.

It is difficult to tell what is the actual use case is. Using Aspects might be the answer.

Solution 2:[2]

In my scenario, I'm trying to get a genrule to call a test rule before proceeding:

genrule(
    name = "generate_buf_image",
    srcs = [":protos", "cookie"],
    outs = ["buf-image.json"],
    cmd = "$(location //third_party/buf:cas_buf_image) //example-grpc/proto/v1:proto_backwards_compatibility_check $(SRCS) >$(OUTS)",
    tools = [
        "//third_party/buf:cas_buf_image",
        "@buf",
    ],
)

If cas_buf_image.sh has ls -l "example-grpc/proto/v1" >&2, it shows:

… cookie -> …/example-grpc/proto/v1/cookie
… example.proto -> …/example-grpc/proto/v1/example.proto

IOW, examining what example-grpc/proto/v1/cookie is linked to and cding to its directory then performing the git commands should work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Konstantin Zadorozhny
Solution 2 Noel Yap