blob: 836416947f3ee7acb1a73ba3ca590683ff09f85d [file] [log] [blame]
Nan Zhangdb0b9a32017-02-27 10:12:13 -08001// Copyright 2017 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 python
16
17// This file contains the "Base" module type for building Python program.
18
19import (
20 "fmt"
21 "path/filepath"
22 "regexp"
Nan Zhangdb0b9a32017-02-27 10:12:13 -080023 "strings"
24
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux19d399d2021-09-17 20:30:21 +000025 "android/soong/bazel"
Liz Kammerbe46fcc2021-11-01 15:32:43 -040026
Nan Zhangdb0b9a32017-02-27 10:12:13 -080027 "github.com/google/blueprint"
Nan Zhangd4e641b2017-07-12 12:55:28 -070028 "github.com/google/blueprint/proptools"
Nan Zhangdb0b9a32017-02-27 10:12:13 -080029
30 "android/soong/android"
31)
32
33func init() {
Paul Duffind0890452021-03-17 21:57:08 +000034 registerPythonMutators(android.InitRegistrationContext)
35}
36
37func registerPythonMutators(ctx android.RegistrationContext) {
38 ctx.PreDepsMutators(RegisterPythonPreDepsMutators)
Liz Kammerdd849a82020-06-12 16:38:45 -070039}
40
Liz Kammerd737d022020-11-16 15:42:51 -080041// Exported to support other packages using Python modules in tests.
Liz Kammerdd849a82020-06-12 16:38:45 -070042func RegisterPythonPreDepsMutators(ctx android.RegisterMutatorsContext) {
Colin Crosse20113d2020-11-22 19:37:44 -080043 ctx.BottomUp("python_version", versionSplitMutator()).Parallel()
Nan Zhangdb0b9a32017-02-27 10:12:13 -080044}
45
Liz Kammerd737d022020-11-16 15:42:51 -080046// the version-specific properties that apply to python modules.
Nan Zhangd4e641b2017-07-12 12:55:28 -070047type VersionProperties struct {
Liz Kammerd737d022020-11-16 15:42:51 -080048 // whether the module is required to be built with this version.
49 // Defaults to true for Python 3, and false otherwise.
Liz Kammer59c0eae2021-09-17 17:48:05 -040050 Enabled *bool
Nan Zhangdb0b9a32017-02-27 10:12:13 -080051
Liz Kammerd737d022020-11-16 15:42:51 -080052 // list of source files specific to this Python version.
53 // Using the syntax ":module", srcs may reference the outputs of other modules that produce source files,
54 // e.g. genrule or filegroup.
Colin Cross27b922f2019-03-04 22:35:41 -080055 Srcs []string `android:"path,arch_variant"`
Nan Zhangd4e641b2017-07-12 12:55:28 -070056
Liz Kammerd737d022020-11-16 15:42:51 -080057 // list of source files that should not be used to build the Python module for this version.
58 // This is most useful to remove files that are not common to all Python versions.
Colin Cross27b922f2019-03-04 22:35:41 -080059 Exclude_srcs []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080060
Liz Kammerd737d022020-11-16 15:42:51 -080061 // list of the Python libraries used only for this Python version.
Nan Zhangd4e641b2017-07-12 12:55:28 -070062 Libs []string `android:"arch_variant"`
63
Liz Kammerd737d022020-11-16 15:42:51 -080064 // whether the binary is required to be built with embedded launcher for this version, defaults to false.
Liz Kammer59c0eae2021-09-17 17:48:05 -040065 Embedded_launcher *bool // TODO(b/174041232): Remove this property
Nan Zhangdb0b9a32017-02-27 10:12:13 -080066}
67
Liz Kammerd737d022020-11-16 15:42:51 -080068// properties that apply to all python modules
Nan Zhangd4e641b2017-07-12 12:55:28 -070069type BaseProperties struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -080070 // the package path prefix within the output artifact at which to place the source/data
71 // files of the current module.
72 // eg. Pkg_path = "a/b/c"; Other packages can reference this module by using
73 // (from a.b.c import ...) statement.
Nan Zhangbea09752018-05-31 12:49:33 -070074 // if left unspecified, all the source/data files path is unchanged within zip file.
Liz Kammer59c0eae2021-09-17 17:48:05 -040075 Pkg_path *string
Nan Zhangd4e641b2017-07-12 12:55:28 -070076
77 // true, if the Python module is used internally, eg, Python std libs.
Liz Kammer59c0eae2021-09-17 17:48:05 -040078 Is_internal *bool
Nan Zhangdb0b9a32017-02-27 10:12:13 -080079
80 // list of source (.py) files compatible both with Python2 and Python3 used to compile the
81 // Python module.
82 // srcs may reference the outputs of other modules that produce source files like genrule
83 // or filegroup using the syntax ":module".
84 // Srcs has to be non-empty.
Colin Cross27b922f2019-03-04 22:35:41 -080085 Srcs []string `android:"path,arch_variant"`
Nan Zhangd4e641b2017-07-12 12:55:28 -070086
87 // list of source files that should not be used to build the C/C++ module.
88 // This is most useful in the arch/multilib variants to remove non-common files
Colin Cross27b922f2019-03-04 22:35:41 -080089 Exclude_srcs []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080090
91 // list of files or filegroup modules that provide data that should be installed alongside
92 // the test. the file extension can be arbitrary except for (.py).
Colin Cross27b922f2019-03-04 22:35:41 -080093 Data []string `android:"path,arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -080094
Colin Cross1bc63932020-11-22 20:12:45 -080095 // list of java modules that provide data that should be installed alongside the test.
96 Java_data []string
97
Nan Zhangdb0b9a32017-02-27 10:12:13 -080098 // list of the Python libraries compatible both with Python2 and Python3.
Nan Zhangd4e641b2017-07-12 12:55:28 -070099 Libs []string `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800100
101 Version struct {
Liz Kammerd737d022020-11-16 15:42:51 -0800102 // Python2-specific properties, including whether Python2 is supported for this module
103 // and version-specific sources, exclusions and dependencies.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700104 Py2 VersionProperties `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800105
Liz Kammerd737d022020-11-16 15:42:51 -0800106 // Python3-specific properties, including whether Python3 is supported for this module
107 // and version-specific sources, exclusions and dependencies.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700108 Py3 VersionProperties `android:"arch_variant"`
109 } `android:"arch_variant"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800110
111 // the actual version each module uses after variations created.
112 // this property name is hidden from users' perspectives, and soong will populate it during
113 // runtime.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700114 Actual_version string `blueprint:"mutated"`
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700115
Liz Kammerd737d022020-11-16 15:42:51 -0800116 // whether the module is required to be built with actual_version.
117 // this is set by the python version mutator based on version-specific properties
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700118 Enabled *bool `blueprint:"mutated"`
119
Liz Kammerd737d022020-11-16 15:42:51 -0800120 // whether the binary is required to be built with embedded launcher for this actual_version.
121 // this is set by the python version mutator based on version-specific properties
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700122 Embedded_launcher *bool `blueprint:"mutated"`
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800123}
124
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux19d399d2021-09-17 20:30:21 +0000125type baseAttributes struct {
126 // TODO(b/200311466): Probably not translate b/c Bazel has no good equiv
127 //Pkg_path bazel.StringAttribute
128 // TODO: Related to Pkg_bath and similarLy gated
129 //Is_internal bazel.BoolAttribute
130 // Combines Srcs and Exclude_srcs
131 Srcs bazel.LabelListAttribute
132 Deps bazel.LabelListAttribute
133 // Combines Data and Java_data (invariant)
Cole Faust01243362022-06-02 12:11:12 -0700134 Data bazel.LabelListAttribute
135 Imports bazel.StringListAttribute
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux19d399d2021-09-17 20:30:21 +0000136}
137
Liz Kammerd737d022020-11-16 15:42:51 -0800138// Used to store files of current module after expanding dependencies
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800139type pathMapping struct {
140 dest string
141 src android.Path
142}
143
Nan Zhangd4e641b2017-07-12 12:55:28 -0700144type Module struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800145 android.ModuleBase
Nan Zhanga3fc4ba2017-07-20 17:43:37 -0700146 android.DefaultableModuleBase
Jingwen Chen13b9b422021-03-08 07:32:28 -0500147 android.BazelModuleBase
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800148
Nan Zhangb8fa1972017-12-22 16:12:00 -0800149 properties BaseProperties
150 protoProperties android.ProtoProperties
Nan Zhangd4e641b2017-07-12 12:55:28 -0700151
152 // initialize before calling Init
153 hod android.HostOrDeviceSupported
154 multilib android.Multilib
155
Liz Kammerd737d022020-11-16 15:42:51 -0800156 // interface used to bootstrap .par executable when embedded_launcher is true
157 // this should be set by Python modules which are runnable, e.g. binaries and tests
158 // bootstrapper might be nil (e.g. Python library module).
Nan Zhangd4e641b2017-07-12 12:55:28 -0700159 bootstrapper bootstrapper
160
Liz Kammerd737d022020-11-16 15:42:51 -0800161 // interface that implements functions required for installation
162 // this should be set by Python modules which are runnable, e.g. binaries and tests
163 // installer might be nil (e.g. Python library module).
Nan Zhangd4e641b2017-07-12 12:55:28 -0700164 installer installer
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800165
166 // the Python files of current module after expanding source dependencies.
167 // pathMapping: <dest: runfile_path, src: source_path>
168 srcsPathMappings []pathMapping
169
170 // the data files of current module after expanding source dependencies.
171 // pathMapping: <dest: runfile_path, src: source_path>
172 dataPathMappings []pathMapping
173
Nan Zhang1db85402017-12-18 13:20:23 -0800174 // the zip filepath for zipping current module source/data files.
175 srcsZip android.Path
Nan Zhangd4e641b2017-07-12 12:55:28 -0700176
Nan Zhang1db85402017-12-18 13:20:23 -0800177 // dependency modules' zip filepath for zipping current module source/data files.
178 depsSrcsZips android.Paths
Nan Zhangd4e641b2017-07-12 12:55:28 -0700179
180 // (.intermediate) module output path as installation source.
181 installSource android.OptionalPath
182
Liz Kammerd737d022020-11-16 15:42:51 -0800183 // Map to ensure sub-part of the AndroidMk for this module is only added once
Nan Zhang5323f8e2017-05-10 13:37:54 -0700184 subAndroidMkOnce map[subAndroidMkProvider]bool
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800185}
186
Liz Kammerd737d022020-11-16 15:42:51 -0800187// newModule generates new Python base module
Nan Zhangd4e641b2017-07-12 12:55:28 -0700188func newModule(hod android.HostOrDeviceSupported, multilib android.Multilib) *Module {
189 return &Module{
190 hod: hod,
191 multilib: multilib,
192 }
193}
194
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux19d399d2021-09-17 20:30:21 +0000195func (m *Module) makeArchVariantBaseAttributes(ctx android.TopDownMutatorContext) baseAttributes {
196 var attrs baseAttributes
197 archVariantBaseProps := m.GetArchVariantProperties(ctx, &BaseProperties{})
198 for axis, configToProps := range archVariantBaseProps {
199 for config, props := range configToProps {
200 if baseProps, ok := props.(*BaseProperties); ok {
201 attrs.Srcs.SetSelectValue(axis, config,
202 android.BazelLabelForModuleSrcExcludes(ctx, baseProps.Srcs, baseProps.Exclude_srcs))
203 attrs.Deps.SetSelectValue(axis, config,
204 android.BazelLabelForModuleDeps(ctx, baseProps.Libs))
205 data := android.BazelLabelForModuleSrc(ctx, baseProps.Data)
206 data.Append(android.BazelLabelForModuleSrc(ctx, baseProps.Java_data))
207 attrs.Data.SetSelectValue(axis, config, data)
208 }
209 }
210 }
Cole Faust53b62092022-05-12 15:37:02 -0700211
212 partitionedSrcs := bazel.PartitionLabelListAttribute(ctx, &attrs.Srcs, bazel.LabelPartitions{
213 "proto": android.ProtoSrcLabelPartition,
214 "py": bazel.LabelPartition{Keep_remainder: true},
215 })
216 attrs.Srcs = partitionedSrcs["py"]
217
218 if !partitionedSrcs["proto"].IsEmpty() {
219 protoInfo, _ := android.Bp2buildProtoProperties(ctx, &m.ModuleBase, partitionedSrcs["proto"])
220 protoLabel := bazel.Label{Label: ":" + protoInfo.Name}
221
222 pyProtoLibraryName := m.Name() + "_py_proto"
223 ctx.CreateBazelTargetModule(bazel.BazelTargetModuleProperties{
224 Rule_class: "py_proto_library",
225 Bzl_load_location: "//build/bazel/rules/python:py_proto.bzl",
226 }, android.CommonAttributes{
227 Name: pyProtoLibraryName,
228 }, &bazelPythonProtoLibraryAttributes{
229 Deps: bazel.MakeSingleLabelListAttribute(protoLabel),
230 })
231
232 attrs.Deps.Add(bazel.MakeLabelAttribute(":" + pyProtoLibraryName))
233 }
Cole Faust01243362022-06-02 12:11:12 -0700234
235 // Bazel normally requires `import path.from.top.of.tree` statements in
236 // python code, but with soong you can directly import modules from libraries.
237 // Add "imports" attributes to the bazel library so it matches soong's behavior.
238 imports := "."
239 if m.properties.Pkg_path != nil {
240 // TODO(b/215119317) This is a hack to handle the fact that we don't convert
241 // pkg_path properly right now. If the folder structure that contains this
242 // Android.bp file matches pkg_path, we can set imports to an appropriate
243 // number of ../..s to emulate moving the files under a pkg_path folder.
244 pkg_path := filepath.Clean(*m.properties.Pkg_path)
245 if strings.HasPrefix(pkg_path, "/") {
246 ctx.ModuleErrorf("pkg_path cannot start with a /: %s", pkg_path)
247 }
248
249 if !strings.HasSuffix(ctx.ModuleDir(), "/"+pkg_path) && ctx.ModuleDir() != pkg_path {
250 ctx.ModuleErrorf("Currently, bp2build only supports pkg_paths that are the same as the folders the Android.bp file is in. pkg_path: %s, module directory: %s", pkg_path, ctx.ModuleDir())
251 }
252 numFolders := strings.Count(pkg_path, "/") + 1
253 dots := make([]string, numFolders)
254 for i := 0; i < numFolders; i++ {
255 dots[i] = ".."
256 }
257 imports = strings.Join(dots, "/")
258 }
259 attrs.Imports = bazel.MakeStringListAttribute([]string{imports})
260
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux19d399d2021-09-17 20:30:21 +0000261 return attrs
262}
263
Liz Kammerd737d022020-11-16 15:42:51 -0800264// bootstrapper interface should be implemented for runnable modules, e.g. binary and test
Nan Zhangd4e641b2017-07-12 12:55:28 -0700265type bootstrapper interface {
266 bootstrapperProps() []interface{}
Nan Zhang1db85402017-12-18 13:20:23 -0800267 bootstrap(ctx android.ModuleContext, ActualVersion string, embeddedLauncher bool,
268 srcsPathMappings []pathMapping, srcsZip android.Path,
269 depsSrcsZips android.Paths) android.OptionalPath
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800270
271 autorun() bool
Nan Zhangd4e641b2017-07-12 12:55:28 -0700272}
273
Liz Kammerd737d022020-11-16 15:42:51 -0800274// installer interface should be implemented for installable modules, e.g. binary and test
Nan Zhangd4e641b2017-07-12 12:55:28 -0700275type installer interface {
276 install(ctx android.ModuleContext, path android.Path)
Logan Chien02880e42018-11-06 17:30:35 +0800277 setAndroidMkSharedLibs(sharedLibs []string)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800278}
279
Liz Kammerd737d022020-11-16 15:42:51 -0800280// interface implemented by Python modules to provide source and data mappings and zip to python
281// modules that depend on it
282type pythonDependency interface {
283 getSrcsPathMappings() []pathMapping
284 getDataPathMappings() []pathMapping
285 getSrcsZip() android.Path
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800286}
287
Liz Kammerd737d022020-11-16 15:42:51 -0800288// getSrcsPathMappings gets this module's path mapping of src source path : runfiles destination
289func (p *Module) getSrcsPathMappings() []pathMapping {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800290 return p.srcsPathMappings
291}
292
Liz Kammerd737d022020-11-16 15:42:51 -0800293// getSrcsPathMappings gets this module's path mapping of data source path : runfiles destination
294func (p *Module) getDataPathMappings() []pathMapping {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800295 return p.dataPathMappings
296}
297
Liz Kammerd737d022020-11-16 15:42:51 -0800298// getSrcsZip returns the filepath where the current module's source/data files are zipped.
299func (p *Module) getSrcsZip() android.Path {
Nan Zhang1db85402017-12-18 13:20:23 -0800300 return p.srcsZip
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800301}
302
Liz Kammerd737d022020-11-16 15:42:51 -0800303var _ pythonDependency = (*Module)(nil)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800304
Liz Kammerd8dceb02020-11-24 08:36:14 -0800305var _ android.AndroidMkEntriesProvider = (*Module)(nil)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800306
Liz Kammerd737d022020-11-16 15:42:51 -0800307func (p *Module) init(additionalProps ...interface{}) android.Module {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800308 p.AddProperties(&p.properties, &p.protoProperties)
Liz Kammerd737d022020-11-16 15:42:51 -0800309
310 // Add additional properties for bootstrapping/installation
311 // This is currently tied to the bootstrapper interface;
312 // however, these are a combination of properties for the installation and bootstrapping of a module
Nan Zhangd4e641b2017-07-12 12:55:28 -0700313 if p.bootstrapper != nil {
314 p.AddProperties(p.bootstrapper.bootstrapperProps()...)
315 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800316
Nan Zhangd4e641b2017-07-12 12:55:28 -0700317 android.InitAndroidArchModule(p, p.hod, p.multilib)
Nan Zhanga3fc4ba2017-07-20 17:43:37 -0700318 android.InitDefaultableModule(p)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800319
Nan Zhangd4e641b2017-07-12 12:55:28 -0700320 return p
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800321}
322
Liz Kammerd737d022020-11-16 15:42:51 -0800323// Python-specific tag to transfer information on the purpose of a dependency.
324// This is used when adding a dependency on a module, which can later be accessed when visiting
325// dependencies.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700326type dependencyTag struct {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800327 blueprint.BaseDependencyTag
Nan Zhangd4e641b2017-07-12 12:55:28 -0700328 name string
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800329}
330
Liz Kammerd737d022020-11-16 15:42:51 -0800331// Python-specific tag that indicates that installed files of this module should depend on installed
332// files of the dependency
Colin Crosse9fe2942020-11-10 18:12:15 -0800333type installDependencyTag struct {
334 blueprint.BaseDependencyTag
Liz Kammerd737d022020-11-16 15:42:51 -0800335 // embedding this struct provides the installation dependency requirement
Colin Crosse9fe2942020-11-10 18:12:15 -0800336 android.InstallAlwaysNeededDependencyTag
337 name string
338}
339
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800340var (
Logan Chien02880e42018-11-06 17:30:35 +0800341 pythonLibTag = dependencyTag{name: "pythonLib"}
Colin Cross1bc63932020-11-22 20:12:45 -0800342 javaDataTag = dependencyTag{name: "javaData"}
Logan Chien02880e42018-11-06 17:30:35 +0800343 launcherTag = dependencyTag{name: "launcher"}
Colin Crosse9fe2942020-11-10 18:12:15 -0800344 launcherSharedLibTag = installDependencyTag{name: "launcherSharedLib"}
Liz Kammerd737d022020-11-16 15:42:51 -0800345 pathComponentRegexp = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
Logan Chien02880e42018-11-06 17:30:35 +0800346 pyExt = ".py"
347 protoExt = ".proto"
348 pyVersion2 = "PY2"
349 pyVersion3 = "PY3"
350 initFileName = "__init__.py"
351 mainFileName = "__main__.py"
352 entryPointFile = "entry_point.txt"
353 parFileExt = ".zip"
Liz Kammerd737d022020-11-16 15:42:51 -0800354 internalPath = "internal"
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800355)
356
Liz Kammerd737d022020-11-16 15:42:51 -0800357// versionSplitMutator creates version variants for modules and appends the version-specific
358// properties for a given variant to the properties in the variant module
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800359func versionSplitMutator() func(android.BottomUpMutatorContext) {
360 return func(mctx android.BottomUpMutatorContext) {
Nan Zhangd4e641b2017-07-12 12:55:28 -0700361 if base, ok := mctx.Module().(*Module); ok {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800362 versionNames := []string{}
Liz Kammerd737d022020-11-16 15:42:51 -0800363 // collect version specific properties, so that we can merge version-specific properties
364 // into the module's overall properties
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700365 versionProps := []VersionProperties{}
Liz Kammerdd849a82020-06-12 16:38:45 -0700366 // PY3 is first so that we alias the PY3 variant rather than PY2 if both
367 // are available
Liz Kammerd737d022020-11-16 15:42:51 -0800368 if proptools.BoolDefault(base.properties.Version.Py3.Enabled, true) {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800369 versionNames = append(versionNames, pyVersion3)
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700370 versionProps = append(versionProps, base.properties.Version.Py3)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800371 }
Liz Kammerd737d022020-11-16 15:42:51 -0800372 if proptools.BoolDefault(base.properties.Version.Py2.Enabled, false) {
Liz Kammerdd849a82020-06-12 16:38:45 -0700373 versionNames = append(versionNames, pyVersion2)
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700374 versionProps = append(versionProps, base.properties.Version.Py2)
Liz Kammerdd849a82020-06-12 16:38:45 -0700375 }
Colin Crosse20113d2020-11-22 19:37:44 -0800376 modules := mctx.CreateLocalVariations(versionNames...)
Liz Kammerd737d022020-11-16 15:42:51 -0800377 // Alias module to the first variant
Liz Kammerdd849a82020-06-12 16:38:45 -0700378 if len(versionNames) > 0 {
379 mctx.AliasVariation(versionNames[0])
380 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800381 for i, v := range versionNames {
382 // set the actual version for Python module.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700383 modules[i].(*Module).properties.Actual_version = v
Liz Kammerd737d022020-11-16 15:42:51 -0800384 // append versioned properties for the Python module to the overall properties
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700385 err := proptools.AppendMatchingProperties([]interface{}{&modules[i].(*Module).properties}, &versionProps[i], nil)
386 if err != nil {
387 panic(err)
388 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800389 }
390 }
391 }
392}
393
Liz Kammerd737d022020-11-16 15:42:51 -0800394// HostToolPath returns a path if appropriate such that this module can be used as a host tool,
395// fulfilling HostToolProvider interface.
Nan Zhangb8bdacf2017-12-06 15:13:10 -0800396func (p *Module) HostToolPath() android.OptionalPath {
Rob Seymour925aa092021-08-10 20:42:03 +0000397 if p.installer != nil {
398 if bin, ok := p.installer.(*binaryDecorator); ok {
399 // TODO: This should only be set when building host binaries -- tests built for device would be
400 // setting this incorrectly.
401 return android.OptionalPathForPath(bin.path)
402 }
Nan Zhangb8bdacf2017-12-06 15:13:10 -0800403 }
Rob Seymour925aa092021-08-10 20:42:03 +0000404
405 return android.OptionalPath{}
406
Nan Zhangb8bdacf2017-12-06 15:13:10 -0800407}
408
Liz Kammerd737d022020-11-16 15:42:51 -0800409// OutputFiles returns output files based on given tag, returns an error if tag is unsupported.
Liz Kammere0070ee2020-06-22 11:52:59 -0700410func (p *Module) OutputFiles(tag string) (android.Paths, error) {
411 switch tag {
412 case "":
413 if outputFile := p.installSource; outputFile.Valid() {
414 return android.Paths{outputFile.Path()}, nil
415 }
416 return android.Paths{}, nil
417 default:
418 return nil, fmt.Errorf("unsupported module reference tag %q", tag)
419 }
420}
421
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700422func (p *Module) isEmbeddedLauncherEnabled() bool {
Liz Kammerd737d022020-11-16 15:42:51 -0800423 return p.installer != nil && Bool(p.properties.Embedded_launcher)
Nan Zhangd4e641b2017-07-12 12:55:28 -0700424}
425
Liz Kammerd737d022020-11-16 15:42:51 -0800426func anyHasExt(paths []string, ext string) bool {
427 for _, p := range paths {
428 if filepath.Ext(p) == ext {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800429 return true
430 }
431 }
432
433 return false
434}
435
Liz Kammerd737d022020-11-16 15:42:51 -0800436func (p *Module) anySrcHasExt(ctx android.BottomUpMutatorContext, ext string) bool {
437 return anyHasExt(p.properties.Srcs, ext)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800438}
439
Liz Kammerd737d022020-11-16 15:42:51 -0800440// DepsMutator mutates dependencies for this module:
Colin Crossd079e0b2022-08-16 10:27:33 -0700441// - handles proto dependencies,
442// - if required, specifies launcher and adds launcher dependencies,
443// - applies python version mutations to Python dependencies
Nan Zhangd4e641b2017-07-12 12:55:28 -0700444func (p *Module) DepsMutator(ctx android.BottomUpMutatorContext) {
Colin Crossfe17f6f2019-03-28 19:30:56 -0700445 android.ProtoDeps(ctx, &p.protoProperties)
446
Colin Crosse20113d2020-11-22 19:37:44 -0800447 versionVariation := []blueprint.Variation{
448 {"python_version", p.properties.Actual_version},
Nan Zhangb8fa1972017-12-22 16:12:00 -0800449 }
Colin Crosse20113d2020-11-22 19:37:44 -0800450
Liz Kammerd737d022020-11-16 15:42:51 -0800451 // If sources contain a proto file, add dependency on libprotobuf-python
452 if p.anySrcHasExt(ctx, protoExt) && p.Name() != "libprotobuf-python" {
Colin Crosse20113d2020-11-22 19:37:44 -0800453 ctx.AddVariationDependencies(versionVariation, pythonLibTag, "libprotobuf-python")
454 }
Liz Kammerd737d022020-11-16 15:42:51 -0800455
456 // Add python library dependencies for this python version variation
Colin Crosse20113d2020-11-22 19:37:44 -0800457 ctx.AddVariationDependencies(versionVariation, pythonLibTag, android.LastUniqueStrings(p.properties.Libs)...)
Liz Kammer7e93e5b2020-10-30 15:44:09 -0700458
Liz Kammerd737d022020-11-16 15:42:51 -0800459 // If this module will be installed and has an embedded launcher, we need to add dependencies for:
460 // * standard library
461 // * launcher
462 // * shared dependencies of the launcher
463 if p.installer != nil && p.isEmbeddedLauncherEnabled() {
464 var stdLib string
465 var launcherModule string
466 // Add launcher shared lib dependencies. Ideally, these should be
467 // derived from the `shared_libs` property of the launcher. However, we
468 // cannot read the property at this stage and it will be too late to add
469 // dependencies later.
470 launcherSharedLibDeps := []string{
471 "libsqlite",
472 }
473 // Add launcher-specific dependencies for bionic
474 if ctx.Target().Os.Bionic() {
475 launcherSharedLibDeps = append(launcherSharedLibDeps, "libc", "libdl", "libm")
476 }
Colin Cross4111c522022-03-08 11:56:27 -0800477 if ctx.Target().Os == android.LinuxMusl && !ctx.Config().HostStaticBinaries() {
478 launcherSharedLibDeps = append(launcherSharedLibDeps, "libc_musl")
479 }
Nan Zhangd4e641b2017-07-12 12:55:28 -0700480
Liz Kammerd737d022020-11-16 15:42:51 -0800481 switch p.properties.Actual_version {
482 case pyVersion2:
483 stdLib = "py2-stdlib"
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800484
Liz Kammerd737d022020-11-16 15:42:51 -0800485 launcherModule = "py2-launcher"
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800486 if p.bootstrapper.autorun() {
487 launcherModule = "py2-launcher-autorun"
488 }
Colin Cross4111c522022-03-08 11:56:27 -0800489
Liz Kammerd737d022020-11-16 15:42:51 -0800490 launcherSharedLibDeps = append(launcherSharedLibDeps, "libc++")
Logan Chien02880e42018-11-06 17:30:35 +0800491
Liz Kammerd737d022020-11-16 15:42:51 -0800492 case pyVersion3:
493 stdLib = "py3-stdlib"
Logan Chien02880e42018-11-06 17:30:35 +0800494
Liz Kammerd737d022020-11-16 15:42:51 -0800495 launcherModule = "py3-launcher"
Dan Willemsen8d4d7be2019-11-04 19:21:04 -0800496 if p.bootstrapper.autorun() {
497 launcherModule = "py3-launcher-autorun"
498 }
Colin Cross4111c522022-03-08 11:56:27 -0800499 if ctx.Config().HostStaticBinaries() && ctx.Target().Os == android.LinuxMusl {
500 launcherModule += "-static"
501 }
Dan Willemsen8d4d7be2019-11-04 19:21:04 -0800502
Dan Willemsend7a1dee2020-01-20 22:08:20 -0800503 if ctx.Device() {
Liz Kammerd737d022020-11-16 15:42:51 -0800504 launcherSharedLibDeps = append(launcherSharedLibDeps, "liblog")
Dan Willemsend7a1dee2020-01-20 22:08:20 -0800505 }
Liz Kammerd737d022020-11-16 15:42:51 -0800506 default:
507 panic(fmt.Errorf("unknown Python Actual_version: %q for module: %q.",
508 p.properties.Actual_version, ctx.ModuleName()))
Nan Zhangd4e641b2017-07-12 12:55:28 -0700509 }
Liz Kammerd737d022020-11-16 15:42:51 -0800510 ctx.AddVariationDependencies(versionVariation, pythonLibTag, stdLib)
511 ctx.AddFarVariationDependencies(ctx.Target().Variations(), launcherTag, launcherModule)
512 ctx.AddFarVariationDependencies(ctx.Target().Variations(), launcherSharedLibTag, launcherSharedLibDeps...)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800513 }
Colin Cross1bc63932020-11-22 20:12:45 -0800514
515 // Emulate the data property for java_data but with the arch variation overridden to "common"
516 // so that it can point to java modules.
517 javaDataVariation := []blueprint.Variation{{"arch", android.Common.String()}}
518 ctx.AddVariationDependencies(javaDataVariation, javaDataTag, p.properties.Java_data...)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800519}
520
Nan Zhangd4e641b2017-07-12 12:55:28 -0700521func (p *Module) GenerateAndroidBuildActions(ctx android.ModuleContext) {
Liz Kammerd737d022020-11-16 15:42:51 -0800522 p.generatePythonBuildActions(ctx)
Nan Zhang5323f8e2017-05-10 13:37:54 -0700523
Liz Kammerd737d022020-11-16 15:42:51 -0800524 // Only Python binary and test modules have non-empty bootstrapper.
Nan Zhangd4e641b2017-07-12 12:55:28 -0700525 if p.bootstrapper != nil {
Liz Kammerd737d022020-11-16 15:42:51 -0800526 // if the module is being installed, we need to collect all transitive dependencies to embed in
527 // the final par
528 p.collectPathsFromTransitiveDeps(ctx)
529 // bootstrap the module, including resolving main file, getting launcher path, and
530 // registering actions to build the par file
531 // bootstrap returns the binary output path
Nan Zhangd4e641b2017-07-12 12:55:28 -0700532 p.installSource = p.bootstrapper.bootstrap(ctx, p.properties.Actual_version,
Liz Kammerd737d022020-11-16 15:42:51 -0800533 p.isEmbeddedLauncherEnabled(), p.srcsPathMappings, p.srcsZip, p.depsSrcsZips)
Nan Zhang5323f8e2017-05-10 13:37:54 -0700534 }
Nan Zhangd4e641b2017-07-12 12:55:28 -0700535
Liz Kammerd737d022020-11-16 15:42:51 -0800536 // Only Python binary and test modules have non-empty installer.
Logan Chien02880e42018-11-06 17:30:35 +0800537 if p.installer != nil {
538 var sharedLibs []string
Liz Kammerd737d022020-11-16 15:42:51 -0800539 // if embedded launcher is enabled, we need to collect the shared library depenendencies of the
540 // launcher
Colin Cross0e446152021-05-03 13:35:32 -0700541 for _, dep := range ctx.GetDirectDepsWithTag(launcherSharedLibTag) {
542 sharedLibs = append(sharedLibs, ctx.OtherModuleName(dep))
543 }
544
Logan Chien02880e42018-11-06 17:30:35 +0800545 p.installer.setAndroidMkSharedLibs(sharedLibs)
546
Liz Kammerd737d022020-11-16 15:42:51 -0800547 // Install the par file from installSource
Logan Chien02880e42018-11-06 17:30:35 +0800548 if p.installSource.Valid() {
549 p.installer.install(ctx, p.installSource.Path())
550 }
Nan Zhangd4e641b2017-07-12 12:55:28 -0700551 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800552}
553
Liz Kammerd737d022020-11-16 15:42:51 -0800554// generatePythonBuildActions performs build actions common to all Python modules
555func (p *Module) generatePythonBuildActions(ctx android.ModuleContext) {
556 expandedSrcs := android.PathsForModuleSrcExcludes(ctx, p.properties.Srcs, p.properties.Exclude_srcs)
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800557 requiresSrcs := true
558 if p.bootstrapper != nil && !p.bootstrapper.autorun() {
559 requiresSrcs = false
560 }
561 if len(expandedSrcs) == 0 && requiresSrcs {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800562 ctx.ModuleErrorf("doesn't have any source files!")
563 }
564
565 // expand data files from "data" property.
Colin Cross8a497952019-03-05 22:25:09 -0800566 expandedData := android.PathsForModuleSrc(ctx, p.properties.Data)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800567
Colin Cross1bc63932020-11-22 20:12:45 -0800568 // Emulate the data property for java_data dependencies.
569 for _, javaData := range ctx.GetDirectDepsWithTag(javaDataTag) {
570 expandedData = append(expandedData, android.OutputFilesForModule(ctx, javaData, "")...)
571 }
572
Liz Kammerd737d022020-11-16 15:42:51 -0800573 // Validate pkg_path property
Nan Zhang1db85402017-12-18 13:20:23 -0800574 pkgPath := String(p.properties.Pkg_path)
575 if pkgPath != "" {
Liz Kammerd737d022020-11-16 15:42:51 -0800576 // TODO: export validation from android/paths.go handling to replace this duplicated functionality
Nan Zhang1db85402017-12-18 13:20:23 -0800577 pkgPath = filepath.Clean(String(p.properties.Pkg_path))
578 if pkgPath == ".." || strings.HasPrefix(pkgPath, "../") ||
579 strings.HasPrefix(pkgPath, "/") {
Nan Zhangd4e641b2017-07-12 12:55:28 -0700580 ctx.PropertyErrorf("pkg_path",
581 "%q must be a relative path contained in par file.",
Nan Zhangea568a42017-11-08 21:20:04 -0800582 String(p.properties.Pkg_path))
Nan Zhangd4e641b2017-07-12 12:55:28 -0700583 return
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800584 }
Liz Kammerd737d022020-11-16 15:42:51 -0800585 }
586 // If property Is_internal is set, prepend pkgPath with internalPath
587 if proptools.BoolDefault(p.properties.Is_internal, false) {
588 pkgPath = filepath.Join(internalPath, pkgPath)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800589 }
590
Liz Kammerd737d022020-11-16 15:42:51 -0800591 // generate src:destination path mappings for this module
Nan Zhang1db85402017-12-18 13:20:23 -0800592 p.genModulePathMappings(ctx, pkgPath, expandedSrcs, expandedData)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800593
Liz Kammerd737d022020-11-16 15:42:51 -0800594 // generate the zipfile of all source and data files
Nan Zhang1db85402017-12-18 13:20:23 -0800595 p.srcsZip = p.createSrcsZip(ctx, pkgPath)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800596}
597
Liz Kammerd737d022020-11-16 15:42:51 -0800598func isValidPythonPath(path string) error {
599 identifiers := strings.Split(strings.TrimSuffix(path, filepath.Ext(path)), "/")
600 for _, token := range identifiers {
601 if !pathComponentRegexp.MatchString(token) {
602 return fmt.Errorf("the path %q contains invalid subpath %q. "+
603 "Subpaths must be at least one character long. "+
604 "The first character must an underscore or letter. "+
605 "Following characters may be any of: letter, digit, underscore, hyphen.",
606 path, token)
607 }
608 }
609 return nil
610}
611
612// For this module, generate unique pathMappings: <dest: runfiles_path, src: source_path>
613// for python/data files expanded from properties.
Nan Zhang1db85402017-12-18 13:20:23 -0800614func (p *Module) genModulePathMappings(ctx android.ModuleContext, pkgPath string,
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800615 expandedSrcs, expandedData android.Paths) {
616 // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
Nan Zhangb8fa1972017-12-22 16:12:00 -0800617 // check current module duplicates.
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800618 destToPySrcs := make(map[string]string)
619 destToPyData := make(map[string]string)
620
621 for _, s := range expandedSrcs {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800622 if s.Ext() != pyExt && s.Ext() != protoExt {
623 ctx.PropertyErrorf("srcs", "found non (.py|.proto) file: %q!", s.String())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800624 continue
625 }
Nan Zhang1db85402017-12-18 13:20:23 -0800626 runfilesPath := filepath.Join(pkgPath, s.Rel())
Liz Kammerd737d022020-11-16 15:42:51 -0800627 if err := isValidPythonPath(runfilesPath); err != nil {
628 ctx.PropertyErrorf("srcs", err.Error())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800629 }
Liz Kammerd737d022020-11-16 15:42:51 -0800630 if !checkForDuplicateOutputPath(ctx, destToPySrcs, runfilesPath, s.String(), p.Name(), p.Name()) {
631 p.srcsPathMappings = append(p.srcsPathMappings, pathMapping{dest: runfilesPath, src: s})
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800632 }
633 }
634
635 for _, d := range expandedData {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800636 if d.Ext() == pyExt || d.Ext() == protoExt {
637 ctx.PropertyErrorf("data", "found (.py|.proto) file: %q!", d.String())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800638 continue
639 }
Nan Zhang1db85402017-12-18 13:20:23 -0800640 runfilesPath := filepath.Join(pkgPath, d.Rel())
Liz Kammerd737d022020-11-16 15:42:51 -0800641 if !checkForDuplicateOutputPath(ctx, destToPyData, runfilesPath, d.String(), p.Name(), p.Name()) {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800642 p.dataPathMappings = append(p.dataPathMappings,
643 pathMapping{dest: runfilesPath, src: d})
644 }
645 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800646}
647
Liz Kammerd737d022020-11-16 15:42:51 -0800648// createSrcsZip registers build actions to zip current module's sources and data.
Nan Zhang1db85402017-12-18 13:20:23 -0800649func (p *Module) createSrcsZip(ctx android.ModuleContext, pkgPath string) android.Path {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800650 relativeRootMap := make(map[string]android.Paths)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800651 pathMappings := append(p.srcsPathMappings, p.dataPathMappings...)
652
Nan Zhangb8fa1972017-12-22 16:12:00 -0800653 var protoSrcs android.Paths
Liz Kammerd737d022020-11-16 15:42:51 -0800654 // "srcs" or "data" properties may contain filegroup so it might happen that
655 // the root directory for each source path is different.
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800656 for _, path := range pathMappings {
Liz Kammerd737d022020-11-16 15:42:51 -0800657 // handle proto sources separately
Nan Zhangb8fa1972017-12-22 16:12:00 -0800658 if path.src.Ext() == protoExt {
659 protoSrcs = append(protoSrcs, path.src)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800660 } else {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800661 var relativeRoot string
662 relativeRoot = strings.TrimSuffix(path.src.String(), path.src.Rel())
663 if v, found := relativeRootMap[relativeRoot]; found {
664 relativeRootMap[relativeRoot] = append(v, path.src)
665 } else {
666 relativeRootMap[relativeRoot] = android.Paths{path.src}
667 }
668 }
669 }
670 var zips android.Paths
671 if len(protoSrcs) > 0 {
Colin Cross19878da2019-03-28 14:45:07 -0700672 protoFlags := android.GetProtoFlags(ctx, &p.protoProperties)
673 protoFlags.OutTypeFlag = "--python_out"
674
Nan Zhangb8fa1972017-12-22 16:12:00 -0800675 for _, srcFile := range protoSrcs {
Colin Cross19878da2019-03-28 14:45:07 -0700676 zip := genProto(ctx, srcFile, protoFlags, pkgPath)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800677 zips = append(zips, zip)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800678 }
679 }
680
Nan Zhangb8fa1972017-12-22 16:12:00 -0800681 if len(relativeRootMap) > 0 {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800682 // in order to keep stable order of soong_zip params, we sort the keys here.
Liz Kammerd737d022020-11-16 15:42:51 -0800683 roots := android.SortedStringKeys(relativeRootMap)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800684
Cole Faust01243362022-06-02 12:11:12 -0700685 // Use -symlinks=false so that the symlinks in the bazel output directory are followed
686 parArgs := []string{"-symlinks=false"}
Nan Zhangf0c4e432018-05-22 14:50:18 -0700687 if pkgPath != "" {
Liz Kammerd737d022020-11-16 15:42:51 -0800688 // use package path as path prefix
Nan Zhangf0c4e432018-05-22 14:50:18 -0700689 parArgs = append(parArgs, `-P `+pkgPath)
690 }
Liz Kammerd737d022020-11-16 15:42:51 -0800691 paths := android.Paths{}
692 for _, root := range roots {
693 // specify relative root of file in following -f arguments
694 parArgs = append(parArgs, `-C `+root)
695 for _, path := range relativeRootMap[root] {
Nan Zhangb8fa1972017-12-22 16:12:00 -0800696 parArgs = append(parArgs, `-f `+path.String())
Liz Kammerd737d022020-11-16 15:42:51 -0800697 paths = append(paths, path)
Nan Zhangb8fa1972017-12-22 16:12:00 -0800698 }
699 }
700
701 origSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".py.srcszip")
702 ctx.Build(pctx, android.BuildParams{
703 Rule: zip,
704 Description: "python library archive",
705 Output: origSrcsZip,
Liz Kammerd737d022020-11-16 15:42:51 -0800706 // as zip rule does not use $in, there is no real need to distinguish between Inputs and Implicits
707 Implicits: paths,
Nan Zhangb8fa1972017-12-22 16:12:00 -0800708 Args: map[string]string{
709 "args": strings.Join(parArgs, " "),
710 },
711 })
712 zips = append(zips, origSrcsZip)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800713 }
Liz Kammerd737d022020-11-16 15:42:51 -0800714 // we may have multiple zips due to separate handling of proto source files
Nan Zhangb8fa1972017-12-22 16:12:00 -0800715 if len(zips) == 1 {
716 return zips[0]
717 } else {
718 combinedSrcsZip := android.PathForModuleOut(ctx, ctx.ModuleName()+".srcszip")
719 ctx.Build(pctx, android.BuildParams{
720 Rule: combineZip,
721 Description: "combine python library archive",
722 Output: combinedSrcsZip,
723 Inputs: zips,
724 })
725 return combinedSrcsZip
726 }
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800727}
728
Liz Kammerd737d022020-11-16 15:42:51 -0800729// isPythonLibModule returns whether the given module is a Python library Module or not
Nan Zhangd4e641b2017-07-12 12:55:28 -0700730func isPythonLibModule(module blueprint.Module) bool {
731 if m, ok := module.(*Module); ok {
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400732 return m.isLibrary()
Nan Zhangd4e641b2017-07-12 12:55:28 -0700733 }
734 return false
735}
736
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400737// This is distinguished by the fact that Python libraries are not installable, while other Python
738// modules are.
739func (p *Module) isLibrary() bool {
740 // Python library has no bootstrapper or installer
741 return p.bootstrapper == nil && p.installer == nil
742}
743
744func (p *Module) isBinary() bool {
745 _, ok := p.bootstrapper.(*binaryDecorator)
746 return ok
747}
748
Liz Kammerd737d022020-11-16 15:42:51 -0800749// collectPathsFromTransitiveDeps checks for source/data files for duplicate paths
750// for module and its transitive dependencies and collects list of data/source file
751// zips for transitive dependencies.
752func (p *Module) collectPathsFromTransitiveDeps(ctx android.ModuleContext) {
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800753 // fetch <runfiles_path, source_path> pairs from "src" and "data" properties to
754 // check duplicates.
755 destToPySrcs := make(map[string]string)
756 destToPyData := make(map[string]string)
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800757 for _, path := range p.srcsPathMappings {
758 destToPySrcs[path.dest] = path.src.String()
759 }
760 for _, path := range p.dataPathMappings {
761 destToPyData[path.dest] = path.src.String()
762 }
763
Colin Cross6b753602018-06-21 13:03:07 -0700764 seen := make(map[android.Module]bool)
765
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800766 // visit all its dependencies in depth first.
Colin Cross6b753602018-06-21 13:03:07 -0700767 ctx.WalkDeps(func(child, parent android.Module) bool {
Liz Kammerd737d022020-11-16 15:42:51 -0800768 // we only collect dependencies tagged as python library deps
Colin Cross6b753602018-06-21 13:03:07 -0700769 if ctx.OtherModuleDependencyTag(child) != pythonLibTag {
770 return false
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800771 }
Colin Cross6b753602018-06-21 13:03:07 -0700772 if seen[child] {
773 return false
774 }
775 seen[child] = true
Nan Zhangb8fa1972017-12-22 16:12:00 -0800776 // Python modules only can depend on Python libraries.
Colin Cross6b753602018-06-21 13:03:07 -0700777 if !isPythonLibModule(child) {
Liz Kammerd737d022020-11-16 15:42:51 -0800778 ctx.PropertyErrorf("libs",
Nan Zhangd4e641b2017-07-12 12:55:28 -0700779 "the dependency %q of module %q is not Python library!",
Alex Márquez Pérez Muñíz Díaz Púras Thaureauxd75507f2021-08-20 21:02:43 +0000780 ctx.OtherModuleName(child), ctx.ModuleName())
Nan Zhangd4e641b2017-07-12 12:55:28 -0700781 }
Liz Kammerd737d022020-11-16 15:42:51 -0800782 // collect source and data paths, checking that there are no duplicate output file conflicts
783 if dep, ok := child.(pythonDependency); ok {
784 srcs := dep.getSrcsPathMappings()
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800785 for _, path := range srcs {
Liz Kammerd737d022020-11-16 15:42:51 -0800786 checkForDuplicateOutputPath(ctx, destToPySrcs,
Colin Cross6b753602018-06-21 13:03:07 -0700787 path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child))
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800788 }
Liz Kammerd737d022020-11-16 15:42:51 -0800789 data := dep.getDataPathMappings()
790 for _, path := range data {
791 checkForDuplicateOutputPath(ctx, destToPyData,
792 path.dest, path.src.String(), ctx.ModuleName(), ctx.OtherModuleName(child))
793 }
794 p.depsSrcsZips = append(p.depsSrcsZips, dep.getSrcsZip())
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800795 }
Colin Cross6b753602018-06-21 13:03:07 -0700796 return true
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800797 })
798}
799
Liz Kammerd737d022020-11-16 15:42:51 -0800800// chckForDuplicateOutputPath checks whether outputPath has already been included in map m, which
801// would result in two files being placed in the same location.
802// If there is a duplicate path, an error is thrown and true is returned
803// Otherwise, outputPath: srcPath is added to m and returns false
804func checkForDuplicateOutputPath(ctx android.ModuleContext, m map[string]string, outputPath, srcPath, curModule, otherModule string) bool {
805 if oldSrcPath, found := m[outputPath]; found {
Nan Zhangbea09752018-05-31 12:49:33 -0700806 ctx.ModuleErrorf("found two files to be placed at the same location within zip %q."+
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800807 " First file: in module %s at path %q."+
808 " Second file: in module %s at path %q.",
Liz Kammerd737d022020-11-16 15:42:51 -0800809 outputPath, curModule, oldSrcPath, otherModule, srcPath)
810 return true
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800811 }
Liz Kammerd737d022020-11-16 15:42:51 -0800812 m[outputPath] = srcPath
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800813
Liz Kammerd737d022020-11-16 15:42:51 -0800814 return false
Nan Zhangdb0b9a32017-02-27 10:12:13 -0800815}
Nan Zhangea568a42017-11-08 21:20:04 -0800816
Liz Kammerd737d022020-11-16 15:42:51 -0800817// InstallInData returns true as Python is not supported in the system partition
Nan Zhangd9ec5e72017-12-01 20:00:31 +0000818func (p *Module) InstallInData() bool {
819 return true
820}
821
Liz Kammerbe46fcc2021-11-01 15:32:43 -0400822func (p *Module) ConvertWithBp2build(ctx android.TopDownMutatorContext) {
823 if p.isLibrary() {
824 pythonLibBp2Build(ctx, p)
825 } else if p.isBinary() {
826 pythonBinaryBp2Build(ctx, p)
827 }
828}
829
Nan Zhangea568a42017-11-08 21:20:04 -0800830var Bool = proptools.Bool
Dan Willemsen6ca390f2019-02-14 23:17:08 -0800831var BoolDefault = proptools.BoolDefault
Nan Zhangea568a42017-11-08 21:20:04 -0800832var String = proptools.String