xref: /aosp_15_r20/build/bazel/rules/common.bzl (revision 7594170e27e0732bc44b93d1440d87a54b6ffe7c)
1# Copyright (C) 2022 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://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,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
16
17def get_dep_targets(attrs, *, predicate = lambda _: True):
18    """get_dep_targets returns all targets listed in the current rule's attributes
19
20    Args:
21        attrs (dict[str, attr]): dictionary containing the rule's attributes.
22            This may come from `ctx.attr` if called from a rule, or
23            `ctx.rule.attr` if called from an aspect.
24        predicate (function(Target) -> bool): a function used to filter out
25            unwanted targets; if predicate(target) == False, then do not include
26            target
27    Returns:
28        targets (dict[str, list[Target]]): map of attr to list of Targets for which
29            predicate returns True
30    """
31    targets = {}
32    for a in dir(attrs):
33        if a.startswith("_"):
34            # Ignore private attributes
35            continue
36        targets[a] = []
37        value = getattr(attrs, a)
38        vlist = value if type(value) == type([]) else [value]
39        for item in vlist:
40            if type(item) == "Target" and predicate(item):
41                targets[a].append(item)
42    return targets
43
44_BP2BUILD_LABEL_SUFFIXES = [
45    # cc rules
46    "_bp2build_cc_library_static",
47    "_cc_proto_lite",
48    "_aidl_code_gen",
49    "_cc_aidl_library",
50]
51
52def strip_bp2build_label_suffix(name):
53    for suffix in _BP2BUILD_LABEL_SUFFIXES:
54        name = name.removesuffix(suffix)
55    return name
56
57def _repeatable_string_flag_impl(ctx):
58    return [BuildSettingInfo(value = [v for v in ctx.build_setting_value])]
59
60repeatable_string_flag = rule(
61    implementation = _repeatable_string_flag_impl,
62    build_setting = config.string(flag = True, allow_multiple = True),
63)
64