blob: e631ed474e732f33bbb7b9caaf6c8c63b089ca6c [file] [log] [blame]
Liz Kammerea6666f2021-02-17 10:17:28 -05001// 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
15package android
16
Liz Kammerba3ea162021-02-17 13:22:03 -050017import (
Wei Libafb6d62021-12-10 03:14:59 -080018 "bufio"
19 "errors"
Liz Kammerba3ea162021-02-17 13:22:03 -050020 "strings"
21
Liz Kammerbdc60992021-02-24 16:55:11 -050022 "github.com/google/blueprint"
Liz Kammerba3ea162021-02-17 13:22:03 -050023 "github.com/google/blueprint/proptools"
Sam Delmerico24c56032022-03-28 19:53:03 +000024
25 "android/soong/android/allowlists"
26)
27
28const (
29 // A sentinel value to be used as a key in Bp2BuildConfig for modules with
30 // no package path. This is also the module dir for top level Android.bp
31 // modules.
32 Bp2BuildTopLevel = "."
Liz Kammerba3ea162021-02-17 13:22:03 -050033)
34
MarkDacekf47e1422023-04-19 16:47:36 +000035type MixedBuildEnabledStatus int
36
37const (
38 // This module can be mixed_built.
39 MixedBuildEnabled = iota
40
41 // There is a technical incompatibility preventing this module from being
42 // bazel-analyzed. Note: the module might also be incompatible.
43 TechnicalIncompatibility
44
45 // This module cannot be mixed_built due to some incompatibility with it
46 // that is not a platform incompatibility. Example: the module-type is not
47 // enabled, or is not bp2build-converted.
48 ModuleIncompatibility
Liz Kammerc13f7852023-05-17 13:01:48 -040049
50 // Missing dependencies. We can't query Bazel for modules if it has missing dependencies, there
51 // will be failures.
52 ModuleMissingDeps
MarkDacekf47e1422023-04-19 16:47:36 +000053)
54
Yu Liu2aa806b2022-09-01 11:54:47 -070055// FileGroupAsLibrary describes a filegroup module that is converted to some library
56// such as aidl_library or proto_library.
57type FileGroupAsLibrary interface {
Vinh Tran444154d2022-08-16 13:10:31 -040058 ShouldConvertToAidlLibrary(ctx BazelConversionPathContext) bool
Yu Liu2aa806b2022-09-01 11:54:47 -070059 ShouldConvertToProtoLibrary(ctx BazelConversionPathContext) bool
Vinh Tran444154d2022-08-16 13:10:31 -040060 GetAidlLibraryLabel(ctx BazelConversionPathContext) string
Yu Liu2aa806b2022-09-01 11:54:47 -070061 GetProtoLibraryLabel(ctx BazelConversionPathContext) string
Vinh Tran444154d2022-08-16 13:10:31 -040062}
63
Sasha Smundaka0954062022-08-02 18:23:58 -070064type BazelConversionStatus struct {
65 // Information about _all_ bp2build targets generated by this module. Multiple targets are
66 // supported as Soong handles some things within a single target that we may choose to split into
67 // multiple targets, e.g. renderscript, protos, yacc within a cc module.
68 Bp2buildInfo []bp2buildInfo `blueprint:"mutated"`
69
70 // UnconvertedBp2buildDep stores the module names of direct dependency that were not converted to
71 // Bazel
72 UnconvertedDeps []string `blueprint:"mutated"`
73
74 // MissingBp2buildDep stores the module names of direct dependency that were not found
75 MissingDeps []string `blueprint:"mutated"`
76}
77
Romain Jobredeaux8242b432023-05-04 10:16:26 -040078type BazelModuleProperties struct {
Jingwen Chen01812022021-11-19 14:29:43 +000079 // The label of the Bazel target replacing this Soong module. When run in conversion mode, this
80 // will import the handcrafted build target into the autogenerated file. Note: this may result in
81 // a conflict due to duplicate targets if bp2build_available is also set.
82 Label *string
83
84 // If true, bp2build will generate the converted Bazel target for this module. Note: this may
85 // cause a conflict due to the duplicate targets if label is also set.
86 //
87 // This is a bool pointer to support tristates: true, false, not set.
88 //
Sasha Smundak39a301c2022-12-29 17:11:49 -080089 // To opt in a module, set bazel_module: { bp2build_available: true }
90 // To opt out a module, set bazel_module: { bp2build_available: false }
Jingwen Chen01812022021-11-19 14:29:43 +000091 // To defer the default setting for the directory, do not set the value.
92 Bp2build_available *bool
Liz Kammerbe46fcc2021-11-01 15:32:43 -040093
94 // CanConvertToBazel is set via InitBazelModule to indicate that a module type can be converted to
95 // Bazel with Bp2build.
96 CanConvertToBazel bool `blueprint:"mutated"`
Jingwen Chen01812022021-11-19 14:29:43 +000097}
98
Liz Kammerba3ea162021-02-17 13:22:03 -050099// Properties contains common module properties for Bazel migration purposes.
100type properties struct {
Chris Parsons1bb58da2022-08-30 13:37:57 -0400101 // In "Bazel mixed build" mode, this represents the Bazel target replacing
Liz Kammerba3ea162021-02-17 13:22:03 -0500102 // this Soong module.
Romain Jobredeaux8242b432023-05-04 10:16:26 -0400103 Bazel_module BazelModuleProperties
Liz Kammerba3ea162021-02-17 13:22:03 -0500104}
Liz Kammerea6666f2021-02-17 10:17:28 -0500105
Jingwen Chen25825ca2021-11-15 12:28:43 +0000106// namespacedVariableProperties is a map from a string representing a Soong
Jingwen Chen84817de2021-11-17 10:57:35 +0000107// config variable namespace, like "android" or "vendor_name" to a slice of
108// pointer to a struct containing a single field called Soong_config_variables
109// whose value mirrors the structure in the Blueprint file.
110type namespacedVariableProperties map[string][]interface{}
Jingwen Chena47f28d2021-11-02 16:43:57 +0000111
Liz Kammerea6666f2021-02-17 10:17:28 -0500112// BazelModuleBase contains the property structs with metadata for modules which can be converted to
113// Bazel.
114type BazelModuleBase struct {
Liz Kammerba3ea162021-02-17 13:22:03 -0500115 bazelProperties properties
Jingwen Chena47f28d2021-11-02 16:43:57 +0000116
117 // namespacedVariableProperties is used for soong_config_module_type support
118 // in bp2build. Soong config modules allow users to set module properties
119 // based on custom product variables defined in Android.bp files. These
120 // variables are namespaced to prevent clobbering, especially when set from
121 // Makefiles.
122 namespacedVariableProperties namespacedVariableProperties
123
124 // baseModuleType is set when this module was created from a module type
125 // defined by a soong_config_module_type. Every soong_config_module_type
126 // "wraps" another module type, e.g. a soong_config_module_type can wrap a
127 // cc_defaults to a custom_cc_defaults, or cc_binary to a custom_cc_binary.
128 // This baseModuleType is set to the wrapped module type.
129 baseModuleType string
Liz Kammerea6666f2021-02-17 10:17:28 -0500130}
131
132// Bazelable is specifies the interface for modules that can be converted to Bazel.
133type Bazelable interface {
Liz Kammerba3ea162021-02-17 13:22:03 -0500134 bazelProps() *properties
135 HasHandcraftedLabel() bool
Liz Kammerbdc60992021-02-24 16:55:11 -0500136 HandcraftedLabel() string
137 GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400138 ShouldConvertWithBp2build(ctx BazelConversionContext) bool
Sam Delmerico24c56032022-03-28 19:53:03 +0000139 shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400140 ConvertWithBp2build(ctx TopDownMutatorContext)
Jingwen Chena47f28d2021-11-02 16:43:57 +0000141
Jingwen Chen84817de2021-11-17 10:57:35 +0000142 // namespacedVariableProps is a map from a soong config variable namespace
143 // (e.g. acme, android) to a map of interfaces{}, which are really
144 // reflect.Struct pointers, representing the value of the
145 // soong_config_variables property of a module. The struct pointer is the
146 // one with the single member called Soong_config_variables, which itself is
147 // a struct containing fields for each supported feature in that namespace.
148 //
Sasha Smundak39a301c2022-12-29 17:11:49 -0800149 // The reason for using a slice of interface{} is to support defaults
Jingwen Chen84817de2021-11-17 10:57:35 +0000150 // propagation of the struct pointers.
Jingwen Chena47f28d2021-11-02 16:43:57 +0000151 namespacedVariableProps() namespacedVariableProperties
152 setNamespacedVariableProps(props namespacedVariableProperties)
153 BaseModuleType() string
Jingwen Chen84817de2021-11-17 10:57:35 +0000154 SetBaseModuleType(baseModuleType string)
Liz Kammerea6666f2021-02-17 10:17:28 -0500155}
156
Spandan Das5af0bd32022-09-28 20:43:08 +0000157// ApiProvider is implemented by modules that contribute to an API surface
158type ApiProvider interface {
159 ConvertWithApiBp2build(ctx TopDownMutatorContext)
160}
161
Chris Parsonsf874e462022-05-10 13:50:12 -0400162// MixedBuildBuildable is an interface that module types should implement in order
163// to be "handled by Bazel" in a mixed build.
164type MixedBuildBuildable interface {
165 // IsMixedBuildSupported returns true if and only if this module should be
166 // "handled by Bazel" in a mixed build.
167 // This "escape hatch" allows modules with corner-case scenarios to opt out
168 // of being built with Bazel.
169 IsMixedBuildSupported(ctx BaseModuleContext) bool
170
171 // QueueBazelCall invokes request-queueing functions on the BazelContext
172 // so that these requests are handled when Bazel's cquery is invoked.
173 QueueBazelCall(ctx BaseModuleContext)
174
175 // ProcessBazelQueryResponse uses Bazel information (obtained from the BazelContext)
176 // to set module fields and providers to propagate this module's metadata upstream.
177 // This effectively "bridges the gap" between Bazel and Soong in a mixed build.
178 // Soong modules depending on this module should be oblivious to the fact that
179 // this module was handled by Bazel.
180 ProcessBazelQueryResponse(ctx ModuleContext)
181}
182
Liz Kammerea6666f2021-02-17 10:17:28 -0500183// BazelModule is a lightweight wrapper interface around Module for Bazel-convertible modules.
184type BazelModule interface {
185 Module
186 Bazelable
187}
188
189// InitBazelModule is a wrapper function that decorates a BazelModule with Bazel-conversion
190// properties.
191func InitBazelModule(module BazelModule) {
192 module.AddProperties(module.bazelProps())
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400193 module.bazelProps().Bazel_module.CanConvertToBazel = true
Liz Kammerea6666f2021-02-17 10:17:28 -0500194}
195
196// bazelProps returns the Bazel properties for the given BazelModuleBase.
Liz Kammerba3ea162021-02-17 13:22:03 -0500197func (b *BazelModuleBase) bazelProps() *properties {
Liz Kammerea6666f2021-02-17 10:17:28 -0500198 return &b.bazelProperties
199}
200
Jingwen Chena47f28d2021-11-02 16:43:57 +0000201func (b *BazelModuleBase) namespacedVariableProps() namespacedVariableProperties {
202 return b.namespacedVariableProperties
203}
204
205func (b *BazelModuleBase) setNamespacedVariableProps(props namespacedVariableProperties) {
206 b.namespacedVariableProperties = props
207}
208
209func (b *BazelModuleBase) BaseModuleType() string {
210 return b.baseModuleType
211}
212
213func (b *BazelModuleBase) SetBaseModuleType(baseModuleType string) {
214 b.baseModuleType = baseModuleType
215}
216
Liz Kammerba3ea162021-02-17 13:22:03 -0500217// HasHandcraftedLabel returns whether this module has a handcrafted Bazel label.
218func (b *BazelModuleBase) HasHandcraftedLabel() bool {
219 return b.bazelProperties.Bazel_module.Label != nil
220}
221
222// HandcraftedLabel returns the handcrafted label for this module, or empty string if there is none
223func (b *BazelModuleBase) HandcraftedLabel() string {
224 return proptools.String(b.bazelProperties.Bazel_module.Label)
225}
226
Liz Kammerea6666f2021-02-17 10:17:28 -0500227// GetBazelLabel returns the Bazel label for the given BazelModuleBase.
Liz Kammerbdc60992021-02-24 16:55:11 -0500228func (b *BazelModuleBase) GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
229 if b.HasHandcraftedLabel() {
230 return b.HandcraftedLabel()
231 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400232 if b.ShouldConvertWithBp2build(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500233 return bp2buildModuleLabel(ctx, module)
234 }
235 return "" // no label for unconverted module
Liz Kammerea6666f2021-02-17 10:17:28 -0500236}
237
Cole Faust324a92e2022-08-23 15:29:05 -0700238type Bp2BuildConversionAllowlist struct {
Sam Delmerico24c56032022-03-28 19:53:03 +0000239 // Configure modules in these directories to enable bp2build_available: true or false by default.
240 defaultConfig allowlists.Bp2BuildConfig
Jingwen Chen12b4c272021-03-10 02:05:59 -0500241
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400242 // Keep any existing BUILD files (and do not generate new BUILD files) for these directories
Jingwen Chenb643c7a2021-07-26 04:45:48 +0000243 // in the synthetic Bazel workspace.
Sam Delmerico24c56032022-03-28 19:53:03 +0000244 keepExistingBuildFile map[string]bool
Jingwen Chen5d72cba2021-03-25 09:28:38 +0000245
Chris Parsonsef615e52022-08-18 22:04:11 -0400246 // Per-module allowlist to always opt modules into both bp2build and Bazel Dev Mode mixed
247 // builds. These modules are usually in directories with many other modules that are not ready
248 // for conversion.
Jingwen Chen7edadab2022-03-04 07:01:29 +0000249 //
250 // A module can either be in this list or its directory allowlisted entirely
251 // in bp2buildDefaultConfig, but not both at the same time.
Sam Delmerico24c56032022-03-28 19:53:03 +0000252 moduleAlwaysConvert map[string]bool
Sam Delmericofa1831c2022-02-22 18:07:55 +0000253
Chris Parsonsef615e52022-08-18 22:04:11 -0400254 // Per-module-type allowlist to always opt modules in to both bp2build and
255 // Bazel Dev Mode mixed builds when they have the same type as one listed.
Sam Delmerico24c56032022-03-28 19:53:03 +0000256 moduleTypeAlwaysConvert map[string]bool
Sam Delmerico85d831a2022-03-07 19:12:42 +0000257
Chris Parsonsad876012022-08-20 14:48:32 -0400258 // Per-module denylist to always opt modules out of bp2build conversion.
Sam Delmerico24c56032022-03-28 19:53:03 +0000259 moduleDoNotConvert map[string]bool
Sam Delmerico24c56032022-03-28 19:53:03 +0000260}
Liz Kammer5c313582021-12-03 15:23:26 -0500261
Cole Faust324a92e2022-08-23 15:29:05 -0700262// NewBp2BuildAllowlist creates a new, empty Bp2BuildConversionAllowlist
Sam Delmerico24c56032022-03-28 19:53:03 +0000263// which can be populated using builder pattern Set* methods
Cole Faust324a92e2022-08-23 15:29:05 -0700264func NewBp2BuildAllowlist() Bp2BuildConversionAllowlist {
265 return Bp2BuildConversionAllowlist{
Sam Delmerico24c56032022-03-28 19:53:03 +0000266 allowlists.Bp2BuildConfig{},
267 map[string]bool{},
268 map[string]bool{},
269 map[string]bool{},
270 map[string]bool{},
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400271 }
272}
273
Sam Delmerico24c56032022-03-28 19:53:03 +0000274// SetDefaultConfig copies the entries from defaultConfig into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700275func (a Bp2BuildConversionAllowlist) SetDefaultConfig(defaultConfig allowlists.Bp2BuildConfig) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000276 if a.defaultConfig == nil {
277 a.defaultConfig = allowlists.Bp2BuildConfig{}
278 }
279 for k, v := range defaultConfig {
280 a.defaultConfig[k] = v
281 }
282
283 return a
284}
285
286// SetKeepExistingBuildFile copies the entries from keepExistingBuildFile into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700287func (a Bp2BuildConversionAllowlist) SetKeepExistingBuildFile(keepExistingBuildFile map[string]bool) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000288 if a.keepExistingBuildFile == nil {
289 a.keepExistingBuildFile = map[string]bool{}
290 }
291 for k, v := range keepExistingBuildFile {
292 a.keepExistingBuildFile[k] = v
293 }
294
295 return a
296}
297
298// SetModuleAlwaysConvertList copies the entries from moduleAlwaysConvert into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700299func (a Bp2BuildConversionAllowlist) SetModuleAlwaysConvertList(moduleAlwaysConvert []string) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000300 if a.moduleAlwaysConvert == nil {
301 a.moduleAlwaysConvert = map[string]bool{}
302 }
303 for _, m := range moduleAlwaysConvert {
304 a.moduleAlwaysConvert[m] = true
305 }
306
307 return a
308}
309
310// SetModuleTypeAlwaysConvertList copies the entries from moduleTypeAlwaysConvert into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700311func (a Bp2BuildConversionAllowlist) SetModuleTypeAlwaysConvertList(moduleTypeAlwaysConvert []string) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000312 if a.moduleTypeAlwaysConvert == nil {
313 a.moduleTypeAlwaysConvert = map[string]bool{}
314 }
315 for _, m := range moduleTypeAlwaysConvert {
316 a.moduleTypeAlwaysConvert[m] = true
317 }
318
319 return a
320}
321
322// SetModuleDoNotConvertList copies the entries from moduleDoNotConvert into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700323func (a Bp2BuildConversionAllowlist) SetModuleDoNotConvertList(moduleDoNotConvert []string) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000324 if a.moduleDoNotConvert == nil {
325 a.moduleDoNotConvert = map[string]bool{}
326 }
327 for _, m := range moduleDoNotConvert {
328 a.moduleDoNotConvert[m] = true
329 }
330
331 return a
332}
333
Sam Delmerico24c56032022-03-28 19:53:03 +0000334// ShouldKeepExistingBuildFileForDir returns whether an existing BUILD file should be
335// added to the build symlink forest based on the current global configuration.
Cole Faust324a92e2022-08-23 15:29:05 -0700336func (a Bp2BuildConversionAllowlist) ShouldKeepExistingBuildFileForDir(dir string) bool {
337 if _, ok := a.keepExistingBuildFile[dir]; ok {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400338 // Exact dir match
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400339 return true
340 }
Usta Shresthaea999642022-11-02 01:03:07 -0400341 var i int
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400342 // Check if subtree match
Usta Shresthaea999642022-11-02 01:03:07 -0400343 for {
344 j := strings.Index(dir[i:], "/")
345 if j == -1 {
346 return false //default
347 }
348 prefix := dir[0 : i+j]
349 i = i + j + 1 // skip the "/"
350 if recursive, ok := a.keepExistingBuildFile[prefix]; ok && recursive {
351 return true
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400352 }
353 }
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400354}
355
Cole Faust324a92e2022-08-23 15:29:05 -0700356var bp2BuildAllowListKey = NewOnceKey("Bp2BuildAllowlist")
357var bp2buildAllowlist OncePer
358
359func GetBp2BuildAllowList() Bp2BuildConversionAllowlist {
360 return bp2buildAllowlist.Once(bp2BuildAllowListKey, func() interface{} {
361 return NewBp2BuildAllowlist().SetDefaultConfig(allowlists.Bp2buildDefaultConfig).
362 SetKeepExistingBuildFile(allowlists.Bp2buildKeepExistingBuildFile).
363 SetModuleAlwaysConvertList(allowlists.Bp2buildModuleAlwaysConvertList).
364 SetModuleTypeAlwaysConvertList(allowlists.Bp2buildModuleTypeAlwaysConvertList).
Sasha Smundak39a301c2022-12-29 17:11:49 -0800365 SetModuleDoNotConvertList(allowlists.Bp2buildModuleDoNotConvertList)
Cole Faust324a92e2022-08-23 15:29:05 -0700366 }).(Bp2BuildConversionAllowlist)
367}
368
MarkDacekf47e1422023-04-19 16:47:36 +0000369// MixedBuildsEnabled returns a MixedBuildEnabledStatus regarding whether
370// a module is ready to be replaced by a converted or handcrafted Bazel target.
371// As a side effect, calling this method will also log whether this module is
372// mixed build enabled for metrics reporting.
373func MixedBuildsEnabled(ctx BaseModuleContext) MixedBuildEnabledStatus {
MarkDacekf47e1422023-04-19 16:47:36 +0000374 platformIncompatible := isPlatformIncompatible(ctx.Os(), ctx.Arch().ArchType)
375 if platformIncompatible {
376 ctx.Config().LogMixedBuild(ctx, false)
377 return TechnicalIncompatibility
378 }
379
Liz Kammerc13f7852023-05-17 13:01:48 -0400380 if ctx.Config().AllowMissingDependencies() {
381 missingDeps := ctx.getMissingDependencies()
382 // If there are missing dependencies, querying Bazel will fail. Soong instead fails at execution
383 // time, not loading/analysis. disable mixed builds and fall back to Soong to maintain that
384 // behavior.
385 if len(missingDeps) > 0 {
386 ctx.Config().LogMixedBuild(ctx, false)
387 return ModuleMissingDeps
388 }
389 }
390
391 module := ctx.Module()
392 apexInfo := ctx.Provider(ApexInfoProvider).(ApexInfo)
393 withinApex := !apexInfo.IsForPlatform()
Sasha Smundak39a301c2022-12-29 17:11:49 -0800394 mixedBuildEnabled := ctx.Config().IsMixedBuildsEnabled() &&
Sasha Smundak39a301c2022-12-29 17:11:49 -0800395 module.Enabled() &&
396 convertedToBazel(ctx, module) &&
Yu Liue4312402023-01-18 09:15:31 -0800397 ctx.Config().BazelContext.IsModuleNameAllowed(module.Name(), withinApex)
MarkDacekff851b82022-04-21 18:33:17 +0000398 ctx.Config().LogMixedBuild(ctx, mixedBuildEnabled)
MarkDacekf47e1422023-04-19 16:47:36 +0000399
400 if mixedBuildEnabled {
401 return MixedBuildEnabled
402 }
403 return ModuleIncompatibility
MarkDacekff851b82022-04-21 18:33:17 +0000404}
405
Liz Kammer6eff3232021-08-26 08:37:59 -0400406// ConvertedToBazel returns whether this module has been converted (with bp2build or manually) to Bazel.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000407func convertedToBazel(ctx BazelConversionContext, module blueprint.Module) bool {
Liz Kammer6eff3232021-08-26 08:37:59 -0400408 b, ok := module.(Bazelable)
409 if !ok {
410 return false
411 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400412 return b.shouldConvertWithBp2build(ctx, module) || b.HasHandcraftedLabel()
Liz Kammer6eff3232021-08-26 08:37:59 -0400413}
414
Sam Delmerico24c56032022-03-28 19:53:03 +0000415// ShouldConvertWithBp2build returns whether the given BazelModuleBase should be converted with bp2build
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400416func (b *BazelModuleBase) ShouldConvertWithBp2build(ctx BazelConversionContext) bool {
417 return b.shouldConvertWithBp2build(ctx, ctx.Module())
Liz Kammer6eff3232021-08-26 08:37:59 -0400418}
419
Sam Delmerico24c56032022-03-28 19:53:03 +0000420type bazelOtherModuleContext interface {
421 ModuleErrorf(format string, args ...interface{})
422 Config() Config
423 OtherModuleType(m blueprint.Module) string
424 OtherModuleName(m blueprint.Module) string
425 OtherModuleDir(m blueprint.Module) string
426}
Sam Delmericofa1831c2022-02-22 18:07:55 +0000427
MarkDacekf47e1422023-04-19 16:47:36 +0000428func isPlatformIncompatible(osType OsType, arch ArchType) bool {
429 return osType == Windows || // Windows toolchains are not currently supported.
430 osType == LinuxBionic || // Linux Bionic toolchains are not currently supported.
431 osType == LinuxMusl || // Linux musl toolchains are not currently supported (b/259266326).
432 arch == Riscv64 // TODO(b/262192655) Riscv64 toolchains are not currently supported.
433}
434
Sam Delmerico24c56032022-03-28 19:53:03 +0000435func (b *BazelModuleBase) shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400436 if !b.bazelProps().Bazel_module.CanConvertToBazel {
437 return false
Jingwen Chen12b4c272021-03-10 02:05:59 -0500438 }
439
Spandan Das5af0bd32022-09-28 20:43:08 +0000440 // In api_bp2build mode, all soong modules that can provide API contributions should be converted
441 // This is irrespective of its presence/absence in bp2build allowlists
442 if ctx.Config().BuildMode == ApiBp2build {
443 _, providesApis := module.(ApiProvider)
444 return providesApis
445 }
446
Sam Delmerico85d831a2022-03-07 19:12:42 +0000447 propValue := b.bazelProperties.Bazel_module.Bp2build_available
Liz Kammer20f0f782023-05-01 13:46:33 -0400448 packagePath := moduleDirWithPossibleOverride(ctx, module)
Sam Delmerico24c56032022-03-28 19:53:03 +0000449
Sam Delmerico85d831a2022-03-07 19:12:42 +0000450 // Modules in unit tests which are enabled in the allowlist by type or name
451 // trigger this conditional because unit tests run under the "." package path
Sam Delmerico24c56032022-03-28 19:53:03 +0000452 isTestModule := packagePath == Bp2BuildTopLevel && proptools.BoolDefault(propValue, false)
453 if isTestModule {
454 return true
455 }
456
Liz Kammer20f0f782023-05-01 13:46:33 -0400457 moduleName := moduleNameWithPossibleOverride(ctx, module)
Cole Faust324a92e2022-08-23 15:29:05 -0700458 allowlist := ctx.Config().Bp2buildPackageConfig
Sam Delmerico24c56032022-03-28 19:53:03 +0000459 moduleNameAllowed := allowlist.moduleAlwaysConvert[moduleName]
460 moduleTypeAllowed := allowlist.moduleTypeAlwaysConvert[ctx.OtherModuleType(module)]
461 allowlistConvert := moduleNameAllowed || moduleTypeAllowed
462 if moduleNameAllowed && moduleTypeAllowed {
463 ctx.ModuleErrorf("A module cannot be in moduleAlwaysConvert and also be in moduleTypeAlwaysConvert")
464 return false
465 }
466
467 if allowlist.moduleDoNotConvert[moduleName] {
Sam Delmerico85d831a2022-03-07 19:12:42 +0000468 if moduleNameAllowed {
Sam Delmerico24c56032022-03-28 19:53:03 +0000469 ctx.ModuleErrorf("a module cannot be in moduleDoNotConvert and also be in moduleAlwaysConvert")
Sam Delmerico85d831a2022-03-07 19:12:42 +0000470 }
Sam Delmerico94d26c22022-02-25 21:34:51 +0000471 return false
472 }
473
Sam Delmerico24c56032022-03-28 19:53:03 +0000474 // This is a tristate value: true, false, or unset.
475 if ok, directoryPath := bp2buildDefaultTrueRecursively(packagePath, allowlist.defaultConfig); ok {
476 if moduleNameAllowed {
477 ctx.ModuleErrorf("A module cannot be in a directory marked Bp2BuildDefaultTrue"+
Yu Liu10853f92022-09-14 16:05:22 -0700478 " or Bp2BuildDefaultTrueRecursively and also be in moduleAlwaysConvert. Directory: '%s'"+
479 " Module: '%s'", directoryPath, moduleName)
Sam Delmerico24c56032022-03-28 19:53:03 +0000480 return false
Sam Delmericofa1831c2022-02-22 18:07:55 +0000481 }
482
Jingwen Chen12b4c272021-03-10 02:05:59 -0500483 // Allow modules to explicitly opt-out.
484 return proptools.BoolDefault(propValue, true)
485 }
486
487 // Allow modules to explicitly opt-in.
Sam Delmerico85d831a2022-03-07 19:12:42 +0000488 return proptools.BoolDefault(propValue, allowlistConvert)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500489}
490
491// bp2buildDefaultTrueRecursively checks that the package contains a prefix from the
492// set of package prefixes where all modules must be converted. That is, if the
493// package is x/y/z, and the list contains either x, x/y, or x/y/z, this function will
494// return true.
495//
496// However, if the package is x/y, and it matches a Bp2BuildDefaultFalse "x/y" entry
497// exactly, this module will return false early.
498//
499// This function will also return false if the package doesn't match anything in
500// the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000501//
502// This function will also return the allowlist entry which caused a particular
503// package to be enabled. Since packages can be enabled via a recursive declaration,
504// the path returned will not always be the same as the one provided.
505func bp2buildDefaultTrueRecursively(packagePath string, config allowlists.Bp2BuildConfig) (bool, string) {
Jingwen Chen294e7742021-08-31 05:58:01 +0000506 // Check if the package path has an exact match in the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000507 if config[packagePath] == allowlists.Bp2BuildDefaultTrue || config[packagePath] == allowlists.Bp2BuildDefaultTrueRecursively {
508 return true, packagePath
MarkDacek756b2962022-10-13 17:50:17 +0000509 } else if config[packagePath] == allowlists.Bp2BuildDefaultFalse || config[packagePath] == allowlists.Bp2BuildDefaultFalseRecursively {
Sam Delmerico24c56032022-03-28 19:53:03 +0000510 return false, packagePath
Jingwen Chen12b4c272021-03-10 02:05:59 -0500511 }
512
Jingwen Chen91220d72021-03-24 02:18:33 -0400513 // If not, check for the config recursively.
MarkDacek756b2962022-10-13 17:50:17 +0000514 packagePrefix := packagePath
515
516 // e.g. for x/y/z, iterate over x/y, then x, taking the most-specific value from the allowlist.
517 for strings.Contains(packagePrefix, "/") {
518 dirIndex := strings.LastIndex(packagePrefix, "/")
519 packagePrefix = packagePrefix[:dirIndex]
520 switch value := config[packagePrefix]; value {
521 case allowlists.Bp2BuildDefaultTrueRecursively:
Jingwen Chen12b4c272021-03-10 02:05:59 -0500522 // package contains this prefix and this prefix should convert all modules
Sam Delmerico24c56032022-03-28 19:53:03 +0000523 return true, packagePrefix
MarkDacek756b2962022-10-13 17:50:17 +0000524 case allowlists.Bp2BuildDefaultFalseRecursively:
525 //package contains this prefix and this prefix should NOT convert any modules
526 return false, packagePrefix
Jingwen Chen12b4c272021-03-10 02:05:59 -0500527 }
528 // Continue to the next part of the package dir.
MarkDacek756b2962022-10-13 17:50:17 +0000529
Jingwen Chen12b4c272021-03-10 02:05:59 -0500530 }
531
Sam Delmerico24c56032022-03-28 19:53:03 +0000532 return false, packagePath
Liz Kammerea6666f2021-02-17 10:17:28 -0500533}
Liz Kammerba3ea162021-02-17 13:22:03 -0500534
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400535func registerBp2buildConversionMutator(ctx RegisterMutatorsContext) {
536 ctx.TopDown("bp2build_conversion", convertWithBp2build).Parallel()
537}
538
539func convertWithBp2build(ctx TopDownMutatorContext) {
Chris Parsons8152a942023-06-06 16:17:50 +0000540 if ctx.Config().HasBazelBuildTargetInSource(ctx) {
541 // Defer to the BUILD target. Generating an additional target would
542 // cause a BUILD file conflict.
543 return
544 }
545
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400546 bModule, ok := ctx.Module().(Bazelable)
547 if !ok || !bModule.shouldConvertWithBp2build(ctx, ctx.Module()) {
548 return
549 }
550
551 bModule.ConvertWithBp2build(ctx)
552}
Wei Libafb6d62021-12-10 03:14:59 -0800553
Spandan Das5af0bd32022-09-28 20:43:08 +0000554func registerApiBp2buildConversionMutator(ctx RegisterMutatorsContext) {
555 ctx.TopDown("apiBp2build_conversion", convertWithApiBp2build).Parallel()
556}
557
558// Generate API contribution targets if the Soong module provides APIs
559func convertWithApiBp2build(ctx TopDownMutatorContext) {
560 if m, ok := ctx.Module().(ApiProvider); ok {
561 m.ConvertWithApiBp2build(ctx)
562 }
563}
564
Wei Libafb6d62021-12-10 03:14:59 -0800565// GetMainClassInManifest scans the manifest file specified in filepath and returns
566// the value of attribute Main-Class in the manifest file if it exists, or returns error.
567// WARNING: this is for bp2build converters of java_* modules only.
568func GetMainClassInManifest(c Config, filepath string) (string, error) {
569 file, err := c.fs.Open(filepath)
570 if err != nil {
571 return "", err
572 }
Liz Kammer0fe123d2022-02-07 10:17:35 -0500573 defer file.Close()
Wei Libafb6d62021-12-10 03:14:59 -0800574 scanner := bufio.NewScanner(file)
575 for scanner.Scan() {
576 line := scanner.Text()
577 if strings.HasPrefix(line, "Main-Class:") {
578 return strings.TrimSpace(line[len("Main-Class:"):]), nil
579 }
580 }
581
582 return "", errors.New("Main-Class is not found.")
583}
Sam Delmerico4ed95e22023-02-03 18:12:15 -0500584
585func AttachValidationActions(ctx ModuleContext, outputFilePath Path, validations Paths) ModuleOutPath {
586 validatedOutputFilePath := PathForModuleOut(ctx, "validated", outputFilePath.Base())
587 ctx.Build(pctx, BuildParams{
588 Rule: CpNoPreserveSymlink,
589 Description: "run validations " + outputFilePath.Base(),
590 Output: validatedOutputFilePath,
591 Input: outputFilePath,
592 Validations: validations,
593 })
594 return validatedOutputFilePath
595}