blob: 183a2f3242a6b3fb61313373e5bd26f05ab4d0e5 [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
Sasha Smundaka0954062022-08-02 18:23:58 -070038type BazelConversionStatus struct {
39 // Information about _all_ bp2build targets generated by this module. Multiple targets are
40 // supported as Soong handles some things within a single target that we may choose to split into
41 // multiple targets, e.g. renderscript, protos, yacc within a cc module.
42 Bp2buildInfo []bp2buildInfo `blueprint:"mutated"`
43
44 // UnconvertedBp2buildDep stores the module names of direct dependency that were not converted to
45 // Bazel
46 UnconvertedDeps []string `blueprint:"mutated"`
47
48 // MissingBp2buildDep stores the module names of direct dependency that were not found
49 MissingDeps []string `blueprint:"mutated"`
50}
51
Jingwen Chen01812022021-11-19 14:29:43 +000052type bazelModuleProperties struct {
53 // The label of the Bazel target replacing this Soong module. When run in conversion mode, this
54 // will import the handcrafted build target into the autogenerated file. Note: this may result in
55 // a conflict due to duplicate targets if bp2build_available is also set.
56 Label *string
57
58 // If true, bp2build will generate the converted Bazel target for this module. Note: this may
59 // cause a conflict due to the duplicate targets if label is also set.
60 //
61 // This is a bool pointer to support tristates: true, false, not set.
62 //
63 // To opt-in a module, set bazel_module: { bp2build_available: true }
64 // To opt-out a module, set bazel_module: { bp2build_available: false }
65 // To defer the default setting for the directory, do not set the value.
66 Bp2build_available *bool
Liz Kammerbe46fcc2021-11-01 15:32:43 -040067
68 // CanConvertToBazel is set via InitBazelModule to indicate that a module type can be converted to
69 // Bazel with Bp2build.
70 CanConvertToBazel bool `blueprint:"mutated"`
Jingwen Chen01812022021-11-19 14:29:43 +000071}
72
Liz Kammerba3ea162021-02-17 13:22:03 -050073// Properties contains common module properties for Bazel migration purposes.
74type properties struct {
75 // In USE_BAZEL_ANALYSIS=1 mode, this represents the Bazel target replacing
76 // this Soong module.
Jingwen Chen01812022021-11-19 14:29:43 +000077 Bazel_module bazelModuleProperties
Liz Kammerba3ea162021-02-17 13:22:03 -050078}
Liz Kammerea6666f2021-02-17 10:17:28 -050079
Jingwen Chen25825ca2021-11-15 12:28:43 +000080// namespacedVariableProperties is a map from a string representing a Soong
Jingwen Chen84817de2021-11-17 10:57:35 +000081// config variable namespace, like "android" or "vendor_name" to a slice of
82// pointer to a struct containing a single field called Soong_config_variables
83// whose value mirrors the structure in the Blueprint file.
84type namespacedVariableProperties map[string][]interface{}
Jingwen Chena47f28d2021-11-02 16:43:57 +000085
Liz Kammerea6666f2021-02-17 10:17:28 -050086// BazelModuleBase contains the property structs with metadata for modules which can be converted to
87// Bazel.
88type BazelModuleBase struct {
Liz Kammerba3ea162021-02-17 13:22:03 -050089 bazelProperties properties
Jingwen Chena47f28d2021-11-02 16:43:57 +000090
91 // namespacedVariableProperties is used for soong_config_module_type support
92 // in bp2build. Soong config modules allow users to set module properties
93 // based on custom product variables defined in Android.bp files. These
94 // variables are namespaced to prevent clobbering, especially when set from
95 // Makefiles.
96 namespacedVariableProperties namespacedVariableProperties
97
98 // baseModuleType is set when this module was created from a module type
99 // defined by a soong_config_module_type. Every soong_config_module_type
100 // "wraps" another module type, e.g. a soong_config_module_type can wrap a
101 // cc_defaults to a custom_cc_defaults, or cc_binary to a custom_cc_binary.
102 // This baseModuleType is set to the wrapped module type.
103 baseModuleType string
Liz Kammerea6666f2021-02-17 10:17:28 -0500104}
105
106// Bazelable is specifies the interface for modules that can be converted to Bazel.
107type Bazelable interface {
Liz Kammerba3ea162021-02-17 13:22:03 -0500108 bazelProps() *properties
109 HasHandcraftedLabel() bool
Liz Kammerbdc60992021-02-24 16:55:11 -0500110 HandcraftedLabel() string
111 GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400112 ShouldConvertWithBp2build(ctx BazelConversionContext) bool
Sam Delmerico24c56032022-03-28 19:53:03 +0000113 shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool
Liz Kammerba3ea162021-02-17 13:22:03 -0500114 GetBazelBuildFileContents(c Config, path, name string) (string, error)
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400115 ConvertWithBp2build(ctx TopDownMutatorContext)
Jingwen Chena47f28d2021-11-02 16:43:57 +0000116
Jingwen Chen84817de2021-11-17 10:57:35 +0000117 // namespacedVariableProps is a map from a soong config variable namespace
118 // (e.g. acme, android) to a map of interfaces{}, which are really
119 // reflect.Struct pointers, representing the value of the
120 // soong_config_variables property of a module. The struct pointer is the
121 // one with the single member called Soong_config_variables, which itself is
122 // a struct containing fields for each supported feature in that namespace.
123 //
124 // The reason for using an slice of interface{} is to support defaults
125 // propagation of the struct pointers.
Jingwen Chena47f28d2021-11-02 16:43:57 +0000126 namespacedVariableProps() namespacedVariableProperties
127 setNamespacedVariableProps(props namespacedVariableProperties)
128 BaseModuleType() string
Jingwen Chen84817de2021-11-17 10:57:35 +0000129 SetBaseModuleType(baseModuleType string)
Liz Kammerea6666f2021-02-17 10:17:28 -0500130}
131
Chris Parsonsf874e462022-05-10 13:50:12 -0400132// MixedBuildBuildable is an interface that module types should implement in order
133// to be "handled by Bazel" in a mixed build.
134type MixedBuildBuildable interface {
135 // IsMixedBuildSupported returns true if and only if this module should be
136 // "handled by Bazel" in a mixed build.
137 // This "escape hatch" allows modules with corner-case scenarios to opt out
138 // of being built with Bazel.
139 IsMixedBuildSupported(ctx BaseModuleContext) bool
140
141 // QueueBazelCall invokes request-queueing functions on the BazelContext
142 // so that these requests are handled when Bazel's cquery is invoked.
143 QueueBazelCall(ctx BaseModuleContext)
144
145 // ProcessBazelQueryResponse uses Bazel information (obtained from the BazelContext)
146 // to set module fields and providers to propagate this module's metadata upstream.
147 // This effectively "bridges the gap" between Bazel and Soong in a mixed build.
148 // Soong modules depending on this module should be oblivious to the fact that
149 // this module was handled by Bazel.
150 ProcessBazelQueryResponse(ctx ModuleContext)
151}
152
Liz Kammerea6666f2021-02-17 10:17:28 -0500153// BazelModule is a lightweight wrapper interface around Module for Bazel-convertible modules.
154type BazelModule interface {
155 Module
156 Bazelable
157}
158
159// InitBazelModule is a wrapper function that decorates a BazelModule with Bazel-conversion
160// properties.
161func InitBazelModule(module BazelModule) {
162 module.AddProperties(module.bazelProps())
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400163 module.bazelProps().Bazel_module.CanConvertToBazel = true
Liz Kammerea6666f2021-02-17 10:17:28 -0500164}
165
166// bazelProps returns the Bazel properties for the given BazelModuleBase.
Liz Kammerba3ea162021-02-17 13:22:03 -0500167func (b *BazelModuleBase) bazelProps() *properties {
Liz Kammerea6666f2021-02-17 10:17:28 -0500168 return &b.bazelProperties
169}
170
Jingwen Chena47f28d2021-11-02 16:43:57 +0000171func (b *BazelModuleBase) namespacedVariableProps() namespacedVariableProperties {
172 return b.namespacedVariableProperties
173}
174
175func (b *BazelModuleBase) setNamespacedVariableProps(props namespacedVariableProperties) {
176 b.namespacedVariableProperties = props
177}
178
179func (b *BazelModuleBase) BaseModuleType() string {
180 return b.baseModuleType
181}
182
183func (b *BazelModuleBase) SetBaseModuleType(baseModuleType string) {
184 b.baseModuleType = baseModuleType
185}
186
Liz Kammerba3ea162021-02-17 13:22:03 -0500187// HasHandcraftedLabel returns whether this module has a handcrafted Bazel label.
188func (b *BazelModuleBase) HasHandcraftedLabel() bool {
189 return b.bazelProperties.Bazel_module.Label != nil
190}
191
192// HandcraftedLabel returns the handcrafted label for this module, or empty string if there is none
193func (b *BazelModuleBase) HandcraftedLabel() string {
194 return proptools.String(b.bazelProperties.Bazel_module.Label)
195}
196
Liz Kammerea6666f2021-02-17 10:17:28 -0500197// GetBazelLabel returns the Bazel label for the given BazelModuleBase.
Liz Kammerbdc60992021-02-24 16:55:11 -0500198func (b *BazelModuleBase) GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
199 if b.HasHandcraftedLabel() {
200 return b.HandcraftedLabel()
201 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400202 if b.ShouldConvertWithBp2build(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500203 return bp2buildModuleLabel(ctx, module)
204 }
205 return "" // no label for unconverted module
Liz Kammerea6666f2021-02-17 10:17:28 -0500206}
207
Sam Delmerico24c56032022-03-28 19:53:03 +0000208type bp2BuildConversionAllowlist struct {
209 // Configure modules in these directories to enable bp2build_available: true or false by default.
210 defaultConfig allowlists.Bp2BuildConfig
Jingwen Chen12b4c272021-03-10 02:05:59 -0500211
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400212 // Keep any existing BUILD files (and do not generate new BUILD files) for these directories
Jingwen Chenb643c7a2021-07-26 04:45:48 +0000213 // in the synthetic Bazel workspace.
Sam Delmerico24c56032022-03-28 19:53:03 +0000214 keepExistingBuildFile map[string]bool
Jingwen Chen5d72cba2021-03-25 09:28:38 +0000215
Sam Delmericofa1831c2022-02-22 18:07:55 +0000216 // Per-module allowlist to always opt modules in of both bp2build and mixed builds.
Jingwen Chen7edadab2022-03-04 07:01:29 +0000217 // These modules are usually in directories with many other modules that are not ready for
218 // conversion.
219 //
220 // A module can either be in this list or its directory allowlisted entirely
221 // in bp2buildDefaultConfig, but not both at the same time.
Sam Delmerico24c56032022-03-28 19:53:03 +0000222 moduleAlwaysConvert map[string]bool
Sam Delmericofa1831c2022-02-22 18:07:55 +0000223
Sam Delmericoa9b047a2022-02-22 19:21:28 +0000224 // Per-module-type allowlist to always opt modules in to both bp2build and mixed builds
Sam Delmerico85d831a2022-03-07 19:12:42 +0000225 // when they have the same type as one listed.
Sam Delmerico24c56032022-03-28 19:53:03 +0000226 moduleTypeAlwaysConvert map[string]bool
Sam Delmerico85d831a2022-03-07 19:12:42 +0000227
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400228 // Per-module denylist to always opt modules out of both bp2build and mixed builds.
Sam Delmerico24c56032022-03-28 19:53:03 +0000229 moduleDoNotConvert map[string]bool
Rupert Shuttleworthc143cc52021-04-13 13:08:04 -0400230
Jingwen Chen179856a2021-05-03 09:15:48 +0000231 // Per-module denylist of cc_library modules to only generate the static
232 // variant if their shared variant isn't ready or buildable by Bazel.
Sam Delmerico24c56032022-03-28 19:53:03 +0000233 ccLibraryStaticOnly map[string]bool
Jingwen Chen179856a2021-05-03 09:15:48 +0000234
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400235 // Per-module denylist to opt modules out of mixed builds. Such modules will
236 // still be generated via bp2build.
Sam Delmerico24c56032022-03-28 19:53:03 +0000237 mixedBuildsDisabled map[string]bool
238}
Liz Kammer5c313582021-12-03 15:23:26 -0500239
Sam Delmerico24c56032022-03-28 19:53:03 +0000240// NewBp2BuildAllowlist creates a new, empty bp2BuildConversionAllowlist
241// which can be populated using builder pattern Set* methods
242func NewBp2BuildAllowlist() bp2BuildConversionAllowlist {
243 return bp2BuildConversionAllowlist{
244 allowlists.Bp2BuildConfig{},
245 map[string]bool{},
246 map[string]bool{},
247 map[string]bool{},
248 map[string]bool{},
249 map[string]bool{},
250 map[string]bool{},
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400251 }
252}
253
Sam Delmerico24c56032022-03-28 19:53:03 +0000254// SetDefaultConfig copies the entries from defaultConfig into the allowlist
255func (a bp2BuildConversionAllowlist) SetDefaultConfig(defaultConfig allowlists.Bp2BuildConfig) bp2BuildConversionAllowlist {
256 if a.defaultConfig == nil {
257 a.defaultConfig = allowlists.Bp2BuildConfig{}
258 }
259 for k, v := range defaultConfig {
260 a.defaultConfig[k] = v
261 }
262
263 return a
264}
265
266// SetKeepExistingBuildFile copies the entries from keepExistingBuildFile into the allowlist
267func (a bp2BuildConversionAllowlist) SetKeepExistingBuildFile(keepExistingBuildFile map[string]bool) bp2BuildConversionAllowlist {
268 if a.keepExistingBuildFile == nil {
269 a.keepExistingBuildFile = map[string]bool{}
270 }
271 for k, v := range keepExistingBuildFile {
272 a.keepExistingBuildFile[k] = v
273 }
274
275 return a
276}
277
278// SetModuleAlwaysConvertList copies the entries from moduleAlwaysConvert into the allowlist
279func (a bp2BuildConversionAllowlist) SetModuleAlwaysConvertList(moduleAlwaysConvert []string) bp2BuildConversionAllowlist {
280 if a.moduleAlwaysConvert == nil {
281 a.moduleAlwaysConvert = map[string]bool{}
282 }
283 for _, m := range moduleAlwaysConvert {
284 a.moduleAlwaysConvert[m] = true
285 }
286
287 return a
288}
289
290// SetModuleTypeAlwaysConvertList copies the entries from moduleTypeAlwaysConvert into the allowlist
291func (a bp2BuildConversionAllowlist) SetModuleTypeAlwaysConvertList(moduleTypeAlwaysConvert []string) bp2BuildConversionAllowlist {
292 if a.moduleTypeAlwaysConvert == nil {
293 a.moduleTypeAlwaysConvert = map[string]bool{}
294 }
295 for _, m := range moduleTypeAlwaysConvert {
296 a.moduleTypeAlwaysConvert[m] = true
297 }
298
299 return a
300}
301
302// SetModuleDoNotConvertList copies the entries from moduleDoNotConvert into the allowlist
303func (a bp2BuildConversionAllowlist) SetModuleDoNotConvertList(moduleDoNotConvert []string) bp2BuildConversionAllowlist {
304 if a.moduleDoNotConvert == nil {
305 a.moduleDoNotConvert = map[string]bool{}
306 }
307 for _, m := range moduleDoNotConvert {
308 a.moduleDoNotConvert[m] = true
309 }
310
311 return a
312}
313
314// SetCcLibraryStaticOnlyList copies the entries from ccLibraryStaticOnly into the allowlist
315func (a bp2BuildConversionAllowlist) SetCcLibraryStaticOnlyList(ccLibraryStaticOnly []string) bp2BuildConversionAllowlist {
316 if a.ccLibraryStaticOnly == nil {
317 a.ccLibraryStaticOnly = map[string]bool{}
318 }
319 for _, m := range ccLibraryStaticOnly {
320 a.ccLibraryStaticOnly[m] = true
321 }
322
323 return a
324}
325
326// SetMixedBuildsDisabledList copies the entries from mixedBuildsDisabled into the allowlist
327func (a bp2BuildConversionAllowlist) SetMixedBuildsDisabledList(mixedBuildsDisabled []string) bp2BuildConversionAllowlist {
328 if a.mixedBuildsDisabled == nil {
329 a.mixedBuildsDisabled = map[string]bool{}
330 }
331 for _, m := range mixedBuildsDisabled {
332 a.mixedBuildsDisabled[m] = true
333 }
334
335 return a
336}
337
Wei Lid7736ec2022-05-12 23:37:53 -0700338var bp2BuildAllowListKey = NewOnceKey("Bp2BuildAllowlist")
339var bp2buildAllowlist OncePer
340
341func getBp2BuildAllowList() bp2BuildConversionAllowlist {
342 return bp2buildAllowlist.Once(bp2BuildAllowListKey, func() interface{} {
343 return NewBp2BuildAllowlist().SetDefaultConfig(allowlists.Bp2buildDefaultConfig).
344 SetKeepExistingBuildFile(allowlists.Bp2buildKeepExistingBuildFile).
345 SetModuleAlwaysConvertList(allowlists.Bp2buildModuleAlwaysConvertList).
346 SetModuleTypeAlwaysConvertList(allowlists.Bp2buildModuleTypeAlwaysConvertList).
347 SetModuleDoNotConvertList(allowlists.Bp2buildModuleDoNotConvertList).
348 SetCcLibraryStaticOnlyList(allowlists.Bp2buildCcLibraryStaticOnlyList).
349 SetMixedBuildsDisabledList(allowlists.MixedBuildsDisabledList)
350 }).(bp2BuildConversionAllowlist)
351}
Sam Delmerico24c56032022-03-28 19:53:03 +0000352
353// GenerateCcLibraryStaticOnly returns whether a cc_library module should only
354// generate a static version of itself based on the current global configuration.
Chris Parsons953b3562021-09-20 15:14:39 -0400355func GenerateCcLibraryStaticOnly(moduleName string) bool {
Wei Lid7736ec2022-05-12 23:37:53 -0700356 return getBp2BuildAllowList().ccLibraryStaticOnly[moduleName]
Jingwen Chen179856a2021-05-03 09:15:48 +0000357}
358
Sam Delmerico24c56032022-03-28 19:53:03 +0000359// ShouldKeepExistingBuildFileForDir returns whether an existing BUILD file should be
360// added to the build symlink forest based on the current global configuration.
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400361func ShouldKeepExistingBuildFileForDir(dir string) bool {
Wei Lid7736ec2022-05-12 23:37:53 -0700362 return shouldKeepExistingBuildFileForDir(getBp2BuildAllowList(), dir)
Sam Delmerico24c56032022-03-28 19:53:03 +0000363}
364
365func shouldKeepExistingBuildFileForDir(allowlist bp2BuildConversionAllowlist, dir string) bool {
366 if _, ok := allowlist.keepExistingBuildFile[dir]; ok {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400367 // Exact dir match
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400368 return true
369 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400370 // Check if subtree match
Sam Delmerico24c56032022-03-28 19:53:03 +0000371 for prefix, recursive := range allowlist.keepExistingBuildFile {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400372 if recursive {
373 if strings.HasPrefix(dir, prefix+"/") {
374 return true
375 }
376 }
377 }
378 // Default
379 return false
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400380}
381
MarkDacekff851b82022-04-21 18:33:17 +0000382// MixedBuildsEnabled returns true if a module is ready to be replaced by a
383// converted or handcrafted Bazel target. As a side effect, calling this
384// method will also log whether this module is mixed build enabled for
385// metrics reporting.
Chris Parsonsf874e462022-05-10 13:50:12 -0400386func MixedBuildsEnabled(ctx BaseModuleContext) bool {
MarkDacekff851b82022-04-21 18:33:17 +0000387 mixedBuildEnabled := mixedBuildPossible(ctx)
388 ctx.Config().LogMixedBuild(ctx, mixedBuildEnabled)
389 return mixedBuildEnabled
390}
391
392// mixedBuildPossible returns true if a module is ready to be replaced by a
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400393// converted or handcrafted Bazel target.
Chris Parsonsf874e462022-05-10 13:50:12 -0400394func mixedBuildPossible(ctx BaseModuleContext) bool {
Chris Parsons494eef32021-11-09 10:29:52 -0500395 if ctx.Os() == Windows {
396 // Windows toolchains are not currently supported.
397 return false
398 }
Chris Parsons58852a02021-12-09 18:10:18 -0500399 if !ctx.Module().Enabled() {
400 return false
401 }
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400402 if !ctx.Config().BazelContext.BazelEnabled() {
403 return false
404 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400405 if !convertedToBazel(ctx, ctx.Module()) {
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400406 return false
407 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400408
Chris Parsons953b3562021-09-20 15:14:39 -0400409 if GenerateCcLibraryStaticOnly(ctx.Module().Name()) {
Jingwen Chen179856a2021-05-03 09:15:48 +0000410 // Don't use partially-converted cc_library targets in mixed builds,
411 // since mixed builds would generally rely on both static and shared
412 // variants of a cc_library.
413 return false
414 }
Wei Lid7736ec2022-05-12 23:37:53 -0700415 return !getBp2BuildAllowList().mixedBuildsDisabled[ctx.Module().Name()]
Rupert Shuttleworth4f43fe92021-03-30 14:13:16 +0000416}
417
Liz Kammer6eff3232021-08-26 08:37:59 -0400418// ConvertedToBazel returns whether this module has been converted (with bp2build or manually) to Bazel.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000419func convertedToBazel(ctx BazelConversionContext, module blueprint.Module) bool {
Liz Kammer6eff3232021-08-26 08:37:59 -0400420 b, ok := module.(Bazelable)
421 if !ok {
422 return false
423 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400424 return b.shouldConvertWithBp2build(ctx, module) || b.HasHandcraftedLabel()
Liz Kammer6eff3232021-08-26 08:37:59 -0400425}
426
Sam Delmerico24c56032022-03-28 19:53:03 +0000427// ShouldConvertWithBp2build returns whether the given BazelModuleBase should be converted with bp2build
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400428func (b *BazelModuleBase) ShouldConvertWithBp2build(ctx BazelConversionContext) bool {
429 return b.shouldConvertWithBp2build(ctx, ctx.Module())
Liz Kammer6eff3232021-08-26 08:37:59 -0400430}
431
Sam Delmerico24c56032022-03-28 19:53:03 +0000432type bazelOtherModuleContext interface {
433 ModuleErrorf(format string, args ...interface{})
434 Config() Config
435 OtherModuleType(m blueprint.Module) string
436 OtherModuleName(m blueprint.Module) string
437 OtherModuleDir(m blueprint.Module) string
438}
Sam Delmericofa1831c2022-02-22 18:07:55 +0000439
Sam Delmerico24c56032022-03-28 19:53:03 +0000440func (b *BazelModuleBase) shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400441 if !b.bazelProps().Bazel_module.CanConvertToBazel {
442 return false
Jingwen Chen12b4c272021-03-10 02:05:59 -0500443 }
444
Sam Delmerico85d831a2022-03-07 19:12:42 +0000445 propValue := b.bazelProperties.Bazel_module.Bp2build_available
Liz Kammer6eff3232021-08-26 08:37:59 -0400446 packagePath := ctx.OtherModuleDir(module)
Sam Delmerico24c56032022-03-28 19:53:03 +0000447
Sam Delmerico85d831a2022-03-07 19:12:42 +0000448 // Modules in unit tests which are enabled in the allowlist by type or name
449 // trigger this conditional because unit tests run under the "." package path
Sam Delmerico24c56032022-03-28 19:53:03 +0000450 isTestModule := packagePath == Bp2BuildTopLevel && proptools.BoolDefault(propValue, false)
451 if isTestModule {
452 return true
453 }
454
455 moduleName := module.Name()
456 allowlist := ctx.Config().bp2buildPackageConfig
457 moduleNameAllowed := allowlist.moduleAlwaysConvert[moduleName]
458 moduleTypeAllowed := allowlist.moduleTypeAlwaysConvert[ctx.OtherModuleType(module)]
459 allowlistConvert := moduleNameAllowed || moduleTypeAllowed
460 if moduleNameAllowed && moduleTypeAllowed {
461 ctx.ModuleErrorf("A module cannot be in moduleAlwaysConvert and also be in moduleTypeAlwaysConvert")
462 return false
463 }
464
465 if allowlist.moduleDoNotConvert[moduleName] {
Sam Delmerico85d831a2022-03-07 19:12:42 +0000466 if moduleNameAllowed {
Sam Delmerico24c56032022-03-28 19:53:03 +0000467 ctx.ModuleErrorf("a module cannot be in moduleDoNotConvert and also be in moduleAlwaysConvert")
Sam Delmerico85d831a2022-03-07 19:12:42 +0000468 }
Sam Delmerico94d26c22022-02-25 21:34:51 +0000469 return false
470 }
471
Sam Delmerico24c56032022-03-28 19:53:03 +0000472 if allowlistConvert && shouldKeepExistingBuildFileForDir(allowlist, packagePath) {
Sam Delmerico85d831a2022-03-07 19:12:42 +0000473 if moduleNameAllowed {
Sam Delmerico24c56032022-03-28 19:53:03 +0000474 ctx.ModuleErrorf("A module cannot be in a directory listed in keepExistingBuildFile"+
475 " and also be in moduleAlwaysConvert. Directory: '%s'", packagePath)
476 return false
477 }
478 }
479
480 // This is a tristate value: true, false, or unset.
481 if ok, directoryPath := bp2buildDefaultTrueRecursively(packagePath, allowlist.defaultConfig); ok {
482 if moduleNameAllowed {
483 ctx.ModuleErrorf("A module cannot be in a directory marked Bp2BuildDefaultTrue"+
484 " or Bp2BuildDefaultTrueRecursively and also be in moduleAlwaysConvert. Directory: '%s'",
485 directoryPath)
486 return false
Sam Delmericofa1831c2022-02-22 18:07:55 +0000487 }
488
Jingwen Chen12b4c272021-03-10 02:05:59 -0500489 // Allow modules to explicitly opt-out.
490 return proptools.BoolDefault(propValue, true)
491 }
492
493 // Allow modules to explicitly opt-in.
Sam Delmerico85d831a2022-03-07 19:12:42 +0000494 return proptools.BoolDefault(propValue, allowlistConvert)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500495}
496
497// bp2buildDefaultTrueRecursively checks that the package contains a prefix from the
498// set of package prefixes where all modules must be converted. That is, if the
499// package is x/y/z, and the list contains either x, x/y, or x/y/z, this function will
500// return true.
501//
502// However, if the package is x/y, and it matches a Bp2BuildDefaultFalse "x/y" entry
503// exactly, this module will return false early.
504//
505// This function will also return false if the package doesn't match anything in
506// the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000507//
508// This function will also return the allowlist entry which caused a particular
509// package to be enabled. Since packages can be enabled via a recursive declaration,
510// the path returned will not always be the same as the one provided.
511func bp2buildDefaultTrueRecursively(packagePath string, config allowlists.Bp2BuildConfig) (bool, string) {
Jingwen Chen294e7742021-08-31 05:58:01 +0000512 // Check if the package path has an exact match in the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000513 if config[packagePath] == allowlists.Bp2BuildDefaultTrue || config[packagePath] == allowlists.Bp2BuildDefaultTrueRecursively {
514 return true, packagePath
515 } else if config[packagePath] == allowlists.Bp2BuildDefaultFalse {
516 return false, packagePath
Jingwen Chen12b4c272021-03-10 02:05:59 -0500517 }
518
Jingwen Chen91220d72021-03-24 02:18:33 -0400519 // If not, check for the config recursively.
Jingwen Chen12b4c272021-03-10 02:05:59 -0500520 packagePrefix := ""
521 // e.g. for x/y/z, iterate over x, x/y, then x/y/z, taking the final value from the allowlist.
522 for _, part := range strings.Split(packagePath, "/") {
523 packagePrefix += part
Sam Delmerico24c56032022-03-28 19:53:03 +0000524 if config[packagePrefix] == allowlists.Bp2BuildDefaultTrueRecursively {
Jingwen Chen12b4c272021-03-10 02:05:59 -0500525 // package contains this prefix and this prefix should convert all modules
Sam Delmerico24c56032022-03-28 19:53:03 +0000526 return true, packagePrefix
Jingwen Chen12b4c272021-03-10 02:05:59 -0500527 }
528 // Continue to the next part of the package dir.
529 packagePrefix += "/"
530 }
531
Sam Delmerico24c56032022-03-28 19:53:03 +0000532 return false, packagePath
Liz Kammerea6666f2021-02-17 10:17:28 -0500533}
Liz Kammerba3ea162021-02-17 13:22:03 -0500534
535// GetBazelBuildFileContents returns the file contents of a hand-crafted BUILD file if available or
536// an error if there are errors reading the file.
537// TODO(b/181575318): currently we append the whole BUILD file, let's change that to do
538// something more targeted based on the rule type and target.
539func (b *BazelModuleBase) GetBazelBuildFileContents(c Config, path, name string) (string, error) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500540 if !strings.Contains(b.HandcraftedLabel(), path) {
541 return "", fmt.Errorf("%q not found in bazel_module.label %q", path, b.HandcraftedLabel())
Liz Kammerba3ea162021-02-17 13:22:03 -0500542 }
543 name = filepath.Join(path, name)
544 f, err := c.fs.Open(name)
545 if err != nil {
546 return "", err
547 }
548 defer f.Close()
549
550 data, err := ioutil.ReadAll(f)
551 if err != nil {
552 return "", err
553 }
554 return string(data[:]), nil
555}
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400556
557func registerBp2buildConversionMutator(ctx RegisterMutatorsContext) {
558 ctx.TopDown("bp2build_conversion", convertWithBp2build).Parallel()
559}
560
561func convertWithBp2build(ctx TopDownMutatorContext) {
562 bModule, ok := ctx.Module().(Bazelable)
563 if !ok || !bModule.shouldConvertWithBp2build(ctx, ctx.Module()) {
564 return
565 }
566
567 bModule.ConvertWithBp2build(ctx)
568}
Wei Libafb6d62021-12-10 03:14:59 -0800569
570// GetMainClassInManifest scans the manifest file specified in filepath and returns
571// the value of attribute Main-Class in the manifest file if it exists, or returns error.
572// WARNING: this is for bp2build converters of java_* modules only.
573func GetMainClassInManifest(c Config, filepath string) (string, error) {
574 file, err := c.fs.Open(filepath)
575 if err != nil {
576 return "", err
577 }
Liz Kammer0fe123d2022-02-07 10:17:35 -0500578 defer file.Close()
Wei Libafb6d62021-12-10 03:14:59 -0800579 scanner := bufio.NewScanner(file)
580 for scanner.Scan() {
581 line := scanner.Text()
582 if strings.HasPrefix(line, "Main-Class:") {
583 return strings.TrimSpace(line[len("Main-Class:"):]), nil
584 }
585 }
586
587 return "", errors.New("Main-Class is not found.")
588}