如何将宏应用于 bazel 中的目标名称数组?

How to apply a macro to an array of names of targets in bazel?

我有一个 bazel 包,它必须使用我为这种情况编写的相同宏生成大量可执行文件(示例)。是否可以将它应用于目标名称数组而不是像这样一个一个地列出它们?

simple_program(
    name = "example1",
)

simple_program(
    name = "example2",
)

simple_program(
    name = "example3",
)

只写出您需要的所有规则的一个好处是您的构建文件更具声明性。构建文件(宏等)中的逻辑越多,就越难弄清楚发生了什么。使用声明式构建文件,您可以使用 Buildozer 等工具进行大规模重构。

也就是说,有多种方法可以满足您的要求。一种是在构建文件中使用列表理解:

[simple_rule(name = n) for n in [
    "example1",
    "example2",
    "example3",
]]

另一种是使用宏,例如:

defs.bzl:

def generate_simple_rules(names):
  for name in names:
    simple_rule(name = name)

BUILD:

load("//:defs.bzl", "generate_simple_rules")
generate_simple_rules(["example1", "example2", "example3"])