首页 > 解决方案 > 如何将规则限制为 cpp 工具链的子集?

问题描述

我有这样的规则

do_action = rule (
    implementation = _impl,
    attrs = {
        ...
        "_cc_toolchain": attr.label(default = Label("@bazel_tools//tools/cpp:current_cc_toolchain")),
    },
    fragments = ["cpp"],
    toolchains = [
        "@bazel_tools//tools/cpp:toolchain_type",
        ],
)

我为自定义 cpu 定义了自定义 cc_toolchain:

toolchain(
    name = "cc-toolchain-%{toolchain_name}",
    toolchain = ":cc-compiler-%{toolchain_name}",
    # can be run on this platform
    target_compatible_with = [
        "@platforms//os:windows",
        "@platforms//cpu:x86_64",
    ],
    toolchain_type = "@bazel_tools//tools/cpp:toolchain_type",
)

cc_toolchain_suite(
    name = "toolchain",
    toolchains = {
        "%{cpu}": ":cc-compiler-%{toolchain_name}",
    },
)

--crostool_top会在需要时选择此工具链。

我只想在 --crostool_top 与我的自定义工具链之一匹配时才允许调用我的自定义规则。这个怎么做?

标签: bazelbazel-rules

解决方案


添加一个新constraint_settingconstraint_value,只有你的工具链是target_compatible_with,然后让所有使用你的规则的目标target_compatible_with

在 BUILD 文件中是这样的:

constraint_setting(name = "is_my_toolchain")

constraint_value(
  name = "yes_my_toolchain",
  constraint_setting = ":is_my_toolchain",
)

然后添加yes_my_toolchaintarget_compatible_with您的所有工具链上。

在每次使用规则时强制使用它的最简单方法是使用。将实际规则重命名为_do_action(因此它是私有的,不能直接从任何BUILD文件加载)并添加:

def do_action(target_compatible_with = [], **kwargs):
  _do_action(
    target_compatible_with = target_compatible_with + [
      "//your_package:yes_my_toolchain",
    ],
    **kwargs
  )

推荐阅读