blob: 40f2917db893be1d5aefbdef28fc3f81bade3555 [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
Chris Parsonsf874e462022-05-10 13:50:12 -0400118// MixedBuildBuildable is an interface that module types should implement in order
119// to be "handled by Bazel" in a mixed build.
120type MixedBuildBuildable interface {
121 // IsMixedBuildSupported returns true if and only if this module should be
122 // "handled by Bazel" in a mixed build.
123 // This "escape hatch" allows modules with corner-case scenarios to opt out
124 // of being built with Bazel.
125 IsMixedBuildSupported(ctx BaseModuleContext) bool
126
127 // QueueBazelCall invokes request-queueing functions on the BazelContext
128 // so that these requests are handled when Bazel's cquery is invoked.
129 QueueBazelCall(ctx BaseModuleContext)
130
131 // ProcessBazelQueryResponse uses Bazel information (obtained from the BazelContext)
132 // to set module fields and providers to propagate this module's metadata upstream.
133 // This effectively "bridges the gap" between Bazel and Soong in a mixed build.
134 // Soong modules depending on this module should be oblivious to the fact that
135 // this module was handled by Bazel.
136 ProcessBazelQueryResponse(ctx ModuleContext)
137}
138
Liz Kammerea6666f2021-02-17 10:17:28 -0500139// BazelModule is a lightweight wrapper interface around Module for Bazel-convertible modules.
140type BazelModule interface {
141 Module
142 Bazelable
143}
144
145// InitBazelModule is a wrapper function that decorates a BazelModule with Bazel-conversion
146// properties.
147func InitBazelModule(module BazelModule) {
148 module.AddProperties(module.bazelProps())
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400149 module.bazelProps().Bazel_module.CanConvertToBazel = true
Liz Kammerea6666f2021-02-17 10:17:28 -0500150}
151
152// bazelProps returns the Bazel properties for the given BazelModuleBase.
Liz Kammerba3ea162021-02-17 13:22:03 -0500153func (b *BazelModuleBase) bazelProps() *properties {
Liz Kammerea6666f2021-02-17 10:17:28 -0500154 return &b.bazelProperties
155}
156
Jingwen Chena47f28d2021-11-02 16:43:57 +0000157func (b *BazelModuleBase) namespacedVariableProps() namespacedVariableProperties {
158 return b.namespacedVariableProperties
159}
160
161func (b *BazelModuleBase) setNamespacedVariableProps(props namespacedVariableProperties) {
162 b.namespacedVariableProperties = props
163}
164
165func (b *BazelModuleBase) BaseModuleType() string {
166 return b.baseModuleType
167}
168
169func (b *BazelModuleBase) SetBaseModuleType(baseModuleType string) {
170 b.baseModuleType = baseModuleType
171}
172
Liz Kammerba3ea162021-02-17 13:22:03 -0500173// HasHandcraftedLabel returns whether this module has a handcrafted Bazel label.
174func (b *BazelModuleBase) HasHandcraftedLabel() bool {
175 return b.bazelProperties.Bazel_module.Label != nil
176}
177
178// HandcraftedLabel returns the handcrafted label for this module, or empty string if there is none
179func (b *BazelModuleBase) HandcraftedLabel() string {
180 return proptools.String(b.bazelProperties.Bazel_module.Label)
181}
182
Liz Kammerea6666f2021-02-17 10:17:28 -0500183// GetBazelLabel returns the Bazel label for the given BazelModuleBase.
Liz Kammerbdc60992021-02-24 16:55:11 -0500184func (b *BazelModuleBase) GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
185 if b.HasHandcraftedLabel() {
186 return b.HandcraftedLabel()
187 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400188 if b.ShouldConvertWithBp2build(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500189 return bp2buildModuleLabel(ctx, module)
190 }
191 return "" // no label for unconverted module
Liz Kammerea6666f2021-02-17 10:17:28 -0500192}
193
Sam Delmerico24c56032022-03-28 19:53:03 +0000194type bp2BuildConversionAllowlist struct {
195 // Configure modules in these directories to enable bp2build_available: true or false by default.
196 defaultConfig allowlists.Bp2BuildConfig
Jingwen Chen12b4c272021-03-10 02:05:59 -0500197
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400198 // Keep any existing BUILD files (and do not generate new BUILD files) for these directories
Jingwen Chenb643c7a2021-07-26 04:45:48 +0000199 // in the synthetic Bazel workspace.
Sam Delmerico24c56032022-03-28 19:53:03 +0000200 keepExistingBuildFile map[string]bool
Jingwen Chen5d72cba2021-03-25 09:28:38 +0000201
Sam Delmericofa1831c2022-02-22 18:07:55 +0000202 // Per-module allowlist to always opt modules in of both bp2build and mixed builds.
Jingwen Chen7edadab2022-03-04 07:01:29 +0000203 // These modules are usually in directories with many other modules that are not ready for
204 // conversion.
205 //
206 // A module can either be in this list or its directory allowlisted entirely
207 // in bp2buildDefaultConfig, but not both at the same time.
Sam Delmerico24c56032022-03-28 19:53:03 +0000208 moduleAlwaysConvert map[string]bool
Sam Delmericofa1831c2022-02-22 18:07:55 +0000209
Sam Delmericoa9b047a2022-02-22 19:21:28 +0000210 // Per-module-type allowlist to always opt modules in to both bp2build and mixed builds
Sam Delmerico85d831a2022-03-07 19:12:42 +0000211 // when they have the same type as one listed.
Sam Delmerico24c56032022-03-28 19:53:03 +0000212 moduleTypeAlwaysConvert map[string]bool
Sam Delmerico85d831a2022-03-07 19:12:42 +0000213
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400214 // Per-module denylist to always opt modules out of both bp2build and mixed builds.
Sam Delmerico24c56032022-03-28 19:53:03 +0000215 moduleDoNotConvert map[string]bool
Rupert Shuttleworthc143cc52021-04-13 13:08:04 -0400216
Jingwen Chen179856a2021-05-03 09:15:48 +0000217 // Per-module denylist of cc_library modules to only generate the static
218 // variant if their shared variant isn't ready or buildable by Bazel.
Sam Delmerico24c56032022-03-28 19:53:03 +0000219 ccLibraryStaticOnly map[string]bool
Jingwen Chen179856a2021-05-03 09:15:48 +0000220
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400221 // Per-module denylist to opt modules out of mixed builds. Such modules will
222 // still be generated via bp2build.
Sam Delmerico24c56032022-03-28 19:53:03 +0000223 mixedBuildsDisabled map[string]bool
224}
Liz Kammer5c313582021-12-03 15:23:26 -0500225
Sam Delmerico24c56032022-03-28 19:53:03 +0000226// NewBp2BuildAllowlist creates a new, empty bp2BuildConversionAllowlist
227// which can be populated using builder pattern Set* methods
228func NewBp2BuildAllowlist() bp2BuildConversionAllowlist {
229 return bp2BuildConversionAllowlist{
230 allowlists.Bp2BuildConfig{},
231 map[string]bool{},
232 map[string]bool{},
233 map[string]bool{},
234 map[string]bool{},
235 map[string]bool{},
236 map[string]bool{},
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400237 }
238}
239
Sam Delmerico24c56032022-03-28 19:53:03 +0000240// SetDefaultConfig copies the entries from defaultConfig into the allowlist
241func (a bp2BuildConversionAllowlist) SetDefaultConfig(defaultConfig allowlists.Bp2BuildConfig) bp2BuildConversionAllowlist {
242 if a.defaultConfig == nil {
243 a.defaultConfig = allowlists.Bp2BuildConfig{}
244 }
245 for k, v := range defaultConfig {
246 a.defaultConfig[k] = v
247 }
248
249 return a
250}
251
252// SetKeepExistingBuildFile copies the entries from keepExistingBuildFile into the allowlist
253func (a bp2BuildConversionAllowlist) SetKeepExistingBuildFile(keepExistingBuildFile map[string]bool) bp2BuildConversionAllowlist {
254 if a.keepExistingBuildFile == nil {
255 a.keepExistingBuildFile = map[string]bool{}
256 }
257 for k, v := range keepExistingBuildFile {
258 a.keepExistingBuildFile[k] = v
259 }
260
261 return a
262}
263
264// SetModuleAlwaysConvertList copies the entries from moduleAlwaysConvert into the allowlist
265func (a bp2BuildConversionAllowlist) SetModuleAlwaysConvertList(moduleAlwaysConvert []string) bp2BuildConversionAllowlist {
266 if a.moduleAlwaysConvert == nil {
267 a.moduleAlwaysConvert = map[string]bool{}
268 }
269 for _, m := range moduleAlwaysConvert {
270 a.moduleAlwaysConvert[m] = true
271 }
272
273 return a
274}
275
276// SetModuleTypeAlwaysConvertList copies the entries from moduleTypeAlwaysConvert into the allowlist
277func (a bp2BuildConversionAllowlist) SetModuleTypeAlwaysConvertList(moduleTypeAlwaysConvert []string) bp2BuildConversionAllowlist {
278 if a.moduleTypeAlwaysConvert == nil {
279 a.moduleTypeAlwaysConvert = map[string]bool{}
280 }
281 for _, m := range moduleTypeAlwaysConvert {
282 a.moduleTypeAlwaysConvert[m] = true
283 }
284
285 return a
286}
287
288// SetModuleDoNotConvertList copies the entries from moduleDoNotConvert into the allowlist
289func (a bp2BuildConversionAllowlist) SetModuleDoNotConvertList(moduleDoNotConvert []string) bp2BuildConversionAllowlist {
290 if a.moduleDoNotConvert == nil {
291 a.moduleDoNotConvert = map[string]bool{}
292 }
293 for _, m := range moduleDoNotConvert {
294 a.moduleDoNotConvert[m] = true
295 }
296
297 return a
298}
299
300// SetCcLibraryStaticOnlyList copies the entries from ccLibraryStaticOnly into the allowlist
301func (a bp2BuildConversionAllowlist) SetCcLibraryStaticOnlyList(ccLibraryStaticOnly []string) bp2BuildConversionAllowlist {
302 if a.ccLibraryStaticOnly == nil {
303 a.ccLibraryStaticOnly = map[string]bool{}
304 }
305 for _, m := range ccLibraryStaticOnly {
306 a.ccLibraryStaticOnly[m] = true
307 }
308
309 return a
310}
311
312// SetMixedBuildsDisabledList copies the entries from mixedBuildsDisabled into the allowlist
313func (a bp2BuildConversionAllowlist) SetMixedBuildsDisabledList(mixedBuildsDisabled []string) bp2BuildConversionAllowlist {
314 if a.mixedBuildsDisabled == nil {
315 a.mixedBuildsDisabled = map[string]bool{}
316 }
317 for _, m := range mixedBuildsDisabled {
318 a.mixedBuildsDisabled[m] = true
319 }
320
321 return a
322}
323
Wei Lid7736ec2022-05-12 23:37:53 -0700324var bp2BuildAllowListKey = NewOnceKey("Bp2BuildAllowlist")
325var bp2buildAllowlist OncePer
326
327func getBp2BuildAllowList() bp2BuildConversionAllowlist {
328 return bp2buildAllowlist.Once(bp2BuildAllowListKey, func() interface{} {
329 return NewBp2BuildAllowlist().SetDefaultConfig(allowlists.Bp2buildDefaultConfig).
330 SetKeepExistingBuildFile(allowlists.Bp2buildKeepExistingBuildFile).
331 SetModuleAlwaysConvertList(allowlists.Bp2buildModuleAlwaysConvertList).
332 SetModuleTypeAlwaysConvertList(allowlists.Bp2buildModuleTypeAlwaysConvertList).
333 SetModuleDoNotConvertList(allowlists.Bp2buildModuleDoNotConvertList).
334 SetCcLibraryStaticOnlyList(allowlists.Bp2buildCcLibraryStaticOnlyList).
335 SetMixedBuildsDisabledList(allowlists.MixedBuildsDisabledList)
336 }).(bp2BuildConversionAllowlist)
337}
Sam Delmerico24c56032022-03-28 19:53:03 +0000338
339// GenerateCcLibraryStaticOnly returns whether a cc_library module should only
340// generate a static version of itself based on the current global configuration.
Chris Parsons953b3562021-09-20 15:14:39 -0400341func GenerateCcLibraryStaticOnly(moduleName string) bool {
Wei Lid7736ec2022-05-12 23:37:53 -0700342 return getBp2BuildAllowList().ccLibraryStaticOnly[moduleName]
Jingwen Chen179856a2021-05-03 09:15:48 +0000343}
344
Sam Delmerico24c56032022-03-28 19:53:03 +0000345// ShouldKeepExistingBuildFileForDir returns whether an existing BUILD file should be
346// added to the build symlink forest based on the current global configuration.
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400347func ShouldKeepExistingBuildFileForDir(dir string) bool {
Wei Lid7736ec2022-05-12 23:37:53 -0700348 return shouldKeepExistingBuildFileForDir(getBp2BuildAllowList(), dir)
Sam Delmerico24c56032022-03-28 19:53:03 +0000349}
350
351func shouldKeepExistingBuildFileForDir(allowlist bp2BuildConversionAllowlist, dir string) bool {
352 if _, ok := allowlist.keepExistingBuildFile[dir]; ok {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400353 // Exact dir match
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400354 return true
355 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400356 // Check if subtree match
Sam Delmerico24c56032022-03-28 19:53:03 +0000357 for prefix, recursive := range allowlist.keepExistingBuildFile {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400358 if recursive {
359 if strings.HasPrefix(dir, prefix+"/") {
360 return true
361 }
362 }
363 }
364 // Default
365 return false
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400366}
367
MarkDacekff851b82022-04-21 18:33:17 +0000368// MixedBuildsEnabled returns true if a module is ready to be replaced by a
369// converted or handcrafted Bazel target. As a side effect, calling this
370// method will also log whether this module is mixed build enabled for
371// metrics reporting.
Chris Parsonsf874e462022-05-10 13:50:12 -0400372func MixedBuildsEnabled(ctx BaseModuleContext) bool {
MarkDacekff851b82022-04-21 18:33:17 +0000373 mixedBuildEnabled := mixedBuildPossible(ctx)
374 ctx.Config().LogMixedBuild(ctx, mixedBuildEnabled)
375 return mixedBuildEnabled
376}
377
378// mixedBuildPossible returns true if a module is ready to be replaced by a
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400379// converted or handcrafted Bazel target.
Chris Parsonsf874e462022-05-10 13:50:12 -0400380func mixedBuildPossible(ctx BaseModuleContext) bool {
Chris Parsons494eef32021-11-09 10:29:52 -0500381 if ctx.Os() == Windows {
382 // Windows toolchains are not currently supported.
383 return false
384 }
Chris Parsons58852a02021-12-09 18:10:18 -0500385 if !ctx.Module().Enabled() {
386 return false
387 }
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400388 if !ctx.Config().BazelContext.BazelEnabled() {
389 return false
390 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400391 if !convertedToBazel(ctx, ctx.Module()) {
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400392 return false
393 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400394
Chris Parsons953b3562021-09-20 15:14:39 -0400395 if GenerateCcLibraryStaticOnly(ctx.Module().Name()) {
Jingwen Chen179856a2021-05-03 09:15:48 +0000396 // Don't use partially-converted cc_library targets in mixed builds,
397 // since mixed builds would generally rely on both static and shared
398 // variants of a cc_library.
399 return false
400 }
Wei Lid7736ec2022-05-12 23:37:53 -0700401 return !getBp2BuildAllowList().mixedBuildsDisabled[ctx.Module().Name()]
Rupert Shuttleworth4f43fe92021-03-30 14:13:16 +0000402}
403
Liz Kammer6eff3232021-08-26 08:37:59 -0400404// ConvertedToBazel returns whether this module has been converted (with bp2build or manually) to Bazel.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000405func convertedToBazel(ctx BazelConversionContext, module blueprint.Module) bool {
Liz Kammer6eff3232021-08-26 08:37:59 -0400406 b, ok := module.(Bazelable)
407 if !ok {
408 return false
409 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400410 return b.shouldConvertWithBp2build(ctx, module) || b.HasHandcraftedLabel()
Liz Kammer6eff3232021-08-26 08:37:59 -0400411}
412
Sam Delmerico24c56032022-03-28 19:53:03 +0000413// ShouldConvertWithBp2build returns whether the given BazelModuleBase should be converted with bp2build
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400414func (b *BazelModuleBase) ShouldConvertWithBp2build(ctx BazelConversionContext) bool {
415 return b.shouldConvertWithBp2build(ctx, ctx.Module())
Liz Kammer6eff3232021-08-26 08:37:59 -0400416}
417
Sam Delmerico24c56032022-03-28 19:53:03 +0000418type bazelOtherModuleContext interface {
419 ModuleErrorf(format string, args ...interface{})
420 Config() Config
421 OtherModuleType(m blueprint.Module) string
422 OtherModuleName(m blueprint.Module) string
423 OtherModuleDir(m blueprint.Module) string
424}
Sam Delmericofa1831c2022-02-22 18:07:55 +0000425
Sam Delmerico24c56032022-03-28 19:53:03 +0000426func (b *BazelModuleBase) shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400427 if !b.bazelProps().Bazel_module.CanConvertToBazel {
428 return false
Jingwen Chen12b4c272021-03-10 02:05:59 -0500429 }
430
Sam Delmerico85d831a2022-03-07 19:12:42 +0000431 propValue := b.bazelProperties.Bazel_module.Bp2build_available
Liz Kammer6eff3232021-08-26 08:37:59 -0400432 packagePath := ctx.OtherModuleDir(module)
Sam Delmerico24c56032022-03-28 19:53:03 +0000433
Sam Delmerico85d831a2022-03-07 19:12:42 +0000434 // Modules in unit tests which are enabled in the allowlist by type or name
435 // trigger this conditional because unit tests run under the "." package path
Sam Delmerico24c56032022-03-28 19:53:03 +0000436 isTestModule := packagePath == Bp2BuildTopLevel && proptools.BoolDefault(propValue, false)
437 if isTestModule {
438 return true
439 }
440
441 moduleName := module.Name()
442 allowlist := ctx.Config().bp2buildPackageConfig
443 moduleNameAllowed := allowlist.moduleAlwaysConvert[moduleName]
444 moduleTypeAllowed := allowlist.moduleTypeAlwaysConvert[ctx.OtherModuleType(module)]
445 allowlistConvert := moduleNameAllowed || moduleTypeAllowed
446 if moduleNameAllowed && moduleTypeAllowed {
447 ctx.ModuleErrorf("A module cannot be in moduleAlwaysConvert and also be in moduleTypeAlwaysConvert")
448 return false
449 }
450
451 if allowlist.moduleDoNotConvert[moduleName] {
Sam Delmerico85d831a2022-03-07 19:12:42 +0000452 if moduleNameAllowed {
Sam Delmerico24c56032022-03-28 19:53:03 +0000453 ctx.ModuleErrorf("a module cannot be in moduleDoNotConvert and also be in moduleAlwaysConvert")
Sam Delmerico85d831a2022-03-07 19:12:42 +0000454 }
Sam Delmerico94d26c22022-02-25 21:34:51 +0000455 return false
456 }
457
Sam Delmerico24c56032022-03-28 19:53:03 +0000458 if allowlistConvert && shouldKeepExistingBuildFileForDir(allowlist, packagePath) {
Sam Delmerico85d831a2022-03-07 19:12:42 +0000459 if moduleNameAllowed {
Sam Delmerico24c56032022-03-28 19:53:03 +0000460 ctx.ModuleErrorf("A module cannot be in a directory listed in keepExistingBuildFile"+
461 " and also be in moduleAlwaysConvert. Directory: '%s'", packagePath)
462 return false
463 }
464 }
465
466 // This is a tristate value: true, false, or unset.
467 if ok, directoryPath := bp2buildDefaultTrueRecursively(packagePath, allowlist.defaultConfig); ok {
468 if moduleNameAllowed {
469 ctx.ModuleErrorf("A module cannot be in a directory marked Bp2BuildDefaultTrue"+
470 " or Bp2BuildDefaultTrueRecursively and also be in moduleAlwaysConvert. Directory: '%s'",
471 directoryPath)
472 return false
Sam Delmericofa1831c2022-02-22 18:07:55 +0000473 }
474
Jingwen Chen12b4c272021-03-10 02:05:59 -0500475 // Allow modules to explicitly opt-out.
476 return proptools.BoolDefault(propValue, true)
477 }
478
479 // Allow modules to explicitly opt-in.
Sam Delmerico85d831a2022-03-07 19:12:42 +0000480 return proptools.BoolDefault(propValue, allowlistConvert)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500481}
482
483// bp2buildDefaultTrueRecursively checks that the package contains a prefix from the
484// set of package prefixes where all modules must be converted. That is, if the
485// package is x/y/z, and the list contains either x, x/y, or x/y/z, this function will
486// return true.
487//
488// However, if the package is x/y, and it matches a Bp2BuildDefaultFalse "x/y" entry
489// exactly, this module will return false early.
490//
491// This function will also return false if the package doesn't match anything in
492// the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000493//
494// This function will also return the allowlist entry which caused a particular
495// package to be enabled. Since packages can be enabled via a recursive declaration,
496// the path returned will not always be the same as the one provided.
497func bp2buildDefaultTrueRecursively(packagePath string, config allowlists.Bp2BuildConfig) (bool, string) {
Jingwen Chen294e7742021-08-31 05:58:01 +0000498 // Check if the package path has an exact match in the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000499 if config[packagePath] == allowlists.Bp2BuildDefaultTrue || config[packagePath] == allowlists.Bp2BuildDefaultTrueRecursively {
500 return true, packagePath
501 } else if config[packagePath] == allowlists.Bp2BuildDefaultFalse {
502 return false, packagePath
Jingwen Chen12b4c272021-03-10 02:05:59 -0500503 }
504
Jingwen Chen91220d72021-03-24 02:18:33 -0400505 // If not, check for the config recursively.
Jingwen Chen12b4c272021-03-10 02:05:59 -0500506 packagePrefix := ""
507 // e.g. for x/y/z, iterate over x, x/y, then x/y/z, taking the final value from the allowlist.
508 for _, part := range strings.Split(packagePath, "/") {
509 packagePrefix += part
Sam Delmerico24c56032022-03-28 19:53:03 +0000510 if config[packagePrefix] == allowlists.Bp2BuildDefaultTrueRecursively {
Jingwen Chen12b4c272021-03-10 02:05:59 -0500511 // package contains this prefix and this prefix should convert all modules
Sam Delmerico24c56032022-03-28 19:53:03 +0000512 return true, packagePrefix
Jingwen Chen12b4c272021-03-10 02:05:59 -0500513 }
514 // Continue to the next part of the package dir.
515 packagePrefix += "/"
516 }
517
Sam Delmerico24c56032022-03-28 19:53:03 +0000518 return false, packagePath
Liz Kammerea6666f2021-02-17 10:17:28 -0500519}
Liz Kammerba3ea162021-02-17 13:22:03 -0500520
521// GetBazelBuildFileContents returns the file contents of a hand-crafted BUILD file if available or
522// an error if there are errors reading the file.
523// TODO(b/181575318): currently we append the whole BUILD file, let's change that to do
524// something more targeted based on the rule type and target.
525func (b *BazelModuleBase) GetBazelBuildFileContents(c Config, path, name string) (string, error) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500526 if !strings.Contains(b.HandcraftedLabel(), path) {
527 return "", fmt.Errorf("%q not found in bazel_module.label %q", path, b.HandcraftedLabel())
Liz Kammerba3ea162021-02-17 13:22:03 -0500528 }
529 name = filepath.Join(path, name)
530 f, err := c.fs.Open(name)
531 if err != nil {
532 return "", err
533 }
534 defer f.Close()
535
536 data, err := ioutil.ReadAll(f)
537 if err != nil {
538 return "", err
539 }
540 return string(data[:]), nil
541}
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400542
543func registerBp2buildConversionMutator(ctx RegisterMutatorsContext) {
544 ctx.TopDown("bp2build_conversion", convertWithBp2build).Parallel()
545}
546
547func convertWithBp2build(ctx TopDownMutatorContext) {
548 bModule, ok := ctx.Module().(Bazelable)
549 if !ok || !bModule.shouldConvertWithBp2build(ctx, ctx.Module()) {
550 return
551 }
552
553 bModule.ConvertWithBp2build(ctx)
554}
Wei Libafb6d62021-12-10 03:14:59 -0800555
556// GetMainClassInManifest scans the manifest file specified in filepath and returns
557// the value of attribute Main-Class in the manifest file if it exists, or returns error.
558// WARNING: this is for bp2build converters of java_* modules only.
559func GetMainClassInManifest(c Config, filepath string) (string, error) {
560 file, err := c.fs.Open(filepath)
561 if err != nil {
562 return "", err
563 }
Liz Kammer0fe123d2022-02-07 10:17:35 -0500564 defer file.Close()
Wei Libafb6d62021-12-10 03:14:59 -0800565 scanner := bufio.NewScanner(file)
566 for scanner.Scan() {
567 line := scanner.Text()
568 if strings.HasPrefix(line, "Main-Class:") {
569 return strings.TrimSpace(line[len("Main-Class:"):]), nil
570 }
571 }
572
573 return "", errors.New("Main-Class is not found.")
574}