blob: 997df64a468012381d8e5ea9a93a1c34d5da7db2 [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
Sam Delmerico5840afc2023-06-12 15:44:03 -040079 // Text to add to the toplevel, root Android.bp file. If Dir is not set, all
80 // ExpectedBazelTargets are assumed to be generated by this file.
Chris Parsons39a16972023-06-08 14:28:51 +000081 Blueprint string
Sam Delmerico5840afc2023-06-12 15:44:03 -040082 // ExpectedBazelTargets compares the BazelTargets generated in `Dir` (if not empty).
83 // Otherwise, it checks the BazelTargets generated by `Blueprint` in the root directory.
84 ExpectedBazelTargets []string
Cole Faust3d927232023-06-27 22:52:07 +000085 Filesystem map[string]string
Sam Delmerico5840afc2023-06-12 15:44:03 -040086 // Dir sets the directory which will be compared against the targets in ExpectedBazelTargets.
87 // This should used in conjunction with the Filesystem property to check for targets
88 // generated from a directory that is not the root.
89 // If not set, all ExpectedBazelTargets are assumed to be generated by the text in the
90 // Blueprint property.
91 Dir string
Trevor Radcliffe58ea4512022-04-07 20:36:39 +000092 // An error with a string contained within the string of the expected error
Sam Delmerico3177a6e2022-06-21 19:28:33 +000093 ExpectedErr error
94 UnconvertedDepsMode unconvertedDepsMode
Jingwen Chen0eeaeb82022-09-21 10:27:42 +000095
96 // For every directory listed here, the BUILD file for that directory will
97 // be merged with the generated BUILD file. This allows custom BUILD targets
98 // to be used in tests, or use BUILD files to draw package boundaries.
99 KeepBuildFileForDirs []string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000100}
101
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000102func RunBp2BuildTestCase(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 bp2buildSetup := android.GroupFixturePreparers(
105 android.FixtureRegisterWithContext(registerModuleTypes),
106 SetBp2BuildTestRunner,
107 )
Spandan Das5af0bd32022-09-28 20:43:08 +0000108 runBp2BuildTestCaseWithSetup(t, bp2buildSetup, 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()
Cole Faust3d927232023-06-27 22:52:07 +0000113 dir := "."
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000114 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 }),
Cole Faust3d927232023-06-27 22:52:07 +0000126 android.FixtureModifyContext(func(ctx *android.TestContext) {
Paul Duffin4c0765a2022-10-29 17:48:00 +0100127 // 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 )
Cole Faust3d927232023-06-27 22:52:07 +0000134 for _, f := range tc.KeepBuildFileForDirs {
Paul Duffin4c0765a2022-10-29 17:48:00 +0100135 bp2buildConfig.SetKeepExistingBuildFile(map[string]bool{
136 f: /*recursive=*/ false,
137 })
138 }
139 ctx.RegisterBp2BuildConfig(bp2buildConfig)
Chris Parsons39a16972023-06-08 14:28:51 +0000140 // This setting is added to bp2build invocations. It prevents bp2build
141 // from cloning modules to their original state after mutators run. This
142 // would lose some data intentionally set by these mutators.
143 ctx.SkipCloneModulesAfterMutators = true
Paul Duffin4c0765a2022-10-29 17:48:00 +0100144 }),
145 android.FixtureModifyEnv(func(env map[string]string) {
146 if tc.UnconvertedDepsMode == errorModulesUnconvertedDeps {
147 env["BP2BUILD_ERROR_UNCONVERTED"] = "true"
148 }
149 }),
Jingwen Chen5146ac02021-09-02 11:44:42 +0000150 }
151
Paul Duffin4c0765a2022-10-29 17:48:00 +0100152 preparer := android.GroupFixturePreparers(preparers...)
153 if tc.ExpectedErr != nil {
154 pattern := "\\Q" + tc.ExpectedErr.Error() + "\\E"
155 preparer = preparer.ExtendWithErrorHandler(android.FixtureExpectsOneErrorPattern(pattern))
156 }
157 result := preparer.RunTestWithCustomResult(t).(*BazelTestResult)
158 if len(result.Errs) > 0 {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000159 return
160 }
161
Cole Faust3d927232023-06-27 22:52:07 +0000162 checkDir := dir
163 if tc.Dir != "" {
164 checkDir = tc.Dir
165 }
Paul Duffin4c0765a2022-10-29 17:48:00 +0100166 expectedTargets := map[string][]string{
167 checkDir: tc.ExpectedBazelTargets,
Liz Kammer6eff3232021-08-26 08:37:59 -0400168 }
Paul Duffin4c0765a2022-10-29 17:48:00 +0100169
170 result.CompareAllBazelTargets(t, tc.Description, expectedTargets, true)
171}
172
173// SetBp2BuildTestRunner customizes the test fixture mechanism to run tests in Bp2Build mode.
Chris Parsons73f411b2023-06-20 21:46:57 +0000174var SetBp2BuildTestRunner = android.FixtureSetTestRunner(&bazelTestRunner{})
Paul Duffin4c0765a2022-10-29 17:48:00 +0100175
Chris Parsons73f411b2023-06-20 21:46:57 +0000176// bazelTestRunner customizes the test fixture mechanism to run tests of the bp2build build mode.
177type bazelTestRunner struct{}
Paul Duffin4c0765a2022-10-29 17:48:00 +0100178
179func (b *bazelTestRunner) FinalPreparer(result *android.TestResult) android.CustomTestResult {
180 ctx := result.TestContext
Chris Parsons73f411b2023-06-20 21:46:57 +0000181 ctx.RegisterForBazelConversion()
Paul Duffin4c0765a2022-10-29 17:48:00 +0100182
183 return &BazelTestResult{TestResult: result}
184}
185
186func (b *bazelTestRunner) PostParseProcessor(result android.CustomTestResult) {
187 bazelResult := result.(*BazelTestResult)
188 ctx := bazelResult.TestContext
189 config := bazelResult.Config
190 _, errs := ctx.ResolveDependencies(config)
191 if bazelResult.CollateErrs(errs) {
192 return
193 }
194
Chris Parsons73f411b2023-06-20 21:46:57 +0000195 codegenCtx := NewCodegenContext(config, ctx.Context, Bp2Build, "")
Paul Duffin4c0765a2022-10-29 17:48:00 +0100196 res, errs := GenerateBazelTargets(codegenCtx, false)
197 if bazelResult.CollateErrs(errs) {
198 return
199 }
200
201 // Store additional data for access by tests.
202 bazelResult.conversionResults = res
203}
204
205// BazelTestResult is a wrapper around android.TestResult to provide type safe access to the bazel
206// specific data stored by the bazelTestRunner.
207type BazelTestResult struct {
208 *android.TestResult
209
210 // The result returned by the GenerateBazelTargets function.
211 conversionResults
212}
213
214// CompareAllBazelTargets compares the BazelTargets produced by the test for all the directories
215// with the supplied set of expected targets.
216//
217// If ignoreUnexpected=false then this enforces an exact match where every BazelTarget produced must
218// have a corresponding expected BazelTarget.
219//
220// If ignoreUnexpected=true then it will ignore directories for which there are no expected targets.
221func (b BazelTestResult) CompareAllBazelTargets(t *testing.T, description string, expectedTargets map[string][]string, ignoreUnexpected bool) {
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400222 t.Helper()
Paul Duffin4c0765a2022-10-29 17:48:00 +0100223 actualTargets := b.buildFileToTargets
224
225 // Generate the sorted set of directories to check.
Cole Faust18994c72023-02-28 16:02:16 -0800226 dirsToCheck := android.SortedKeys(expectedTargets)
Paul Duffin4c0765a2022-10-29 17:48:00 +0100227 if !ignoreUnexpected {
228 // This needs to perform an exact match so add the directories in which targets were
229 // produced to the list of directories to check.
Cole Faust18994c72023-02-28 16:02:16 -0800230 dirsToCheck = append(dirsToCheck, android.SortedKeys(actualTargets)...)
Paul Duffin4c0765a2022-10-29 17:48:00 +0100231 dirsToCheck = android.SortedUniqueStrings(dirsToCheck)
232 }
233
234 for _, dir := range dirsToCheck {
235 expected := expectedTargets[dir]
236 actual := actualTargets[dir]
237
238 if expected == nil {
239 if actual != nil {
240 t.Errorf("did not expect any bazel modules in %q but found %d", dir, len(actual))
241 }
242 } else if actual == nil {
243 expectedCount := len(expected)
244 if expectedCount > 0 {
245 t.Errorf("expected %d bazel modules in %q but did not find any", expectedCount, dir)
246 }
247 } else {
248 b.CompareBazelTargets(t, description, expected, actual)
249 }
250 }
251}
252
253func (b BazelTestResult) CompareBazelTargets(t *testing.T, description string, expectedContents []string, actualTargets BazelTargets) {
Liz Kammer748d7072023-01-25 12:07:43 -0500254 t.Helper()
Paul Duffin4c0765a2022-10-29 17:48:00 +0100255 if actualCount, expectedCount := len(actualTargets), len(expectedContents); actualCount != expectedCount {
Sasha Smundak9d2f1742022-08-04 13:28:38 -0700256 t.Errorf("%s: Expected %d bazel target (%s), got %d (%s)",
Paul Duffin4c0765a2022-10-29 17:48:00 +0100257 description, expectedCount, expectedContents, actualCount, actualTargets)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000258 } else {
Zi Wangfba0a212023-03-07 16:48:19 -0800259 sort.SliceStable(actualTargets, func(i, j int) bool {
260 return actualTargets[i].name < actualTargets[j].name
261 })
262 sort.SliceStable(expectedContents, func(i, j int) bool {
263 return getTargetName(expectedContents[i]) < getTargetName(expectedContents[j])
264 })
Paul Duffin4c0765a2022-10-29 17:48:00 +0100265 for i, actualTarget := range actualTargets {
266 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 +0000267 t.Errorf(
Paul Duffin4c0765a2022-10-29 17:48:00 +0100268 "%s[%d]: Expected generated Bazel target to be `%s`, got `%s`",
269 description, i, w, g)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000270 }
271 }
272 }
273}
274
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800275type nestedProps struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500276 Nested_prop *string
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800277}
278
Liz Kammer32a03392021-09-14 11:17:21 -0400279type EmbeddedProps struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500280 Embedded_prop *string
Liz Kammer32a03392021-09-14 11:17:21 -0400281}
282
283type OtherEmbeddedProps struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500284 Other_embedded_prop *string
Liz Kammer32a03392021-09-14 11:17:21 -0400285}
286
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800287type customProps struct {
Liz Kammer32a03392021-09-14 11:17:21 -0400288 EmbeddedProps
289 *OtherEmbeddedProps
290
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800291 Bool_prop bool
292 Bool_ptr_prop *bool
293 // 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 +0000294 Int_prop int `blueprint:"mutated"`
295 Int64_ptr_prop *int64
296 String_prop string
297 String_literal_prop *string `android:"arch_variant"`
298 String_ptr_prop *string
299 String_list_prop []string
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800300
301 Nested_props nestedProps
302 Nested_props_ptr *nestedProps
Liz Kammer4562a3b2021-04-21 18:15:34 -0400303
Liz Kammer32b77cf2021-08-04 15:17:02 -0400304 Arch_paths []string `android:"path,arch_variant"`
305 Arch_paths_exclude []string `android:"path,arch_variant"`
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400306
307 // Prop used to indicate this conversion should be 1 module -> multiple targets
308 One_to_many_prop *bool
Spandan Das5af0bd32022-09-28 20:43:08 +0000309
310 Api *string // File describing the APIs of this module
Spandan Das6a448ec2023-04-19 17:36:12 +0000311
312 Test_config_setting *bool // Used to test generation of config_setting targets
Spandan Das3131d672023-08-03 22:33:47 +0000313
314 Dir *string // Dir in which the Bazel Target will be created
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800315}
316
317type customModule struct {
318 android.ModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500319 android.BazelModuleBase
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800320
321 props customProps
322}
323
324// OutputFiles is needed because some instances of this module use dist with a
325// tag property which requires the module implements OutputFileProducer.
326func (m *customModule) OutputFiles(tag string) (android.Paths, error) {
327 return android.PathsForTesting("path" + tag), nil
328}
329
330func (m *customModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
331 // nothing for now.
332}
333
334func customModuleFactoryBase() android.Module {
335 module := &customModule{}
336 module.AddProperties(&module.props)
Liz Kammerea6666f2021-02-17 10:17:28 -0500337 android.InitBazelModule(module)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800338 return module
339}
340
Liz Kammerdfeb1202022-05-13 17:20:20 -0400341func customModuleFactoryHostAndDevice() android.Module {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800342 m := customModuleFactoryBase()
Liz Kammer4562a3b2021-04-21 18:15:34 -0400343 android.InitAndroidArchModule(m, android.HostAndDeviceSupported, android.MultilibBoth)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800344 return m
345}
346
Liz Kammerdfeb1202022-05-13 17:20:20 -0400347func customModuleFactoryDeviceSupported() android.Module {
348 m := customModuleFactoryBase()
349 android.InitAndroidArchModule(m, android.DeviceSupported, android.MultilibBoth)
350 return m
351}
352
353func customModuleFactoryHostSupported() android.Module {
354 m := customModuleFactoryBase()
355 android.InitAndroidArchModule(m, android.HostSupported, android.MultilibBoth)
356 return m
357}
358
359func customModuleFactoryHostAndDeviceDefault() android.Module {
360 m := customModuleFactoryBase()
361 android.InitAndroidArchModule(m, android.HostAndDeviceDefault, android.MultilibBoth)
362 return m
363}
364
365func customModuleFactoryNeitherHostNorDeviceSupported() android.Module {
366 m := customModuleFactoryBase()
367 android.InitAndroidArchModule(m, android.NeitherHostNorDeviceSupported, android.MultilibBoth)
368 return m
369}
370
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800371type testProps struct {
372 Test_prop struct {
373 Test_string_prop string
374 }
375}
376
377type customTestModule struct {
378 android.ModuleBase
379
380 props customProps
381 test_props testProps
382}
383
384func (m *customTestModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
385 // nothing for now.
386}
387
388func customTestModuleFactoryBase() android.Module {
389 m := &customTestModule{}
390 m.AddProperties(&m.props)
391 m.AddProperties(&m.test_props)
392 return m
393}
394
395func customTestModuleFactory() android.Module {
396 m := customTestModuleFactoryBase()
397 android.InitAndroidModule(m)
398 return m
399}
400
401type customDefaultsModule struct {
402 android.ModuleBase
403 android.DefaultsModuleBase
404}
405
406func customDefaultsModuleFactoryBase() android.DefaultsModule {
407 module := &customDefaultsModule{}
408 module.AddProperties(&customProps{})
409 return module
410}
411
412func customDefaultsModuleFactoryBasic() android.Module {
413 return customDefaultsModuleFactoryBase()
414}
415
416func customDefaultsModuleFactory() android.Module {
417 m := customDefaultsModuleFactoryBase()
418 android.InitDefaultsModule(m)
419 return m
420}
Jingwen Chen73850672020-12-14 08:25:34 -0500421
Liz Kammer32a03392021-09-14 11:17:21 -0400422type EmbeddedAttr struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500423 Embedded_attr *string
Liz Kammer32a03392021-09-14 11:17:21 -0400424}
425
426type OtherEmbeddedAttr struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500427 Other_embedded_attr *string
Liz Kammer32a03392021-09-14 11:17:21 -0400428}
429
Jingwen Chen73850672020-12-14 08:25:34 -0500430type customBazelModuleAttributes struct {
Liz Kammer32a03392021-09-14 11:17:21 -0400431 EmbeddedAttr
432 *OtherEmbeddedAttr
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000433 String_literal_prop bazel.StringAttribute
434 String_ptr_prop *string
435 String_list_prop []string
436 Arch_paths bazel.LabelListAttribute
Spandan Das5af0bd32022-09-28 20:43:08 +0000437 Api bazel.LabelAttribute
Jingwen Chen73850672020-12-14 08:25:34 -0500438}
439
Spandan Das3131d672023-08-03 22:33:47 +0000440func (m *customModule) dir() *string {
441 return m.props.Dir
442}
443
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400444func (m *customModule) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400445 if p := m.props.One_to_many_prop; p != nil && *p {
446 customBp2buildOneToMany(ctx, m)
447 return
448 }
Liz Kammer4562a3b2021-04-21 18:15:34 -0400449
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000450 paths := bazel.LabelListAttribute{}
451 strAttr := bazel.StringAttribute{}
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400452 for axis, configToProps := range m.GetArchVariantProperties(ctx, &customProps{}) {
453 for config, props := range configToProps {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000454 if custProps, ok := props.(*customProps); ok {
455 if custProps.Arch_paths != nil {
456 paths.SetSelectValue(axis, config, android.BazelLabelForModuleSrcExcludes(ctx, custProps.Arch_paths, custProps.Arch_paths_exclude))
457 }
458 if custProps.String_literal_prop != nil {
459 strAttr.SetSelectValue(axis, config, custProps.String_literal_prop)
460 }
Liz Kammer4562a3b2021-04-21 18:15:34 -0400461 }
462 }
Jingwen Chen73850672020-12-14 08:25:34 -0500463 }
Cole Faust912bc882023-03-08 12:29:50 -0800464 productVariableProps := android.ProductVariableProperties(ctx, ctx.Module())
Liz Kammer9d2d4102022-12-21 14:51:37 -0500465 if props, ok := productVariableProps["String_literal_prop"]; ok {
466 for c, p := range props {
467 if val, ok := p.(*string); ok {
468 strAttr.SetSelectValue(c.ConfigurationAxis(), c.SelectKey(), val)
469 }
470 }
471 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400472
473 paths.ResolveExcludes()
474
475 attrs := &customBazelModuleAttributes{
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000476 String_literal_prop: strAttr,
477 String_ptr_prop: m.props.String_ptr_prop,
478 String_list_prop: m.props.String_list_prop,
479 Arch_paths: paths,
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400480 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000481
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400482 attrs.Embedded_attr = m.props.Embedded_prop
483 if m.props.OtherEmbeddedProps != nil {
484 attrs.OtherEmbeddedAttr = &OtherEmbeddedAttr{Other_embedded_attr: m.props.OtherEmbeddedProps.Other_embedded_prop}
485 }
486
487 props := bazel.BazelTargetModuleProperties{
488 Rule_class: "custom",
489 }
490
Spandan Das3131d672023-08-03 22:33:47 +0000491 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name(), Dir: m.dir()}, attrs)
Spandan Das6a448ec2023-04-19 17:36:12 +0000492
493 if proptools.Bool(m.props.Test_config_setting) {
494 m.createConfigSetting(ctx)
495 }
496
497}
498
499func (m *customModule) createConfigSetting(ctx android.TopDownMutatorContext) {
500 csa := bazel.ConfigSettingAttributes{
501 Flag_values: bazel.StringMapAttribute{
502 "//build/bazel/rules/my_string_setting": m.Name(),
503 },
504 }
505 ca := android.CommonAttributes{
506 Name: m.Name() + "_config_setting",
507 }
508 ctx.CreateBazelConfigSetting(
509 csa,
510 ca,
511 ctx.ModuleDir(),
512 )
Jingwen Chen73850672020-12-14 08:25:34 -0500513}
Jingwen Chen40067de2021-01-26 21:58:43 -0500514
Spandan Das5af0bd32022-09-28 20:43:08 +0000515var _ android.ApiProvider = (*customModule)(nil)
516
517func (c *customModule) ConvertWithApiBp2build(ctx android.TopDownMutatorContext) {
518 props := bazel.BazelTargetModuleProperties{
519 Rule_class: "custom_api_contribution",
520 }
521 apiAttribute := bazel.MakeLabelAttribute(
522 android.BazelLabelForModuleSrcSingle(ctx, proptools.String(c.props.Api)).Label,
523 )
524 attrs := &customBazelModuleAttributes{
525 Api: *apiAttribute,
526 }
527 ctx.CreateBazelTargetModule(props,
528 android.CommonAttributes{Name: c.Name()},
529 attrs)
530}
531
Jingwen Chen40067de2021-01-26 21:58:43 -0500532// A bp2build mutator that uses load statements and creates a 1:M mapping from
533// module to target.
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400534func customBp2buildOneToMany(ctx android.TopDownMutatorContext, m *customModule) {
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500535
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400536 baseName := m.Name()
537 attrs := &customBazelModuleAttributes{}
Jingwen Chen1fd14692021-02-05 03:01:50 -0500538
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400539 myLibraryProps := bazel.BazelTargetModuleProperties{
540 Rule_class: "my_library",
541 Bzl_load_location: "//build/bazel/rules:rules.bzl",
Jingwen Chen40067de2021-01-26 21:58:43 -0500542 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400543 ctx.CreateBazelTargetModule(myLibraryProps, android.CommonAttributes{Name: baseName}, attrs)
544
545 protoLibraryProps := bazel.BazelTargetModuleProperties{
546 Rule_class: "proto_library",
547 Bzl_load_location: "//build/bazel/rules:proto.bzl",
548 }
549 ctx.CreateBazelTargetModule(protoLibraryProps, android.CommonAttributes{Name: baseName + "_proto_library_deps"}, attrs)
550
551 myProtoLibraryProps := bazel.BazelTargetModuleProperties{
552 Rule_class: "my_proto_library",
553 Bzl_load_location: "//build/bazel/rules:proto.bzl",
554 }
555 ctx.CreateBazelTargetModule(myProtoLibraryProps, android.CommonAttributes{Name: baseName + "_my_proto_library_deps"}, attrs)
Jingwen Chen40067de2021-01-26 21:58:43 -0500556}
Jingwen Chenba369ad2021-02-22 10:19:34 -0500557
558// Helper method for tests to easily access the targets in a dir.
Liz Kammer6eff3232021-08-26 08:37:59 -0400559func generateBazelTargetsForDir(codegenCtx *CodegenContext, dir string) (BazelTargets, []error) {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400560 // TODO: Set generateFilegroups to true and/or remove the generateFilegroups argument completely
Liz Kammer6eff3232021-08-26 08:37:59 -0400561 res, err := GenerateBazelTargets(codegenCtx, false)
Alix94e26032022-08-16 20:37:33 +0000562 if err != nil {
563 return BazelTargets{}, err
564 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400565 return res.buildFileToTargets[dir], err
Jingwen Chenba369ad2021-02-22 10:19:34 -0500566}
Liz Kammer32b77cf2021-08-04 15:17:02 -0400567
568func registerCustomModuleForBp2buildConversion(ctx *android.TestContext) {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400569 ctx.RegisterModuleType("custom", customModuleFactoryHostAndDevice)
Liz Kammer32b77cf2021-08-04 15:17:02 -0400570 ctx.RegisterForBazelConversion()
571}
Liz Kammer7a210ac2021-09-22 15:52:58 -0400572
573func simpleModuleDoNotConvertBp2build(typ, name string) string {
574 return fmt.Sprintf(`
575%s {
576 name: "%s",
577 bazel_module: { bp2build_available: false },
578}`, typ, name)
579}
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500580
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000581type AttrNameToString map[string]string
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500582
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000583func (a AttrNameToString) clone() AttrNameToString {
584 newAttrs := make(AttrNameToString, len(a))
Liz Kammerdfeb1202022-05-13 17:20:20 -0400585 for k, v := range a {
586 newAttrs[k] = v
587 }
588 return newAttrs
589}
590
591// makeBazelTargetNoRestrictions returns bazel target build file definition that can be host or
592// device specific, or independent of host/device.
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000593func makeBazelTargetHostOrDevice(typ, name string, attrs AttrNameToString, hod android.HostOrDeviceSupported) string {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400594 if _, ok := attrs["target_compatible_with"]; !ok {
595 switch hod {
596 case android.HostSupported:
597 attrs["target_compatible_with"] = `select({
598 "//build/bazel/platforms/os:android": ["@platforms//:incompatible"],
599 "//conditions:default": [],
600 })`
601 case android.DeviceSupported:
602 attrs["target_compatible_with"] = `["//build/bazel/platforms/os:android"]`
603 }
604 }
605
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500606 attrStrings := make([]string, 0, len(attrs)+1)
Sasha Smundakfb589492022-08-04 11:13:27 -0700607 if name != "" {
608 attrStrings = append(attrStrings, fmt.Sprintf(` name = "%s",`, name))
609 }
Cole Faust18994c72023-02-28 16:02:16 -0800610 for _, k := range android.SortedKeys(attrs) {
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500611 attrStrings = append(attrStrings, fmt.Sprintf(" %s = %s,", k, attrs[k]))
612 }
613 return fmt.Sprintf(`%s(
614%s
615)`, typ, strings.Join(attrStrings, "\n"))
616}
Liz Kammerdfeb1202022-05-13 17:20:20 -0400617
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000618// MakeBazelTargetNoRestrictions returns bazel target build file definition that does not add a
Liz Kammerdfeb1202022-05-13 17:20:20 -0400619// target_compatible_with. This is useful for module types like filegroup and genrule that arch not
620// arch variant
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000621func MakeBazelTargetNoRestrictions(typ, name string, attrs AttrNameToString) string {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400622 return makeBazelTargetHostOrDevice(typ, name, attrs, android.HostAndDeviceDefault)
623}
624
625// makeBazelTargetNoRestrictions returns bazel target build file definition that is device specific
626// as this is the most common default in Soong.
Alixe06d75b2022-08-31 18:28:19 +0000627func MakeBazelTarget(typ, name string, attrs AttrNameToString) string {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400628 return makeBazelTargetHostOrDevice(typ, name, attrs, android.DeviceSupported)
629}
Sasha Smundak9d2f1742022-08-04 13:28:38 -0700630
631type ExpectedRuleTarget struct {
632 Rule string
633 Name string
634 Attrs AttrNameToString
635 Hod android.HostOrDeviceSupported
636}
637
638func (ebr ExpectedRuleTarget) String() string {
639 return makeBazelTargetHostOrDevice(ebr.Rule, ebr.Name, ebr.Attrs, ebr.Hod)
640}
Trevor Radcliffe087af542022-09-16 15:36:10 +0000641
642func makeCcStubSuiteTargets(name string, attrs AttrNameToString) string {
643 if _, hasStubs := attrs["stubs_symbol_file"]; !hasStubs {
644 return ""
645 }
646 STUB_SUITE_ATTRS := map[string]string{
Sam Delmerico5f906492023-03-15 18:06:18 -0400647 "stubs_symbol_file": "symbol_file",
648 "stubs_versions": "versions",
649 "soname": "soname",
650 "source_library_label": "source_library_label",
Trevor Radcliffe087af542022-09-16 15:36:10 +0000651 }
652
653 stubSuiteAttrs := AttrNameToString{}
654 for key, _ := range attrs {
655 if _, stubSuiteAttr := STUB_SUITE_ATTRS[key]; stubSuiteAttr {
656 stubSuiteAttrs[STUB_SUITE_ATTRS[key]] = attrs[key]
Sam Delmerico5f906492023-03-15 18:06:18 -0400657 } else {
658 panic(fmt.Sprintf("unused cc_stub_suite attr %q\n", key))
Trevor Radcliffe087af542022-09-16 15:36:10 +0000659 }
660 }
661 return MakeBazelTarget("cc_stub_suite", name+"_stub_libs", stubSuiteAttrs)
662}
Alix341484b2022-10-31 19:08:18 +0000663
664func MakeNeverlinkDuplicateTarget(moduleType string, name string) string {
Liz Kammer02914402023-08-07 13:38:18 -0400665 return MakeNeverlinkDuplicateTargetWithAttrs(moduleType, name, AttrNameToString{
666 "sdk_version": `"current"`, // use as default
667 })
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -0500668}
669
670func MakeNeverlinkDuplicateTargetWithAttrs(moduleType string, name string, extraAttrs AttrNameToString) string {
671 attrs := extraAttrs
672 attrs["neverlink"] = `True`
673 attrs["exports"] = `[":` + name + `"]`
674 return MakeBazelTarget(moduleType, name+"-neverlink", attrs)
Alix341484b2022-10-31 19:08:18 +0000675}
Zi Wangfba0a212023-03-07 16:48:19 -0800676
677func getTargetName(targetContent string) string {
678 data := strings.Split(targetContent, "name = \"")
679 if len(data) < 2 {
680 return ""
681 } else {
682 endIndex := strings.Index(data[1], "\"")
683 return data[1][:endIndex]
684 }
685}