blob: 7b227bddd0bafb04399a15a0a160abe1d1d57ce3 [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
Yu Liu2aa806b2022-09-01 11:54:47 -070035// FileGroupAsLibrary describes a filegroup module that is converted to some library
36// such as aidl_library or proto_library.
37type FileGroupAsLibrary interface {
Vinh Tran444154d2022-08-16 13:10:31 -040038 ShouldConvertToAidlLibrary(ctx BazelConversionPathContext) bool
Yu Liu2aa806b2022-09-01 11:54:47 -070039 ShouldConvertToProtoLibrary(ctx BazelConversionPathContext) bool
Vinh Tran444154d2022-08-16 13:10:31 -040040 GetAidlLibraryLabel(ctx BazelConversionPathContext) string
Yu Liu2aa806b2022-09-01 11:54:47 -070041 GetProtoLibraryLabel(ctx BazelConversionPathContext) string
Vinh Tran444154d2022-08-16 13:10:31 -040042}
43
Sasha Smundaka0954062022-08-02 18:23:58 -070044type BazelConversionStatus struct {
45 // Information about _all_ bp2build targets generated by this module. Multiple targets are
46 // supported as Soong handles some things within a single target that we may choose to split into
47 // multiple targets, e.g. renderscript, protos, yacc within a cc module.
48 Bp2buildInfo []bp2buildInfo `blueprint:"mutated"`
49
50 // UnconvertedBp2buildDep stores the module names of direct dependency that were not converted to
51 // Bazel
52 UnconvertedDeps []string `blueprint:"mutated"`
53
54 // MissingBp2buildDep stores the module names of direct dependency that were not found
55 MissingDeps []string `blueprint:"mutated"`
56}
57
Jingwen Chen01812022021-11-19 14:29:43 +000058type bazelModuleProperties struct {
59 // The label of the Bazel target replacing this Soong module. When run in conversion mode, this
60 // will import the handcrafted build target into the autogenerated file. Note: this may result in
61 // a conflict due to duplicate targets if bp2build_available is also set.
62 Label *string
63
64 // If true, bp2build will generate the converted Bazel target for this module. Note: this may
65 // cause a conflict due to the duplicate targets if label is also set.
66 //
67 // This is a bool pointer to support tristates: true, false, not set.
68 //
69 // To opt-in a module, set bazel_module: { bp2build_available: true }
70 // To opt-out a module, set bazel_module: { bp2build_available: false }
71 // To defer the default setting for the directory, do not set the value.
72 Bp2build_available *bool
Liz Kammerbe46fcc2021-11-01 15:32:43 -040073
74 // CanConvertToBazel is set via InitBazelModule to indicate that a module type can be converted to
75 // Bazel with Bp2build.
76 CanConvertToBazel bool `blueprint:"mutated"`
Jingwen Chen01812022021-11-19 14:29:43 +000077}
78
Liz Kammerba3ea162021-02-17 13:22:03 -050079// Properties contains common module properties for Bazel migration purposes.
80type properties struct {
Chris Parsons1bb58da2022-08-30 13:37:57 -040081 // In "Bazel mixed build" mode, this represents the Bazel target replacing
Liz Kammerba3ea162021-02-17 13:22:03 -050082 // this Soong module.
Jingwen Chen01812022021-11-19 14:29:43 +000083 Bazel_module bazelModuleProperties
Liz Kammerba3ea162021-02-17 13:22:03 -050084}
Liz Kammerea6666f2021-02-17 10:17:28 -050085
Jingwen Chen25825ca2021-11-15 12:28:43 +000086// namespacedVariableProperties is a map from a string representing a Soong
Jingwen Chen84817de2021-11-17 10:57:35 +000087// config variable namespace, like "android" or "vendor_name" to a slice of
88// pointer to a struct containing a single field called Soong_config_variables
89// whose value mirrors the structure in the Blueprint file.
90type namespacedVariableProperties map[string][]interface{}
Jingwen Chena47f28d2021-11-02 16:43:57 +000091
Liz Kammerea6666f2021-02-17 10:17:28 -050092// BazelModuleBase contains the property structs with metadata for modules which can be converted to
93// Bazel.
94type BazelModuleBase struct {
Liz Kammerba3ea162021-02-17 13:22:03 -050095 bazelProperties properties
Jingwen Chena47f28d2021-11-02 16:43:57 +000096
97 // namespacedVariableProperties is used for soong_config_module_type support
98 // in bp2build. Soong config modules allow users to set module properties
99 // based on custom product variables defined in Android.bp files. These
100 // variables are namespaced to prevent clobbering, especially when set from
101 // Makefiles.
102 namespacedVariableProperties namespacedVariableProperties
103
104 // baseModuleType is set when this module was created from a module type
105 // defined by a soong_config_module_type. Every soong_config_module_type
106 // "wraps" another module type, e.g. a soong_config_module_type can wrap a
107 // cc_defaults to a custom_cc_defaults, or cc_binary to a custom_cc_binary.
108 // This baseModuleType is set to the wrapped module type.
109 baseModuleType string
Liz Kammerea6666f2021-02-17 10:17:28 -0500110}
111
112// Bazelable is specifies the interface for modules that can be converted to Bazel.
113type Bazelable interface {
Liz Kammerba3ea162021-02-17 13:22:03 -0500114 bazelProps() *properties
115 HasHandcraftedLabel() bool
Liz Kammerbdc60992021-02-24 16:55:11 -0500116 HandcraftedLabel() string
117 GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400118 ShouldConvertWithBp2build(ctx BazelConversionContext) bool
Sam Delmerico24c56032022-03-28 19:53:03 +0000119 shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400120 ConvertWithBp2build(ctx TopDownMutatorContext)
Jingwen Chena47f28d2021-11-02 16:43:57 +0000121
Jingwen Chen84817de2021-11-17 10:57:35 +0000122 // namespacedVariableProps is a map from a soong config variable namespace
123 // (e.g. acme, android) to a map of interfaces{}, which are really
124 // reflect.Struct pointers, representing the value of the
125 // soong_config_variables property of a module. The struct pointer is the
126 // one with the single member called Soong_config_variables, which itself is
127 // a struct containing fields for each supported feature in that namespace.
128 //
129 // The reason for using an slice of interface{} is to support defaults
130 // propagation of the struct pointers.
Jingwen Chena47f28d2021-11-02 16:43:57 +0000131 namespacedVariableProps() namespacedVariableProperties
132 setNamespacedVariableProps(props namespacedVariableProperties)
133 BaseModuleType() string
Jingwen Chen84817de2021-11-17 10:57:35 +0000134 SetBaseModuleType(baseModuleType string)
Liz Kammerea6666f2021-02-17 10:17:28 -0500135}
136
Spandan Das5af0bd32022-09-28 20:43:08 +0000137// ApiProvider is implemented by modules that contribute to an API surface
138type ApiProvider interface {
139 ConvertWithApiBp2build(ctx TopDownMutatorContext)
140}
141
Chris Parsonsf874e462022-05-10 13:50:12 -0400142// MixedBuildBuildable is an interface that module types should implement in order
143// to be "handled by Bazel" in a mixed build.
144type MixedBuildBuildable interface {
145 // IsMixedBuildSupported returns true if and only if this module should be
146 // "handled by Bazel" in a mixed build.
147 // This "escape hatch" allows modules with corner-case scenarios to opt out
148 // of being built with Bazel.
149 IsMixedBuildSupported(ctx BaseModuleContext) bool
150
151 // QueueBazelCall invokes request-queueing functions on the BazelContext
152 // so that these requests are handled when Bazel's cquery is invoked.
153 QueueBazelCall(ctx BaseModuleContext)
154
155 // ProcessBazelQueryResponse uses Bazel information (obtained from the BazelContext)
156 // to set module fields and providers to propagate this module's metadata upstream.
157 // This effectively "bridges the gap" between Bazel and Soong in a mixed build.
158 // Soong modules depending on this module should be oblivious to the fact that
159 // this module was handled by Bazel.
160 ProcessBazelQueryResponse(ctx ModuleContext)
161}
162
Liz Kammerea6666f2021-02-17 10:17:28 -0500163// BazelModule is a lightweight wrapper interface around Module for Bazel-convertible modules.
164type BazelModule interface {
165 Module
166 Bazelable
167}
168
169// InitBazelModule is a wrapper function that decorates a BazelModule with Bazel-conversion
170// properties.
171func InitBazelModule(module BazelModule) {
172 module.AddProperties(module.bazelProps())
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400173 module.bazelProps().Bazel_module.CanConvertToBazel = true
Liz Kammerea6666f2021-02-17 10:17:28 -0500174}
175
176// bazelProps returns the Bazel properties for the given BazelModuleBase.
Liz Kammerba3ea162021-02-17 13:22:03 -0500177func (b *BazelModuleBase) bazelProps() *properties {
Liz Kammerea6666f2021-02-17 10:17:28 -0500178 return &b.bazelProperties
179}
180
Jingwen Chena47f28d2021-11-02 16:43:57 +0000181func (b *BazelModuleBase) namespacedVariableProps() namespacedVariableProperties {
182 return b.namespacedVariableProperties
183}
184
185func (b *BazelModuleBase) setNamespacedVariableProps(props namespacedVariableProperties) {
186 b.namespacedVariableProperties = props
187}
188
189func (b *BazelModuleBase) BaseModuleType() string {
190 return b.baseModuleType
191}
192
193func (b *BazelModuleBase) SetBaseModuleType(baseModuleType string) {
194 b.baseModuleType = baseModuleType
195}
196
Liz Kammerba3ea162021-02-17 13:22:03 -0500197// HasHandcraftedLabel returns whether this module has a handcrafted Bazel label.
198func (b *BazelModuleBase) HasHandcraftedLabel() bool {
199 return b.bazelProperties.Bazel_module.Label != nil
200}
201
202// HandcraftedLabel returns the handcrafted label for this module, or empty string if there is none
203func (b *BazelModuleBase) HandcraftedLabel() string {
204 return proptools.String(b.bazelProperties.Bazel_module.Label)
205}
206
Liz Kammerea6666f2021-02-17 10:17:28 -0500207// GetBazelLabel returns the Bazel label for the given BazelModuleBase.
Liz Kammerbdc60992021-02-24 16:55:11 -0500208func (b *BazelModuleBase) GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
209 if b.HasHandcraftedLabel() {
210 return b.HandcraftedLabel()
211 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400212 if b.ShouldConvertWithBp2build(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500213 return bp2buildModuleLabel(ctx, module)
214 }
215 return "" // no label for unconverted module
Liz Kammerea6666f2021-02-17 10:17:28 -0500216}
217
Cole Faust324a92e2022-08-23 15:29:05 -0700218type Bp2BuildConversionAllowlist struct {
Sam Delmerico24c56032022-03-28 19:53:03 +0000219 // Configure modules in these directories to enable bp2build_available: true or false by default.
220 defaultConfig allowlists.Bp2BuildConfig
Jingwen Chen12b4c272021-03-10 02:05:59 -0500221
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400222 // Keep any existing BUILD files (and do not generate new BUILD files) for these directories
Jingwen Chenb643c7a2021-07-26 04:45:48 +0000223 // in the synthetic Bazel workspace.
Sam Delmerico24c56032022-03-28 19:53:03 +0000224 keepExistingBuildFile map[string]bool
Jingwen Chen5d72cba2021-03-25 09:28:38 +0000225
Chris Parsonsef615e52022-08-18 22:04:11 -0400226 // Per-module allowlist to always opt modules into both bp2build and Bazel Dev Mode mixed
227 // builds. These modules are usually in directories with many other modules that are not ready
228 // for conversion.
Jingwen Chen7edadab2022-03-04 07:01:29 +0000229 //
230 // A module can either be in this list or its directory allowlisted entirely
231 // in bp2buildDefaultConfig, but not both at the same time.
Sam Delmerico24c56032022-03-28 19:53:03 +0000232 moduleAlwaysConvert map[string]bool
Sam Delmericofa1831c2022-02-22 18:07:55 +0000233
Chris Parsonsef615e52022-08-18 22:04:11 -0400234 // Per-module-type allowlist to always opt modules in to both bp2build and
235 // Bazel Dev Mode mixed builds when they have the same type as one listed.
Sam Delmerico24c56032022-03-28 19:53:03 +0000236 moduleTypeAlwaysConvert map[string]bool
Sam Delmerico85d831a2022-03-07 19:12:42 +0000237
Chris Parsonsad876012022-08-20 14:48:32 -0400238 // Per-module denylist to always opt modules out of bp2build conversion.
Sam Delmerico24c56032022-03-28 19:53:03 +0000239 moduleDoNotConvert map[string]bool
Rupert Shuttleworthc143cc52021-04-13 13:08:04 -0400240
Jingwen Chen179856a2021-05-03 09:15:48 +0000241 // Per-module denylist of cc_library modules to only generate the static
242 // variant if their shared variant isn't ready or buildable by Bazel.
Sam Delmerico24c56032022-03-28 19:53:03 +0000243 ccLibraryStaticOnly map[string]bool
Chris Parsonsad876012022-08-20 14:48:32 -0400244}
Jingwen Chen179856a2021-05-03 09:15:48 +0000245
Chris Parsonsad876012022-08-20 14:48:32 -0400246// GenerateCcLibraryStaticOnly returns whether a cc_library module should only
247// generate a static version of itself based on the current global configuration.
Cole Faust324a92e2022-08-23 15:29:05 -0700248func (a Bp2BuildConversionAllowlist) GenerateCcLibraryStaticOnly(moduleName string) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400249 return a.ccLibraryStaticOnly[moduleName]
Sam Delmerico24c56032022-03-28 19:53:03 +0000250}
Liz Kammer5c313582021-12-03 15:23:26 -0500251
Cole Faust324a92e2022-08-23 15:29:05 -0700252// NewBp2BuildAllowlist creates a new, empty Bp2BuildConversionAllowlist
Sam Delmerico24c56032022-03-28 19:53:03 +0000253// which can be populated using builder pattern Set* methods
Cole Faust324a92e2022-08-23 15:29:05 -0700254func NewBp2BuildAllowlist() Bp2BuildConversionAllowlist {
255 return Bp2BuildConversionAllowlist{
Sam Delmerico24c56032022-03-28 19:53:03 +0000256 allowlists.Bp2BuildConfig{},
257 map[string]bool{},
258 map[string]bool{},
259 map[string]bool{},
260 map[string]bool{},
261 map[string]bool{},
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400262 }
263}
264
Sam Delmerico24c56032022-03-28 19:53:03 +0000265// SetDefaultConfig copies the entries from defaultConfig into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700266func (a Bp2BuildConversionAllowlist) SetDefaultConfig(defaultConfig allowlists.Bp2BuildConfig) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000267 if a.defaultConfig == nil {
268 a.defaultConfig = allowlists.Bp2BuildConfig{}
269 }
270 for k, v := range defaultConfig {
271 a.defaultConfig[k] = v
272 }
273
274 return a
275}
276
277// SetKeepExistingBuildFile copies the entries from keepExistingBuildFile into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700278func (a Bp2BuildConversionAllowlist) SetKeepExistingBuildFile(keepExistingBuildFile map[string]bool) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000279 if a.keepExistingBuildFile == nil {
280 a.keepExistingBuildFile = map[string]bool{}
281 }
282 for k, v := range keepExistingBuildFile {
283 a.keepExistingBuildFile[k] = v
284 }
285
286 return a
287}
288
289// SetModuleAlwaysConvertList copies the entries from moduleAlwaysConvert into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700290func (a Bp2BuildConversionAllowlist) SetModuleAlwaysConvertList(moduleAlwaysConvert []string) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000291 if a.moduleAlwaysConvert == nil {
292 a.moduleAlwaysConvert = map[string]bool{}
293 }
294 for _, m := range moduleAlwaysConvert {
295 a.moduleAlwaysConvert[m] = true
296 }
297
298 return a
299}
300
301// SetModuleTypeAlwaysConvertList copies the entries from moduleTypeAlwaysConvert into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700302func (a Bp2BuildConversionAllowlist) SetModuleTypeAlwaysConvertList(moduleTypeAlwaysConvert []string) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000303 if a.moduleTypeAlwaysConvert == nil {
304 a.moduleTypeAlwaysConvert = map[string]bool{}
305 }
306 for _, m := range moduleTypeAlwaysConvert {
307 a.moduleTypeAlwaysConvert[m] = true
308 }
309
310 return a
311}
312
313// SetModuleDoNotConvertList copies the entries from moduleDoNotConvert into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700314func (a Bp2BuildConversionAllowlist) SetModuleDoNotConvertList(moduleDoNotConvert []string) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000315 if a.moduleDoNotConvert == nil {
316 a.moduleDoNotConvert = map[string]bool{}
317 }
318 for _, m := range moduleDoNotConvert {
319 a.moduleDoNotConvert[m] = true
320 }
321
322 return a
323}
324
325// SetCcLibraryStaticOnlyList copies the entries from ccLibraryStaticOnly into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700326func (a Bp2BuildConversionAllowlist) SetCcLibraryStaticOnlyList(ccLibraryStaticOnly []string) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000327 if a.ccLibraryStaticOnly == nil {
328 a.ccLibraryStaticOnly = map[string]bool{}
329 }
330 for _, m := range ccLibraryStaticOnly {
331 a.ccLibraryStaticOnly[m] = true
332 }
333
334 return a
335}
336
Sam Delmerico24c56032022-03-28 19:53:03 +0000337// ShouldKeepExistingBuildFileForDir returns whether an existing BUILD file should be
338// added to the build symlink forest based on the current global configuration.
Cole Faust324a92e2022-08-23 15:29:05 -0700339func (a Bp2BuildConversionAllowlist) ShouldKeepExistingBuildFileForDir(dir string) bool {
340 if _, ok := a.keepExistingBuildFile[dir]; ok {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400341 // Exact dir match
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400342 return true
343 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400344 // Check if subtree match
Cole Faust324a92e2022-08-23 15:29:05 -0700345 for prefix, recursive := range a.keepExistingBuildFile {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400346 if recursive {
347 if strings.HasPrefix(dir, prefix+"/") {
348 return true
349 }
350 }
351 }
352 // Default
353 return false
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).
365 SetModuleDoNotConvertList(allowlists.Bp2buildModuleDoNotConvertList).
366 SetCcLibraryStaticOnlyList(allowlists.Bp2buildCcLibraryStaticOnlyList)
367 }).(Bp2BuildConversionAllowlist)
368}
369
MarkDacekff851b82022-04-21 18:33:17 +0000370// MixedBuildsEnabled returns true if a module is ready to be replaced by a
371// converted or handcrafted Bazel target. As a side effect, calling this
372// method will also log whether this module is mixed build enabled for
373// metrics reporting.
Chris Parsonsf874e462022-05-10 13:50:12 -0400374func MixedBuildsEnabled(ctx BaseModuleContext) bool {
MarkDacekff851b82022-04-21 18:33:17 +0000375 mixedBuildEnabled := mixedBuildPossible(ctx)
376 ctx.Config().LogMixedBuild(ctx, mixedBuildEnabled)
377 return mixedBuildEnabled
378}
379
380// mixedBuildPossible returns true if a module is ready to be replaced by a
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400381// converted or handcrafted Bazel target.
Chris Parsonsf874e462022-05-10 13:50:12 -0400382func mixedBuildPossible(ctx BaseModuleContext) bool {
Chris Parsons494eef32021-11-09 10:29:52 -0500383 if ctx.Os() == Windows {
384 // Windows toolchains are not currently supported.
385 return false
386 }
Chris Parsons58852a02021-12-09 18:10:18 -0500387 if !ctx.Module().Enabled() {
388 return false
389 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400390 if !convertedToBazel(ctx, ctx.Module()) {
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400391 return false
392 }
Chris Parsonsad876012022-08-20 14:48:32 -0400393 return ctx.Config().BazelContext.BazelAllowlisted(ctx.Module().Name())
Rupert Shuttleworth4f43fe92021-03-30 14:13:16 +0000394}
395
Liz Kammer6eff3232021-08-26 08:37:59 -0400396// ConvertedToBazel returns whether this module has been converted (with bp2build or manually) to Bazel.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000397func convertedToBazel(ctx BazelConversionContext, module blueprint.Module) bool {
Liz Kammer6eff3232021-08-26 08:37:59 -0400398 b, ok := module.(Bazelable)
399 if !ok {
400 return false
401 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400402 return b.shouldConvertWithBp2build(ctx, module) || b.HasHandcraftedLabel()
Liz Kammer6eff3232021-08-26 08:37:59 -0400403}
404
Sam Delmerico24c56032022-03-28 19:53:03 +0000405// ShouldConvertWithBp2build returns whether the given BazelModuleBase should be converted with bp2build
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400406func (b *BazelModuleBase) ShouldConvertWithBp2build(ctx BazelConversionContext) bool {
407 return b.shouldConvertWithBp2build(ctx, ctx.Module())
Liz Kammer6eff3232021-08-26 08:37:59 -0400408}
409
Sam Delmerico24c56032022-03-28 19:53:03 +0000410type bazelOtherModuleContext interface {
411 ModuleErrorf(format string, args ...interface{})
412 Config() Config
413 OtherModuleType(m blueprint.Module) string
414 OtherModuleName(m blueprint.Module) string
415 OtherModuleDir(m blueprint.Module) string
416}
Sam Delmericofa1831c2022-02-22 18:07:55 +0000417
Sam Delmerico24c56032022-03-28 19:53:03 +0000418func (b *BazelModuleBase) shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400419 if !b.bazelProps().Bazel_module.CanConvertToBazel {
420 return false
Jingwen Chen12b4c272021-03-10 02:05:59 -0500421 }
422
Spandan Das5af0bd32022-09-28 20:43:08 +0000423 // In api_bp2build mode, all soong modules that can provide API contributions should be converted
424 // This is irrespective of its presence/absence in bp2build allowlists
425 if ctx.Config().BuildMode == ApiBp2build {
426 _, providesApis := module.(ApiProvider)
427 return providesApis
428 }
429
Sam Delmerico85d831a2022-03-07 19:12:42 +0000430 propValue := b.bazelProperties.Bazel_module.Bp2build_available
Liz Kammer6eff3232021-08-26 08:37:59 -0400431 packagePath := ctx.OtherModuleDir(module)
Sam Delmerico24c56032022-03-28 19:53:03 +0000432
Sam Delmerico85d831a2022-03-07 19:12:42 +0000433 // Modules in unit tests which are enabled in the allowlist by type or name
434 // trigger this conditional because unit tests run under the "." package path
Sam Delmerico24c56032022-03-28 19:53:03 +0000435 isTestModule := packagePath == Bp2BuildTopLevel && proptools.BoolDefault(propValue, false)
436 if isTestModule {
437 return true
438 }
439
440 moduleName := module.Name()
Cole Faust324a92e2022-08-23 15:29:05 -0700441 allowlist := ctx.Config().Bp2buildPackageConfig
Sam Delmerico24c56032022-03-28 19:53:03 +0000442 moduleNameAllowed := allowlist.moduleAlwaysConvert[moduleName]
443 moduleTypeAllowed := allowlist.moduleTypeAlwaysConvert[ctx.OtherModuleType(module)]
444 allowlistConvert := moduleNameAllowed || moduleTypeAllowed
445 if moduleNameAllowed && moduleTypeAllowed {
446 ctx.ModuleErrorf("A module cannot be in moduleAlwaysConvert and also be in moduleTypeAlwaysConvert")
447 return false
448 }
449
450 if allowlist.moduleDoNotConvert[moduleName] {
Sam Delmerico85d831a2022-03-07 19:12:42 +0000451 if moduleNameAllowed {
Sam Delmerico24c56032022-03-28 19:53:03 +0000452 ctx.ModuleErrorf("a module cannot be in moduleDoNotConvert and also be in moduleAlwaysConvert")
Sam Delmerico85d831a2022-03-07 19:12:42 +0000453 }
Sam Delmerico94d26c22022-02-25 21:34:51 +0000454 return false
455 }
456
Sam Delmerico24c56032022-03-28 19:53:03 +0000457 // This is a tristate value: true, false, or unset.
458 if ok, directoryPath := bp2buildDefaultTrueRecursively(packagePath, allowlist.defaultConfig); ok {
459 if moduleNameAllowed {
460 ctx.ModuleErrorf("A module cannot be in a directory marked Bp2BuildDefaultTrue"+
Yu Liu10853f92022-09-14 16:05:22 -0700461 " or Bp2BuildDefaultTrueRecursively and also be in moduleAlwaysConvert. Directory: '%s'"+
462 " Module: '%s'", directoryPath, moduleName)
Sam Delmerico24c56032022-03-28 19:53:03 +0000463 return false
Sam Delmericofa1831c2022-02-22 18:07:55 +0000464 }
465
Jingwen Chen12b4c272021-03-10 02:05:59 -0500466 // Allow modules to explicitly opt-out.
467 return proptools.BoolDefault(propValue, true)
468 }
469
470 // Allow modules to explicitly opt-in.
Sam Delmerico85d831a2022-03-07 19:12:42 +0000471 return proptools.BoolDefault(propValue, allowlistConvert)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500472}
473
474// bp2buildDefaultTrueRecursively checks that the package contains a prefix from the
475// set of package prefixes where all modules must be converted. That is, if the
476// package is x/y/z, and the list contains either x, x/y, or x/y/z, this function will
477// return true.
478//
479// However, if the package is x/y, and it matches a Bp2BuildDefaultFalse "x/y" entry
480// exactly, this module will return false early.
481//
482// This function will also return false if the package doesn't match anything in
483// the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000484//
485// This function will also return the allowlist entry which caused a particular
486// package to be enabled. Since packages can be enabled via a recursive declaration,
487// the path returned will not always be the same as the one provided.
488func bp2buildDefaultTrueRecursively(packagePath string, config allowlists.Bp2BuildConfig) (bool, string) {
Jingwen Chen294e7742021-08-31 05:58:01 +0000489 // Check if the package path has an exact match in the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000490 if config[packagePath] == allowlists.Bp2BuildDefaultTrue || config[packagePath] == allowlists.Bp2BuildDefaultTrueRecursively {
491 return true, packagePath
492 } else if config[packagePath] == allowlists.Bp2BuildDefaultFalse {
493 return false, packagePath
Jingwen Chen12b4c272021-03-10 02:05:59 -0500494 }
495
Jingwen Chen91220d72021-03-24 02:18:33 -0400496 // If not, check for the config recursively.
Jingwen Chen12b4c272021-03-10 02:05:59 -0500497 packagePrefix := ""
498 // e.g. for x/y/z, iterate over x, x/y, then x/y/z, taking the final value from the allowlist.
499 for _, part := range strings.Split(packagePath, "/") {
500 packagePrefix += part
Sam Delmerico24c56032022-03-28 19:53:03 +0000501 if config[packagePrefix] == allowlists.Bp2BuildDefaultTrueRecursively {
Jingwen Chen12b4c272021-03-10 02:05:59 -0500502 // package contains this prefix and this prefix should convert all modules
Sam Delmerico24c56032022-03-28 19:53:03 +0000503 return true, packagePrefix
Jingwen Chen12b4c272021-03-10 02:05:59 -0500504 }
505 // Continue to the next part of the package dir.
506 packagePrefix += "/"
507 }
508
Sam Delmerico24c56032022-03-28 19:53:03 +0000509 return false, packagePath
Liz Kammerea6666f2021-02-17 10:17:28 -0500510}
Liz Kammerba3ea162021-02-17 13:22:03 -0500511
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400512func registerBp2buildConversionMutator(ctx RegisterMutatorsContext) {
513 ctx.TopDown("bp2build_conversion", convertWithBp2build).Parallel()
514}
515
516func convertWithBp2build(ctx TopDownMutatorContext) {
517 bModule, ok := ctx.Module().(Bazelable)
518 if !ok || !bModule.shouldConvertWithBp2build(ctx, ctx.Module()) {
519 return
520 }
521
522 bModule.ConvertWithBp2build(ctx)
523}
Wei Libafb6d62021-12-10 03:14:59 -0800524
Spandan Das5af0bd32022-09-28 20:43:08 +0000525func registerApiBp2buildConversionMutator(ctx RegisterMutatorsContext) {
526 ctx.TopDown("apiBp2build_conversion", convertWithApiBp2build).Parallel()
527}
528
529// Generate API contribution targets if the Soong module provides APIs
530func convertWithApiBp2build(ctx TopDownMutatorContext) {
531 if m, ok := ctx.Module().(ApiProvider); ok {
532 m.ConvertWithApiBp2build(ctx)
533 }
534}
535
Wei Libafb6d62021-12-10 03:14:59 -0800536// GetMainClassInManifest scans the manifest file specified in filepath and returns
537// the value of attribute Main-Class in the manifest file if it exists, or returns error.
538// WARNING: this is for bp2build converters of java_* modules only.
539func GetMainClassInManifest(c Config, filepath string) (string, error) {
540 file, err := c.fs.Open(filepath)
541 if err != nil {
542 return "", err
543 }
Liz Kammer0fe123d2022-02-07 10:17:35 -0500544 defer file.Close()
Wei Libafb6d62021-12-10 03:14:59 -0800545 scanner := bufio.NewScanner(file)
546 for scanner.Scan() {
547 line := scanner.Text()
548 if strings.HasPrefix(line, "Main-Class:") {
549 return strings.TrimSpace(line[len("Main-Class:"):]), nil
550 }
551 }
552
553 return "", errors.New("Main-Class is not found.")
554}