blob: 89ef07bf8d9a1da40af1262162b0477e9f7f206e [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"
Chris Parsonse1f25232023-06-16 20:47:03 +000024 "path/filepath"
Zi Wangfba0a212023-03-07 16:48:19 -080025 "sort"
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000026 "strings"
Rupert Shuttleworth06559d02021-05-19 09:14:26 -040027 "testing"
28
Spandan Das5af0bd32022-09-28 20:43:08 +000029 "github.com/google/blueprint/proptools"
30
Liz Kammer2dd9ca42020-11-25 16:06:39 -080031 "android/soong/android"
Sam Delmerico24c56032022-03-28 19:53:03 +000032 "android/soong/android/allowlists"
Jingwen Chen73850672020-12-14 08:25:34 -050033 "android/soong/bazel"
Liz Kammer2dd9ca42020-11-25 16:06:39 -080034)
35
Jingwen Chen91220d72021-03-24 02:18:33 -040036var (
Rupert Shuttleworth06559d02021-05-19 09:14:26 -040037 buildDir string
Jingwen Chen91220d72021-03-24 02:18:33 -040038)
39
Jingwen Chen5146ac02021-09-02 11:44:42 +000040func 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 +000041 t.Helper()
Jingwen Chen5146ac02021-09-02 11:44:42 +000042
Jingwen Chen5146ac02021-09-02 11:44:42 +000043 if len(errs) != 1 {
Liz Kammer6eff3232021-08-26 08:37:59 -040044 return false
Jingwen Chen5146ac02021-09-02 11:44:42 +000045 }
Liz Kammer54309532021-12-14 12:21:22 -050046 if strings.Contains(errs[0].Error(), expectedErr.Error()) {
Jingwen Chen5146ac02021-09-02 11:44:42 +000047 return true
48 }
49
50 return false
51}
52
Sam Delmerico3177a6e2022-06-21 19:28:33 +000053func errored(t *testing.T, tc Bp2buildTestCase, errs []error) bool {
Jingwen Chen5146ac02021-09-02 11:44:42 +000054 t.Helper()
Sam Delmerico3177a6e2022-06-21 19:28:33 +000055 if tc.ExpectedErr != nil {
Jingwen Chen5146ac02021-09-02 11:44:42 +000056 // Rely on checkErrors, as this test case is expected to have an error.
57 return false
58 }
59
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000060 if len(errs) > 0 {
61 for _, err := range errs {
Sam Delmerico3177a6e2022-06-21 19:28:33 +000062 t.Errorf("%s: %s", tc.Description, err)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000063 }
64 return true
65 }
Jingwen Chen5146ac02021-09-02 11:44:42 +000066
67 // All good, continue execution.
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000068 return false
69}
70
Trevor Radcliffe1b4b2d92022-09-01 18:57:01 +000071func RunBp2BuildTestCaseSimple(t *testing.T, tc Bp2buildTestCase) {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000072 t.Helper()
Sam Delmerico3177a6e2022-06-21 19:28:33 +000073 RunBp2BuildTestCase(t, func(ctx android.RegistrationContext) {}, tc)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +000074}
75
Sam Delmerico3177a6e2022-06-21 19:28:33 +000076type Bp2buildTestCase struct {
77 Description string
78 ModuleTypeUnderTest string
79 ModuleTypeUnderTestFactory android.ModuleFactory
Sam Delmerico5840afc2023-06-12 15:44:03 -040080 // Text to add to the toplevel, root Android.bp file. If Dir is not set, all
81 // ExpectedBazelTargets are assumed to be generated by this file.
Chris Parsons39a16972023-06-08 14:28:51 +000082 Blueprint string
Sam Delmerico5840afc2023-06-12 15:44:03 -040083 // ExpectedBazelTargets compares the BazelTargets generated in `Dir` (if not empty).
84 // Otherwise, it checks the BazelTargets generated by `Blueprint` in the root directory.
85 ExpectedBazelTargets []string
Chris Parsonse1f25232023-06-16 20:47:03 +000086 // AlreadyExistingBuildContents, if non-empty, simulates an already-present source BUILD file
87 // in the directory under test. The BUILD file has the given contents. This BUILD file
88 // will also be treated as "BUILD file to keep" by the simulated bp2build environment.
89 AlreadyExistingBuildContents string
90
91 Filesystem map[string]string
Sam Delmerico5840afc2023-06-12 15:44:03 -040092 // Dir sets the directory which will be compared against the targets in ExpectedBazelTargets.
93 // This should used in conjunction with the Filesystem property to check for targets
94 // generated from a directory that is not the root.
95 // If not set, all ExpectedBazelTargets are assumed to be generated by the text in the
96 // Blueprint property.
97 Dir string
Trevor Radcliffe58ea4512022-04-07 20:36:39 +000098 // An error with a string contained within the string of the expected error
Sam Delmerico3177a6e2022-06-21 19:28:33 +000099 ExpectedErr error
100 UnconvertedDepsMode unconvertedDepsMode
Jingwen Chen0eeaeb82022-09-21 10:27:42 +0000101
102 // For every directory listed here, the BUILD file for that directory will
103 // be merged with the generated BUILD file. This allows custom BUILD targets
104 // to be used in tests, or use BUILD files to draw package boundaries.
105 KeepBuildFileForDirs []string
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000106}
107
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000108func RunBp2BuildTestCase(t *testing.T, registerModuleTypes func(ctx android.RegistrationContext), tc Bp2buildTestCase) {
Liz Kammerffc17e42022-11-23 09:42:05 -0500109 t.Helper()
Paul Duffin4c0765a2022-10-29 17:48:00 +0100110 bp2buildSetup := android.GroupFixturePreparers(
111 android.FixtureRegisterWithContext(registerModuleTypes),
112 SetBp2BuildTestRunner,
113 )
Spandan Das5af0bd32022-09-28 20:43:08 +0000114 runBp2BuildTestCaseWithSetup(t, bp2buildSetup, tc)
115}
116
117func RunApiBp2BuildTestCase(t *testing.T, registerModuleTypes func(ctx android.RegistrationContext), tc Bp2buildTestCase) {
Liz Kammerffc17e42022-11-23 09:42:05 -0500118 t.Helper()
Paul Duffin4c0765a2022-10-29 17:48:00 +0100119 apiBp2BuildSetup := android.GroupFixturePreparers(
120 android.FixtureRegisterWithContext(registerModuleTypes),
121 SetApiBp2BuildTestRunner,
122 )
Spandan Das5af0bd32022-09-28 20:43:08 +0000123 runBp2BuildTestCaseWithSetup(t, apiBp2BuildSetup, tc)
124}
125
Paul Duffin4c0765a2022-10-29 17:48:00 +0100126func 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 +0000127 t.Helper()
Chris Parsonse1f25232023-06-16 20:47:03 +0000128 checkDir := "."
129 if tc.Dir != "" {
130 checkDir = tc.Dir
131 }
132 keepExistingBuildDirs := tc.KeepBuildFileForDirs
133 buildFilesToParse := []string{}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000134 filesystem := make(map[string][]byte)
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000135 for f, content := range tc.Filesystem {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000136 filesystem[f] = []byte(content)
137 }
Chris Parsonse1f25232023-06-16 20:47:03 +0000138 if len(tc.AlreadyExistingBuildContents) > 0 {
139 buildFilePath := filepath.Join(checkDir, "BUILD")
140 filesystem[buildFilePath] = []byte(tc.AlreadyExistingBuildContents)
141 keepExistingBuildDirs = append(keepExistingBuildDirs, checkDir)
142 buildFilesToParse = append(buildFilesToParse, buildFilePath)
143 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000144
Paul Duffin4c0765a2022-10-29 17:48:00 +0100145 preparers := []android.FixturePreparer{
146 extraPreparer,
147 android.FixtureMergeMockFs(filesystem),
148 android.FixtureWithRootAndroidBp(tc.Blueprint),
149 android.FixtureRegisterWithContext(func(ctx android.RegistrationContext) {
150 ctx.RegisterModuleType(tc.ModuleTypeUnderTest, tc.ModuleTypeUnderTestFactory)
151 }),
Chris Parsonse1f25232023-06-16 20:47:03 +0000152 android.FixtureModifyContextWithMockFs(func(ctx *android.TestContext) {
Paul Duffin4c0765a2022-10-29 17:48:00 +0100153 // A default configuration for tests to not have to specify bp2build_available on top level
154 // targets.
155 bp2buildConfig := android.NewBp2BuildAllowlist().SetDefaultConfig(
156 allowlists.Bp2BuildConfig{
157 android.Bp2BuildTopLevel: allowlists.Bp2BuildDefaultTrueRecursively,
158 },
159 )
Chris Parsonse1f25232023-06-16 20:47:03 +0000160 for _, f := range keepExistingBuildDirs {
Paul Duffin4c0765a2022-10-29 17:48:00 +0100161 bp2buildConfig.SetKeepExistingBuildFile(map[string]bool{
162 f: /*recursive=*/ false,
163 })
164 }
165 ctx.RegisterBp2BuildConfig(bp2buildConfig)
Chris Parsons39a16972023-06-08 14:28:51 +0000166 // This setting is added to bp2build invocations. It prevents bp2build
167 // from cloning modules to their original state after mutators run. This
168 // would lose some data intentionally set by these mutators.
169 ctx.SkipCloneModulesAfterMutators = true
Chris Parsonse1f25232023-06-16 20:47:03 +0000170 err := ctx.ParseBuildFiles(".", buildFilesToParse)
171 if err != nil {
172 t.Errorf("error parsing build files in test setup: %s", err)
173 }
Paul Duffin4c0765a2022-10-29 17:48:00 +0100174 }),
175 android.FixtureModifyEnv(func(env map[string]string) {
176 if tc.UnconvertedDepsMode == errorModulesUnconvertedDeps {
177 env["BP2BUILD_ERROR_UNCONVERTED"] = "true"
178 }
179 }),
Jingwen Chen5146ac02021-09-02 11:44:42 +0000180 }
181
Paul Duffin4c0765a2022-10-29 17:48:00 +0100182 preparer := android.GroupFixturePreparers(preparers...)
183 if tc.ExpectedErr != nil {
184 pattern := "\\Q" + tc.ExpectedErr.Error() + "\\E"
185 preparer = preparer.ExtendWithErrorHandler(android.FixtureExpectsOneErrorPattern(pattern))
186 }
187 result := preparer.RunTestWithCustomResult(t).(*BazelTestResult)
188 if len(result.Errs) > 0 {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000189 return
190 }
191
Paul Duffin4c0765a2022-10-29 17:48:00 +0100192 expectedTargets := map[string][]string{
193 checkDir: tc.ExpectedBazelTargets,
Liz Kammer6eff3232021-08-26 08:37:59 -0400194 }
Paul Duffin4c0765a2022-10-29 17:48:00 +0100195
196 result.CompareAllBazelTargets(t, tc.Description, expectedTargets, true)
197}
198
199// SetBp2BuildTestRunner customizes the test fixture mechanism to run tests in Bp2Build mode.
200var SetBp2BuildTestRunner = android.FixtureSetTestRunner(&bazelTestRunner{Bp2Build})
201
202// SetApiBp2BuildTestRunner customizes the test fixture mechanism to run tests in ApiBp2build mode.
203var SetApiBp2BuildTestRunner = android.FixtureSetTestRunner(&bazelTestRunner{ApiBp2build})
204
205// bazelTestRunner customizes the test fixture mechanism to run tests of the bp2build and
206// apiBp2build build modes.
207type bazelTestRunner struct {
208 mode CodegenMode
209}
210
211func (b *bazelTestRunner) FinalPreparer(result *android.TestResult) android.CustomTestResult {
212 ctx := result.TestContext
213 switch b.mode {
214 case Bp2Build:
215 ctx.RegisterForBazelConversion()
216 case ApiBp2build:
217 ctx.RegisterForApiBazelConversion()
218 default:
219 panic(fmt.Errorf("unknown build mode: %d", b.mode))
220 }
221
222 return &BazelTestResult{TestResult: result}
223}
224
225func (b *bazelTestRunner) PostParseProcessor(result android.CustomTestResult) {
226 bazelResult := result.(*BazelTestResult)
227 ctx := bazelResult.TestContext
228 config := bazelResult.Config
229 _, errs := ctx.ResolveDependencies(config)
230 if bazelResult.CollateErrs(errs) {
231 return
232 }
233
Chris Parsons39a16972023-06-08 14:28:51 +0000234 codegenMode := Bp2Build
235 if ctx.Config().BuildMode == android.ApiBp2build {
236 codegenMode = ApiBp2build
237 }
238 codegenCtx := NewCodegenContext(config, ctx.Context, codegenMode, "")
Paul Duffin4c0765a2022-10-29 17:48:00 +0100239 res, errs := GenerateBazelTargets(codegenCtx, false)
240 if bazelResult.CollateErrs(errs) {
241 return
242 }
243
244 // Store additional data for access by tests.
245 bazelResult.conversionResults = res
246}
247
248// BazelTestResult is a wrapper around android.TestResult to provide type safe access to the bazel
249// specific data stored by the bazelTestRunner.
250type BazelTestResult struct {
251 *android.TestResult
252
253 // The result returned by the GenerateBazelTargets function.
254 conversionResults
255}
256
257// CompareAllBazelTargets compares the BazelTargets produced by the test for all the directories
258// with the supplied set of expected targets.
259//
260// If ignoreUnexpected=false then this enforces an exact match where every BazelTarget produced must
261// have a corresponding expected BazelTarget.
262//
263// If ignoreUnexpected=true then it will ignore directories for which there are no expected targets.
264func (b BazelTestResult) CompareAllBazelTargets(t *testing.T, description string, expectedTargets map[string][]string, ignoreUnexpected bool) {
Liz Kammer2b3f56e2023-03-23 11:51:49 -0400265 t.Helper()
Paul Duffin4c0765a2022-10-29 17:48:00 +0100266 actualTargets := b.buildFileToTargets
267
268 // Generate the sorted set of directories to check.
Cole Faust18994c72023-02-28 16:02:16 -0800269 dirsToCheck := android.SortedKeys(expectedTargets)
Paul Duffin4c0765a2022-10-29 17:48:00 +0100270 if !ignoreUnexpected {
271 // This needs to perform an exact match so add the directories in which targets were
272 // produced to the list of directories to check.
Cole Faust18994c72023-02-28 16:02:16 -0800273 dirsToCheck = append(dirsToCheck, android.SortedKeys(actualTargets)...)
Paul Duffin4c0765a2022-10-29 17:48:00 +0100274 dirsToCheck = android.SortedUniqueStrings(dirsToCheck)
275 }
276
277 for _, dir := range dirsToCheck {
278 expected := expectedTargets[dir]
279 actual := actualTargets[dir]
280
281 if expected == nil {
282 if actual != nil {
283 t.Errorf("did not expect any bazel modules in %q but found %d", dir, len(actual))
284 }
285 } else if actual == nil {
286 expectedCount := len(expected)
287 if expectedCount > 0 {
288 t.Errorf("expected %d bazel modules in %q but did not find any", expectedCount, dir)
289 }
290 } else {
291 b.CompareBazelTargets(t, description, expected, actual)
292 }
293 }
294}
295
296func (b BazelTestResult) CompareBazelTargets(t *testing.T, description string, expectedContents []string, actualTargets BazelTargets) {
Liz Kammer748d7072023-01-25 12:07:43 -0500297 t.Helper()
Paul Duffin4c0765a2022-10-29 17:48:00 +0100298 if actualCount, expectedCount := len(actualTargets), len(expectedContents); actualCount != expectedCount {
Sasha Smundak9d2f1742022-08-04 13:28:38 -0700299 t.Errorf("%s: Expected %d bazel target (%s), got %d (%s)",
Paul Duffin4c0765a2022-10-29 17:48:00 +0100300 description, expectedCount, expectedContents, actualCount, actualTargets)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000301 } else {
Zi Wangfba0a212023-03-07 16:48:19 -0800302 sort.SliceStable(actualTargets, func(i, j int) bool {
303 return actualTargets[i].name < actualTargets[j].name
304 })
305 sort.SliceStable(expectedContents, func(i, j int) bool {
306 return getTargetName(expectedContents[i]) < getTargetName(expectedContents[j])
307 })
Paul Duffin4c0765a2022-10-29 17:48:00 +0100308 for i, actualTarget := range actualTargets {
309 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 +0000310 t.Errorf(
Paul Duffin4c0765a2022-10-29 17:48:00 +0100311 "%s[%d]: Expected generated Bazel target to be `%s`, got `%s`",
312 description, i, w, g)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux1c92aef2021-08-23 16:10:00 +0000313 }
314 }
315 }
316}
317
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800318type nestedProps struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500319 Nested_prop *string
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800320}
321
Liz Kammer32a03392021-09-14 11:17:21 -0400322type EmbeddedProps struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500323 Embedded_prop *string
Liz Kammer32a03392021-09-14 11:17:21 -0400324}
325
326type OtherEmbeddedProps struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500327 Other_embedded_prop *string
Liz Kammer32a03392021-09-14 11:17:21 -0400328}
329
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800330type customProps struct {
Liz Kammer32a03392021-09-14 11:17:21 -0400331 EmbeddedProps
332 *OtherEmbeddedProps
333
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800334 Bool_prop bool
335 Bool_ptr_prop *bool
336 // 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 +0000337 Int_prop int `blueprint:"mutated"`
338 Int64_ptr_prop *int64
339 String_prop string
340 String_literal_prop *string `android:"arch_variant"`
341 String_ptr_prop *string
342 String_list_prop []string
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800343
344 Nested_props nestedProps
345 Nested_props_ptr *nestedProps
Liz Kammer4562a3b2021-04-21 18:15:34 -0400346
Liz Kammer32b77cf2021-08-04 15:17:02 -0400347 Arch_paths []string `android:"path,arch_variant"`
348 Arch_paths_exclude []string `android:"path,arch_variant"`
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400349
350 // Prop used to indicate this conversion should be 1 module -> multiple targets
351 One_to_many_prop *bool
Spandan Das5af0bd32022-09-28 20:43:08 +0000352
353 Api *string // File describing the APIs of this module
Spandan Das6a448ec2023-04-19 17:36:12 +0000354
355 Test_config_setting *bool // Used to test generation of config_setting targets
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800356}
357
358type customModule struct {
359 android.ModuleBase
Liz Kammerea6666f2021-02-17 10:17:28 -0500360 android.BazelModuleBase
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800361
362 props customProps
363}
364
365// OutputFiles is needed because some instances of this module use dist with a
366// tag property which requires the module implements OutputFileProducer.
367func (m *customModule) OutputFiles(tag string) (android.Paths, error) {
368 return android.PathsForTesting("path" + tag), nil
369}
370
371func (m *customModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
372 // nothing for now.
373}
374
375func customModuleFactoryBase() android.Module {
376 module := &customModule{}
377 module.AddProperties(&module.props)
Liz Kammerea6666f2021-02-17 10:17:28 -0500378 android.InitBazelModule(module)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800379 return module
380}
381
Liz Kammerdfeb1202022-05-13 17:20:20 -0400382func customModuleFactoryHostAndDevice() android.Module {
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800383 m := customModuleFactoryBase()
Liz Kammer4562a3b2021-04-21 18:15:34 -0400384 android.InitAndroidArchModule(m, android.HostAndDeviceSupported, android.MultilibBoth)
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800385 return m
386}
387
Liz Kammerdfeb1202022-05-13 17:20:20 -0400388func customModuleFactoryDeviceSupported() android.Module {
389 m := customModuleFactoryBase()
390 android.InitAndroidArchModule(m, android.DeviceSupported, android.MultilibBoth)
391 return m
392}
393
394func customModuleFactoryHostSupported() android.Module {
395 m := customModuleFactoryBase()
396 android.InitAndroidArchModule(m, android.HostSupported, android.MultilibBoth)
397 return m
398}
399
400func customModuleFactoryHostAndDeviceDefault() android.Module {
401 m := customModuleFactoryBase()
402 android.InitAndroidArchModule(m, android.HostAndDeviceDefault, android.MultilibBoth)
403 return m
404}
405
406func customModuleFactoryNeitherHostNorDeviceSupported() android.Module {
407 m := customModuleFactoryBase()
408 android.InitAndroidArchModule(m, android.NeitherHostNorDeviceSupported, android.MultilibBoth)
409 return m
410}
411
Liz Kammer2dd9ca42020-11-25 16:06:39 -0800412type testProps struct {
413 Test_prop struct {
414 Test_string_prop string
415 }
416}
417
418type customTestModule struct {
419 android.ModuleBase
420
421 props customProps
422 test_props testProps
423}
424
425func (m *customTestModule) GenerateAndroidBuildActions(ctx android.ModuleContext) {
426 // nothing for now.
427}
428
429func customTestModuleFactoryBase() android.Module {
430 m := &customTestModule{}
431 m.AddProperties(&m.props)
432 m.AddProperties(&m.test_props)
433 return m
434}
435
436func customTestModuleFactory() android.Module {
437 m := customTestModuleFactoryBase()
438 android.InitAndroidModule(m)
439 return m
440}
441
442type customDefaultsModule struct {
443 android.ModuleBase
444 android.DefaultsModuleBase
445}
446
447func customDefaultsModuleFactoryBase() android.DefaultsModule {
448 module := &customDefaultsModule{}
449 module.AddProperties(&customProps{})
450 return module
451}
452
453func customDefaultsModuleFactoryBasic() android.Module {
454 return customDefaultsModuleFactoryBase()
455}
456
457func customDefaultsModuleFactory() android.Module {
458 m := customDefaultsModuleFactoryBase()
459 android.InitDefaultsModule(m)
460 return m
461}
Jingwen Chen73850672020-12-14 08:25:34 -0500462
Liz Kammer32a03392021-09-14 11:17:21 -0400463type EmbeddedAttr struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500464 Embedded_attr *string
Liz Kammer32a03392021-09-14 11:17:21 -0400465}
466
467type OtherEmbeddedAttr struct {
Liz Kammer46fb7ab2021-12-01 10:09:34 -0500468 Other_embedded_attr *string
Liz Kammer32a03392021-09-14 11:17:21 -0400469}
470
Jingwen Chen73850672020-12-14 08:25:34 -0500471type customBazelModuleAttributes struct {
Liz Kammer32a03392021-09-14 11:17:21 -0400472 EmbeddedAttr
473 *OtherEmbeddedAttr
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000474 String_literal_prop bazel.StringAttribute
475 String_ptr_prop *string
476 String_list_prop []string
477 Arch_paths bazel.LabelListAttribute
Spandan Das5af0bd32022-09-28 20:43:08 +0000478 Api bazel.LabelAttribute
Jingwen Chen73850672020-12-14 08:25:34 -0500479}
480
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400481func (m *customModule) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400482 if p := m.props.One_to_many_prop; p != nil && *p {
483 customBp2buildOneToMany(ctx, m)
484 return
485 }
Liz Kammer4562a3b2021-04-21 18:15:34 -0400486
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000487 paths := bazel.LabelListAttribute{}
488 strAttr := bazel.StringAttribute{}
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400489 for axis, configToProps := range m.GetArchVariantProperties(ctx, &customProps{}) {
490 for config, props := range configToProps {
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000491 if custProps, ok := props.(*customProps); ok {
492 if custProps.Arch_paths != nil {
493 paths.SetSelectValue(axis, config, android.BazelLabelForModuleSrcExcludes(ctx, custProps.Arch_paths, custProps.Arch_paths_exclude))
494 }
495 if custProps.String_literal_prop != nil {
496 strAttr.SetSelectValue(axis, config, custProps.String_literal_prop)
497 }
Liz Kammer4562a3b2021-04-21 18:15:34 -0400498 }
499 }
Jingwen Chen73850672020-12-14 08:25:34 -0500500 }
Cole Faust912bc882023-03-08 12:29:50 -0800501 productVariableProps := android.ProductVariableProperties(ctx, ctx.Module())
Liz Kammer9d2d4102022-12-21 14:51:37 -0500502 if props, ok := productVariableProps["String_literal_prop"]; ok {
503 for c, p := range props {
504 if val, ok := p.(*string); ok {
505 strAttr.SetSelectValue(c.ConfigurationAxis(), c.SelectKey(), val)
506 }
507 }
508 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400509
510 paths.ResolveExcludes()
511
512 attrs := &customBazelModuleAttributes{
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000513 String_literal_prop: strAttr,
514 String_ptr_prop: m.props.String_ptr_prop,
515 String_list_prop: m.props.String_list_prop,
516 Arch_paths: paths,
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400517 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux3a019a62022-06-23 16:02:44 +0000518
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400519 attrs.Embedded_attr = m.props.Embedded_prop
520 if m.props.OtherEmbeddedProps != nil {
521 attrs.OtherEmbeddedAttr = &OtherEmbeddedAttr{Other_embedded_attr: m.props.OtherEmbeddedProps.Other_embedded_prop}
522 }
523
524 props := bazel.BazelTargetModuleProperties{
525 Rule_class: "custom",
526 }
527
528 ctx.CreateBazelTargetModule(props, android.CommonAttributes{Name: m.Name()}, attrs)
Spandan Das6a448ec2023-04-19 17:36:12 +0000529
530 if proptools.Bool(m.props.Test_config_setting) {
531 m.createConfigSetting(ctx)
532 }
533
534}
535
536func (m *customModule) createConfigSetting(ctx android.TopDownMutatorContext) {
537 csa := bazel.ConfigSettingAttributes{
538 Flag_values: bazel.StringMapAttribute{
539 "//build/bazel/rules/my_string_setting": m.Name(),
540 },
541 }
542 ca := android.CommonAttributes{
543 Name: m.Name() + "_config_setting",
544 }
545 ctx.CreateBazelConfigSetting(
546 csa,
547 ca,
548 ctx.ModuleDir(),
549 )
Jingwen Chen73850672020-12-14 08:25:34 -0500550}
Jingwen Chen40067de2021-01-26 21:58:43 -0500551
Spandan Das5af0bd32022-09-28 20:43:08 +0000552var _ android.ApiProvider = (*customModule)(nil)
553
554func (c *customModule) ConvertWithApiBp2build(ctx android.TopDownMutatorContext) {
555 props := bazel.BazelTargetModuleProperties{
556 Rule_class: "custom_api_contribution",
557 }
558 apiAttribute := bazel.MakeLabelAttribute(
559 android.BazelLabelForModuleSrcSingle(ctx, proptools.String(c.props.Api)).Label,
560 )
561 attrs := &customBazelModuleAttributes{
562 Api: *apiAttribute,
563 }
564 ctx.CreateBazelTargetModule(props,
565 android.CommonAttributes{Name: c.Name()},
566 attrs)
567}
568
Jingwen Chen40067de2021-01-26 21:58:43 -0500569// A bp2build mutator that uses load statements and creates a 1:M mapping from
570// module to target.
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400571func customBp2buildOneToMany(ctx android.TopDownMutatorContext, m *customModule) {
Jingwen Chen77e8b7b2021-02-05 03:03:24 -0500572
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400573 baseName := m.Name()
574 attrs := &customBazelModuleAttributes{}
Jingwen Chen1fd14692021-02-05 03:01:50 -0500575
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400576 myLibraryProps := bazel.BazelTargetModuleProperties{
577 Rule_class: "my_library",
578 Bzl_load_location: "//build/bazel/rules:rules.bzl",
Jingwen Chen40067de2021-01-26 21:58:43 -0500579 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400580 ctx.CreateBazelTargetModule(myLibraryProps, android.CommonAttributes{Name: baseName}, attrs)
581
582 protoLibraryProps := bazel.BazelTargetModuleProperties{
583 Rule_class: "proto_library",
584 Bzl_load_location: "//build/bazel/rules:proto.bzl",
585 }
586 ctx.CreateBazelTargetModule(protoLibraryProps, android.CommonAttributes{Name: baseName + "_proto_library_deps"}, attrs)
587
588 myProtoLibraryProps := bazel.BazelTargetModuleProperties{
589 Rule_class: "my_proto_library",
590 Bzl_load_location: "//build/bazel/rules:proto.bzl",
591 }
592 ctx.CreateBazelTargetModule(myProtoLibraryProps, android.CommonAttributes{Name: baseName + "_my_proto_library_deps"}, attrs)
Jingwen Chen40067de2021-01-26 21:58:43 -0500593}
Jingwen Chenba369ad2021-02-22 10:19:34 -0500594
595// Helper method for tests to easily access the targets in a dir.
Liz Kammer6eff3232021-08-26 08:37:59 -0400596func generateBazelTargetsForDir(codegenCtx *CodegenContext, dir string) (BazelTargets, []error) {
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400597 // TODO: Set generateFilegroups to true and/or remove the generateFilegroups argument completely
Liz Kammer6eff3232021-08-26 08:37:59 -0400598 res, err := GenerateBazelTargets(codegenCtx, false)
Alix94e26032022-08-16 20:37:33 +0000599 if err != nil {
600 return BazelTargets{}, err
601 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400602 return res.buildFileToTargets[dir], err
Jingwen Chenba369ad2021-02-22 10:19:34 -0500603}
Liz Kammer32b77cf2021-08-04 15:17:02 -0400604
605func registerCustomModuleForBp2buildConversion(ctx *android.TestContext) {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400606 ctx.RegisterModuleType("custom", customModuleFactoryHostAndDevice)
Liz Kammer32b77cf2021-08-04 15:17:02 -0400607 ctx.RegisterForBazelConversion()
608}
Liz Kammer7a210ac2021-09-22 15:52:58 -0400609
610func simpleModuleDoNotConvertBp2build(typ, name string) string {
611 return fmt.Sprintf(`
612%s {
613 name: "%s",
614 bazel_module: { bp2build_available: false },
615}`, typ, name)
616}
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500617
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000618type AttrNameToString map[string]string
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500619
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000620func (a AttrNameToString) clone() AttrNameToString {
621 newAttrs := make(AttrNameToString, len(a))
Liz Kammerdfeb1202022-05-13 17:20:20 -0400622 for k, v := range a {
623 newAttrs[k] = v
624 }
625 return newAttrs
626}
627
628// makeBazelTargetNoRestrictions returns bazel target build file definition that can be host or
629// device specific, or independent of host/device.
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000630func makeBazelTargetHostOrDevice(typ, name string, attrs AttrNameToString, hod android.HostOrDeviceSupported) string {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400631 if _, ok := attrs["target_compatible_with"]; !ok {
632 switch hod {
633 case android.HostSupported:
634 attrs["target_compatible_with"] = `select({
635 "//build/bazel/platforms/os:android": ["@platforms//:incompatible"],
636 "//conditions:default": [],
637 })`
638 case android.DeviceSupported:
639 attrs["target_compatible_with"] = `["//build/bazel/platforms/os:android"]`
640 }
641 }
642
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500643 attrStrings := make([]string, 0, len(attrs)+1)
Sasha Smundakfb589492022-08-04 11:13:27 -0700644 if name != "" {
645 attrStrings = append(attrStrings, fmt.Sprintf(` name = "%s",`, name))
646 }
Cole Faust18994c72023-02-28 16:02:16 -0800647 for _, k := range android.SortedKeys(attrs) {
Liz Kammer78cfdaa2021-11-08 12:56:31 -0500648 attrStrings = append(attrStrings, fmt.Sprintf(" %s = %s,", k, attrs[k]))
649 }
650 return fmt.Sprintf(`%s(
651%s
652)`, typ, strings.Join(attrStrings, "\n"))
653}
Liz Kammerdfeb1202022-05-13 17:20:20 -0400654
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000655// MakeBazelTargetNoRestrictions returns bazel target build file definition that does not add a
Liz Kammerdfeb1202022-05-13 17:20:20 -0400656// target_compatible_with. This is useful for module types like filegroup and genrule that arch not
657// arch variant
Sam Delmerico3177a6e2022-06-21 19:28:33 +0000658func MakeBazelTargetNoRestrictions(typ, name string, attrs AttrNameToString) string {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400659 return makeBazelTargetHostOrDevice(typ, name, attrs, android.HostAndDeviceDefault)
660}
661
662// makeBazelTargetNoRestrictions returns bazel target build file definition that is device specific
663// as this is the most common default in Soong.
Alixe06d75b2022-08-31 18:28:19 +0000664func MakeBazelTarget(typ, name string, attrs AttrNameToString) string {
Liz Kammerdfeb1202022-05-13 17:20:20 -0400665 return makeBazelTargetHostOrDevice(typ, name, attrs, android.DeviceSupported)
666}
Sasha Smundak9d2f1742022-08-04 13:28:38 -0700667
668type ExpectedRuleTarget struct {
669 Rule string
670 Name string
671 Attrs AttrNameToString
672 Hod android.HostOrDeviceSupported
673}
674
675func (ebr ExpectedRuleTarget) String() string {
676 return makeBazelTargetHostOrDevice(ebr.Rule, ebr.Name, ebr.Attrs, ebr.Hod)
677}
Trevor Radcliffe087af542022-09-16 15:36:10 +0000678
679func makeCcStubSuiteTargets(name string, attrs AttrNameToString) string {
680 if _, hasStubs := attrs["stubs_symbol_file"]; !hasStubs {
681 return ""
682 }
683 STUB_SUITE_ATTRS := map[string]string{
Sam Delmerico5f906492023-03-15 18:06:18 -0400684 "stubs_symbol_file": "symbol_file",
685 "stubs_versions": "versions",
686 "soname": "soname",
687 "source_library_label": "source_library_label",
Trevor Radcliffe087af542022-09-16 15:36:10 +0000688 }
689
690 stubSuiteAttrs := AttrNameToString{}
691 for key, _ := range attrs {
692 if _, stubSuiteAttr := STUB_SUITE_ATTRS[key]; stubSuiteAttr {
693 stubSuiteAttrs[STUB_SUITE_ATTRS[key]] = attrs[key]
Sam Delmerico5f906492023-03-15 18:06:18 -0400694 } else {
695 panic(fmt.Sprintf("unused cc_stub_suite attr %q\n", key))
Trevor Radcliffe087af542022-09-16 15:36:10 +0000696 }
697 }
698 return MakeBazelTarget("cc_stub_suite", name+"_stub_libs", stubSuiteAttrs)
699}
Alix341484b2022-10-31 19:08:18 +0000700
701func MakeNeverlinkDuplicateTarget(moduleType string, name string) string {
Romain Jobredeaux2eef2e12023-02-24 12:07:08 -0500702 return MakeNeverlinkDuplicateTargetWithAttrs(moduleType, name, AttrNameToString{})
703}
704
705func MakeNeverlinkDuplicateTargetWithAttrs(moduleType string, name string, extraAttrs AttrNameToString) string {
706 attrs := extraAttrs
707 attrs["neverlink"] = `True`
708 attrs["exports"] = `[":` + name + `"]`
709 return MakeBazelTarget(moduleType, name+"-neverlink", attrs)
Alix341484b2022-10-31 19:08:18 +0000710}
Zi Wangfba0a212023-03-07 16:48:19 -0800711
712func getTargetName(targetContent string) string {
713 data := strings.Split(targetContent, "name = \"")
714 if len(data) < 2 {
715 return ""
716 } else {
717 endIndex := strings.Index(data[1], "\"")
718 return data[1][:endIndex]
719 }
720}