xref: /aosp_15_r20/external/pigweed/pw_toolchain/xcode.bzl (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1# Copyright 2024 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""A basic extension for exposing a macOS host's local Xcode libraries."""
15
16def _get_xcode_sdk_root(extension_ctx):
17    xcrun_result = extension_ctx.execute(["/usr/bin/xcrun", "--show-sdk-path"])
18    if xcrun_result.return_code != 0:
19        fail("Failed locating Xcode SDK: {}".format(xcrun_result.stderr))
20    return xcrun_result.stdout.replace("\n", "")
21
22# If you squint hard enough, this looks like a new_local_repository, but
23# we very intentionally avoid using new_local_repository here since the xcode
24# SDK path gets baked into the MODULE.bazel.lock which breaks CI/CQ bots.
25#
26# See https://issues.pigweed.dev/issues/346388161#comment24 for more details.
27def _xcode_repository_impl(repository_ctx):
28    if repository_ctx.os.name != "mac os x":
29        fail(
30            "Cannot expose a local Xcode SDK on {} hosts. This repository " +
31            "rule only works on macOS hosts. It's possible a rule from one " +
32            "of your build files is referencing this repository and is not " +
33            "properly gated behind a `target_compatible_with` expression or " +
34            "`select()` statement." % (repository_ctx.os,),
35        )
36    p = repository_ctx.path(_get_xcode_sdk_root(repository_ctx))
37    children = p.readdir()
38    for child in children:
39        repository_ctx.symlink(child, child.basename)
40    repository_ctx.symlink(repository_ctx.attr.build_file, "BUILD")
41
42xcode_sdk_repository = repository_rule(
43    implementation = _xcode_repository_impl,
44    attrs = {
45        "build_file": attr.label(
46            allow_single_file = True,
47        ),
48    },
49    local = True,
50    configure = True,
51)
52