blob: eb6aca4e929bb26db61a394b6369071a81568bcf [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
Vinh Tran444154d2022-08-16 13:10:31 -040035// Bp2buildAidlLibrary describes a filegroup module that are converted to aidl_library
36type Bp2buildAidlLibrary interface {
37 ShouldConvertToAidlLibrary(ctx BazelConversionPathContext) bool
38 GetAidlLibraryLabel(ctx BazelConversionPathContext) string
39}
40
Sasha Smundaka0954062022-08-02 18:23:58 -070041type BazelConversionStatus struct {
42 // Information about _all_ bp2build targets generated by this module. Multiple targets are
43 // supported as Soong handles some things within a single target that we may choose to split into
44 // multiple targets, e.g. renderscript, protos, yacc within a cc module.
45 Bp2buildInfo []bp2buildInfo `blueprint:"mutated"`
46
47 // UnconvertedBp2buildDep stores the module names of direct dependency that were not converted to
48 // Bazel
49 UnconvertedDeps []string `blueprint:"mutated"`
50
51 // MissingBp2buildDep stores the module names of direct dependency that were not found
52 MissingDeps []string `blueprint:"mutated"`
53}
54
Jingwen Chen01812022021-11-19 14:29:43 +000055type bazelModuleProperties struct {
56 // The label of the Bazel target replacing this Soong module. When run in conversion mode, this
57 // will import the handcrafted build target into the autogenerated file. Note: this may result in
58 // a conflict due to duplicate targets if bp2build_available is also set.
59 Label *string
60
61 // If true, bp2build will generate the converted Bazel target for this module. Note: this may
62 // cause a conflict due to the duplicate targets if label is also set.
63 //
64 // This is a bool pointer to support tristates: true, false, not set.
65 //
66 // To opt-in a module, set bazel_module: { bp2build_available: true }
67 // To opt-out a module, set bazel_module: { bp2build_available: false }
68 // To defer the default setting for the directory, do not set the value.
69 Bp2build_available *bool
Liz Kammerbe46fcc2021-11-01 15:32:43 -040070
71 // CanConvertToBazel is set via InitBazelModule to indicate that a module type can be converted to
72 // Bazel with Bp2build.
73 CanConvertToBazel bool `blueprint:"mutated"`
Jingwen Chen01812022021-11-19 14:29:43 +000074}
75
Liz Kammerba3ea162021-02-17 13:22:03 -050076// Properties contains common module properties for Bazel migration purposes.
77type properties struct {
Chris Parsons1bb58da2022-08-30 13:37:57 -040078 // In "Bazel mixed build" mode, this represents the Bazel target replacing
Liz Kammerba3ea162021-02-17 13:22:03 -050079 // this Soong module.
Jingwen Chen01812022021-11-19 14:29:43 +000080 Bazel_module bazelModuleProperties
Liz Kammerba3ea162021-02-17 13:22:03 -050081}
Liz Kammerea6666f2021-02-17 10:17:28 -050082
Jingwen Chen25825ca2021-11-15 12:28:43 +000083// namespacedVariableProperties is a map from a string representing a Soong
Jingwen Chen84817de2021-11-17 10:57:35 +000084// config variable namespace, like "android" or "vendor_name" to a slice of
85// pointer to a struct containing a single field called Soong_config_variables
86// whose value mirrors the structure in the Blueprint file.
87type namespacedVariableProperties map[string][]interface{}
Jingwen Chena47f28d2021-11-02 16:43:57 +000088
Liz Kammerea6666f2021-02-17 10:17:28 -050089// BazelModuleBase contains the property structs with metadata for modules which can be converted to
90// Bazel.
91type BazelModuleBase struct {
Liz Kammerba3ea162021-02-17 13:22:03 -050092 bazelProperties properties
Jingwen Chena47f28d2021-11-02 16:43:57 +000093
94 // namespacedVariableProperties is used for soong_config_module_type support
95 // in bp2build. Soong config modules allow users to set module properties
96 // based on custom product variables defined in Android.bp files. These
97 // variables are namespaced to prevent clobbering, especially when set from
98 // Makefiles.
99 namespacedVariableProperties namespacedVariableProperties
100
101 // baseModuleType is set when this module was created from a module type
102 // defined by a soong_config_module_type. Every soong_config_module_type
103 // "wraps" another module type, e.g. a soong_config_module_type can wrap a
104 // cc_defaults to a custom_cc_defaults, or cc_binary to a custom_cc_binary.
105 // This baseModuleType is set to the wrapped module type.
106 baseModuleType string
Liz Kammerea6666f2021-02-17 10:17:28 -0500107}
108
109// Bazelable is specifies the interface for modules that can be converted to Bazel.
110type Bazelable interface {
Liz Kammerba3ea162021-02-17 13:22:03 -0500111 bazelProps() *properties
112 HasHandcraftedLabel() bool
Liz Kammerbdc60992021-02-24 16:55:11 -0500113 HandcraftedLabel() string
114 GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400115 ShouldConvertWithBp2build(ctx BazelConversionContext) bool
Sam Delmerico24c56032022-03-28 19:53:03 +0000116 shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400117 ConvertWithBp2build(ctx TopDownMutatorContext)
Jingwen Chena47f28d2021-11-02 16:43:57 +0000118
Jingwen Chen84817de2021-11-17 10:57:35 +0000119 // namespacedVariableProps is a map from a soong config variable namespace
120 // (e.g. acme, android) to a map of interfaces{}, which are really
121 // reflect.Struct pointers, representing the value of the
122 // soong_config_variables property of a module. The struct pointer is the
123 // one with the single member called Soong_config_variables, which itself is
124 // a struct containing fields for each supported feature in that namespace.
125 //
126 // The reason for using an slice of interface{} is to support defaults
127 // propagation of the struct pointers.
Jingwen Chena47f28d2021-11-02 16:43:57 +0000128 namespacedVariableProps() namespacedVariableProperties
129 setNamespacedVariableProps(props namespacedVariableProperties)
130 BaseModuleType() string
Jingwen Chen84817de2021-11-17 10:57:35 +0000131 SetBaseModuleType(baseModuleType string)
Liz Kammerea6666f2021-02-17 10:17:28 -0500132}
133
Chris Parsonsf874e462022-05-10 13:50:12 -0400134// MixedBuildBuildable is an interface that module types should implement in order
135// to be "handled by Bazel" in a mixed build.
136type MixedBuildBuildable interface {
137 // IsMixedBuildSupported returns true if and only if this module should be
138 // "handled by Bazel" in a mixed build.
139 // This "escape hatch" allows modules with corner-case scenarios to opt out
140 // of being built with Bazel.
141 IsMixedBuildSupported(ctx BaseModuleContext) bool
142
143 // QueueBazelCall invokes request-queueing functions on the BazelContext
144 // so that these requests are handled when Bazel's cquery is invoked.
145 QueueBazelCall(ctx BaseModuleContext)
146
147 // ProcessBazelQueryResponse uses Bazel information (obtained from the BazelContext)
148 // to set module fields and providers to propagate this module's metadata upstream.
149 // This effectively "bridges the gap" between Bazel and Soong in a mixed build.
150 // Soong modules depending on this module should be oblivious to the fact that
151 // this module was handled by Bazel.
152 ProcessBazelQueryResponse(ctx ModuleContext)
153}
154
Liz Kammerea6666f2021-02-17 10:17:28 -0500155// BazelModule is a lightweight wrapper interface around Module for Bazel-convertible modules.
156type BazelModule interface {
157 Module
158 Bazelable
159}
160
161// InitBazelModule is a wrapper function that decorates a BazelModule with Bazel-conversion
162// properties.
163func InitBazelModule(module BazelModule) {
164 module.AddProperties(module.bazelProps())
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400165 module.bazelProps().Bazel_module.CanConvertToBazel = true
Liz Kammerea6666f2021-02-17 10:17:28 -0500166}
167
168// bazelProps returns the Bazel properties for the given BazelModuleBase.
Liz Kammerba3ea162021-02-17 13:22:03 -0500169func (b *BazelModuleBase) bazelProps() *properties {
Liz Kammerea6666f2021-02-17 10:17:28 -0500170 return &b.bazelProperties
171}
172
Jingwen Chena47f28d2021-11-02 16:43:57 +0000173func (b *BazelModuleBase) namespacedVariableProps() namespacedVariableProperties {
174 return b.namespacedVariableProperties
175}
176
177func (b *BazelModuleBase) setNamespacedVariableProps(props namespacedVariableProperties) {
178 b.namespacedVariableProperties = props
179}
180
181func (b *BazelModuleBase) BaseModuleType() string {
182 return b.baseModuleType
183}
184
185func (b *BazelModuleBase) SetBaseModuleType(baseModuleType string) {
186 b.baseModuleType = baseModuleType
187}
188
Liz Kammerba3ea162021-02-17 13:22:03 -0500189// HasHandcraftedLabel returns whether this module has a handcrafted Bazel label.
190func (b *BazelModuleBase) HasHandcraftedLabel() bool {
191 return b.bazelProperties.Bazel_module.Label != nil
192}
193
194// HandcraftedLabel returns the handcrafted label for this module, or empty string if there is none
195func (b *BazelModuleBase) HandcraftedLabel() string {
196 return proptools.String(b.bazelProperties.Bazel_module.Label)
197}
198
Liz Kammerea6666f2021-02-17 10:17:28 -0500199// GetBazelLabel returns the Bazel label for the given BazelModuleBase.
Liz Kammerbdc60992021-02-24 16:55:11 -0500200func (b *BazelModuleBase) GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
201 if b.HasHandcraftedLabel() {
202 return b.HandcraftedLabel()
203 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400204 if b.ShouldConvertWithBp2build(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500205 return bp2buildModuleLabel(ctx, module)
206 }
207 return "" // no label for unconverted module
Liz Kammerea6666f2021-02-17 10:17:28 -0500208}
209
Cole Faust324a92e2022-08-23 15:29:05 -0700210type Bp2BuildConversionAllowlist struct {
Sam Delmerico24c56032022-03-28 19:53:03 +0000211 // Configure modules in these directories to enable bp2build_available: true or false by default.
212 defaultConfig allowlists.Bp2BuildConfig
Jingwen Chen12b4c272021-03-10 02:05:59 -0500213
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400214 // Keep any existing BUILD files (and do not generate new BUILD files) for these directories
Jingwen Chenb643c7a2021-07-26 04:45:48 +0000215 // in the synthetic Bazel workspace.
Sam Delmerico24c56032022-03-28 19:53:03 +0000216 keepExistingBuildFile map[string]bool
Jingwen Chen5d72cba2021-03-25 09:28:38 +0000217
Chris Parsonsef615e52022-08-18 22:04:11 -0400218 // Per-module allowlist to always opt modules into both bp2build and Bazel Dev Mode mixed
219 // builds. These modules are usually in directories with many other modules that are not ready
220 // for conversion.
Jingwen Chen7edadab2022-03-04 07:01:29 +0000221 //
222 // A module can either be in this list or its directory allowlisted entirely
223 // in bp2buildDefaultConfig, but not both at the same time.
Sam Delmerico24c56032022-03-28 19:53:03 +0000224 moduleAlwaysConvert map[string]bool
Sam Delmericofa1831c2022-02-22 18:07:55 +0000225
Chris Parsonsef615e52022-08-18 22:04:11 -0400226 // Per-module-type allowlist to always opt modules in to both bp2build and
227 // Bazel Dev Mode mixed builds when they have the same type as one listed.
Sam Delmerico24c56032022-03-28 19:53:03 +0000228 moduleTypeAlwaysConvert map[string]bool
Sam Delmerico85d831a2022-03-07 19:12:42 +0000229
Chris Parsonsad876012022-08-20 14:48:32 -0400230 // Per-module denylist to always opt modules out of bp2build conversion.
Sam Delmerico24c56032022-03-28 19:53:03 +0000231 moduleDoNotConvert map[string]bool
Rupert Shuttleworthc143cc52021-04-13 13:08:04 -0400232
Jingwen Chen179856a2021-05-03 09:15:48 +0000233 // Per-module denylist of cc_library modules to only generate the static
234 // variant if their shared variant isn't ready or buildable by Bazel.
Sam Delmerico24c56032022-03-28 19:53:03 +0000235 ccLibraryStaticOnly map[string]bool
Chris Parsonsad876012022-08-20 14:48:32 -0400236}
Jingwen Chen179856a2021-05-03 09:15:48 +0000237
Chris Parsonsad876012022-08-20 14:48:32 -0400238// GenerateCcLibraryStaticOnly returns whether a cc_library module should only
239// generate a static version of itself based on the current global configuration.
Cole Faust324a92e2022-08-23 15:29:05 -0700240func (a Bp2BuildConversionAllowlist) GenerateCcLibraryStaticOnly(moduleName string) bool {
Chris Parsonsad876012022-08-20 14:48:32 -0400241 return a.ccLibraryStaticOnly[moduleName]
Sam Delmerico24c56032022-03-28 19:53:03 +0000242}
Liz Kammer5c313582021-12-03 15:23:26 -0500243
Cole Faust324a92e2022-08-23 15:29:05 -0700244// NewBp2BuildAllowlist creates a new, empty Bp2BuildConversionAllowlist
Sam Delmerico24c56032022-03-28 19:53:03 +0000245// which can be populated using builder pattern Set* methods
Cole Faust324a92e2022-08-23 15:29:05 -0700246func NewBp2BuildAllowlist() Bp2BuildConversionAllowlist {
247 return Bp2BuildConversionAllowlist{
Sam Delmerico24c56032022-03-28 19:53:03 +0000248 allowlists.Bp2BuildConfig{},
249 map[string]bool{},
250 map[string]bool{},
251 map[string]bool{},
252 map[string]bool{},
253 map[string]bool{},
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400254 }
255}
256
Sam Delmerico24c56032022-03-28 19:53:03 +0000257// SetDefaultConfig copies the entries from defaultConfig into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700258func (a Bp2BuildConversionAllowlist) SetDefaultConfig(defaultConfig allowlists.Bp2BuildConfig) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000259 if a.defaultConfig == nil {
260 a.defaultConfig = allowlists.Bp2BuildConfig{}
261 }
262 for k, v := range defaultConfig {
263 a.defaultConfig[k] = v
264 }
265
266 return a
267}
268
269// SetKeepExistingBuildFile copies the entries from keepExistingBuildFile into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700270func (a Bp2BuildConversionAllowlist) SetKeepExistingBuildFile(keepExistingBuildFile map[string]bool) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000271 if a.keepExistingBuildFile == nil {
272 a.keepExistingBuildFile = map[string]bool{}
273 }
274 for k, v := range keepExistingBuildFile {
275 a.keepExistingBuildFile[k] = v
276 }
277
278 return a
279}
280
281// SetModuleAlwaysConvertList copies the entries from moduleAlwaysConvert into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700282func (a Bp2BuildConversionAllowlist) SetModuleAlwaysConvertList(moduleAlwaysConvert []string) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000283 if a.moduleAlwaysConvert == nil {
284 a.moduleAlwaysConvert = map[string]bool{}
285 }
286 for _, m := range moduleAlwaysConvert {
287 a.moduleAlwaysConvert[m] = true
288 }
289
290 return a
291}
292
293// SetModuleTypeAlwaysConvertList copies the entries from moduleTypeAlwaysConvert into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700294func (a Bp2BuildConversionAllowlist) SetModuleTypeAlwaysConvertList(moduleTypeAlwaysConvert []string) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000295 if a.moduleTypeAlwaysConvert == nil {
296 a.moduleTypeAlwaysConvert = map[string]bool{}
297 }
298 for _, m := range moduleTypeAlwaysConvert {
299 a.moduleTypeAlwaysConvert[m] = true
300 }
301
302 return a
303}
304
305// SetModuleDoNotConvertList copies the entries from moduleDoNotConvert into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700306func (a Bp2BuildConversionAllowlist) SetModuleDoNotConvertList(moduleDoNotConvert []string) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000307 if a.moduleDoNotConvert == nil {
308 a.moduleDoNotConvert = map[string]bool{}
309 }
310 for _, m := range moduleDoNotConvert {
311 a.moduleDoNotConvert[m] = true
312 }
313
314 return a
315}
316
317// SetCcLibraryStaticOnlyList copies the entries from ccLibraryStaticOnly into the allowlist
Cole Faust324a92e2022-08-23 15:29:05 -0700318func (a Bp2BuildConversionAllowlist) SetCcLibraryStaticOnlyList(ccLibraryStaticOnly []string) Bp2BuildConversionAllowlist {
Sam Delmerico24c56032022-03-28 19:53:03 +0000319 if a.ccLibraryStaticOnly == nil {
320 a.ccLibraryStaticOnly = map[string]bool{}
321 }
322 for _, m := range ccLibraryStaticOnly {
323 a.ccLibraryStaticOnly[m] = true
324 }
325
326 return a
327}
328
Sam Delmerico24c56032022-03-28 19:53:03 +0000329// ShouldKeepExistingBuildFileForDir returns whether an existing BUILD file should be
330// added to the build symlink forest based on the current global configuration.
Cole Faust324a92e2022-08-23 15:29:05 -0700331func (a Bp2BuildConversionAllowlist) ShouldKeepExistingBuildFileForDir(dir string) bool {
332 if _, ok := a.keepExistingBuildFile[dir]; ok {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400333 // Exact dir match
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400334 return true
335 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400336 // Check if subtree match
Cole Faust324a92e2022-08-23 15:29:05 -0700337 for prefix, recursive := range a.keepExistingBuildFile {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400338 if recursive {
339 if strings.HasPrefix(dir, prefix+"/") {
340 return true
341 }
342 }
343 }
344 // Default
345 return false
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400346}
347
Cole Faust324a92e2022-08-23 15:29:05 -0700348var bp2BuildAllowListKey = NewOnceKey("Bp2BuildAllowlist")
349var bp2buildAllowlist OncePer
350
351func GetBp2BuildAllowList() Bp2BuildConversionAllowlist {
352 return bp2buildAllowlist.Once(bp2BuildAllowListKey, func() interface{} {
353 return NewBp2BuildAllowlist().SetDefaultConfig(allowlists.Bp2buildDefaultConfig).
354 SetKeepExistingBuildFile(allowlists.Bp2buildKeepExistingBuildFile).
355 SetModuleAlwaysConvertList(allowlists.Bp2buildModuleAlwaysConvertList).
356 SetModuleTypeAlwaysConvertList(allowlists.Bp2buildModuleTypeAlwaysConvertList).
357 SetModuleDoNotConvertList(allowlists.Bp2buildModuleDoNotConvertList).
358 SetCcLibraryStaticOnlyList(allowlists.Bp2buildCcLibraryStaticOnlyList)
359 }).(Bp2BuildConversionAllowlist)
360}
361
MarkDacekff851b82022-04-21 18:33:17 +0000362// MixedBuildsEnabled returns true if a module is ready to be replaced by a
363// converted or handcrafted Bazel target. As a side effect, calling this
364// method will also log whether this module is mixed build enabled for
365// metrics reporting.
Chris Parsonsf874e462022-05-10 13:50:12 -0400366func MixedBuildsEnabled(ctx BaseModuleContext) bool {
MarkDacekff851b82022-04-21 18:33:17 +0000367 mixedBuildEnabled := mixedBuildPossible(ctx)
368 ctx.Config().LogMixedBuild(ctx, mixedBuildEnabled)
369 return mixedBuildEnabled
370}
371
372// mixedBuildPossible returns true if a module is ready to be replaced by a
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400373// converted or handcrafted Bazel target.
Chris Parsonsf874e462022-05-10 13:50:12 -0400374func mixedBuildPossible(ctx BaseModuleContext) bool {
Chris Parsons494eef32021-11-09 10:29:52 -0500375 if ctx.Os() == Windows {
376 // Windows toolchains are not currently supported.
377 return false
378 }
Chris Parsons58852a02021-12-09 18:10:18 -0500379 if !ctx.Module().Enabled() {
380 return false
381 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400382 if !convertedToBazel(ctx, ctx.Module()) {
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400383 return false
384 }
Chris Parsonsad876012022-08-20 14:48:32 -0400385 return ctx.Config().BazelContext.BazelAllowlisted(ctx.Module().Name())
Rupert Shuttleworth4f43fe92021-03-30 14:13:16 +0000386}
387
Liz Kammer6eff3232021-08-26 08:37:59 -0400388// ConvertedToBazel returns whether this module has been converted (with bp2build or manually) to Bazel.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000389func convertedToBazel(ctx BazelConversionContext, module blueprint.Module) bool {
Liz Kammer6eff3232021-08-26 08:37:59 -0400390 b, ok := module.(Bazelable)
391 if !ok {
392 return false
393 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400394 return b.shouldConvertWithBp2build(ctx, module) || b.HasHandcraftedLabel()
Liz Kammer6eff3232021-08-26 08:37:59 -0400395}
396
Sam Delmerico24c56032022-03-28 19:53:03 +0000397// ShouldConvertWithBp2build returns whether the given BazelModuleBase should be converted with bp2build
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400398func (b *BazelModuleBase) ShouldConvertWithBp2build(ctx BazelConversionContext) bool {
399 return b.shouldConvertWithBp2build(ctx, ctx.Module())
Liz Kammer6eff3232021-08-26 08:37:59 -0400400}
401
Sam Delmerico24c56032022-03-28 19:53:03 +0000402type bazelOtherModuleContext interface {
403 ModuleErrorf(format string, args ...interface{})
404 Config() Config
405 OtherModuleType(m blueprint.Module) string
406 OtherModuleName(m blueprint.Module) string
407 OtherModuleDir(m blueprint.Module) string
408}
Sam Delmericofa1831c2022-02-22 18:07:55 +0000409
Sam Delmerico24c56032022-03-28 19:53:03 +0000410func (b *BazelModuleBase) shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400411 if !b.bazelProps().Bazel_module.CanConvertToBazel {
412 return false
Jingwen Chen12b4c272021-03-10 02:05:59 -0500413 }
414
Sam Delmerico85d831a2022-03-07 19:12:42 +0000415 propValue := b.bazelProperties.Bazel_module.Bp2build_available
Liz Kammer6eff3232021-08-26 08:37:59 -0400416 packagePath := ctx.OtherModuleDir(module)
Sam Delmerico24c56032022-03-28 19:53:03 +0000417
Sam Delmerico85d831a2022-03-07 19:12:42 +0000418 // Modules in unit tests which are enabled in the allowlist by type or name
419 // trigger this conditional because unit tests run under the "." package path
Sam Delmerico24c56032022-03-28 19:53:03 +0000420 isTestModule := packagePath == Bp2BuildTopLevel && proptools.BoolDefault(propValue, false)
421 if isTestModule {
422 return true
423 }
424
425 moduleName := module.Name()
Cole Faust324a92e2022-08-23 15:29:05 -0700426 allowlist := ctx.Config().Bp2buildPackageConfig
Sam Delmerico24c56032022-03-28 19:53:03 +0000427 moduleNameAllowed := allowlist.moduleAlwaysConvert[moduleName]
428 moduleTypeAllowed := allowlist.moduleTypeAlwaysConvert[ctx.OtherModuleType(module)]
429 allowlistConvert := moduleNameAllowed || moduleTypeAllowed
430 if moduleNameAllowed && moduleTypeAllowed {
431 ctx.ModuleErrorf("A module cannot be in moduleAlwaysConvert and also be in moduleTypeAlwaysConvert")
432 return false
433 }
434
435 if allowlist.moduleDoNotConvert[moduleName] {
Sam Delmerico85d831a2022-03-07 19:12:42 +0000436 if moduleNameAllowed {
Sam Delmerico24c56032022-03-28 19:53:03 +0000437 ctx.ModuleErrorf("a module cannot be in moduleDoNotConvert and also be in moduleAlwaysConvert")
Sam Delmerico85d831a2022-03-07 19:12:42 +0000438 }
Sam Delmerico94d26c22022-02-25 21:34:51 +0000439 return false
440 }
441
Sam Delmerico24c56032022-03-28 19:53:03 +0000442 // This is a tristate value: true, false, or unset.
443 if ok, directoryPath := bp2buildDefaultTrueRecursively(packagePath, allowlist.defaultConfig); ok {
444 if moduleNameAllowed {
445 ctx.ModuleErrorf("A module cannot be in a directory marked Bp2BuildDefaultTrue"+
446 " or Bp2BuildDefaultTrueRecursively and also be in moduleAlwaysConvert. Directory: '%s'",
447 directoryPath)
448 return false
Sam Delmericofa1831c2022-02-22 18:07:55 +0000449 }
450
Jingwen Chen12b4c272021-03-10 02:05:59 -0500451 // Allow modules to explicitly opt-out.
452 return proptools.BoolDefault(propValue, true)
453 }
454
455 // Allow modules to explicitly opt-in.
Sam Delmerico85d831a2022-03-07 19:12:42 +0000456 return proptools.BoolDefault(propValue, allowlistConvert)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500457}
458
459// bp2buildDefaultTrueRecursively checks that the package contains a prefix from the
460// set of package prefixes where all modules must be converted. That is, if the
461// package is x/y/z, and the list contains either x, x/y, or x/y/z, this function will
462// return true.
463//
464// However, if the package is x/y, and it matches a Bp2BuildDefaultFalse "x/y" entry
465// exactly, this module will return false early.
466//
467// This function will also return false if the package doesn't match anything in
468// the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000469//
470// This function will also return the allowlist entry which caused a particular
471// package to be enabled. Since packages can be enabled via a recursive declaration,
472// the path returned will not always be the same as the one provided.
473func bp2buildDefaultTrueRecursively(packagePath string, config allowlists.Bp2BuildConfig) (bool, string) {
Jingwen Chen294e7742021-08-31 05:58:01 +0000474 // Check if the package path has an exact match in the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000475 if config[packagePath] == allowlists.Bp2BuildDefaultTrue || config[packagePath] == allowlists.Bp2BuildDefaultTrueRecursively {
476 return true, packagePath
477 } else if config[packagePath] == allowlists.Bp2BuildDefaultFalse {
478 return false, packagePath
Jingwen Chen12b4c272021-03-10 02:05:59 -0500479 }
480
Jingwen Chen91220d72021-03-24 02:18:33 -0400481 // If not, check for the config recursively.
Jingwen Chen12b4c272021-03-10 02:05:59 -0500482 packagePrefix := ""
483 // e.g. for x/y/z, iterate over x, x/y, then x/y/z, taking the final value from the allowlist.
484 for _, part := range strings.Split(packagePath, "/") {
485 packagePrefix += part
Sam Delmerico24c56032022-03-28 19:53:03 +0000486 if config[packagePrefix] == allowlists.Bp2BuildDefaultTrueRecursively {
Jingwen Chen12b4c272021-03-10 02:05:59 -0500487 // package contains this prefix and this prefix should convert all modules
Sam Delmerico24c56032022-03-28 19:53:03 +0000488 return true, packagePrefix
Jingwen Chen12b4c272021-03-10 02:05:59 -0500489 }
490 // Continue to the next part of the package dir.
491 packagePrefix += "/"
492 }
493
Sam Delmerico24c56032022-03-28 19:53:03 +0000494 return false, packagePath
Liz Kammerea6666f2021-02-17 10:17:28 -0500495}
Liz Kammerba3ea162021-02-17 13:22:03 -0500496
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400497func registerBp2buildConversionMutator(ctx RegisterMutatorsContext) {
498 ctx.TopDown("bp2build_conversion", convertWithBp2build).Parallel()
499}
500
501func convertWithBp2build(ctx TopDownMutatorContext) {
502 bModule, ok := ctx.Module().(Bazelable)
503 if !ok || !bModule.shouldConvertWithBp2build(ctx, ctx.Module()) {
504 return
505 }
506
507 bModule.ConvertWithBp2build(ctx)
508}
Wei Libafb6d62021-12-10 03:14:59 -0800509
510// GetMainClassInManifest scans the manifest file specified in filepath and returns
511// the value of attribute Main-Class in the manifest file if it exists, or returns error.
512// WARNING: this is for bp2build converters of java_* modules only.
513func GetMainClassInManifest(c Config, filepath string) (string, error) {
514 file, err := c.fs.Open(filepath)
515 if err != nil {
516 return "", err
517 }
Liz Kammer0fe123d2022-02-07 10:17:35 -0500518 defer file.Close()
Wei Libafb6d62021-12-10 03:14:59 -0800519 scanner := bufio.NewScanner(file)
520 for scanner.Scan() {
521 line := scanner.Text()
522 if strings.HasPrefix(line, "Main-Class:") {
523 return strings.TrimSpace(line[len("Main-Class:"):]), nil
524 }
525 }
526
527 return "", errors.New("Main-Class is not found.")
528}