Add imports property to py_library rules
This is to avoid having it hardcoded in a fork of the
py_library rule.
Most import attributes should just be set to ".", but
our previous solution always hardcoded it to ".." instead,
for ndkstubgen. ndkstubgen uses pkg_path: "ndkstubgen",
i.e., it set pkg_path to the name of the folder that
contained the Android.bp file. In this specific scenario,
imports = ".." works. Recreate that behavior here as well,
because we don't handle pkg_path properly yet.
Fixes: 233081071
Test: build/bazel/ci/bp2build.sh
Change-Id: Ib5e6a8edf428c74d4b5947f0ec53a2151001367a
diff --git a/python/library.go b/python/library.go
index d026c13..3a27591 100644
--- a/python/library.go
+++ b/python/library.go
@@ -17,6 +17,9 @@
// This file contains the module types for building Python library.
import (
+ "path/filepath"
+ "strings"
+
"android/soong/android"
"android/soong/bazel"
@@ -43,6 +46,7 @@
type bazelPythonLibraryAttributes struct {
Srcs bazel.LabelListAttribute
Deps bazel.LabelListAttribute
+ Imports bazel.StringListAttribute
Srcs_version *string
}
@@ -64,16 +68,44 @@
// do nothing, since python_version defaults to PY2ANDPY3
}
+ // Bazel normally requires `import path.from.top.of.tree` statements in
+ // python code, but with soong you can directly import modules from libraries.
+ // Add "imports" attributes to the bazel library so it matches soong's behavior.
+ imports := "."
+ if m.properties.Pkg_path != nil {
+ // TODO(b/215119317) This is a hack to handle the fact that we don't convert
+ // pkg_path properly right now. If the folder structure that contains this
+ // Android.bp file matches pkg_path, we can set imports to an appropriate
+ // number of ../..s to emulate moving the files under a pkg_path folder.
+ pkg_path := filepath.Clean(*m.properties.Pkg_path)
+ if strings.HasPrefix(pkg_path, "/") {
+ ctx.ModuleErrorf("pkg_path cannot start with a /: %s", pkg_path)
+ return
+ }
+
+ if !strings.HasSuffix(ctx.ModuleDir(), "/"+pkg_path) && ctx.ModuleDir() != pkg_path {
+ 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())
+ return
+ }
+ numFolders := strings.Count(pkg_path, "/") + 1
+ dots := make([]string, numFolders)
+ for i := 0; i < numFolders; i++ {
+ dots[i] = ".."
+ }
+ imports = strings.Join(dots, "/")
+ }
+
baseAttrs := m.makeArchVariantBaseAttributes(ctx)
attrs := &bazelPythonLibraryAttributes{
Srcs: baseAttrs.Srcs,
Deps: baseAttrs.Deps,
Srcs_version: python_version,
+ Imports: bazel.MakeStringListAttribute([]string{imports}),
}
props := bazel.BazelTargetModuleProperties{
- Rule_class: "py_library",
- Bzl_load_location: "//build/bazel/rules/python:library.bzl",
+ // Use the native py_library rule.
+ Rule_class: "py_library",
}
ctx.CreateBazelTargetModule(props, android.CommonAttributes{