blob: aff611660158129f7856334d0cf93709b507b72a [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
Vinh Tran444154d2022-08-16 13:10:31 -040038// Bp2buildAidlLibrary describes a filegroup module that are converted to aidl_library
39type Bp2buildAidlLibrary interface {
40 ShouldConvertToAidlLibrary(ctx BazelConversionPathContext) bool
41 GetAidlLibraryLabel(ctx BazelConversionPathContext) string
42}
43
Sasha Smundaka0954062022-08-02 18:23:58 -070044type BazelConversionStatus struct {
45 // Information about _all_ bp2build targets generated by this module. Multiple targets are
46 // supported as Soong handles some things within a single target that we may choose to split into
47 // multiple targets, e.g. renderscript, protos, yacc within a cc module.
48 Bp2buildInfo []bp2buildInfo `blueprint:"mutated"`
49
50 // UnconvertedBp2buildDep stores the module names of direct dependency that were not converted to
51 // Bazel
52 UnconvertedDeps []string `blueprint:"mutated"`
53
54 // MissingBp2buildDep stores the module names of direct dependency that were not found
55 MissingDeps []string `blueprint:"mutated"`
56}
57
Jingwen Chen01812022021-11-19 14:29:43 +000058type bazelModuleProperties struct {
59 // The label of the Bazel target replacing this Soong module. When run in conversion mode, this
60 // will import the handcrafted build target into the autogenerated file. Note: this may result in
61 // a conflict due to duplicate targets if bp2build_available is also set.
62 Label *string
63
64 // If true, bp2build will generate the converted Bazel target for this module. Note: this may
65 // cause a conflict due to the duplicate targets if label is also set.
66 //
67 // This is a bool pointer to support tristates: true, false, not set.
68 //
69 // To opt-in a module, set bazel_module: { bp2build_available: true }
70 // To opt-out a module, set bazel_module: { bp2build_available: false }
71 // To defer the default setting for the directory, do not set the value.
72 Bp2build_available *bool
Liz Kammerbe46fcc2021-11-01 15:32:43 -040073
74 // CanConvertToBazel is set via InitBazelModule to indicate that a module type can be converted to
75 // Bazel with Bp2build.
76 CanConvertToBazel bool `blueprint:"mutated"`
Jingwen Chen01812022021-11-19 14:29:43 +000077}
78
Liz Kammerba3ea162021-02-17 13:22:03 -050079// Properties contains common module properties for Bazel migration purposes.
80type properties struct {
81 // In USE_BAZEL_ANALYSIS=1 mode, this represents the Bazel target replacing
82 // this Soong module.
Jingwen Chen01812022021-11-19 14:29:43 +000083 Bazel_module bazelModuleProperties
Liz Kammerba3ea162021-02-17 13:22:03 -050084}
Liz Kammerea6666f2021-02-17 10:17:28 -050085
Jingwen Chen25825ca2021-11-15 12:28:43 +000086// namespacedVariableProperties is a map from a string representing a Soong
Jingwen Chen84817de2021-11-17 10:57:35 +000087// config variable namespace, like "android" or "vendor_name" to a slice of
88// pointer to a struct containing a single field called Soong_config_variables
89// whose value mirrors the structure in the Blueprint file.
90type namespacedVariableProperties map[string][]interface{}
Jingwen Chena47f28d2021-11-02 16:43:57 +000091
Liz Kammerea6666f2021-02-17 10:17:28 -050092// BazelModuleBase contains the property structs with metadata for modules which can be converted to
93// Bazel.
94type BazelModuleBase struct {
Liz Kammerba3ea162021-02-17 13:22:03 -050095 bazelProperties properties
Jingwen Chena47f28d2021-11-02 16:43:57 +000096
97 // namespacedVariableProperties is used for soong_config_module_type support
98 // in bp2build. Soong config modules allow users to set module properties
99 // based on custom product variables defined in Android.bp files. These
100 // variables are namespaced to prevent clobbering, especially when set from
101 // Makefiles.
102 namespacedVariableProperties namespacedVariableProperties
103
104 // baseModuleType is set when this module was created from a module type
105 // defined by a soong_config_module_type. Every soong_config_module_type
106 // "wraps" another module type, e.g. a soong_config_module_type can wrap a
107 // cc_defaults to a custom_cc_defaults, or cc_binary to a custom_cc_binary.
108 // This baseModuleType is set to the wrapped module type.
109 baseModuleType string
Liz Kammerea6666f2021-02-17 10:17:28 -0500110}
111
112// Bazelable is specifies the interface for modules that can be converted to Bazel.
113type Bazelable interface {
Liz Kammerba3ea162021-02-17 13:22:03 -0500114 bazelProps() *properties
115 HasHandcraftedLabel() bool
Liz Kammerbdc60992021-02-24 16:55:11 -0500116 HandcraftedLabel() string
117 GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400118 ShouldConvertWithBp2build(ctx BazelConversionContext) bool
Sam Delmerico24c56032022-03-28 19:53:03 +0000119 shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool
Liz Kammerba3ea162021-02-17 13:22:03 -0500120 GetBazelBuildFileContents(c Config, path, name string) (string, error)
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400121 ConvertWithBp2build(ctx TopDownMutatorContext)
Jingwen Chena47f28d2021-11-02 16:43:57 +0000122
Jingwen Chen84817de2021-11-17 10:57:35 +0000123 // namespacedVariableProps is a map from a soong config variable namespace
124 // (e.g. acme, android) to a map of interfaces{}, which are really
125 // reflect.Struct pointers, representing the value of the
126 // soong_config_variables property of a module. The struct pointer is the
127 // one with the single member called Soong_config_variables, which itself is
128 // a struct containing fields for each supported feature in that namespace.
129 //
130 // The reason for using an slice of interface{} is to support defaults
131 // propagation of the struct pointers.
Jingwen Chena47f28d2021-11-02 16:43:57 +0000132 namespacedVariableProps() namespacedVariableProperties
133 setNamespacedVariableProps(props namespacedVariableProperties)
134 BaseModuleType() string
Jingwen Chen84817de2021-11-17 10:57:35 +0000135 SetBaseModuleType(baseModuleType string)
Liz Kammerea6666f2021-02-17 10:17:28 -0500136}
137
Chris Parsonsf874e462022-05-10 13:50:12 -0400138// MixedBuildBuildable is an interface that module types should implement in order
139// to be "handled by Bazel" in a mixed build.
140type MixedBuildBuildable interface {
141 // IsMixedBuildSupported returns true if and only if this module should be
142 // "handled by Bazel" in a mixed build.
143 // This "escape hatch" allows modules with corner-case scenarios to opt out
144 // of being built with Bazel.
145 IsMixedBuildSupported(ctx BaseModuleContext) bool
146
147 // QueueBazelCall invokes request-queueing functions on the BazelContext
148 // so that these requests are handled when Bazel's cquery is invoked.
149 QueueBazelCall(ctx BaseModuleContext)
150
151 // ProcessBazelQueryResponse uses Bazel information (obtained from the BazelContext)
152 // to set module fields and providers to propagate this module's metadata upstream.
153 // This effectively "bridges the gap" between Bazel and Soong in a mixed build.
154 // Soong modules depending on this module should be oblivious to the fact that
155 // this module was handled by Bazel.
156 ProcessBazelQueryResponse(ctx ModuleContext)
157}
158
Liz Kammerea6666f2021-02-17 10:17:28 -0500159// BazelModule is a lightweight wrapper interface around Module for Bazel-convertible modules.
160type BazelModule interface {
161 Module
162 Bazelable
163}
164
165// InitBazelModule is a wrapper function that decorates a BazelModule with Bazel-conversion
166// properties.
167func InitBazelModule(module BazelModule) {
168 module.AddProperties(module.bazelProps())
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400169 module.bazelProps().Bazel_module.CanConvertToBazel = true
Liz Kammerea6666f2021-02-17 10:17:28 -0500170}
171
172// bazelProps returns the Bazel properties for the given BazelModuleBase.
Liz Kammerba3ea162021-02-17 13:22:03 -0500173func (b *BazelModuleBase) bazelProps() *properties {
Liz Kammerea6666f2021-02-17 10:17:28 -0500174 return &b.bazelProperties
175}
176
Jingwen Chena47f28d2021-11-02 16:43:57 +0000177func (b *BazelModuleBase) namespacedVariableProps() namespacedVariableProperties {
178 return b.namespacedVariableProperties
179}
180
181func (b *BazelModuleBase) setNamespacedVariableProps(props namespacedVariableProperties) {
182 b.namespacedVariableProperties = props
183}
184
185func (b *BazelModuleBase) BaseModuleType() string {
186 return b.baseModuleType
187}
188
189func (b *BazelModuleBase) SetBaseModuleType(baseModuleType string) {
190 b.baseModuleType = baseModuleType
191}
192
Liz Kammerba3ea162021-02-17 13:22:03 -0500193// HasHandcraftedLabel returns whether this module has a handcrafted Bazel label.
194func (b *BazelModuleBase) HasHandcraftedLabel() bool {
195 return b.bazelProperties.Bazel_module.Label != nil
196}
197
198// HandcraftedLabel returns the handcrafted label for this module, or empty string if there is none
199func (b *BazelModuleBase) HandcraftedLabel() string {
200 return proptools.String(b.bazelProperties.Bazel_module.Label)
201}
202
Liz Kammerea6666f2021-02-17 10:17:28 -0500203// GetBazelLabel returns the Bazel label for the given BazelModuleBase.
Liz Kammerbdc60992021-02-24 16:55:11 -0500204func (b *BazelModuleBase) GetBazelLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
205 if b.HasHandcraftedLabel() {
206 return b.HandcraftedLabel()
207 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400208 if b.ShouldConvertWithBp2build(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500209 return bp2buildModuleLabel(ctx, module)
210 }
211 return "" // no label for unconverted module
Liz Kammerea6666f2021-02-17 10:17:28 -0500212}
213
Sam Delmerico24c56032022-03-28 19:53:03 +0000214type bp2BuildConversionAllowlist struct {
215 // Configure modules in these directories to enable bp2build_available: true or false by default.
216 defaultConfig allowlists.Bp2BuildConfig
Jingwen Chen12b4c272021-03-10 02:05:59 -0500217
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400218 // Keep any existing BUILD files (and do not generate new BUILD files) for these directories
Jingwen Chenb643c7a2021-07-26 04:45:48 +0000219 // in the synthetic Bazel workspace.
Sam Delmerico24c56032022-03-28 19:53:03 +0000220 keepExistingBuildFile map[string]bool
Jingwen Chen5d72cba2021-03-25 09:28:38 +0000221
Sam Delmericofa1831c2022-02-22 18:07:55 +0000222 // Per-module allowlist to always opt modules in of both bp2build and mixed builds.
Jingwen Chen7edadab2022-03-04 07:01:29 +0000223 // These modules are usually in directories with many other modules that are not ready for
224 // conversion.
225 //
226 // A module can either be in this list or its directory allowlisted entirely
227 // in bp2buildDefaultConfig, but not both at the same time.
Sam Delmerico24c56032022-03-28 19:53:03 +0000228 moduleAlwaysConvert map[string]bool
Sam Delmericofa1831c2022-02-22 18:07:55 +0000229
Sam Delmericoa9b047a2022-02-22 19:21:28 +0000230 // Per-module-type allowlist to always opt modules in to both bp2build and mixed builds
Sam Delmerico85d831a2022-03-07 19:12:42 +0000231 // when they have the same type as one listed.
Sam Delmerico24c56032022-03-28 19:53:03 +0000232 moduleTypeAlwaysConvert map[string]bool
Sam Delmerico85d831a2022-03-07 19:12:42 +0000233
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400234 // Per-module denylist to always opt modules out of both bp2build and mixed builds.
Sam Delmerico24c56032022-03-28 19:53:03 +0000235 moduleDoNotConvert map[string]bool
Rupert Shuttleworthc143cc52021-04-13 13:08:04 -0400236
Jingwen Chen179856a2021-05-03 09:15:48 +0000237 // Per-module denylist of cc_library modules to only generate the static
238 // variant if their shared variant isn't ready or buildable by Bazel.
Sam Delmerico24c56032022-03-28 19:53:03 +0000239 ccLibraryStaticOnly map[string]bool
Jingwen Chen179856a2021-05-03 09:15:48 +0000240
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400241 // Per-module denylist to opt modules out of mixed builds. Such modules will
242 // still be generated via bp2build.
Sam Delmerico24c56032022-03-28 19:53:03 +0000243 mixedBuildsDisabled map[string]bool
244}
Liz Kammer5c313582021-12-03 15:23:26 -0500245
Sam Delmerico24c56032022-03-28 19:53:03 +0000246// NewBp2BuildAllowlist creates a new, empty bp2BuildConversionAllowlist
247// which can be populated using builder pattern Set* methods
248func NewBp2BuildAllowlist() bp2BuildConversionAllowlist {
249 return bp2BuildConversionAllowlist{
250 allowlists.Bp2BuildConfig{},
251 map[string]bool{},
252 map[string]bool{},
253 map[string]bool{},
254 map[string]bool{},
255 map[string]bool{},
256 map[string]bool{},
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400257 }
258}
259
Sam Delmerico24c56032022-03-28 19:53:03 +0000260// SetDefaultConfig copies the entries from defaultConfig into the allowlist
261func (a bp2BuildConversionAllowlist) SetDefaultConfig(defaultConfig allowlists.Bp2BuildConfig) bp2BuildConversionAllowlist {
262 if a.defaultConfig == nil {
263 a.defaultConfig = allowlists.Bp2BuildConfig{}
264 }
265 for k, v := range defaultConfig {
266 a.defaultConfig[k] = v
267 }
268
269 return a
270}
271
272// SetKeepExistingBuildFile copies the entries from keepExistingBuildFile into the allowlist
273func (a bp2BuildConversionAllowlist) SetKeepExistingBuildFile(keepExistingBuildFile map[string]bool) bp2BuildConversionAllowlist {
274 if a.keepExistingBuildFile == nil {
275 a.keepExistingBuildFile = map[string]bool{}
276 }
277 for k, v := range keepExistingBuildFile {
278 a.keepExistingBuildFile[k] = v
279 }
280
281 return a
282}
283
284// SetModuleAlwaysConvertList copies the entries from moduleAlwaysConvert into the allowlist
285func (a bp2BuildConversionAllowlist) SetModuleAlwaysConvertList(moduleAlwaysConvert []string) bp2BuildConversionAllowlist {
286 if a.moduleAlwaysConvert == nil {
287 a.moduleAlwaysConvert = map[string]bool{}
288 }
289 for _, m := range moduleAlwaysConvert {
290 a.moduleAlwaysConvert[m] = true
291 }
292
293 return a
294}
295
296// SetModuleTypeAlwaysConvertList copies the entries from moduleTypeAlwaysConvert into the allowlist
297func (a bp2BuildConversionAllowlist) SetModuleTypeAlwaysConvertList(moduleTypeAlwaysConvert []string) bp2BuildConversionAllowlist {
298 if a.moduleTypeAlwaysConvert == nil {
299 a.moduleTypeAlwaysConvert = map[string]bool{}
300 }
301 for _, m := range moduleTypeAlwaysConvert {
302 a.moduleTypeAlwaysConvert[m] = true
303 }
304
305 return a
306}
307
308// SetModuleDoNotConvertList copies the entries from moduleDoNotConvert into the allowlist
309func (a bp2BuildConversionAllowlist) SetModuleDoNotConvertList(moduleDoNotConvert []string) bp2BuildConversionAllowlist {
310 if a.moduleDoNotConvert == nil {
311 a.moduleDoNotConvert = map[string]bool{}
312 }
313 for _, m := range moduleDoNotConvert {
314 a.moduleDoNotConvert[m] = true
315 }
316
317 return a
318}
319
320// SetCcLibraryStaticOnlyList copies the entries from ccLibraryStaticOnly into the allowlist
321func (a bp2BuildConversionAllowlist) SetCcLibraryStaticOnlyList(ccLibraryStaticOnly []string) bp2BuildConversionAllowlist {
322 if a.ccLibraryStaticOnly == nil {
323 a.ccLibraryStaticOnly = map[string]bool{}
324 }
325 for _, m := range ccLibraryStaticOnly {
326 a.ccLibraryStaticOnly[m] = true
327 }
328
329 return a
330}
331
332// SetMixedBuildsDisabledList copies the entries from mixedBuildsDisabled into the allowlist
333func (a bp2BuildConversionAllowlist) SetMixedBuildsDisabledList(mixedBuildsDisabled []string) bp2BuildConversionAllowlist {
334 if a.mixedBuildsDisabled == nil {
335 a.mixedBuildsDisabled = map[string]bool{}
336 }
337 for _, m := range mixedBuildsDisabled {
338 a.mixedBuildsDisabled[m] = true
339 }
340
341 return a
342}
343
Wei Lid7736ec2022-05-12 23:37:53 -0700344var bp2BuildAllowListKey = NewOnceKey("Bp2BuildAllowlist")
345var bp2buildAllowlist OncePer
346
347func getBp2BuildAllowList() bp2BuildConversionAllowlist {
348 return bp2buildAllowlist.Once(bp2BuildAllowListKey, func() interface{} {
349 return NewBp2BuildAllowlist().SetDefaultConfig(allowlists.Bp2buildDefaultConfig).
350 SetKeepExistingBuildFile(allowlists.Bp2buildKeepExistingBuildFile).
351 SetModuleAlwaysConvertList(allowlists.Bp2buildModuleAlwaysConvertList).
352 SetModuleTypeAlwaysConvertList(allowlists.Bp2buildModuleTypeAlwaysConvertList).
353 SetModuleDoNotConvertList(allowlists.Bp2buildModuleDoNotConvertList).
354 SetCcLibraryStaticOnlyList(allowlists.Bp2buildCcLibraryStaticOnlyList).
355 SetMixedBuildsDisabledList(allowlists.MixedBuildsDisabledList)
356 }).(bp2BuildConversionAllowlist)
357}
Sam Delmerico24c56032022-03-28 19:53:03 +0000358
359// GenerateCcLibraryStaticOnly returns whether a cc_library module should only
360// generate a static version of itself based on the current global configuration.
Chris Parsons953b3562021-09-20 15:14:39 -0400361func GenerateCcLibraryStaticOnly(moduleName string) bool {
Wei Lid7736ec2022-05-12 23:37:53 -0700362 return getBp2BuildAllowList().ccLibraryStaticOnly[moduleName]
Jingwen Chen179856a2021-05-03 09:15:48 +0000363}
364
Sam Delmerico24c56032022-03-28 19:53:03 +0000365// ShouldKeepExistingBuildFileForDir returns whether an existing BUILD file should be
366// added to the build symlink forest based on the current global configuration.
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400367func ShouldKeepExistingBuildFileForDir(dir string) bool {
Wei Lid7736ec2022-05-12 23:37:53 -0700368 return shouldKeepExistingBuildFileForDir(getBp2BuildAllowList(), dir)
Sam Delmerico24c56032022-03-28 19:53:03 +0000369}
370
371func shouldKeepExistingBuildFileForDir(allowlist bp2BuildConversionAllowlist, dir string) bool {
372 if _, ok := allowlist.keepExistingBuildFile[dir]; ok {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400373 // Exact dir match
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400374 return true
375 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400376 // Check if subtree match
Sam Delmerico24c56032022-03-28 19:53:03 +0000377 for prefix, recursive := range allowlist.keepExistingBuildFile {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400378 if recursive {
379 if strings.HasPrefix(dir, prefix+"/") {
380 return true
381 }
382 }
383 }
384 // Default
385 return false
Rupert Shuttleworth2a4fc3e2021-04-21 07:10:09 -0400386}
387
MarkDacekff851b82022-04-21 18:33:17 +0000388// MixedBuildsEnabled returns true if a module is ready to be replaced by a
389// converted or handcrafted Bazel target. As a side effect, calling this
390// method will also log whether this module is mixed build enabled for
391// metrics reporting.
Chris Parsonsf874e462022-05-10 13:50:12 -0400392func MixedBuildsEnabled(ctx BaseModuleContext) bool {
MarkDacekff851b82022-04-21 18:33:17 +0000393 mixedBuildEnabled := mixedBuildPossible(ctx)
394 ctx.Config().LogMixedBuild(ctx, mixedBuildEnabled)
395 return mixedBuildEnabled
396}
397
398// mixedBuildPossible returns true if a module is ready to be replaced by a
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400399// converted or handcrafted Bazel target.
Chris Parsonsf874e462022-05-10 13:50:12 -0400400func mixedBuildPossible(ctx BaseModuleContext) bool {
Chris Parsons494eef32021-11-09 10:29:52 -0500401 if ctx.Os() == Windows {
402 // Windows toolchains are not currently supported.
403 return false
404 }
Chris Parsons58852a02021-12-09 18:10:18 -0500405 if !ctx.Module().Enabled() {
406 return false
407 }
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400408 if !ctx.Config().BazelContext.BazelEnabled() {
409 return false
410 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400411 if !convertedToBazel(ctx, ctx.Module()) {
Chris Parsonsbab4d7e2021-04-15 17:27:08 -0400412 return false
413 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400414
Chris Parsons953b3562021-09-20 15:14:39 -0400415 if GenerateCcLibraryStaticOnly(ctx.Module().Name()) {
Jingwen Chen179856a2021-05-03 09:15:48 +0000416 // Don't use partially-converted cc_library targets in mixed builds,
417 // since mixed builds would generally rely on both static and shared
418 // variants of a cc_library.
419 return false
420 }
Wei Lid7736ec2022-05-12 23:37:53 -0700421 return !getBp2BuildAllowList().mixedBuildsDisabled[ctx.Module().Name()]
Rupert Shuttleworth4f43fe92021-03-30 14:13:16 +0000422}
423
Liz Kammer6eff3232021-08-26 08:37:59 -0400424// ConvertedToBazel returns whether this module has been converted (with bp2build or manually) to Bazel.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000425func convertedToBazel(ctx BazelConversionContext, module blueprint.Module) bool {
Liz Kammer6eff3232021-08-26 08:37:59 -0400426 b, ok := module.(Bazelable)
427 if !ok {
428 return false
429 }
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400430 return b.shouldConvertWithBp2build(ctx, module) || b.HasHandcraftedLabel()
Liz Kammer6eff3232021-08-26 08:37:59 -0400431}
432
Sam Delmerico24c56032022-03-28 19:53:03 +0000433// ShouldConvertWithBp2build returns whether the given BazelModuleBase should be converted with bp2build
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400434func (b *BazelModuleBase) ShouldConvertWithBp2build(ctx BazelConversionContext) bool {
435 return b.shouldConvertWithBp2build(ctx, ctx.Module())
Liz Kammer6eff3232021-08-26 08:37:59 -0400436}
437
Sam Delmerico24c56032022-03-28 19:53:03 +0000438type bazelOtherModuleContext interface {
439 ModuleErrorf(format string, args ...interface{})
440 Config() Config
441 OtherModuleType(m blueprint.Module) string
442 OtherModuleName(m blueprint.Module) string
443 OtherModuleDir(m blueprint.Module) string
444}
Sam Delmericofa1831c2022-02-22 18:07:55 +0000445
Sam Delmerico24c56032022-03-28 19:53:03 +0000446func (b *BazelModuleBase) shouldConvertWithBp2build(ctx bazelOtherModuleContext, module blueprint.Module) bool {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400447 if !b.bazelProps().Bazel_module.CanConvertToBazel {
448 return false
Jingwen Chen12b4c272021-03-10 02:05:59 -0500449 }
450
Sam Delmerico85d831a2022-03-07 19:12:42 +0000451 propValue := b.bazelProperties.Bazel_module.Bp2build_available
Liz Kammer6eff3232021-08-26 08:37:59 -0400452 packagePath := ctx.OtherModuleDir(module)
Sam Delmerico24c56032022-03-28 19:53:03 +0000453
Sam Delmerico85d831a2022-03-07 19:12:42 +0000454 // Modules in unit tests which are enabled in the allowlist by type or name
455 // trigger this conditional because unit tests run under the "." package path
Sam Delmerico24c56032022-03-28 19:53:03 +0000456 isTestModule := packagePath == Bp2BuildTopLevel && proptools.BoolDefault(propValue, false)
457 if isTestModule {
458 return true
459 }
460
461 moduleName := module.Name()
462 allowlist := ctx.Config().bp2buildPackageConfig
463 moduleNameAllowed := allowlist.moduleAlwaysConvert[moduleName]
464 moduleTypeAllowed := allowlist.moduleTypeAlwaysConvert[ctx.OtherModuleType(module)]
465 allowlistConvert := moduleNameAllowed || moduleTypeAllowed
466 if moduleNameAllowed && moduleTypeAllowed {
467 ctx.ModuleErrorf("A module cannot be in moduleAlwaysConvert and also be in moduleTypeAlwaysConvert")
468 return false
469 }
470
471 if allowlist.moduleDoNotConvert[moduleName] {
Sam Delmerico85d831a2022-03-07 19:12:42 +0000472 if moduleNameAllowed {
Sam Delmerico24c56032022-03-28 19:53:03 +0000473 ctx.ModuleErrorf("a module cannot be in moduleDoNotConvert and also be in moduleAlwaysConvert")
Sam Delmerico85d831a2022-03-07 19:12:42 +0000474 }
Sam Delmerico94d26c22022-02-25 21:34:51 +0000475 return false
476 }
477
Sam Delmerico24c56032022-03-28 19:53:03 +0000478 if allowlistConvert && shouldKeepExistingBuildFileForDir(allowlist, packagePath) {
Sam Delmerico85d831a2022-03-07 19:12:42 +0000479 if moduleNameAllowed {
Sam Delmerico24c56032022-03-28 19:53:03 +0000480 ctx.ModuleErrorf("A module cannot be in a directory listed in keepExistingBuildFile"+
481 " and also be in moduleAlwaysConvert. Directory: '%s'", packagePath)
482 return false
483 }
484 }
485
486 // This is a tristate value: true, false, or unset.
487 if ok, directoryPath := bp2buildDefaultTrueRecursively(packagePath, allowlist.defaultConfig); ok {
488 if moduleNameAllowed {
489 ctx.ModuleErrorf("A module cannot be in a directory marked Bp2BuildDefaultTrue"+
490 " or Bp2BuildDefaultTrueRecursively and also be in moduleAlwaysConvert. Directory: '%s'",
491 directoryPath)
492 return false
Sam Delmericofa1831c2022-02-22 18:07:55 +0000493 }
494
Jingwen Chen12b4c272021-03-10 02:05:59 -0500495 // Allow modules to explicitly opt-out.
496 return proptools.BoolDefault(propValue, true)
497 }
498
499 // Allow modules to explicitly opt-in.
Sam Delmerico85d831a2022-03-07 19:12:42 +0000500 return proptools.BoolDefault(propValue, allowlistConvert)
Jingwen Chen12b4c272021-03-10 02:05:59 -0500501}
502
503// bp2buildDefaultTrueRecursively checks that the package contains a prefix from the
504// set of package prefixes where all modules must be converted. That is, if the
505// package is x/y/z, and the list contains either x, x/y, or x/y/z, this function will
506// return true.
507//
508// However, if the package is x/y, and it matches a Bp2BuildDefaultFalse "x/y" entry
509// exactly, this module will return false early.
510//
511// This function will also return false if the package doesn't match anything in
512// the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000513//
514// This function will also return the allowlist entry which caused a particular
515// package to be enabled. Since packages can be enabled via a recursive declaration,
516// the path returned will not always be the same as the one provided.
517func bp2buildDefaultTrueRecursively(packagePath string, config allowlists.Bp2BuildConfig) (bool, string) {
Jingwen Chen294e7742021-08-31 05:58:01 +0000518 // Check if the package path has an exact match in the config.
Sam Delmerico24c56032022-03-28 19:53:03 +0000519 if config[packagePath] == allowlists.Bp2BuildDefaultTrue || config[packagePath] == allowlists.Bp2BuildDefaultTrueRecursively {
520 return true, packagePath
521 } else if config[packagePath] == allowlists.Bp2BuildDefaultFalse {
522 return false, packagePath
Jingwen Chen12b4c272021-03-10 02:05:59 -0500523 }
524
Jingwen Chen91220d72021-03-24 02:18:33 -0400525 // If not, check for the config recursively.
Jingwen Chen12b4c272021-03-10 02:05:59 -0500526 packagePrefix := ""
527 // e.g. for x/y/z, iterate over x, x/y, then x/y/z, taking the final value from the allowlist.
528 for _, part := range strings.Split(packagePath, "/") {
529 packagePrefix += part
Sam Delmerico24c56032022-03-28 19:53:03 +0000530 if config[packagePrefix] == allowlists.Bp2BuildDefaultTrueRecursively {
Jingwen Chen12b4c272021-03-10 02:05:59 -0500531 // package contains this prefix and this prefix should convert all modules
Sam Delmerico24c56032022-03-28 19:53:03 +0000532 return true, packagePrefix
Jingwen Chen12b4c272021-03-10 02:05:59 -0500533 }
534 // Continue to the next part of the package dir.
535 packagePrefix += "/"
536 }
537
Sam Delmerico24c56032022-03-28 19:53:03 +0000538 return false, packagePath
Liz Kammerea6666f2021-02-17 10:17:28 -0500539}
Liz Kammerba3ea162021-02-17 13:22:03 -0500540
541// GetBazelBuildFileContents returns the file contents of a hand-crafted BUILD file if available or
542// an error if there are errors reading the file.
543// TODO(b/181575318): currently we append the whole BUILD file, let's change that to do
544// something more targeted based on the rule type and target.
545func (b *BazelModuleBase) GetBazelBuildFileContents(c Config, path, name string) (string, error) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500546 if !strings.Contains(b.HandcraftedLabel(), path) {
547 return "", fmt.Errorf("%q not found in bazel_module.label %q", path, b.HandcraftedLabel())
Liz Kammerba3ea162021-02-17 13:22:03 -0500548 }
549 name = filepath.Join(path, name)
550 f, err := c.fs.Open(name)
551 if err != nil {
552 return "", err
553 }
554 defer f.Close()
555
556 data, err := ioutil.ReadAll(f)
557 if err != nil {
558 return "", err
559 }
560 return string(data[:]), nil
561}
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400562
563func registerBp2buildConversionMutator(ctx RegisterMutatorsContext) {
564 ctx.TopDown("bp2build_conversion", convertWithBp2build).Parallel()
565}
566
567func convertWithBp2build(ctx TopDownMutatorContext) {
568 bModule, ok := ctx.Module().(Bazelable)
569 if !ok || !bModule.shouldConvertWithBp2build(ctx, ctx.Module()) {
570 return
571 }
572
573 bModule.ConvertWithBp2build(ctx)
574}
Wei Libafb6d62021-12-10 03:14:59 -0800575
576// GetMainClassInManifest scans the manifest file specified in filepath and returns
577// the value of attribute Main-Class in the manifest file if it exists, or returns error.
578// WARNING: this is for bp2build converters of java_* modules only.
579func GetMainClassInManifest(c Config, filepath string) (string, error) {
580 file, err := c.fs.Open(filepath)
581 if err != nil {
582 return "", err
583 }
Liz Kammer0fe123d2022-02-07 10:17:35 -0500584 defer file.Close()
Wei Libafb6d62021-12-10 03:14:59 -0800585 scanner := bufio.NewScanner(file)
586 for scanner.Scan() {
587 line := scanner.Text()
588 if strings.HasPrefix(line, "Main-Class:") {
589 return strings.TrimSpace(line[len("Main-Class:"):]), nil
590 }
591 }
592
593 return "", errors.New("Main-Class is not found.")
594}