blob: 3b866550d523137c4b8824955b1716ee78f94c14 [file] [log] [blame]
Colin Cross068e0fe2016-12-13 15:23:47 -08001// Copyright 2016 Google Inc. All rights reserved.
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
Pirama Arumuga Nainar955dc492018-04-17 14:58:42 -070015package android
Colin Cross068e0fe2016-12-13 15:23:47 -080016
17import (
Vinh Tran16fe8e12022-08-16 16:45:44 -040018 "path/filepath"
Sam Delmerico97bd1272022-08-25 14:45:31 -040019 "regexp"
Colin Crossd91d7ac2017-09-12 22:52:12 -070020 "strings"
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0d990452021-08-11 16:46:13 +000021
22 "android/soong/bazel"
Chris Parsonsf874e462022-05-10 13:50:12 -040023 "android/soong/bazel/cquery"
Chris Parsons39a16972023-06-08 14:28:51 +000024 "android/soong/ui/metrics/bp2build_metrics_proto"
Sam Delmericoc7681022022-02-04 21:01:20 +000025
26 "github.com/google/blueprint"
Colin Cross068e0fe2016-12-13 15:23:47 -080027)
28
29func init() {
Anton Hansson7d6dd8b2023-03-06 11:26:17 +000030 RegisterFilegroupBuildComponents(InitRegistrationContext)
Jingwen Chen32b4ece2021-01-21 03:20:18 -050031}
32
Paul Duffin35816122021-02-24 01:49:52 +000033var PrepareForTestWithFilegroup = FixtureRegisterWithContext(func(ctx RegistrationContext) {
Anton Hansson7d6dd8b2023-03-06 11:26:17 +000034 RegisterFilegroupBuildComponents(ctx)
Paul Duffin35816122021-02-24 01:49:52 +000035})
36
Anton Hansson7d6dd8b2023-03-06 11:26:17 +000037func RegisterFilegroupBuildComponents(ctx RegistrationContext) {
38 ctx.RegisterModuleType("filegroup", FileGroupFactory)
39 ctx.RegisterModuleType("filegroup_defaults", FileGroupDefaultsFactory)
40}
41
Yu Liu2aa806b2022-09-01 11:54:47 -070042var convertedProtoLibrarySuffix = "_bp2build_converted"
43
Sam Delmericoc7681022022-02-04 21:01:20 +000044// IsFilegroup checks that a module is a filegroup type
45func IsFilegroup(ctx bazel.OtherModuleContext, m blueprint.Module) bool {
46 return ctx.OtherModuleType(m) == "filegroup"
47}
48
Sam Delmerico97bd1272022-08-25 14:45:31 -040049var (
50 // ignoring case, checks for proto or protos as an independent word in the name, whether at the
51 // beginning, end, or middle. e.g. "proto.foo", "bar-protos", "baz_proto_srcs" would all match
52 filegroupLikelyProtoPattern = regexp.MustCompile("(?i)(^|[^a-z])proto(s)?([^a-z]|$)")
53 filegroupLikelyAidlPattern = regexp.MustCompile("(?i)(^|[^a-z])aidl([^a-z]|$)")
54
55 ProtoSrcLabelPartition = bazel.LabelPartition{
56 Extensions: []string{".proto"},
57 LabelMapper: isFilegroupWithPattern(filegroupLikelyProtoPattern),
58 }
59 AidlSrcLabelPartition = bazel.LabelPartition{
60 Extensions: []string{".aidl"},
61 LabelMapper: isFilegroupWithPattern(filegroupLikelyAidlPattern),
62 }
63)
64
65func isFilegroupWithPattern(pattern *regexp.Regexp) bazel.LabelMapper {
66 return func(ctx bazel.OtherModuleContext, label bazel.Label) (string, bool) {
67 m, exists := ctx.ModuleFromName(label.OriginalModuleName)
68 labelStr := label.Label
69 if !exists || !IsFilegroup(ctx, m) {
70 return labelStr, false
71 }
72 likelyMatched := pattern.MatchString(label.OriginalModuleName)
73 return labelStr, likelyMatched
74 }
75}
76
Jingwen Chen32b4ece2021-01-21 03:20:18 -050077// https://docs.bazel.build/versions/master/be/general.html#filegroup
78type bazelFilegroupAttributes struct {
Wei Li2c9e8d62023-05-05 01:07:15 -070079 Srcs bazel.LabelListAttribute
80 Applicable_licenses bazel.LabelListAttribute
Jingwen Chen32b4ece2021-01-21 03:20:18 -050081}
82
Vinh Tran444154d2022-08-16 13:10:31 -040083type bazelAidlLibraryAttributes struct {
84 Srcs bazel.LabelListAttribute
85 Strip_import_prefix *string
86}
87
Spandan Dasbd52ea92023-03-09 23:03:07 +000088// api srcs can be contained in filegroups.
89// this should be generated in api_bp2build workspace as well.
90func (fg *fileGroup) ConvertWithApiBp2build(ctx TopDownMutatorContext) {
91 fg.ConvertWithBp2build(ctx)
92}
93
Liz Kammerbe46fcc2021-11-01 15:32:43 -040094// ConvertWithBp2build performs bp2build conversion of filegroup
95func (fg *fileGroup) ConvertWithBp2build(ctx TopDownMutatorContext) {
Jingwen Chen07027912021-03-15 06:02:43 -040096 srcs := bazel.MakeLabelListAttribute(
97 BazelLabelForModuleSrcExcludes(ctx, fg.properties.Srcs, fg.properties.Exclude_srcs))
Jingwen Chen5146ac02021-09-02 11:44:42 +000098
99 // For Bazel compatibility, don't generate the filegroup if there is only 1
100 // source file, and that the source file is named the same as the module
101 // itself. In Bazel, eponymous filegroups like this would be an error.
102 //
103 // Instead, dependents on this single-file filegroup can just depend
104 // on the file target, instead of rule target, directly.
105 //
106 // You may ask: what if a filegroup has multiple files, and one of them
107 // shares the name? The answer: we haven't seen that in the wild, and
108 // should lock Soong itself down to prevent the behavior. For now,
109 // we raise an error if bp2build sees this problem.
110 for _, f := range srcs.Value.Includes {
111 if f.Label == fg.Name() {
112 if len(srcs.Value.Includes) > 1 {
113 ctx.ModuleErrorf("filegroup '%s' cannot contain a file with the same name", fg.Name())
114 }
Chris Parsons39a16972023-06-08 14:28:51 +0000115 ctx.MarkBp2buildUnconvertible(bp2build_metrics_proto.UnconvertedReasonType_SRC_NAME_COLLISION, "")
Jingwen Chen5146ac02021-09-02 11:44:42 +0000116 return
117 }
118 }
119
Vinh Tran444154d2022-08-16 13:10:31 -0400120 // Convert module that has only AIDL files to aidl_library
121 // If the module has a mixed bag of AIDL and non-AIDL files, split the filegroup manually
122 // and then convert
123 if fg.ShouldConvertToAidlLibrary(ctx) {
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400124 tags := []string{"apex_available=//apex_available:anyapex"}
Vinh Tran444154d2022-08-16 13:10:31 -0400125 attrs := &bazelAidlLibraryAttributes{
126 Srcs: srcs,
127 Strip_import_prefix: fg.properties.Path,
128 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500129
Vinh Tran444154d2022-08-16 13:10:31 -0400130 props := bazel.BazelTargetModuleProperties{
131 Rule_class: "aidl_library",
Sam Delmericoe55bf082023-03-31 09:47:28 -0400132 Bzl_load_location: "//build/bazel/rules/aidl:aidl_library.bzl",
Vinh Tran444154d2022-08-16 13:10:31 -0400133 }
Jingwen Chen1fd14692021-02-05 03:01:50 -0500134
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400135 ctx.CreateBazelTargetModule(
136 props,
137 CommonAttributes{
138 Name: fg.Name(),
139 Tags: bazel.MakeStringListAttribute(tags),
140 },
141 attrs)
Vinh Tran444154d2022-08-16 13:10:31 -0400142 } else {
Yu Liu2aa806b2022-09-01 11:54:47 -0700143 if fg.ShouldConvertToProtoLibrary(ctx) {
144 attrs := &ProtoAttrs{
145 Srcs: srcs,
146 Strip_import_prefix: fg.properties.Path,
147 }
148
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400149 tags := []string{
150 "apex_available=//apex_available:anyapex",
151 // TODO(b/246997908): we can remove this tag if we could figure out a solution for this bug.
152 "manual",
153 }
Yu Liu2aa806b2022-09-01 11:54:47 -0700154 ctx.CreateBazelTargetModule(
155 bazel.BazelTargetModuleProperties{Rule_class: "proto_library"},
Sam Delmericoe9b33f72022-11-21 15:38:54 -0500156 CommonAttributes{
157 Name: fg.Name() + convertedProtoLibrarySuffix,
158 Tags: bazel.MakeStringListAttribute(tags),
159 },
Yu Liu2aa806b2022-09-01 11:54:47 -0700160 attrs)
161 }
162
163 // TODO(b/242847534): Still convert to a filegroup because other unconverted
164 // modules may depend on the filegroup
Vinh Tran444154d2022-08-16 13:10:31 -0400165 attrs := &bazelFilegroupAttributes{
166 Srcs: srcs,
167 }
168
169 props := bazel.BazelTargetModuleProperties{
170 Rule_class: "filegroup",
171 Bzl_load_location: "//build/bazel/rules:filegroup.bzl",
172 }
173
174 ctx.CreateBazelTargetModule(props, CommonAttributes{Name: fg.Name()}, attrs)
175 }
Colin Cross068e0fe2016-12-13 15:23:47 -0800176}
177
Alixb29a3cd2023-05-09 20:37:49 +0000178type FileGroupPath interface {
179 GetPath(ctx TopDownMutatorContext) string
180}
181
182func (fg *fileGroup) GetPath(ctx TopDownMutatorContext) string {
183 if fg.properties.Path != nil {
184 return *fg.properties.Path
185 }
186 return ""
187}
188
Colin Cross068e0fe2016-12-13 15:23:47 -0800189type fileGroupProperties struct {
190 // srcs lists files that will be included in this filegroup
Colin Cross27b922f2019-03-04 22:35:41 -0800191 Srcs []string `android:"path"`
Colin Cross068e0fe2016-12-13 15:23:47 -0800192
Colin Cross27b922f2019-03-04 22:35:41 -0800193 Exclude_srcs []string `android:"path"`
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800194
195 // The base path to the files. May be used by other modules to determine which portion
196 // of the path to use. For example, when a filegroup is used as data in a cc_test rule,
197 // the base path is stripped off the path and the remaining path is used as the
198 // installation directory.
Nan Zhangea568a42017-11-08 21:20:04 -0800199 Path *string
Colin Crossd91d7ac2017-09-12 22:52:12 -0700200
201 // Create a make variable with the specified name that contains the list of files in the
202 // filegroup, relative to the root of the source tree.
Nan Zhangea568a42017-11-08 21:20:04 -0800203 Export_to_make_var *string
Colin Cross068e0fe2016-12-13 15:23:47 -0800204}
205
206type fileGroup struct {
Pirama Arumuga Nainar955dc492018-04-17 14:58:42 -0700207 ModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500208 BazelModuleBase
Anton Hansson7d6dd8b2023-03-06 11:26:17 +0000209 DefaultableModuleBase
Yu Liu2aa806b2022-09-01 11:54:47 -0700210 FileGroupAsLibrary
Alixb29a3cd2023-05-09 20:37:49 +0000211 FileGroupPath
Colin Cross068e0fe2016-12-13 15:23:47 -0800212 properties fileGroupProperties
Pirama Arumuga Nainar955dc492018-04-17 14:58:42 -0700213 srcs Paths
Colin Cross068e0fe2016-12-13 15:23:47 -0800214}
215
Chris Parsonsf874e462022-05-10 13:50:12 -0400216var _ MixedBuildBuildable = (*fileGroup)(nil)
Pirama Arumuga Nainar955dc492018-04-17 14:58:42 -0700217var _ SourceFileProducer = (*fileGroup)(nil)
Yu Liu2aa806b2022-09-01 11:54:47 -0700218var _ FileGroupAsLibrary = (*fileGroup)(nil)
Alixb29a3cd2023-05-09 20:37:49 +0000219var _ FileGroupPath = (*fileGroup)(nil)
Colin Cross068e0fe2016-12-13 15:23:47 -0800220
Patrice Arruda8958a942019-03-12 10:06:00 -0700221// filegroup contains a list of files that are referenced by other modules
222// properties (such as "srcs") using the syntax ":<name>". filegroup are
223// also be used to export files across package boundaries.
Pirama Arumuga Nainar955dc492018-04-17 14:58:42 -0700224func FileGroupFactory() Module {
Colin Cross068e0fe2016-12-13 15:23:47 -0800225 module := &fileGroup{}
Colin Cross36242852017-06-23 15:06:31 -0700226 module.AddProperties(&module.properties)
Pirama Arumuga Nainar955dc492018-04-17 14:58:42 -0700227 InitAndroidModule(module)
Liz Kammerea6666f2021-02-17 10:17:28 -0500228 InitBazelModule(module)
Anton Hansson7d6dd8b2023-03-06 11:26:17 +0000229 InitDefaultableModule(module)
Colin Cross36242852017-06-23 15:06:31 -0700230 return module
Colin Cross068e0fe2016-12-13 15:23:47 -0800231}
232
Liz Kammer5edc1412022-05-25 11:12:44 -0400233var _ blueprint.JSONActionSupplier = (*fileGroup)(nil)
234
235func (fg *fileGroup) JSONActions() []blueprint.JSONAction {
236 ins := make([]string, 0, len(fg.srcs))
237 outs := make([]string, 0, len(fg.srcs))
238 for _, p := range fg.srcs {
239 ins = append(ins, p.String())
240 outs = append(outs, p.Rel())
241 }
242 return []blueprint.JSONAction{
243 blueprint.JSONAction{
244 Inputs: ins,
245 Outputs: outs,
246 },
247 }
248}
249
Liz Kammer5bde22f2021-04-19 14:04:14 -0400250func (fg *fileGroup) GenerateAndroidBuildActions(ctx ModuleContext) {
Liz Kammer5bde22f2021-04-19 14:04:14 -0400251 fg.srcs = PathsForModuleSrcExcludes(ctx, fg.properties.Srcs, fg.properties.Exclude_srcs)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800252 if fg.properties.Path != nil {
253 fg.srcs = PathsWithModuleSrcSubDir(ctx, fg.srcs, String(fg.properties.Path))
254 }
Colin Cross068e0fe2016-12-13 15:23:47 -0800255}
256
Pirama Arumuga Nainar955dc492018-04-17 14:58:42 -0700257func (fg *fileGroup) Srcs() Paths {
258 return append(Paths{}, fg.srcs...)
Colin Cross068e0fe2016-12-13 15:23:47 -0800259}
Colin Crossd91d7ac2017-09-12 22:52:12 -0700260
Dan Willemsen6a6478d2020-07-17 19:28:53 -0700261func (fg *fileGroup) MakeVars(ctx MakeVarsModuleContext) {
262 if makeVar := String(fg.properties.Export_to_make_var); makeVar != "" {
263 ctx.StrictRaw(makeVar, strings.Join(fg.srcs.Strings(), " "))
Colin Crossd91d7ac2017-09-12 22:52:12 -0700264 }
265}
Chris Parsonsf874e462022-05-10 13:50:12 -0400266
267func (fg *fileGroup) QueueBazelCall(ctx BaseModuleContext) {
268 bazelCtx := ctx.Config().BazelContext
269
270 bazelCtx.QueueBazelRequest(
271 fg.GetBazelLabel(ctx, fg),
272 cquery.GetOutputFiles,
Yu Liue4312402023-01-18 09:15:31 -0800273 configKey{arch: Common.String(), osType: CommonOS})
Chris Parsonsf874e462022-05-10 13:50:12 -0400274}
275
276func (fg *fileGroup) IsMixedBuildSupported(ctx BaseModuleContext) bool {
Liz Kammer748209c2022-10-24 10:43:27 -0400277 // TODO(b/247782695), TODO(b/242847534) Fix mixed builds for filegroups
278 return false
Chris Parsonsf874e462022-05-10 13:50:12 -0400279}
280
281func (fg *fileGroup) ProcessBazelQueryResponse(ctx ModuleContext) {
Vinh Tran16fe8e12022-08-16 16:45:44 -0400282 bazelCtx := ctx.Config().BazelContext
283 // This is a short-term solution because we rely on info from Android.bp to handle
284 // a converted module. This will block when we want to remove Android.bp for all
285 // converted modules at some point.
286 // TODO(b/242847534): Implement a long-term solution in which we don't need to rely
287 // on info form Android.bp for modules that are already converted to Bazel
288 relativeRoot := ctx.ModuleDir()
Chris Parsonsf874e462022-05-10 13:50:12 -0400289 if fg.properties.Path != nil {
Vinh Tran16fe8e12022-08-16 16:45:44 -0400290 relativeRoot = filepath.Join(relativeRoot, *fg.properties.Path)
Chris Parsonsf874e462022-05-10 13:50:12 -0400291 }
292
Yu Liue4312402023-01-18 09:15:31 -0800293 filePaths, err := bazelCtx.GetOutputFiles(fg.GetBazelLabel(ctx, fg), configKey{arch: Common.String(), osType: CommonOS})
Chris Parsonsf874e462022-05-10 13:50:12 -0400294 if err != nil {
295 ctx.ModuleErrorf(err.Error())
296 return
297 }
298
299 bazelOuts := make(Paths, 0, len(filePaths))
300 for _, p := range filePaths {
Vinh Tran16fe8e12022-08-16 16:45:44 -0400301 bazelOuts = append(bazelOuts, PathForBazelOutRelative(ctx, relativeRoot, p))
Chris Parsonsf874e462022-05-10 13:50:12 -0400302 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400303 fg.srcs = bazelOuts
304}
Vinh Tran444154d2022-08-16 13:10:31 -0400305
306func (fg *fileGroup) ShouldConvertToAidlLibrary(ctx BazelConversionPathContext) bool {
Yu Liu2aa806b2022-09-01 11:54:47 -0700307 return fg.shouldConvertToLibrary(ctx, ".aidl")
308}
309
310func (fg *fileGroup) ShouldConvertToProtoLibrary(ctx BazelConversionPathContext) bool {
311 return fg.shouldConvertToLibrary(ctx, ".proto")
312}
313
314func (fg *fileGroup) shouldConvertToLibrary(ctx BazelConversionPathContext, suffix string) bool {
Vinh Tran444154d2022-08-16 13:10:31 -0400315 if len(fg.properties.Srcs) == 0 || !fg.ShouldConvertWithBp2build(ctx) {
316 return false
317 }
318 for _, src := range fg.properties.Srcs {
Yu Liu2aa806b2022-09-01 11:54:47 -0700319 if !strings.HasSuffix(src, suffix) {
Vinh Tran444154d2022-08-16 13:10:31 -0400320 return false
321 }
322 }
323 return true
324}
325
326func (fg *fileGroup) GetAidlLibraryLabel(ctx BazelConversionPathContext) string {
Yu Liu2aa806b2022-09-01 11:54:47 -0700327 return fg.getFileGroupAsLibraryLabel(ctx)
328}
329
330func (fg *fileGroup) GetProtoLibraryLabel(ctx BazelConversionPathContext) string {
331 return fg.getFileGroupAsLibraryLabel(ctx) + convertedProtoLibrarySuffix
332}
333
334func (fg *fileGroup) getFileGroupAsLibraryLabel(ctx BazelConversionPathContext) string {
Vinh Tran444154d2022-08-16 13:10:31 -0400335 if ctx.OtherModuleDir(fg.module) == ctx.ModuleDir() {
336 return ":" + fg.Name()
337 } else {
338 return fg.GetBazelLabel(ctx, fg)
339 }
340}
Sam Delmerico97bd1272022-08-25 14:45:31 -0400341
342// Given a name in srcs prop, check to see if the name references a filegroup
343// and the filegroup is converted to aidl_library
344func IsConvertedToAidlLibrary(ctx BazelConversionPathContext, name string) bool {
Yu Liu2aa806b2022-09-01 11:54:47 -0700345 if fg, ok := ToFileGroupAsLibrary(ctx, name); ok {
346 return fg.ShouldConvertToAidlLibrary(ctx)
347 }
348 return false
349}
350
351func ToFileGroupAsLibrary(ctx BazelConversionPathContext, name string) (FileGroupAsLibrary, bool) {
Sam Delmerico97bd1272022-08-25 14:45:31 -0400352 if module, ok := ctx.ModuleFromName(name); ok {
353 if IsFilegroup(ctx, module) {
Yu Liu2aa806b2022-09-01 11:54:47 -0700354 if fg, ok := module.(FileGroupAsLibrary); ok {
355 return fg, true
Sam Delmerico97bd1272022-08-25 14:45:31 -0400356 }
357 }
358 }
Yu Liu2aa806b2022-09-01 11:54:47 -0700359 return nil, false
Sam Delmerico97bd1272022-08-25 14:45:31 -0400360}
Anton Hansson7d6dd8b2023-03-06 11:26:17 +0000361
362// Defaults
363type FileGroupDefaults struct {
364 ModuleBase
365 DefaultsModuleBase
366}
367
368func FileGroupDefaultsFactory() Module {
369 module := &FileGroupDefaults{}
370 module.AddProperties(&fileGroupProperties{})
371 InitDefaultsModule(module)
372
373 return module
374}