From 9333569bc87179c0bedbbf8d04c34bf25b65f1aa Mon Sep 17 00:00:00 2001 From: Googler Date: Fri, 6 Sep 2024 07:59:21 -0700 Subject: [PATCH] Add support for the `mandatory` param to `find_cc_toolchain` in `@rules_cc` PiperOrigin-RevId: 671758214 Change-Id: I37d0ca1f9b083513cb5933984153e1ba608313ca --- cc/find_cc_toolchain.bzl | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/cc/find_cc_toolchain.bzl b/cc/find_cc_toolchain.bzl index d2f2d9f..4129680 100644 --- a/cc/find_cc_toolchain.bzl +++ b/cc/find_cc_toolchain.bzl @@ -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 -def find_cc_toolchain(ctx): +def find_cc_toolchain(ctx, *, mandatory = True): """ Returns the current `CcToolchainInfo`. Args: 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: - 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. @@ -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.") toolchain_info = ctx.toolchains[CC_TOOLCHAIN_TYPE] if toolchain_info == None: + if not mandatory: + return None + # 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" % (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] # 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.") def find_cpp_toolchain(ctx):