Add support for the `mandatory` param to `find_cc_toolchain` in `@rules_cc`

PiperOrigin-RevId: 671758214
Change-Id: I37d0ca1f9b083513cb5933984153e1ba608313ca
This commit is contained in:
Googler 2024-09-06 07:59:21 -07:00 committed by Copybara-Service
parent 8b63556334
commit 9333569bc8
1 changed files with 10 additions and 2 deletions

View File

@ -55,15 +55,18 @@ Bazel version is not needed), it's enough to only keep the toolchain type.
CC_TOOLCHAIN_TYPE = "@bazel_tools//tools/cpp:toolchain_type" # copybara-use-repo-external-label CC_TOOLCHAIN_TYPE = "@bazel_tools//tools/cpp:toolchain_type" # copybara-use-repo-external-label
def find_cc_toolchain(ctx): def find_cc_toolchain(ctx, *, mandatory = True):
""" """
Returns the current `CcToolchainInfo`. Returns the current `CcToolchainInfo`.
Args: Args:
ctx: The rule context for which to find a toolchain. ctx: The rule context for which to find a toolchain.
mandatory: (bool) If this is set to False, this function will return None
rather than fail if no toolchain is found.
Returns: Returns:
A CcToolchainInfo. A CcToolchainInfo or None if the c++ toolchain is declared as
optional, mandatory is False and no toolchain has been found.
""" """
# Check the incompatible flag for toolchain resolution. # Check the incompatible flag for toolchain resolution.
@ -72,6 +75,9 @@ Returns the current `CcToolchainInfo`.
fail("In order to use find_cc_toolchain, your rule has to depend on C++ toolchain. See find_cc_toolchain.bzl docs for details.") fail("In order to use find_cc_toolchain, your rule has to depend on C++ toolchain. See find_cc_toolchain.bzl docs for details.")
toolchain_info = ctx.toolchains[CC_TOOLCHAIN_TYPE] toolchain_info = ctx.toolchains[CC_TOOLCHAIN_TYPE]
if toolchain_info == None: if toolchain_info == None:
if not mandatory:
return None
# No cpp toolchain was found, so report an error. # No cpp toolchain was found, so report an error.
fail("Unable to find a CC toolchain using toolchain resolution. Target: %s, Platform: %s, Exec platform: %s" % fail("Unable to find a CC toolchain using toolchain resolution. Target: %s, Platform: %s, Exec platform: %s" %
(ctx.label, ctx.fragments.platform.platform, ctx.fragments.platform.host_platform)) (ctx.label, ctx.fragments.platform.platform, ctx.fragments.platform.host_platform))
@ -84,6 +90,8 @@ Returns the current `CcToolchainInfo`.
return ctx.attr._cc_toolchain[cc_common.CcToolchainInfo] return ctx.attr._cc_toolchain[cc_common.CcToolchainInfo]
# We didn't find anything. # We didn't find anything.
if not mandatory:
return None
fail("In order to use find_cc_toolchain, your rule has to depend on C++ toolchain. See find_cc_toolchain.bzl docs for details.") fail("In order to use find_cc_toolchain, your rule has to depend on C++ toolchain. See find_cc_toolchain.bzl docs for details.")
def find_cpp_toolchain(ctx): def find_cpp_toolchain(ctx):