blob: fd99ff007a0044a4b8eadb3bee7888084d7c0d62 [file] [log] [blame]
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxf5a3eac2021-08-23 17:05:17 +00001// Copyright 2021 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
Liz Kammer2dd9ca42020-11-25 16:06:39 -080015package bp2build
16
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux0da7ce62021-08-23 17:04:20 +000017/*
18For shareable/common bp2build testing functionality and dumping ground for
19specific-but-shared functionality among tests in package
20*/
21
Liz Kammer2dd9ca42020-11-25 16:06:39 -080022import (
Liz Kammer7a210ac2021-09-22 15:52:58 -040023 "fmt"
Zi Wangfba0a212023-03-07 16:48:19 -080024 "sort"
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000025 "strings"
Rupert Shuttleworth06559d02021-05-19 09:14:26 -040026 "testing"
27
Spandan Das5af0bd32022-09-28 20:43:08 +000028 "github.com/google/blueprint/proptools"
29
Liz Kammer2dd9ca42020-11-25 16:06:39 -080030 "android/soong/android"
Sam Delmerico24c56032022-03-28 19:53:03 +000031 "android/soong/android/allowlists"
Jingwen Chen73850672020-12-14 08:25:34 -050032 "android/soong/bazel"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080033)
34
Jingwen Chen91220d72021-03-24 02:18:33 -040035var (
Rupert Shuttleworth06559d02021-05-19 09:14:26 -040036 buildDir string
Jingwen Chen91220d72021-03-24 02:18:33 -040037)
38
Jingwen Chen5146ac02021-09-02 11:44:42 +000039func checkError(t *testing.T, errs []error, expectedErr error) bool {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000040 t.Helper()
Jingwen Chen5146ac02021-09-02 11:44:42 +000041
Jingwen Chen5146ac02021-09-02 11:44:42 +000042 if len(errs) != 1 {
Liz Kammer6eff3232021-08-26 08:37:59 -040043 return false
Jingwen Chen5146ac02021-09-02 11:44:42 +000044 }
Liz Kammer54309532021-12-14 12:21:22 -050045 if strings.Contains(errs[0].Error(), expectedErr.Error()) {
Jingwen Chen5146ac02021-09-02 11:44:42 +000046 return true
47 }
48
49 return false
50}
51
Sam Delmerico3177a6e2022-06-21 19:28:33 +000052func errored(t *testing.T, tc Bp2buildTestCase, errs []error) bool {
Jingwen Chen5146ac02021-09-02 11:44:42 +000053 t.Helper()
Sam Delmerico3177a6e2022-06-21 19:28:33 +000054 if tc.ExpectedErr != nil {
Jingwen Chen5146ac02021-09-02 11:44:42 +000055 // Rely on checkErrors, as this test case is expected to have an error.
56 return false
57 }
58
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000059 if len(errs) > 0 {
60 for _, err := range errs {
Sam Delmerico3177a6e2022-06-21 19:28:33 +000061 t.Errorf("%s: %s", tc.Description, err)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000062 }
63 return true
64 }
Jingwen Chen5146ac02021-09-02 11:44:42 +000065
66 // All good, continue execution.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000067 return false
68}
69
Trevor Radcliffe1b4b2d92022-09-01 18:57:01 +000070func RunBp2BuildTestCaseSimple(t *testing.T, tc Bp2buildTestCase) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000071 t.Helper()
Sam Delmerico3177a6e2022-06-21 19:28:33 +000072 RunBp2BuildTestCase(t, func(ctx android.RegistrationContext) {}, tc)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000073}
74
Sam Delmerico3177a6e2022-06-21 19:28:33 +000075type Bp2buildTestCase struct {
76 Description string
77 ModuleTypeUnderTest string
78 ModuleTypeUnderTestFactory android.ModuleFactory
79 Blueprint string
80 ExpectedBazelTargets []string
81 Filesystem map[string]string
82 Dir string
Trevor Radcliffe58ea4512022-04-07 20:36:39 +000083 // An error with a string contained within the string of the expected error
Sam Delmerico3177a6e2022-06-21 19:28:33 +000084 ExpectedErr error
85 UnconvertedDepsMode unconvertedDepsMode
Jingwen Chen0eeaeb82022-09-21 10:27:42 +000086
87 // For every directory listed here, the BUILD file for that directory will
88 // be merged with the generated BUILD file. This allows custom BUILD targets
89 // to be used in tests, or use BUILD files to draw package boundaries.
90 KeepBuildFileForDirs []string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000091}
92
Sam Delmerico3177a6e2022-06-21 19:28:33 +000093func RunBp2BuildTestCase(t *testing.T, registerModuleTypes func(ctx android.RegistrationContext), tc Bp2buildTestCase) {
Liz Kammerffc17e42022-11-23 09:42:05 -050094 t.Helper()
Paul Duffin4c0765a2022-10-29 17:48:00 +010095 bp2buildSetup := android.GroupFixturePreparers(
96 android.FixtureRegisterWithContext(registerModuleTypes),
97 SetBp2BuildTestRunner,
98 )
Spandan Das5af0bd32022-09-28 20:43:08 +000099 runBp2BuildTestCaseWithSetup(t, bp2buildSetup, tc)
100}
101
102func RunApiBp2BuildTestCase(t *testing.T, registerModuleTypes func(ctx android.RegistrationContext), tc Bp2buildTestCase) {
Liz Kammerffc17e42022-11-23 09:42:05 -0500103 t.Helper()
Paul Duffin4c0765a2022-10-29 17:48:00 +0100104 apiBp2BuildSetup := android.GroupFixturePreparers(
105 android.FixtureRegisterWithContext(registerModuleTypes),
106 SetApiBp2BuildTestRunner,
107 )
Spandan Das5af0bd32022-09-28 20:43:08 +0000108 runBp2BuildTestCaseWithSetup(t, apiBp2BuildSetup, tc)
109}
110
Paul Duffin4c0765a2022-10-29 17:48:00 +0100111func runBp2BuildTestCaseWithSetup(t *testing.T, extraPreparer android.FixturePreparer, tc Bp2buildTestCase) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000112 t.Helper()
113 dir := "."
114 filesystem := make(map[string][]byte)
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000115 for f, content := range tc.Filesystem {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000116 filesystem[f] = []byte(content)
117 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000118
Paul Duffin4c0765a2022-10-29 17:48:00 +0100119 preparers := []android.FixturePreparer{
120 extraPreparer,
121 android.FixtureMergeMockFs(filesystem),
122 android.FixtureWithRootAndroidBp(tc.Blueprint),
123 android.FixtureRegisterWithContext(func(ctx android.RegistrationContext) {
124 ctx.RegisterModuleType(tc.ModuleTypeUnderTest, tc.ModuleTypeUnderTestFactory)
125 }),
126 android.FixtureModifyContext(func(ctx *android.TestContext) {
127 // A default configuration for tests to not have to specify bp2build_available on top level
128 // targets.
129 bp2buildConfig := android.NewBp2BuildAllowlist().SetDefaultConfig(
130 allowlists.Bp2BuildConfig{
131 android.Bp2BuildTopLevel: allowlists.Bp2BuildDefaultTrueRecursively,
132 },
133 )
134 for _, f := range tc.KeepBuildFileForDirs {
135 bp2buildConfig.SetKeepExistingBuildFile(map[string]bool{
136 f: /*recursive=*/ false,
137 })
138 }
139 ctx.RegisterBp2BuildConfig(bp2buildConfig)
140 }),
141 android.FixtureModifyEnv(func(env map[string]string) {
142 if tc.UnconvertedDepsMode == errorModulesUnconvertedDeps {
143 env["BP2BUILD_ERROR_UNCONVERTED"] = "true"
144 }
145 }),
Jingwen Chen5146ac02021-09-02 11:44:42 +0000146 }
147
Paul Duffin4c0765a2022-10-29 17:48:00 +0100148 preparer := android.GroupFixturePreparers(preparers...)
149 if tc.ExpectedErr != nil {
150 pattern := "\\Q" + tc.ExpectedErr.Error() + "\\E"
151 preparer = preparer.ExtendWithErrorHandler(android.FixtureExpectsOneErrorPattern(pattern))
152 }
153 result := preparer.RunTestWithCustomResult(t).(*BazelTestResult)
154 if len(result.Errs) > 0 {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000155 return
156 }
157
158 checkDir := dir
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000159 if tc.Dir != "" {
160 checkDir = tc.Dir
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000161 }
Paul Duffin4c0765a2022-10-29 17:48:00 +0100162 expectedTargets := map[string][]string{
163 checkDir: tc.ExpectedBazelTargets,
Liz Kammer6eff3232021-08-26 08:37:59 -0400164 }
Paul Duffin4c0765a2022-10-29 17:48:00 +0100165
166 result.CompareAllBazelTargets(t, tc.Description, expectedTargets, true)
167}
168
169// SetBp2BuildTestRunner customizes the test fixture mechanism to run tests in Bp2Build mode.
170var SetBp2BuildTestRunner = android.FixtureSetTestRunner(&bazelTestRunner{Bp2Build})
171
172// SetApiBp2BuildTestRunner customizes the test fixture mechanism to run tests in ApiBp2build mode.
173var SetApiBp2BuildTestRunner = android.FixtureSetTestRunner(&bazelTestRunner{ApiBp2build})
174
175// bazelTestRunner customizes the test fixture mechanism to run tests of the bp2build and
176// apiBp2build build modes.
177type bazelTestRunner struct {
178 mode CodegenMode
179}
180
181func (b *bazelTestRunner) FinalPreparer(result *android.TestResult) android.CustomTestResult {
182 ctx := result.TestContext
183 switch b.mode {
184 case Bp2Build:
185 ctx.RegisterForBazelConversion()
186 case ApiBp2build:
187 ctx.RegisterForApiBazelConversion()
188 default:
189 panic(fmt.Errorf("unknown build mode: %d", b.mode))
190 }
191
192 return &BazelTestResult{TestResult: result}
193}
194
195func (b *bazelTestRunner) PostParseProcessor(result android.CustomTestResult) {
196 bazelResult := result.(*BazelTestResult)
197 ctx := bazelResult.TestContext
198 config := bazelResult.Config
199 _, errs := ctx.ResolveDependencies(config)
200 if bazelResult.CollateErrs(errs) {
201 return
202 }
203
Cole Faustb85d1a12022-11-08 18:14:01 -0800204 codegenCtx := NewCodegenContext(config, ctx.Context, Bp2Build, "")
Paul Duffin4c0765a2022-10-29 17:48:00 +0100205 res, errs := GenerateBazelTargets(codegenCtx, false)
206 if bazelResult.CollateErrs(errs) {
207 return
208 }
209
210 // Store additional data for access by tests.
211 bazelResult.conversionResults = res
212}
213
214// BazelTestResult is a wrapper around android.TestResult to provide type safe access to the bazel
215// specific data stored by the bazelTestRunner.
216type BazelTestResult struct {
217 *android.TestResult
218
219 // The result returned by the GenerateBazelTargets function.
220 conversionResults
221}
222
223// CompareAllBazelTargets compares the BazelTargets produced by the test for all the directories
224// with the supplied set of expected targets.
225//
226// If ignoreUnexpected=false then this enforces an exact match where every BazelTarget produced must
227// have a corresponding expected BazelTarget.
228//
229// If ignoreUnexpected=true then it will ignore directories for which there are no expected targets.
230func (b BazelTestResult) CompareAllBazelTargets(t *testing.T, description string, expectedTargets map[string][]string, ignoreUnexpected bool) {
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400231 t.Helper()
Paul Duffin4c0765a2022-10-29 17:48:00 +0100232 actualTargets := b.buildFileToTargets
233
234 // Generate the sorted set of directories to check.
Cole Faust18994c72023-02-28 16:02:16 -0800235 dirsToCheck := android.SortedKeys(expectedTargets)
Paul Duffin4c0765a2022-10-29 17:48:00 +0100236 if !ignoreUnexpected {
237 // This needs to perform an exact match so add the directories in which targets were
238 // produced to the list of directories to check.
Cole Faust18994c72023-02-28 16:02:16 -0800239 dirsToCheck = append(dirsToCheck, android.SortedKeys(actualTargets)...)
Paul Duffin4c0765a2022-10-29 17:48:00 +0100240 dirsToCheck = android.SortedUniqueStrings(dirsToCheck)
241 }
242
243 for _, dir := range dirsToCheck {
244 expected := expectedTargets[dir]
245 actual := actualTargets[dir]
246
247 if expected == nil {
248 if actual != nil {
249 t.Errorf("did not expect any bazel modules in %q but found %d", dir, len(actual))
250 }
251 } else if actual == nil {
252 expectedCount := len(expected)
253 if expectedCount > 0 {
254 t.Errorf("expected %d bazel modules in %q but did not find any", expectedCount, dir)
255 }
256 } else {
257 b.CompareBazelTargets(t, description, expected, actual)
258 }
259 }
260}
261
262func (b BazelTestResult) CompareBazelTargets(t *testing.T, description string, expectedContents []string, actualTargets BazelTargets) {
Liz Kammer748d7072023-01-25 12:07:43 -0500263 t.Helper()
Paul Duffin4c0765a2022-10-29 17:48:00 +0100264 if actualCount, expectedCount := len(actualTargets), len(expectedContents); actualCount != expectedCount {
Sasha Smundak9d2f1742022-08-04 13:28:38 -0700265 t.Errorf("%s: Expected %d bazel target (%s), got %d (%s)",
Paul Duffin4c0765a2022-10-29 17:48:00 +0100266 description, expectedCount, expectedContents, actualCount, actualTargets)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000267 } else {
Zi Wangfba0a212023-03-07 16:48:19 -0800268 sort.SliceStable(actualTargets, func(i, j int) bool {
269 return actualTargets[i].name < actualTargets[j].name
270 })
271 sort.SliceStable(expectedContents, func(i, j int) bool {
272 return getTargetName(expectedContents[i]) < getTargetName(expectedContents[j])
273 })
Paul Duffin4c0765a2022-10-29 17:48:00 +0100274 for i, actualTarget := range actualTargets {
275 if w, g := expectedContents[i], actualTarget.content; w != g {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000276 t.Errorf(
Paul Duffin4c0765a2022-10-29 17:48:00 +0100277 "%s[%d]: Expected generated Bazel target to be `%s`, got `%s`",
278 description, i, w, g)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000279 }
280 }
281 }
282}
283
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800284type nestedProps struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500285 Nested_prop *string
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800286}
287
Liz Kammer32a03392021-09-14 11:17:21 -0400288type EmbeddedProps struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500289 Embedded_prop *string
Liz Kammer32a03392021-09-14 11:17:21 -0400290}
291
292type OtherEmbeddedProps struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500293 Other_embedded_prop *string
Liz Kammer32a03392021-09-14 11:17:21 -0400294}
295
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800296type customProps struct {
Liz Kammer32a03392021-09-14 11:17:21 -0400297 EmbeddedProps
298 *OtherEmbeddedProps
299
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800300 Bool_prop bool
301 Bool_ptr_prop *bool
302 // Ensure that properties tagged `blueprint:mutated` are omitted
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000303 Int_prop int `blueprint:"mutated"`
304 Int64_ptr_prop *int64
305 String_prop string
306 String_literal_prop *string `android:"arch_variant"`
307 String_ptr_prop *string
308 String_list_prop []string
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800309
310 Nested_props nestedProps
311 Nested_props_ptr *nestedProps
Liz Kammer4562a3b2021-04-21 18:15:34 -0400312
Liz Kammer32b77cf2021-08-04 15:17:02 -0400313 Arch_paths []string `android:"path,arch_variant"`
314 Arch_paths_exclude []string `android:"path,arch_variant"`
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400315
316 // Prop used to indicate this conversion should be 1 module -> multiple targets
317 One_to_many_prop *bool
Spandan Das5af0bd32022-09-28 20:43:08 +0000318
319 Api *string // File describing the APIs of this module
Spandan Das6a448ec2023-04-19 17:36:12 +0000320
321 Test_config_setting *bool // Used to test generation of config_setting targets
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800322}
323
324type customModule struct {
325 android.ModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500326 android.BazelModuleBase
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800327
328 props customProps
329}
330
331// OutputFiles is needed because some instances of this module use dist with a
332// tag property which requires the module implements OutputFileProducer.
333func (m *customModule) OutputFiles(tag string) (android.Paths, error) {
334 return android.PathsForTesting("path" + tag), nil
335}
336
337func (m *customModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
338 // nothing for now.
339}
340
341func customModuleFactoryBase() android.Module {
342 module := &customModule{}
343 module.AddProperties(&module.props)
Liz Kammerea6666f2021-02-17 10:17:28 -0500344 android.InitBazelModule(module)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800345 return module
346}
347
Liz Kammerdfeb1202022-05-13 17:20:20 -0400348func customModuleFactoryHostAndDevice() android.Module {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800349 m := customModuleFactoryBase()
Liz Kammer4562a3b2021-04-21 18:15:34 -0400350 android.InitAndroidArchModule(m, android.HostAndDeviceSupported, android.MultilibBoth)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800351 return m
352}
353
Liz Kammerdfeb1202022-05-13 17:20:20 -0400354func customModuleFactoryDeviceSupported() android.Module {
355 m := customModuleFactoryBase()
356 android.InitAndroidArchModule(m, android.DeviceSupported, android.MultilibBoth)
357 return m
358}
359
360func customModuleFactoryHostSupported() android.Module {
361 m := customModuleFactoryBase()
362 android.InitAndroidArchModule(m, android.HostSupported, android.MultilibBoth)
363 return m
364}
365
366func customModuleFactoryHostAndDeviceDefault() android.Module {
367 m := customModuleFactoryBase()
368 android.InitAndroidArchModule(m, android.HostAndDeviceDefault, android.MultilibBoth)
369 return m
370}
371
372func customModuleFactoryNeitherHostNorDeviceSupported() android.Module {
373 m := customModuleFactoryBase()
374 android.InitAndroidArchModule(m, android.NeitherHostNorDeviceSupported, android.MultilibBoth)
375 return m
376}
377
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800378type testProps struct {
379 Test_prop struct {
380 Test_string_prop string
381 }
382}
383
384type customTestModule struct {
385 android.ModuleBase
386
387 props customProps
388 test_props testProps
389}
390
391func (m *customTestModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
392 // nothing for now.
393}
394
395func customTestModuleFactoryBase() android.Module {
396 m := &customTestModule{}
397 m.AddProperties(&m.props)
398 m.AddProperties(&m.test_props)
399 return m
400}
401
402func customTestModuleFactory() android.Module {
403 m := customTestModuleFactoryBase()
404 android.InitAndroidModule(m)
405 return m
406}
407
408type customDefaultsModule struct {
409 android.ModuleBase
410 android.DefaultsModuleBase
411}
412
413func customDefaultsModuleFactoryBase() android.DefaultsModule {
414 module := &customDefaultsModule{}
415 module.AddProperties(&customProps{})
416 return module
417}
418
419func customDefaultsModuleFactoryBasic() android.Module {
420 return customDefaultsModuleFactoryBase()
421}
422
423func customDefaultsModuleFactory() android.Module {
424 m := customDefaultsModuleFactoryBase()
425 android.InitDefaultsModule(m)
426 return m
427}
Jingwen Chen73850672020-12-14 08:25:34 -0500428
Liz Kammer32a03392021-09-14 11:17:21 -0400429type EmbeddedAttr struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500430 Embedded_attr *string
Liz Kammer32a03392021-09-14 11:17:21 -0400431}
432
433type OtherEmbeddedAttr struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500434 Other_embedded_attr *string
Liz Kammer32a03392021-09-14 11:17:21 -0400435}
436
Jingwen Chen73850672020-12-14 08:25:34 -0500437type customBazelModuleAttributes struct {
Liz Kammer32a03392021-09-14 11:17:21 -0400438 EmbeddedAttr
439 *OtherEmbeddedAttr
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000440 String_literal_prop bazel.StringAttribute
441 String_ptr_prop *string
442 String_list_prop []string
443 Arch_paths bazel.LabelListAttribute
Spandan Das5af0bd32022-09-28 20:43:08 +0000444 Api bazel.LabelAttribute
Jingwen Chen73850672020-12-14 08:25:34 -0500445}
446
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400447func (m *customModule) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400448 if p := m.props.One_to_many_prop; p != nil && *p {
449 customBp2buildOneToMany(ctx, m)
450 return
451 }
Liz Kammer4562a3b2021-04-21 18:15:34 -0400452
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000453 paths := bazel.LabelListAttribute{}
454 strAttr := bazel.StringAttribute{}
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400455 for axis, configToProps := range m.GetArchVariantProperties(ctx, &customProps{}) {
456 for config, props := range configToProps {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000457 if custProps, ok := props.(*customProps); ok {
458 if custProps.Arch_paths != nil {
459 paths.SetSelectValue(axis, config, android.BazelLabelForModuleSrcExcludes(ctx, custProps.Arch_paths, custProps.Arch_paths_exclude))
460 }
461 if custProps.String_literal_prop != nil {
462 strAttr.SetSelectValue(axis, config, custProps.String_literal_prop)
463 }
Liz Kammer4562a3b2021-04-21 18:15:34 -0400464 }
465 }
Jingwen Chen73850672020-12-14 08:25:34 -0500466 }
Cole Faust912bc882023-03-08 12:29:50 -0800467 productVariableProps := android.ProductVariableProperties(ctx, ctx.Module())
Liz Kammer9d2d4102022-12-21 14:51:37 -0500468 if props, ok := productVariableProps["String_literal_prop"]; ok {
469 for c, p := range props {
470 if val, ok := p.(*string); ok {
471 strAttr.SetSelectValue(c.ConfigurationAxis(), c.SelectKey(), val)
472 }
473 }
474 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400475
476 paths.ResolveExcludes()
477
478 attrs := &customBazelModuleAttributes{
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000479 String_literal_prop: strAttr,
480 String_ptr_prop: m.props.String_ptr_prop,
481 String_list_prop: m.props.String_list_prop,
482 Arch_paths: paths,
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400483 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000484
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400485 attrs.Embedded_attr = m.props.Embedded_prop
486 if m.props.OtherEmbeddedProps != nil {
487 attrs.OtherEmbeddedAttr = &OtherEmbeddedAttr{Other_embedded_attr: m.props.OtherEmbeddedProps.Other_embedded_prop}
488 }
489
490 props := bazel.BazelTargetModuleProperties{
491 Rule_class: "custom",
492 }
493
494 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
Spandan Das6a448ec2023-04-19 17:36:12 +0000495
496 if proptools.Bool(m.props.Test_config_setting) {
497 m.createConfigSetting(ctx)
498 }
499
500}
501
502func (m *customModule) createConfigSetting(ctx android.TopDownMutatorContext) {
503 csa := bazel.ConfigSettingAttributes{
504 Flag_values: bazel.StringMapAttribute{
505 "//build/bazel/rules/my_string_setting": m.Name(),
506 },
507 }
508 ca := android.CommonAttributes{
509 Name: m.Name() + "_config_setting",
510 }
511 ctx.CreateBazelConfigSetting(
512 csa,
513 ca,
514 ctx.ModuleDir(),
515 )
Jingwen Chen73850672020-12-14 08:25:34 -0500516}
Jingwen Chen40067de2021-01-26 21:58:43 -0500517
Spandan Das5af0bd32022-09-28 20:43:08 +0000518var _ android.ApiProvider = (*customModule)(nil)
519
520func (c *customModule) ConvertWithApiBp2build(ctx android.TopDownMutatorContext) {
521 props := bazel.BazelTargetModuleProperties{
522 Rule_class: "custom_api_contribution",
523 }
524 apiAttribute := bazel.MakeLabelAttribute(
525 android.BazelLabelForModuleSrcSingle(ctx, proptools.String(c.props.Api)).Label,
526 )
527 attrs := &customBazelModuleAttributes{
528 Api: *apiAttribute,
529 }
530 ctx.CreateBazelTargetModule(props,
531 android.CommonAttributes{Name: c.Name()},
532 attrs)
533}
534
Jingwen Chen40067de2021-01-26 21:58:43 -0500535// A bp2build mutator that uses load statements and creates a 1:M mapping from
536// module to target.
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400537func customBp2buildOneToMany(ctx android.TopDownMutatorContext, m *customModule) {
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500538
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400539 baseName := m.Name()
540 attrs := &customBazelModuleAttributes{}
Jingwen Chen1fd14692021-02-05 03:01:50 -0500541
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400542 myLibraryProps := bazel.BazelTargetModuleProperties{
543 Rule_class: "my_library",
544 Bzl_load_location: "//build/bazel/rules:rules.bzl",
Jingwen Chen40067de2021-01-26 21:58:43 -0500545 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400546 ctx.CreateBazelTargetModule(myLibraryProps, android.CommonAttributes{Name: baseName}, attrs)
547
548 protoLibraryProps := bazel.BazelTargetModuleProperties{
549 Rule_class: "proto_library",
550 Bzl_load_location: "//build/bazel/rules:proto.bzl",
551 }
552 ctx.CreateBazelTargetModule(protoLibraryProps, android.CommonAttributes{Name: baseName + "_proto_library_deps"}, attrs)
553
554 myProtoLibraryProps := bazel.BazelTargetModuleProperties{
555 Rule_class: "my_proto_library",
556 Bzl_load_location: "//build/bazel/rules:proto.bzl",
557 }
558 ctx.CreateBazelTargetModule(myProtoLibraryProps, android.CommonAttributes{Name: baseName + "_my_proto_library_deps"}, attrs)
Jingwen Chen40067de2021-01-26 21:58:43 -0500559}
Jingwen Chenba369ad2021-02-22 10:19:34 -0500560
561// Helper method for tests to easily access the targets in a dir.
Liz Kammer6eff3232021-08-26 08:37:59 -0400562func generateBazelTargetsForDir(codegenCtx *CodegenContext, dir string) (BazelTargets, []error) {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400563 // TODO: Set generateFilegroups to true and/or remove the generateFilegroups argument completely
Liz Kammer6eff3232021-08-26 08:37:59 -0400564 res, err := GenerateBazelTargets(codegenCtx, false)
Alix94e26032022-08-16 20:37:33 +0000565 if err != nil {
566 return BazelTargets{}, err
567 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400568 return res.buildFileToTargets[dir], err
Jingwen Chenba369ad2021-02-22 10:19:34 -0500569}
Liz Kammer32b77cf2021-08-04 15:17:02 -0400570
571func registerCustomModuleForBp2buildConversion(ctx *android.TestContext) {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400572 ctx.RegisterModuleType("custom", customModuleFactoryHostAndDevice)
Liz Kammer32b77cf2021-08-04 15:17:02 -0400573 ctx.RegisterForBazelConversion()
574}
Liz Kammer7a210ac2021-09-22 15:52:58 -0400575
576func simpleModuleDoNotConvertBp2build(typ, name string) string {
577 return fmt.Sprintf(`
578%s {
579 name: "%s",
580 bazel_module: { bp2build_available: false },
581}`, typ, name)
582}
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500583
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000584type AttrNameToString map[string]string
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500585
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000586func (a AttrNameToString) clone() AttrNameToString {
587 newAttrs := make(AttrNameToString, len(a))
Liz Kammerdfeb1202022-05-13 17:20:20 -0400588 for k, v := range a {
589 newAttrs[k] = v
590 }
591 return newAttrs
592}
593
594// makeBazelTargetNoRestrictions returns bazel target build file definition that can be host or
595// device specific, or independent of host/device.
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000596func makeBazelTargetHostOrDevice(typ, name string, attrs AttrNameToString, hod android.HostOrDeviceSupported) string {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400597 if _, ok := attrs["target_compatible_with"]; !ok {
598 switch hod {
599 case android.HostSupported:
600 attrs["target_compatible_with"] = `select({
601 "//build/bazel/platforms/os:android": ["@platforms//:incompatible"],
602 "//conditions:default": [],
603 })`
604 case android.DeviceSupported:
605 attrs["target_compatible_with"] = `["//build/bazel/platforms/os:android"]`
606 }
607 }
608
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500609 attrStrings := make([]string, 0, len(attrs)+1)
Sasha Smundakfb589492022-08-04 11:13:27 -0700610 if name != "" {
611 attrStrings = append(attrStrings, fmt.Sprintf(` name = "%s",`, name))
612 }
Cole Faust18994c72023-02-28 16:02:16 -0800613 for _, k := range android.SortedKeys(attrs) {
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500614 attrStrings = append(attrStrings, fmt.Sprintf(" %s = %s,", k, attrs[k]))
615 }
616 return fmt.Sprintf(`%s(
617%s
618)`, typ, strings.Join(attrStrings, "\n"))
619}
Liz Kammerdfeb1202022-05-13 17:20:20 -0400620
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000621// MakeBazelTargetNoRestrictions returns bazel target build file definition that does not add a
Liz Kammerdfeb1202022-05-13 17:20:20 -0400622// target_compatible_with. This is useful for module types like filegroup and genrule that arch not
623// arch variant
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000624func MakeBazelTargetNoRestrictions(typ, name string, attrs AttrNameToString) string {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400625 return makeBazelTargetHostOrDevice(typ, name, attrs, android.HostAndDeviceDefault)
626}
627
628// makeBazelTargetNoRestrictions returns bazel target build file definition that is device specific
629// as this is the most common default in Soong.
Alixe06d75b2022-08-31 18:28:19 +0000630func MakeBazelTarget(typ, name string, attrs AttrNameToString) string {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400631 return makeBazelTargetHostOrDevice(typ, name, attrs, android.DeviceSupported)
632}
Sasha Smundak9d2f1742022-08-04 13:28:38 -0700633
634type ExpectedRuleTarget struct {
635 Rule string
636 Name string
637 Attrs AttrNameToString
638 Hod android.HostOrDeviceSupported
639}
640
641func (ebr ExpectedRuleTarget) String() string {
642 return makeBazelTargetHostOrDevice(ebr.Rule, ebr.Name, ebr.Attrs, ebr.Hod)
643}
Trevor Radcliffe087af542022-09-16 15:36:10 +0000644
645func makeCcStubSuiteTargets(name string, attrs AttrNameToString) string {
646 if _, hasStubs := attrs["stubs_symbol_file"]; !hasStubs {
647 return ""
648 }
649 STUB_SUITE_ATTRS := map[string]string{
Sam Delmerico5f906492023-03-15 18:06:18 -0400650 "stubs_symbol_file": "symbol_file",
651 "stubs_versions": "versions",
652 "soname": "soname",
653 "source_library_label": "source_library_label",
Trevor Radcliffe087af542022-09-16 15:36:10 +0000654 }
655
656 stubSuiteAttrs := AttrNameToString{}
657 for key, _ := range attrs {
658 if _, stubSuiteAttr := STUB_SUITE_ATTRS[key]; stubSuiteAttr {
659 stubSuiteAttrs[STUB_SUITE_ATTRS[key]] = attrs[key]
Sam Delmerico5f906492023-03-15 18:06:18 -0400660 } else {
661 panic(fmt.Sprintf("unused cc_stub_suite attr %q\n", key))
Trevor Radcliffe087af542022-09-16 15:36:10 +0000662 }
663 }
664 return MakeBazelTarget("cc_stub_suite", name+"_stub_libs", stubSuiteAttrs)
665}
Alix341484b2022-10-31 19:08:18 +0000666
667func MakeNeverlinkDuplicateTarget(moduleType string, name string) string {
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -0500668 return MakeNeverlinkDuplicateTargetWithAttrs(moduleType, name, AttrNameToString{})
669}
670
671func MakeNeverlinkDuplicateTargetWithAttrs(moduleType string, name string, extraAttrs AttrNameToString) string {
672 attrs := extraAttrs
673 attrs["neverlink"] = `True`
674 attrs["exports"] = `[":` + name + `"]`
675 return MakeBazelTarget(moduleType, name+"-neverlink", attrs)
Alix341484b2022-10-31 19:08:18 +0000676}
Zi Wangfba0a212023-03-07 16:48:19 -0800677
678func getTargetName(targetContent string) string {
679 data := strings.Split(targetContent, "name = \"")
680 if len(data) < 2 {
681 return ""
682 } else {
683 endIndex := strings.Index(data[1], "\"")
684 return data[1][:endIndex]
685 }
686}