get value of specific attribute of given bazel target

Viewed 1696

I am sure this is documented somewhere but unable to find the answer anywhere.

if I have:

```bazel_rule(
    name = "foo",
    srcs = ["foo.cpp"],
    attr_bar = "bar"
)```

if I have a reference to this rule (//src:foo) in a Starlark (.bzl) file, how can I query the target to get a value of a specific attribute. e.g. get_attribute("//src:foo", "attr_bar") should return "bar" in this example.

1 Answers

It depends on whether you're trying to read the attribute from a macro, a rule, or an aspect.

Short answers:

A macro can't read attributes of a target (roughly, macros are evaluated at build file loading time, and attributes are evaluated later at analysis time). You can do things like taking in the attributes you care about and creating the rule (bazel_rule in your example) within the macro, so that the macro has the attribute value, but this usually quickly becomes messy and hard to follow.

A Starlark rule also can't directly read attribute values from dependencies (it can read its own attributes though, of course). The rule you're interested in (bazel_rule here) has to put the information in a provider and the Starlark rule reads the provider from its dependencies.

An aspect can read the attributes of the rule its being evaluated on directly through ctx.rule.attr.<attr_name>(the example here does this).

Related