xref: /aosp_15_r20/build/bazel/rules/filegroup.bzl (revision 7594170e27e0732bc44b93d1440d87a54b6ffe7c)
1# Copyright (C) 2021 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("//build/bazel/rules/cc:cc_constants.bzl", "constants")
16
17def extension(f):
18    return f.split(".")[-1]
19
20def group_files_by_ext(files):
21    cpp = []
22    c = []
23    asm = []
24
25    # This for-loop iterator works because filegroups in Android don't use
26    # configurable selects.
27    for f in files:
28        if extension(f) in constants.c_src_exts:
29            c.append(f)
30        elif extension(f) in constants.cpp_src_exts:
31            cpp.append(f)
32        elif extension(f) in constants.as_src_exts:
33            asm.append(f)
34        else:
35            # not C based
36            continue
37    return cpp, c, asm
38
39# Filegroup is a macro because it needs to expand to language specific source
40# files for cc_library's srcs_as, srcs_c and srcs attributes.
41def filegroup(name, srcs = [], **kwargs):
42    native.filegroup(
43        name = name,
44        srcs = srcs,
45        **kwargs
46    )
47
48    # These genrule prevent empty filegroups being used as deps to cc libraries,
49    # avoiding the error:
50    #
51    # in srcs attribute of cc_library rule //foo/bar:baz:
52    # '//foo/bar/some_other:baz2' does not produce any cc_library srcs files.
53    native.genrule(
54        name = name + "_null_cc",
55        outs = [name + "_null.cc"],
56        tags = ["manual"],
57        cmd = "touch $@",
58    )
59    native.genrule(
60        name = name + "_null_c",
61        outs = [name + "_null.c"],
62        tags = ["manual"],
63        cmd = "touch $@",
64    )
65    native.genrule(
66        name = name + "_null_s",
67        outs = [name + "_null.S"],
68        tags = ["manual"],
69        cmd = "touch $@",
70    )
71
72    cpp_srcs, c_srcs, as_srcs = group_files_by_ext(srcs)
73    native.filegroup(
74        name = name + "_cpp_srcs",
75        srcs = [name + "_null.cc"] + cpp_srcs,
76        tags = ["manual"],
77    )
78    native.filegroup(
79        name = name + "_c_srcs",
80        srcs = [name + "_null.c"] + c_srcs,
81        tags = ["manual"],
82    )
83    native.filegroup(
84        name = name + "_as_srcs",
85        srcs = [name + "_null.S"] + as_srcs,
86        tags = ["manual"],
87    )
88