blob: 67002ecf66d05105fa98e17a84aa88d9bdb37a00 [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 "fmt"
21 "io/ioutil"
22 "path/filepath"
23 "strings"
24
Liz Kammerbdc60992021-02-24 16:55:11 -050025 "github.com/google/blueprint"
Liz Kammerba3ea162021-02-17 13:22:03 -050026 "github.com/google/blueprint/proptools"
Sam Delmerico24c56032022-03-28 19:53:03 +000027
28 "android/soong/android/allowlists"
29)
30
31const (
32 // A sentinel value to be used as a key in Bp2BuildConfig for modules with
33 // no package path. This is also the module dir for top level Android.bp
34 // modules.
35 Bp2BuildTopLevel = "."
Liz Kammerba3ea162021-02-17 13:22:03 -050036)
37
Jingwen Chen01812022021-11-19 14:29:43 +000038type bazelModuleProperties struct {
39 // The label of the Bazel target replacing this Soong module. When run in conversion mode, this
40 // will import the handcrafted build target into the autogenerated file. Note: this may result in
41 // a conflict due to duplicate targets if bp2build_available is also set.
42 Label *string
43
44 // If true, bp2build will generate the converted Bazel target for this module. Note: this may
45 // cause a conflict due to the duplicate targets if label is also set.
46 //
47 // This is a bool pointer to support tristates: true, false, not set.
48 //
49 // To opt-in a module, set bazel_module: { bp2build_available: true }
50 // To opt-out a module, set bazel_module: { bp2build_available: false }
51 // To defer the default setting for the directory, do not set the value.
52 Bp2build_available *bool
Liz Kammerbe46fcc2021-11-01 15:32:43 -040053
54 // CanConvertToBazel is set via InitBazelModule to indicate that a module type can be converted to
55 // Bazel with Bp2build.
56 CanConvertToBazel bool `blueprint:"mutated"`
Jingwen Chen01812022021-11-19 14:29:43 +000057}
58
Liz Kammerba3ea162021-02-17 13:22:03 -050059// Properties contains common module properties for Bazel migration purposes.
60type properties struct {
61 // In USE_BAZEL_ANALYSIS=1 mode, this represents the Bazel target replacing
62 // this Soong module.
Jingwen Chen01812022021-11-19 14:29:43 +000063 Bazel_module bazelModuleProperties
Liz Kammerba3ea162021-02-17 13:22:03 -050064}
Liz Kammerea6666f2021-02-17 10:17:28 -050065
Jingwen Chen25825ca2021-11-15 12:28:43 +000066// namespacedVariableProperties is a map from a string representing a Soong
Jingwen Chen84817de2021-11-17 10:57:35 +000067// config variable namespace, like "android" or "vendor_name" to a slice of
68// pointer to a struct containing a single field called Soong_config_variables
69// whose value mirrors the structure in the Blueprint file.
70type namespacedVariableProperties map[string][]interface{}
Jingwen Chena47f28d2021-11-02 16:43:57 +000071
Liz Kammerea6666f2021-02-17 10:17:28 -050072// BazelModuleBase contains the property structs with metadata for modules which can be converted to
73// Bazel.
74type BazelModuleBase struct {
Liz Kammerba3ea162021-02-17 13:22:03 -050075 bazelProperties properties
Jingwen Chena47f28d2021-11-02 16:43:57 +000076
77 // namespacedVariableProperties is used for soong_config_module_type support
78 // in bp2build. Soong config modules allow users to set module properties
79 // based on custom product variables defined in Android.bp files. These
80 // variables are namespaced to prevent clobbering, especially when set from
81 // Makefiles.
82 namespacedVariableProperties namespacedVariableProperties
83
84 // baseModuleType is set when this module was created from a module type
85 // defined by a soong_config_module_type. Every soong_config_module_type
86 // "wraps" another module type, e.g. a soong_config_module_type can wrap a
87 // cc_defaults to a custom_cc_defaults, or cc_binary to a custom_cc_binary.
88 // This baseModuleType is set to the wrapped module type.
89 baseModuleType string
Liz Kammerea6666f2021-02-17 10:17:28 -050090}
91
92// Bazelable is specifies the interface for modules that can be converted to Bazel.
93type Bazelable interface {
Liz Kammerba3ea162021-02-17 13:22:03 -050094 bazelProps() *properties
95 HasHandcraftedLabel() bool
Liz Kammerbdc60992021-02-24 16:55:11 -050096 HandcraftedLabel() string
97 GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string
Liz Kammerbe46fcc2021-11-01 15:32:43 -040098 ShouldConvertWithBp2build(ctx BazelConversionContext) bool
Sam Delmerico24c56032022-03-28 19:53:03 +000099 shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool
Liz Kammerba3ea162021-02-17 13:22:03 -0500100 GetBazelBuildFileContents(c Config, path, name string) (string, error)
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400101 ConvertWithBp2build(ctx TopDownMutatorContext)
Jingwen Chena47f28d2021-11-02 16:43:57 +0000102
Jingwen Chen84817de2021-11-17 10:57:35 +0000103 // namespacedVariableProps is a map from a soong config variable namespace
104 // (e.g. acme, android) to a map of interfaces{}, which are really
105 // reflect.Struct pointers, representing the value of the
106 // soong_config_variables property of a module. The struct pointer is the
107 // one with the single member called Soong_config_variables, which itself is
108 // a struct containing fields for each supported feature in that namespace.
109 //
110 // The reason for using an slice of interface{} is to support defaults
111 // propagation of the struct pointers.
Jingwen Chena47f28d2021-11-02 16:43:57 +0000112 namespacedVariableProps() namespacedVariableProperties
113 setNamespacedVariableProps(props namespacedVariableProperties)
114 BaseModuleType() string
Jingwen Chen84817de2021-11-17 10:57:35 +0000115 SetBaseModuleType(baseModuleType string)
Liz Kammerea6666f2021-02-17 10:17:28 -0500116}
117
118// BazelModule is a lightweight wrapper interface around Module for Bazel-convertible modules.
119type BazelModule interface {
120 Module
121 Bazelable
122}
123
124// InitBazelModule is a wrapper function that decorates a BazelModule with Bazel-conversion
125// properties.
126func InitBazelModule(module BazelModule) {
127 module.AddProperties(module.bazelProps())
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400128 module.bazelProps().Bazel_module.CanConvertToBazel = true
Liz Kammerea6666f2021-02-17 10:17:28 -0500129}
130
131// bazelProps returns the Bazel properties for the given BazelModuleBase.
Liz Kammerba3ea162021-02-17 13:22:03 -0500132func (b *BazelModuleBase) bazelProps() *properties {
Liz Kammerea6666f2021-02-17 10:17:28 -0500133 return &b.bazelProperties
134}
135
Jingwen Chena47f28d2021-11-02 16:43:57 +0000136func (b *BazelModuleBase) namespacedVariableProps() namespacedVariableProperties {
137 return b.namespacedVariableProperties
138}
139
140func (b *BazelModuleBase) setNamespacedVariableProps(props namespacedVariableProperties) {
141 b.namespacedVariableProperties = props
142}
143
144func (b *BazelModuleBase) BaseModuleType() string {
145 return b.baseModuleType
146}
147
148func (b *BazelModuleBase) SetBaseModuleType(baseModuleType string) {
149 b.baseModuleType = baseModuleType
150}
151
Liz Kammerba3ea162021-02-17 13:22:03 -0500152// HasHandcraftedLabel returns whether this module has a handcrafted Bazel label.
153func (b *BazelModuleBase) HasHandcraftedLabel() bool {
154 return b.bazelProperties.Bazel_module.Label != nil
155}
156
157// HandcraftedLabel returns the handcrafted label for this module, or empty string if there is none
158func (b *BazelModuleBase) HandcraftedLabel() string {
159 return proptools.String(b.bazelProperties.Bazel_module.Label)
160}
161
Liz Kammerea6666f2021-02-17 10:17:28 -0500162// GetBazelLabel returns the Bazel label for the given BazelModuleBase.
Liz Kammerbdc60992021-02-24 16:55:11 -0500163func (b *BazelModuleBase) GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
164 if b.HasHandcraftedLabel() {
165 return b.HandcraftedLabel()
166 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400167 if b.ShouldConvertWithBp2build(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500168 return bp2buildModuleLabel(ctx, module)
169 }
170 return "" // no label for unconverted module
Liz Kammerea6666f2021-02-17 10:17:28 -0500171}
172
Sam Delmerico24c56032022-03-28 19:53:03 +0000173type bp2BuildConversionAllowlist struct {
174 // Configure modules in these directories to enable bp2build_available: true or false by default.
175 defaultConfig allowlists.Bp2BuildConfig
Jingwen Chen12b4c272021-03-10 02:05:59 -0500176
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400177 // Keep any existing BUILD files (and do not generate new BUILD files) for these directories
Jingwen Chenb643c7a2021-07-26 04:45:48 +0000178 // in the synthetic Bazel workspace.
Sam Delmerico24c56032022-03-28 19:53:03 +0000179 keepExistingBuildFile map[string]bool
Jingwen Chen5d72cba2021-03-25 09:28:38 +0000180
Sam Delmericofa1831c2022-02-22 18:07:55 +0000181 // Per-module allowlist to always opt modules in of both bp2build and mixed builds.
Jingwen Chen7edadab2022-03-04 07:01:29 +0000182 // These modules are usually in directories with many other modules that are not ready for
183 // conversion.
184 //
185 // A module can either be in this list or its directory allowlisted entirely
186 // in bp2buildDefaultConfig, but not both at the same time.
Sam Delmerico24c56032022-03-28 19:53:03 +0000187 moduleAlwaysConvert map[string]bool
Sam Delmericofa1831c2022-02-22 18:07:55 +0000188
Sam Delmericoa9b047a2022-02-22 19:21:28 +0000189 // Per-module-type allowlist to always opt modules in to both bp2build and mixed builds
Sam Delmerico85d831a2022-03-07 19:12:42 +0000190 // when they have the same type as one listed.
Sam Delmerico24c56032022-03-28 19:53:03 +0000191 moduleTypeAlwaysConvert map[string]bool
Sam Delmerico85d831a2022-03-07 19:12:42 +0000192
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400193 // Per-module denylist to always opt modules out of both bp2build and mixed builds.
Sam Delmerico24c56032022-03-28 19:53:03 +0000194 moduleDoNotConvert map[string]bool
Rupert Shuttleworthc143cc52021-04-13 13:08:04 -0400195
Jingwen Chen179856a2021-05-03 09:15:48 +0000196 // Per-module denylist of cc_library modules to only generate the static
197 // variant if their shared variant isn't ready or buildable by Bazel.
Sam Delmerico24c56032022-03-28 19:53:03 +0000198 ccLibraryStaticOnly map[string]bool
Jingwen Chen179856a2021-05-03 09:15:48 +0000199
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400200 // Per-module denylist to opt modules out of mixed builds. Such modules will
201 // still be generated via bp2build.
Sam Delmerico24c56032022-03-28 19:53:03 +0000202 mixedBuildsDisabled map[string]bool
203}
Liz Kammer5c313582021-12-03 15:23:26 -0500204
Sam Delmerico24c56032022-03-28 19:53:03 +0000205// NewBp2BuildAllowlist creates a new, empty bp2BuildConversionAllowlist
206// which can be populated using builder pattern Set* methods
207func NewBp2BuildAllowlist() bp2BuildConversionAllowlist {
208 return bp2BuildConversionAllowlist{
209 allowlists.Bp2BuildConfig{},
210 map[string]bool{},
211 map[string]bool{},
212 map[string]bool{},
213 map[string]bool{},
214 map[string]bool{},
215 map[string]bool{},
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400216 }
217}
218
Sam Delmerico24c56032022-03-28 19:53:03 +0000219// SetDefaultConfig copies the entries from defaultConfig into the allowlist
220func (a bp2BuildConversionAllowlist) SetDefaultConfig(defaultConfig allowlists.Bp2BuildConfig) bp2BuildConversionAllowlist {
221 if a.defaultConfig == nil {
222 a.defaultConfig = allowlists.Bp2BuildConfig{}
223 }
224 for k, v := range defaultConfig {
225 a.defaultConfig[k] = v
226 }
227
228 return a
229}
230
231// SetKeepExistingBuildFile copies the entries from keepExistingBuildFile into the allowlist
232func (a bp2BuildConversionAllowlist) SetKeepExistingBuildFile(keepExistingBuildFile map[string]bool) bp2BuildConversionAllowlist {
233 if a.keepExistingBuildFile == nil {
234 a.keepExistingBuildFile = map[string]bool{}
235 }
236 for k, v := range keepExistingBuildFile {
237 a.keepExistingBuildFile[k] = v
238 }
239
240 return a
241}
242
243// SetModuleAlwaysConvertList copies the entries from moduleAlwaysConvert into the allowlist
244func (a bp2BuildConversionAllowlist) SetModuleAlwaysConvertList(moduleAlwaysConvert []string) bp2BuildConversionAllowlist {
245 if a.moduleAlwaysConvert == nil {
246 a.moduleAlwaysConvert = map[string]bool{}
247 }
248 for _, m := range moduleAlwaysConvert {
249 a.moduleAlwaysConvert[m] = true
250 }
251
252 return a
253}
254
255// SetModuleTypeAlwaysConvertList copies the entries from moduleTypeAlwaysConvert into the allowlist
256func (a bp2BuildConversionAllowlist) SetModuleTypeAlwaysConvertList(moduleTypeAlwaysConvert []string) bp2BuildConversionAllowlist {
257 if a.moduleTypeAlwaysConvert == nil {
258 a.moduleTypeAlwaysConvert = map[string]bool{}
259 }
260 for _, m := range moduleTypeAlwaysConvert {
261 a.moduleTypeAlwaysConvert[m] = true
262 }
263
264 return a
265}
266
267// SetModuleDoNotConvertList copies the entries from moduleDoNotConvert into the allowlist
268func (a bp2BuildConversionAllowlist) SetModuleDoNotConvertList(moduleDoNotConvert []string) bp2BuildConversionAllowlist {
269 if a.moduleDoNotConvert == nil {
270 a.moduleDoNotConvert = map[string]bool{}
271 }
272 for _, m := range moduleDoNotConvert {
273 a.moduleDoNotConvert[m] = true
274 }
275
276 return a
277}
278
279// SetCcLibraryStaticOnlyList copies the entries from ccLibraryStaticOnly into the allowlist
280func (a bp2BuildConversionAllowlist) SetCcLibraryStaticOnlyList(ccLibraryStaticOnly []string) bp2BuildConversionAllowlist {
281 if a.ccLibraryStaticOnly == nil {
282 a.ccLibraryStaticOnly = map[string]bool{}
283 }
284 for _, m := range ccLibraryStaticOnly {
285 a.ccLibraryStaticOnly[m] = true
286 }
287
288 return a
289}
290
291// SetMixedBuildsDisabledList copies the entries from mixedBuildsDisabled into the allowlist
292func (a bp2BuildConversionAllowlist) SetMixedBuildsDisabledList(mixedBuildsDisabled []string) bp2BuildConversionAllowlist {
293 if a.mixedBuildsDisabled == nil {
294 a.mixedBuildsDisabled = map[string]bool{}
295 }
296 for _, m := range mixedBuildsDisabled {
297 a.mixedBuildsDisabled[m] = true
298 }
299
300 return a
301}
302
303var bp2buildAllowlist = NewBp2BuildAllowlist().
304 SetDefaultConfig(allowlists.Bp2buildDefaultConfig).
305 SetKeepExistingBuildFile(allowlists.Bp2buildKeepExistingBuildFile).
306 SetModuleAlwaysConvertList(allowlists.Bp2buildModuleAlwaysConvertList).
307 SetModuleTypeAlwaysConvertList(allowlists.Bp2buildModuleTypeAlwaysConvertList).
308 SetModuleDoNotConvertList(allowlists.Bp2buildModuleDoNotConvertList).
309 SetCcLibraryStaticOnlyList(allowlists.Bp2buildCcLibraryStaticOnlyList).
310 SetMixedBuildsDisabledList(allowlists.MixedBuildsDisabledList)
311
312// GenerateCcLibraryStaticOnly returns whether a cc_library module should only
313// generate a static version of itself based on the current global configuration.
Chris Parsons953b3562021-09-20 15:14:39 -0400314func GenerateCcLibraryStaticOnly(moduleName string) bool {
Sam Delmerico24c56032022-03-28 19:53:03 +0000315 return bp2buildAllowlist.ccLibraryStaticOnly[moduleName]
Jingwen Chen179856a2021-05-03 09:15:48 +0000316}
317
Sam Delmerico24c56032022-03-28 19:53:03 +0000318// ShouldKeepExistingBuildFileForDir returns whether an existing BUILD file should be
319// added to the build symlink forest based on the current global configuration.
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400320func ShouldKeepExistingBuildFileForDir(dir string) bool {
Sam Delmerico24c56032022-03-28 19:53:03 +0000321 return shouldKeepExistingBuildFileForDir(bp2buildAllowlist, dir)
322}
323
324func shouldKeepExistingBuildFileForDir(allowlist bp2BuildConversionAllowlist, dir string) bool {
325 if _, ok := allowlist.keepExistingBuildFile[dir]; ok {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400326 // Exact dir match
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400327 return true
328 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400329 // Check if subtree match
Sam Delmerico24c56032022-03-28 19:53:03 +0000330 for prefix, recursive := range allowlist.keepExistingBuildFile {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400331 if recursive {
332 if strings.HasPrefix(dir, prefix+"/") {
333 return true
334 }
335 }
336 }
337 // Default
338 return false
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400339}
340
MarkDacekff851b82022-04-21 18:33:17 +0000341// MixedBuildsEnabled returns true if a module is ready to be replaced by a
342// converted or handcrafted Bazel target. As a side effect, calling this
343// method will also log whether this module is mixed build enabled for
344// metrics reporting.
345func MixedBuildsEnabled(ctx ModuleContext) bool {
346 mixedBuildEnabled := mixedBuildPossible(ctx)
347 ctx.Config().LogMixedBuild(ctx, mixedBuildEnabled)
348 return mixedBuildEnabled
349}
350
351// mixedBuildPossible returns true if a module is ready to be replaced by a
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400352// converted or handcrafted Bazel target.
MarkDacekff851b82022-04-21 18:33:17 +0000353func mixedBuildPossible(ctx ModuleContext) bool {
Chris Parsons494eef32021-11-09 10:29:52 -0500354 if ctx.Os() == Windows {
355 // Windows toolchains are not currently supported.
356 return false
357 }
Chris Parsons58852a02021-12-09 18:10:18 -0500358 if !ctx.Module().Enabled() {
359 return false
360 }
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400361 if !ctx.Config().BazelContext.BazelEnabled() {
362 return false
363 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400364 if !convertedToBazel(ctx, ctx.Module()) {
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400365 return false
366 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400367
Chris Parsons953b3562021-09-20 15:14:39 -0400368 if GenerateCcLibraryStaticOnly(ctx.Module().Name()) {
Jingwen Chen179856a2021-05-03 09:15:48 +0000369 // Don't use partially-converted cc_library targets in mixed builds,
370 // since mixed builds would generally rely on both static and shared
371 // variants of a cc_library.
372 return false
373 }
Sam Delmerico24c56032022-03-28 19:53:03 +0000374 return !bp2buildAllowlist.mixedBuildsDisabled[ctx.Module().Name()]
Rupert Shuttleworth4f43fe92021-03-30 14:13:16 +0000375}
376
Liz Kammer6eff3232021-08-26 08:37:59 -0400377// ConvertedToBazel returns whether this module has been converted (with bp2build or manually) to Bazel.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000378func convertedToBazel(ctx BazelConversionContext, module blueprint.Module) bool {
Liz Kammer6eff3232021-08-26 08:37:59 -0400379 b, ok := module.(Bazelable)
380 if !ok {
381 return false
382 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400383 return b.shouldConvertWithBp2build(ctx, module) || b.HasHandcraftedLabel()
Liz Kammer6eff3232021-08-26 08:37:59 -0400384}
385
Sam Delmerico24c56032022-03-28 19:53:03 +0000386// ShouldConvertWithBp2build returns whether the given BazelModuleBase should be converted with bp2build
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400387func (b *BazelModuleBase) ShouldConvertWithBp2build(ctx BazelConversionContext) bool {
388 return b.shouldConvertWithBp2build(ctx, ctx.Module())
Liz Kammer6eff3232021-08-26 08:37:59 -0400389}
390
Sam Delmerico24c56032022-03-28 19:53:03 +0000391type bazelOtherModuleContext interface {
392 ModuleErrorf(format string, args ...interface{})
393 Config() Config
394 OtherModuleType(m blueprint.Module) string
395 OtherModuleName(m blueprint.Module) string
396 OtherModuleDir(m blueprint.Module) string
397}
Sam Delmericofa1831c2022-02-22 18:07:55 +0000398
Sam Delmerico24c56032022-03-28 19:53:03 +0000399func (b *BazelModuleBase) shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400400 if !b.bazelProps().Bazel_module.CanConvertToBazel {
401 return false
Jingwen Chen12b4c272021-03-10 02:05:59 -0500402 }
403
Sam Delmerico85d831a2022-03-07 19:12:42 +0000404 propValue := b.bazelProperties.Bazel_module.Bp2build_available
Liz Kammer6eff3232021-08-26 08:37:59 -0400405 packagePath := ctx.OtherModuleDir(module)
Sam Delmerico24c56032022-03-28 19:53:03 +0000406
Sam Delmerico85d831a2022-03-07 19:12:42 +0000407 // Modules in unit tests which are enabled in the allowlist by type or name
408 // trigger this conditional because unit tests run under the "." package path
Sam Delmerico24c56032022-03-28 19:53:03 +0000409 isTestModule := packagePath == Bp2BuildTopLevel && proptools.BoolDefault(propValue, false)
410 if isTestModule {
411 return true
412 }
413
414 moduleName := module.Name()
415 allowlist := ctx.Config().bp2buildPackageConfig
416 moduleNameAllowed := allowlist.moduleAlwaysConvert[moduleName]
417 moduleTypeAllowed := allowlist.moduleTypeAlwaysConvert[ctx.OtherModuleType(module)]
418 allowlistConvert := moduleNameAllowed || moduleTypeAllowed
419 if moduleNameAllowed && moduleTypeAllowed {
420 ctx.ModuleErrorf("A module cannot be in moduleAlwaysConvert and also be in moduleTypeAlwaysConvert")
421 return false
422 }
423
424 if allowlist.moduleDoNotConvert[moduleName] {
Sam Delmerico85d831a2022-03-07 19:12:42 +0000425 if moduleNameAllowed {
Sam Delmerico24c56032022-03-28 19:53:03 +0000426 ctx.ModuleErrorf("a module cannot be in moduleDoNotConvert and also be in moduleAlwaysConvert")
Sam Delmerico85d831a2022-03-07 19:12:42 +0000427 }
Sam Delmerico94d26c22022-02-25 21:34:51 +0000428 return false
429 }
430
Sam Delmerico24c56032022-03-28 19:53:03 +0000431 if allowlistConvert && shouldKeepExistingBuildFileForDir(allowlist, packagePath) {
Sam Delmerico85d831a2022-03-07 19:12:42 +0000432 if moduleNameAllowed {
Sam Delmerico24c56032022-03-28 19:53:03 +0000433 ctx.ModuleErrorf("A module cannot be in a directory listed in keepExistingBuildFile"+
434 " and also be in moduleAlwaysConvert. Directory: '%s'", packagePath)
435 return false
436 }
437 }
438
439 // This is a tristate value: true, false, or unset.
440 if ok, directoryPath := bp2buildDefaultTrueRecursively(packagePath, allowlist.defaultConfig); ok {
441 if moduleNameAllowed {
442 ctx.ModuleErrorf("A module cannot be in a directory marked Bp2BuildDefaultTrue"+
443 " or Bp2BuildDefaultTrueRecursively and also be in moduleAlwaysConvert. Directory: '%s'",
444 directoryPath)
445 return false
Sam Delmericofa1831c2022-02-22 18:07:55 +0000446 }
447
Jingwen Chen12b4c272021-03-10 02:05:59 -0500448 // Allow modules to explicitly opt-out.
449 return proptools.BoolDefault(propValue, true)
450 }
451
452 // Allow modules to explicitly opt-in.
Sam Delmerico85d831a2022-03-07 19:12:42 +0000453 return proptools.BoolDefault(propValue, allowlistConvert)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500454}
455
456// bp2buildDefaultTrueRecursively checks that the package contains a prefix from the
457// set of package prefixes where all modules must be converted. That is, if the
458// package is x/y/z, and the list contains either x, x/y, or x/y/z, this function will
459// return true.
460//
461// However, if the package is x/y, and it matches a Bp2BuildDefaultFalse "x/y" entry
462// exactly, this module will return false early.
463//
464// This function will also return false if the package doesn't match anything in
465// the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000466//
467// This function will also return the allowlist entry which caused a particular
468// package to be enabled. Since packages can be enabled via a recursive declaration,
469// the path returned will not always be the same as the one provided.
470func bp2buildDefaultTrueRecursively(packagePath string, config allowlists.Bp2BuildConfig) (bool, string) {
Jingwen Chen294e7742021-08-31 05:58:01 +0000471 // Check if the package path has an exact match in the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000472 if config[packagePath] == allowlists.Bp2BuildDefaultTrue || config[packagePath] == allowlists.Bp2BuildDefaultTrueRecursively {
473 return true, packagePath
474 } else if config[packagePath] == allowlists.Bp2BuildDefaultFalse {
475 return false, packagePath
Jingwen Chen12b4c272021-03-10 02:05:59 -0500476 }
477
Jingwen Chen91220d72021-03-24 02:18:33 -0400478 // If not, check for the config recursively.
Jingwen Chen12b4c272021-03-10 02:05:59 -0500479 packagePrefix := ""
480 // e.g. for x/y/z, iterate over x, x/y, then x/y/z, taking the final value from the allowlist.
481 for _, part := range strings.Split(packagePath, "/") {
482 packagePrefix += part
Sam Delmerico24c56032022-03-28 19:53:03 +0000483 if config[packagePrefix] == allowlists.Bp2BuildDefaultTrueRecursively {
Jingwen Chen12b4c272021-03-10 02:05:59 -0500484 // package contains this prefix and this prefix should convert all modules
Sam Delmerico24c56032022-03-28 19:53:03 +0000485 return true, packagePrefix
Jingwen Chen12b4c272021-03-10 02:05:59 -0500486 }
487 // Continue to the next part of the package dir.
488 packagePrefix += "/"
489 }
490
Sam Delmerico24c56032022-03-28 19:53:03 +0000491 return false, packagePath
Liz Kammerea6666f2021-02-17 10:17:28 -0500492}
Liz Kammerba3ea162021-02-17 13:22:03 -0500493
494// GetBazelBuildFileContents returns the file contents of a hand-crafted BUILD file if available or
495// an error if there are errors reading the file.
496// TODO(b/181575318): currently we append the whole BUILD file, let's change that to do
497// something more targeted based on the rule type and target.
498func (b *BazelModuleBase) GetBazelBuildFileContents(c Config, path, name string) (string, error) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500499 if !strings.Contains(b.HandcraftedLabel(), path) {
500 return "", fmt.Errorf("%q not found in bazel_module.label %q", path, b.HandcraftedLabel())
Liz Kammerba3ea162021-02-17 13:22:03 -0500501 }
502 name = filepath.Join(path, name)
503 f, err := c.fs.Open(name)
504 if err != nil {
505 return "", err
506 }
507 defer f.Close()
508
509 data, err := ioutil.ReadAll(f)
510 if err != nil {
511 return "", err
512 }
513 return string(data[:]), nil
514}
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400515
516func registerBp2buildConversionMutator(ctx RegisterMutatorsContext) {
517 ctx.TopDown("bp2build_conversion", convertWithBp2build).Parallel()
518}
519
520func convertWithBp2build(ctx TopDownMutatorContext) {
521 bModule, ok := ctx.Module().(Bazelable)
522 if !ok || !bModule.shouldConvertWithBp2build(ctx, ctx.Module()) {
523 return
524 }
525
526 bModule.ConvertWithBp2build(ctx)
527}
Wei Libafb6d62021-12-10 03:14:59 -0800528
529// GetMainClassInManifest scans the manifest file specified in filepath and returns
530// the value of attribute Main-Class in the manifest file if it exists, or returns error.
531// WARNING: this is for bp2build converters of java_* modules only.
532func GetMainClassInManifest(c Config, filepath string) (string, error) {
533 file, err := c.fs.Open(filepath)
534 if err != nil {
535 return "", err
536 }
Liz Kammer0fe123d2022-02-07 10:17:35 -0500537 defer file.Close()
Wei Libafb6d62021-12-10 03:14:59 -0800538 scanner := bufio.NewScanner(file)
539 for scanner.Scan() {
540 line := scanner.Text()
541 if strings.HasPrefix(line, "Main-Class:") {
542 return strings.TrimSpace(line[len("Main-Class:"):]), nil
543 }
544 }
545
546 return "", errors.New("Main-Class is not found.")
547}