blob: b08a4cad7881950d3c4a3e495372cb343b88d367 [file] [log] [blame]
Liz Kammer620dea62021-04-14 17:36:10 -04001// Copyright 2015 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
17import (
Liz Kammer620dea62021-04-14 17:36:10 -040018 "fmt"
19 "path/filepath"
20 "strings"
21
Chris Parsons953b3562021-09-20 15:14:39 -040022 "android/soong/bazel"
23
Liz Kammer620dea62021-04-14 17:36:10 -040024 "github.com/google/blueprint"
25 "github.com/google/blueprint/pathtools"
26)
27
28// bazel_paths contains methods to:
29// * resolve Soong path and module references into bazel.LabelList
30// * resolve Bazel path references into Soong-compatible paths
31//
32// There is often a similar method for Bazel as there is for Soong path handling and should be used
33// in similar circumstances
34//
Usta Shresthadb46a9b2022-07-11 11:29:56 -040035// Bazel Soong
36// ==============================================================
37// BazelLabelForModuleSrc PathForModuleSrc
38// BazelLabelForModuleSrcExcludes PathForModuleSrcExcludes
39// BazelLabelForModuleDeps n/a
40// tbd PathForSource
41// tbd ExistentPathsForSources
42// PathForBazelOut PathForModuleOut
Liz Kammer620dea62021-04-14 17:36:10 -040043//
44// Use cases:
45// * Module contains a property (often tagged `android:"path"`) that expects paths *relative to the
46// module directory*:
47// * BazelLabelForModuleSrcExcludes, if the module also contains an excludes_<propname> property
48// * BazelLabelForModuleSrc, otherwise
49// * Converting references to other modules to Bazel Labels:
50// BazelLabelForModuleDeps
51// * Converting a path obtained from bazel_handler cquery results:
52// PathForBazelOut
53//
54// NOTE: all Soong globs are expanded within Soong rather than being converted to a Bazel glob
55// syntax. This occurs because Soong does not have a concept of crossing package boundaries,
56// so the glob as computed by Soong may contain paths that cross package-boundaries. These
57// would be unknowingly omitted if the glob were handled by Bazel. By expanding globs within
58// Soong, we support identification and detection (within Bazel) use of paths that cross
59// package boundaries.
60//
61// Path resolution:
62// * filepath/globs: resolves as itself or is converted to an absolute Bazel label (e.g.
63// //path/to/dir:<filepath>) if path exists in a separate package or subpackage.
64// * references to other modules (using the ":name{.tag}" syntax). These resolve as a Bazel label
65// for a target. If the Bazel target is in the local module directory, it will be returned
66// relative to the current package (e.g. ":<target>"). Otherwise, it will be returned as an
67// absolute Bazel label (e.g. "//path/to/dir:<target>"). If the reference to another module
68// cannot be resolved,the function will panic. This is often due to the dependency not being added
69// via an AddDependency* method.
70
Usta Shresthadb46a9b2022-07-11 11:29:56 -040071// BazelConversionContext is a minimal context interface to check if a module should be converted by bp2build,
Jingwen Chen55bc8202021-11-02 06:40:51 +000072// with functions containing information to match against allowlists and denylists.
73// If a module is deemed to be convertible by bp2build, then it should rely on a
74// BazelConversionPathContext for more functions for dep/path features.
75type BazelConversionContext interface {
76 Config() Config
Liz Kammer620dea62021-04-14 17:36:10 -040077
Liz Kammer620dea62021-04-14 17:36:10 -040078 Module() Module
Liz Kammer6eff3232021-08-26 08:37:59 -040079 OtherModuleType(m blueprint.Module) string
Liz Kammer620dea62021-04-14 17:36:10 -040080 OtherModuleName(m blueprint.Module) string
81 OtherModuleDir(m blueprint.Module) string
Sam Delmerico24c56032022-03-28 19:53:03 +000082 ModuleErrorf(format string, args ...interface{})
Jingwen Chen55bc8202021-11-02 06:40:51 +000083}
84
85// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
86// order to form a Bazel-compatible label for conversion.
87type BazelConversionPathContext interface {
88 EarlyModulePathContext
89 BazelConversionContext
90
91 ModuleErrorf(fmt string, args ...interface{})
92 PropertyErrorf(property, fmt string, args ...interface{})
93 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
94 ModuleFromName(name string) (blueprint.Module, bool)
Liz Kammer6eff3232021-08-26 08:37:59 -040095 AddUnconvertedBp2buildDep(string)
Liz Kammerdaa09ef2021-12-15 15:35:38 -050096 AddMissingBp2buildDep(dep string)
Liz Kammer620dea62021-04-14 17:36:10 -040097}
98
99// BazelLabelForModuleDeps expects a list of reference to other modules, ("<module>"
100// or ":<module>") and returns a Bazel-compatible label which corresponds to dependencies on the
101// module within the given ctx.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000102func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400103 return BazelLabelForModuleDepsWithFn(ctx, modules, BazelModuleLabel)
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400104}
105
106// BazelLabelForModuleWholeDepsExcludes expects two lists: modules (containing modules to include in
107// the list), and excludes (modules to exclude from the list). Both of these should contain
108// references to other modules, ("<module>" or ":<module>"). It returns a Bazel-compatible label
109// list which corresponds to dependencies on the module within the given ctx, and the excluded
110// dependencies. Prebuilt dependencies will be appended with _alwayslink so they can be handled as
111// whole static libraries.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000112func BazelLabelForModuleDepsExcludes(ctx BazelConversionPathContext, modules, excludes []string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400113 return BazelLabelForModuleDepsExcludesWithFn(ctx, modules, excludes, BazelModuleLabel)
Liz Kammer2d7bbe32021-06-10 18:20:06 -0400114}
115
Chris Parsons953b3562021-09-20 15:14:39 -0400116// BazelLabelForModuleDepsWithFn expects a list of reference to other modules, ("<module>"
117// or ":<module>") and applies moduleToLabelFn to determine and return a Bazel-compatible label
118// which corresponds to dependencies on the module within the given ctx.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000119func BazelLabelForModuleDepsWithFn(ctx BazelConversionPathContext, modules []string,
120 moduleToLabelFn func(BazelConversionPathContext, blueprint.Module) string) bazel.LabelList {
Liz Kammer620dea62021-04-14 17:36:10 -0400121 var labels bazel.LabelList
Chris Parsons51f8c392021-08-03 21:01:05 -0400122 // In some cases, a nil string list is different than an explicitly empty list.
123 if len(modules) == 0 && modules != nil {
124 labels.Includes = []bazel.Label{}
125 return labels
126 }
Cole Faust5c84c622023-08-01 11:07:02 -0700127 modules = FirstUniqueStrings(modules)
Liz Kammer620dea62021-04-14 17:36:10 -0400128 for _, module := range modules {
129 bpText := module
130 if m := SrcIsModule(module); m == "" {
131 module = ":" + module
132 }
133 if m, t := SrcIsModuleWithTag(module); m != "" {
Chris Parsons953b3562021-09-20 15:14:39 -0400134 l := getOtherModuleLabel(ctx, m, t, moduleToLabelFn)
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500135 if l != nil {
136 l.OriginalModuleName = bpText
137 labels.Includes = append(labels.Includes, *l)
138 }
Liz Kammer620dea62021-04-14 17:36:10 -0400139 } else {
140 ctx.ModuleErrorf("%q, is not a module reference", module)
141 }
142 }
143 return labels
144}
145
Chris Parsons953b3562021-09-20 15:14:39 -0400146// BazelLabelForModuleDepsExcludesWithFn expects two lists: modules (containing modules to include in the
147// list), and excludes (modules to exclude from the list). Both of these should contain references
148// to other modules, ("<module>" or ":<module>"). It applies moduleToLabelFn to determine and return a
149// Bazel-compatible label list which corresponds to dependencies on the module within the given ctx, and
150// the excluded dependencies.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000151func BazelLabelForModuleDepsExcludesWithFn(ctx BazelConversionPathContext, modules, excludes []string,
152 moduleToLabelFn func(BazelConversionPathContext, blueprint.Module) string) bazel.LabelList {
Chris Parsons953b3562021-09-20 15:14:39 -0400153 moduleLabels := BazelLabelForModuleDepsWithFn(ctx, RemoveListFromList(modules, excludes), moduleToLabelFn)
Liz Kammer47535c52021-06-02 16:02:22 -0400154 if len(excludes) == 0 {
155 return moduleLabels
156 }
Chris Parsons953b3562021-09-20 15:14:39 -0400157 excludeLabels := BazelLabelForModuleDepsWithFn(ctx, excludes, moduleToLabelFn)
Liz Kammer47535c52021-06-02 16:02:22 -0400158 return bazel.LabelList{
159 Includes: moduleLabels.Includes,
160 Excludes: excludeLabels.Includes,
161 }
162}
163
Jingwen Chen55bc8202021-11-02 06:40:51 +0000164func BazelLabelForModuleSrcSingle(ctx BazelConversionPathContext, path string) bazel.Label {
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500165 if srcs := BazelLabelForModuleSrcExcludes(ctx, []string{path}, []string(nil)).Includes; len(srcs) > 0 {
166 return srcs[0]
167 }
168 return bazel.Label{}
Lukacs T. Berki1353e592021-04-30 15:35:09 +0200169}
170
Jingwen Chen55bc8202021-11-02 06:40:51 +0000171func BazelLabelForModuleDepSingle(ctx BazelConversionPathContext, path string) bazel.Label {
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500172 if srcs := BazelLabelForModuleDepsExcludes(ctx, []string{path}, []string(nil)).Includes; len(srcs) > 0 {
173 return srcs[0]
174 }
175 return bazel.Label{}
Rupert Shuttleworth6e4950a2021-07-27 01:34:59 -0400176}
177
Liz Kammer620dea62021-04-14 17:36:10 -0400178// BazelLabelForModuleSrc expects a list of path (relative to local module directory) and module
179// references (":<module>") and returns a bazel.LabelList{} containing the resolved references in
180// paths, relative to the local module, or Bazel-labels (absolute if in a different package or
181// relative if within the same package).
182// Properties must have been annotated with struct tag `android:"path"` so that dependencies modules
Spandan Das950091c2023-07-19 22:26:37 +0000183// will have already been handled by the pathdeps mutator.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000184func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
Liz Kammer620dea62021-04-14 17:36:10 -0400185 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
186}
187
188// BazelLabelForModuleSrc expects lists of path and excludes (relative to local module directory)
189// and module references (":<module>") and returns a bazel.LabelList{} containing the resolved
190// references in paths, minus those in excludes, relative to the local module, or Bazel-labels
191// (absolute if in a different package or relative if within the same package).
192// Properties must have been annotated with struct tag `android:"path"` so that dependencies modules
Spandan Das950091c2023-07-19 22:26:37 +0000193// will have already been handled by the pathdeps mutator.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000194func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
Liz Kammer620dea62021-04-14 17:36:10 -0400195 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
196 excluded := make([]string, 0, len(excludeLabels.Includes))
197 for _, e := range excludeLabels.Includes {
198 excluded = append(excluded, e.Label)
199 }
200 labels := expandSrcsForBazel(ctx, paths, excluded)
201 labels.Excludes = excludeLabels.Includes
Spandan Das0a8a2752023-06-21 01:50:33 +0000202 labels = TransformSubpackagePaths(ctx.Config(), ctx.ModuleDir(), labels)
Liz Kammer620dea62021-04-14 17:36:10 -0400203 return labels
204}
205
Jingwen Chen0eeaeb82022-09-21 10:27:42 +0000206// Returns true if a prefix + components[:i] is a package boundary.
207//
208// A package boundary is determined by a BUILD file in the directory. This can happen in 2 cases:
209//
Usta Shresthad5580312022-09-23 16:46:38 -0400210// 1. An Android.bp exists, which bp2build will always convert to a sibling BUILD file.
211// 2. An Android.bp doesn't exist, but a checked-in BUILD/BUILD.bazel file exists, and that file
212// is allowlisted by the bp2build configuration to be merged into the symlink forest workspace.
Jingwen Chen0eeaeb82022-09-21 10:27:42 +0000213func isPackageBoundary(config Config, prefix string, components []string, componentIndex int) bool {
214 prefix = filepath.Join(prefix, filepath.Join(components[:componentIndex+1]...))
215 if exists, _, _ := config.fs.Exists(filepath.Join(prefix, "Android.bp")); exists {
Liz Kammer620dea62021-04-14 17:36:10 -0400216 return true
Jingwen Chen0eeaeb82022-09-21 10:27:42 +0000217 } else if config.Bp2buildPackageConfig.ShouldKeepExistingBuildFileForDir(prefix) {
218 if exists, _, _ := config.fs.Exists(filepath.Join(prefix, "BUILD")); exists {
219 return true
220 } else if exists, _, _ := config.fs.Exists(filepath.Join(prefix, "BUILD.bazel")); exists {
221 return true
222 }
Liz Kammer620dea62021-04-14 17:36:10 -0400223 }
Jingwen Chen0eeaeb82022-09-21 10:27:42 +0000224
225 return false
Liz Kammer620dea62021-04-14 17:36:10 -0400226}
227
228// Transform a path (if necessary) to acknowledge package boundaries
229//
230// e.g. something like
Colin Crossd079e0b2022-08-16 10:27:33 -0700231//
232// async_safe/include/async_safe/CHECK.h
233//
Liz Kammer620dea62021-04-14 17:36:10 -0400234// might become
Colin Crossd079e0b2022-08-16 10:27:33 -0700235//
236// //bionic/libc/async_safe:include/async_safe/CHECK.h
237//
Liz Kammer620dea62021-04-14 17:36:10 -0400238// if the "async_safe" directory is actually a package and not just a directory.
239//
240// In particular, paths that extend into packages are transformed into absolute labels beginning with //.
Spandan Das0a8a2752023-06-21 01:50:33 +0000241func transformSubpackagePath(cfg Config, dir string, path bazel.Label) bazel.Label {
Liz Kammer620dea62021-04-14 17:36:10 -0400242 var newPath bazel.Label
243
Jingwen Chen38e62642021-04-19 05:00:15 +0000244 // Don't transform OriginalModuleName
245 newPath.OriginalModuleName = path.OriginalModuleName
Liz Kammer1e753242023-06-02 19:03:06 -0400246 // if it wasn't a module, store the original path. We may need the original path to replace
247 // references if it is actually in another package
248 if path.OriginalModuleName == "" {
249 newPath.OriginalModuleName = path.Label
250 }
Liz Kammer620dea62021-04-14 17:36:10 -0400251
252 if strings.HasPrefix(path.Label, "//") {
253 // Assume absolute labels are already correct (e.g. //path/to/some/package:foo.h)
254 newPath.Label = path.Label
255 return newPath
256 }
Usta Shresthad5580312022-09-23 16:46:38 -0400257 if strings.HasPrefix(path.Label, "./") {
258 // Drop "./" for consistent handling of paths.
259 // Specifically, to not let "." be considered a package boundary.
260 // Say `inputPath` is `x/Android.bp` and that file has some module
261 // with `srcs=["y/a.c", "z/b.c"]`.
262 // And say the directory tree is:
263 // x
264 // ├── Android.bp
265 // ├── y
266 // │ ├── a.c
267 // │ └── Android.bp
268 // └── z
269 // └── b.c
270 // Then bazel equivalent labels in srcs should be:
271 // //x/y:a.c, x/z/b.c
272 // The above should still be the case if `x/Android.bp` had
273 // srcs=["./y/a.c", "./z/b.c"]
274 // However, if we didn't strip "./", we'd get
275 // //x/./y:a.c, //x/.:z/b.c
276 path.Label = strings.TrimPrefix(path.Label, "./")
277 }
Liz Kammer620dea62021-04-14 17:36:10 -0400278 pathComponents := strings.Split(path.Label, "/")
Usta Shresthad5580312022-09-23 16:46:38 -0400279 newLabel := ""
Jingwen Chen0eeaeb82022-09-21 10:27:42 +0000280 foundPackageBoundary := false
Liz Kammer620dea62021-04-14 17:36:10 -0400281 // Check the deepest subdirectory first and work upwards
282 for i := len(pathComponents) - 1; i >= 0; i-- {
283 pathComponent := pathComponents[i]
284 var sep string
Spandan Das0a8a2752023-06-21 01:50:33 +0000285 if !foundPackageBoundary && isPackageBoundary(cfg, dir, pathComponents, i) {
Liz Kammer620dea62021-04-14 17:36:10 -0400286 sep = ":"
Jingwen Chen0eeaeb82022-09-21 10:27:42 +0000287 foundPackageBoundary = true
Liz Kammer620dea62021-04-14 17:36:10 -0400288 } else {
289 sep = "/"
290 }
291 if newLabel == "" {
292 newLabel = pathComponent
293 } else {
294 newLabel = pathComponent + sep + newLabel
295 }
296 }
Jingwen Chen0eeaeb82022-09-21 10:27:42 +0000297 if foundPackageBoundary {
Liz Kammer620dea62021-04-14 17:36:10 -0400298 // Ensure paths end up looking like //bionic/... instead of //./bionic/...
Spandan Das0a8a2752023-06-21 01:50:33 +0000299 moduleDir := dir
Liz Kammer620dea62021-04-14 17:36:10 -0400300 if strings.HasPrefix(moduleDir, ".") {
301 moduleDir = moduleDir[1:]
302 }
303 // Make the path into an absolute label (e.g. //bionic/libc/foo:bar.h instead of just foo:bar.h)
304 if moduleDir == "" {
305 newLabel = "//" + newLabel
306 } else {
307 newLabel = "//" + moduleDir + "/" + newLabel
308 }
309 }
310 newPath.Label = newLabel
311
312 return newPath
313}
314
315// Transform paths to acknowledge package boundaries
316// See transformSubpackagePath() for more information
Spandan Das0a8a2752023-06-21 01:50:33 +0000317func TransformSubpackagePaths(cfg Config, dir string, paths bazel.LabelList) bazel.LabelList {
Liz Kammer620dea62021-04-14 17:36:10 -0400318 var newPaths bazel.LabelList
319 for _, include := range paths.Includes {
Spandan Das0a8a2752023-06-21 01:50:33 +0000320 newPaths.Includes = append(newPaths.Includes, transformSubpackagePath(cfg, dir, include))
Liz Kammer620dea62021-04-14 17:36:10 -0400321 }
322 for _, exclude := range paths.Excludes {
Spandan Das0a8a2752023-06-21 01:50:33 +0000323 newPaths.Excludes = append(newPaths.Excludes, transformSubpackagePath(cfg, dir, exclude))
Liz Kammer620dea62021-04-14 17:36:10 -0400324 }
325 return newPaths
326}
327
Romain Jobredeaux1282c422021-10-29 10:52:59 -0400328// Converts root-relative Paths to a list of bazel.Label relative to the module in ctx.
329func RootToModuleRelativePaths(ctx BazelConversionPathContext, paths Paths) []bazel.Label {
330 var newPaths []bazel.Label
331 for _, path := range PathsWithModuleSrcSubDir(ctx, paths, "") {
332 s := path.Rel()
333 newPaths = append(newPaths, bazel.Label{Label: s})
334 }
335 return newPaths
336}
337
Liz Kammer620dea62021-04-14 17:36:10 -0400338// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local source
339// directory and Bazel target labels, excluding those included in the excludes argument (which
340// should already be expanded to resolve references to Soong-modules). Valid elements of paths
341// include:
Colin Crossd079e0b2022-08-16 10:27:33 -0700342// - filepath, relative to local module directory, resolves as a filepath relative to the local
343// source directory
344// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
345// module directory. Because Soong does not have a concept of crossing package boundaries, the
346// glob as computed by Soong may contain paths that cross package-boundaries that would be
347// unknowingly omitted if the glob were handled by Bazel. To allow identification and detect
348// (within Bazel) use of paths that cross package boundaries, we expand globs within Soong rather
349// than converting Soong glob syntax to Bazel glob syntax. **Invalid for excludes.**
350// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
351// or OutputFileProducer. These resolve as a Bazel label for a target. If the Bazel target is in
352// the local module directory, it will be returned relative to the current package (e.g.
353// ":<target>"). Otherwise, it will be returned as an absolute Bazel label (e.g.
354// "//path/to/dir:<target>"). If the reference to another module cannot be resolved,the function
355// will panic.
356//
Liz Kammer620dea62021-04-14 17:36:10 -0400357// Properties passed as the paths or excludes argument must have been annotated with struct tag
358// `android:"path"` so that dependencies on other modules will have already been handled by the
Spandan Das950091c2023-07-19 22:26:37 +0000359// pathdeps mutator.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000360func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammer620dea62021-04-14 17:36:10 -0400361 if paths == nil {
362 return bazel.LabelList{}
363 }
364 labels := bazel.LabelList{
365 Includes: []bazel.Label{},
366 }
Jingwen Chen4ecc67d2021-04-27 09:47:02 +0000367
368 // expandedExcludes contain module-dir relative paths, but root-relative paths
369 // are needed for GlobFiles later.
370 var rootRelativeExpandedExcludes []string
371 for _, e := range expandedExcludes {
372 rootRelativeExpandedExcludes = append(rootRelativeExpandedExcludes, filepath.Join(ctx.ModuleDir(), e))
373 }
374
Liz Kammer620dea62021-04-14 17:36:10 -0400375 for _, p := range paths {
376 if m, tag := SrcIsModuleWithTag(p); m != "" {
Chris Parsons953b3562021-09-20 15:14:39 -0400377 l := getOtherModuleLabel(ctx, m, tag, BazelModuleLabel)
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500378 if l != nil && !InList(l.Label, expandedExcludes) {
Jingwen Chen38e62642021-04-19 05:00:15 +0000379 l.OriginalModuleName = fmt.Sprintf(":%s", m)
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500380 labels.Includes = append(labels.Includes, *l)
Liz Kammer620dea62021-04-14 17:36:10 -0400381 }
382 } else {
383 var expandedPaths []bazel.Label
384 if pathtools.IsGlob(p) {
Jingwen Chen4ecc67d2021-04-27 09:47:02 +0000385 // e.g. turn "math/*.c" in
386 // external/arm-optimized-routines to external/arm-optimized-routines/math/*.c
387 rootRelativeGlobPath := pathForModuleSrc(ctx, p).String()
Romain Jobredeaux1282c422021-10-29 10:52:59 -0400388 expandedPaths = RootToModuleRelativePaths(ctx, GlobFiles(ctx, rootRelativeGlobPath, rootRelativeExpandedExcludes))
Liz Kammer620dea62021-04-14 17:36:10 -0400389 } else {
390 if !InList(p, expandedExcludes) {
391 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
392 }
393 }
394 labels.Includes = append(labels.Includes, expandedPaths...)
395 }
396 }
397 return labels
398}
399
400// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
401// module. The label will be relative to the current directory if appropriate. The dependency must
402// already be resolved by either deps mutator or path deps mutator.
Jingwen Chen55bc8202021-11-02 06:40:51 +0000403func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string,
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500404 labelFromModule func(BazelConversionPathContext, blueprint.Module) string) *bazel.Label {
Chris Parsons5a34ffb2021-07-21 14:34:58 -0400405 m, _ := ctx.ModuleFromName(dep)
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500406 // The module was not found in an Android.bp file, this is often due to:
407 // * a limited manifest
408 // * a required module not being converted from Android.mk
Liz Kammer620dea62021-04-14 17:36:10 -0400409 if m == nil {
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500410 ctx.AddMissingBp2buildDep(dep)
411 return &bazel.Label{
412 Label: ":" + dep + "__BP2BUILD__MISSING__DEP",
413 }
Liz Kammer620dea62021-04-14 17:36:10 -0400414 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400415 if !convertedToBazel(ctx, m) {
416 ctx.AddUnconvertedBp2buildDep(dep)
417 }
Chris Parsons953b3562021-09-20 15:14:39 -0400418 label := BazelModuleLabel(ctx, ctx.Module())
419 otherLabel := labelFromModule(ctx, m)
420
421 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
422
Liz Kammer620dea62021-04-14 17:36:10 -0400423 if samePackage(label, otherLabel) {
424 otherLabel = bazelShortLabel(otherLabel)
425 }
426
Liz Kammerdaa09ef2021-12-15 15:35:38 -0500427 return &bazel.Label{
Liz Kammer620dea62021-04-14 17:36:10 -0400428 Label: otherLabel,
429 }
430}
431
Jingwen Chen55bc8202021-11-02 06:40:51 +0000432func BazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
Liz Kammer620dea62021-04-14 17:36:10 -0400433 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
Spandan Das64852422023-08-02 21:58:41 +0000434 if !convertedToBazel(ctx, module) || isGoModule(module) {
Liz Kammer620dea62021-04-14 17:36:10 -0400435 return bp2buildModuleLabel(ctx, module)
436 }
Liz Kammer6eff3232021-08-26 08:37:59 -0400437 b, _ := module.(Bazelable)
Liz Kammer620dea62021-04-14 17:36:10 -0400438 return b.GetBazelLabel(ctx, module)
439}
440
441func bazelShortLabel(label string) string {
442 i := strings.Index(label, ":")
Jingwen Chen80b6b642021-11-02 06:23:07 +0000443 if i == -1 {
444 panic(fmt.Errorf("Could not find the ':' character in '%s', expected a fully qualified label.", label))
445 }
Liz Kammer620dea62021-04-14 17:36:10 -0400446 return label[i:]
447}
448
449func bazelPackage(label string) string {
450 i := strings.Index(label, ":")
Jingwen Chen80b6b642021-11-02 06:23:07 +0000451 if i == -1 {
452 panic(fmt.Errorf("Could not find the ':' character in '%s', expected a fully qualified label.", label))
453 }
Liz Kammer620dea62021-04-14 17:36:10 -0400454 return label[0:i]
455}
456
457func samePackage(label1, label2 string) bool {
458 return bazelPackage(label1) == bazelPackage(label2)
459}
460
Jingwen Chen55bc8202021-11-02 06:40:51 +0000461func bp2buildModuleLabel(ctx BazelConversionContext, module blueprint.Module) string {
Liz Kammer20f0f782023-05-01 13:46:33 -0400462 moduleName := moduleNameWithPossibleOverride(ctx, module)
463 moduleDir := moduleDirWithPossibleOverride(ctx, module)
Jingwen Chen889f2f22022-12-16 08:16:01 +0000464 if moduleDir == Bp2BuildTopLevel {
465 moduleDir = ""
466 }
Liz Kammer620dea62021-04-14 17:36:10 -0400467 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
468}
469
470// BazelOutPath is a Bazel output path compatible to be used for mixed builds within Soong/Ninja.
471type BazelOutPath struct {
472 OutputPath
473}
474
Liz Kammer0f3b7d22021-09-28 13:48:21 -0400475// ensure BazelOutPath implements Path
Liz Kammer620dea62021-04-14 17:36:10 -0400476var _ Path = BazelOutPath{}
Liz Kammer0f3b7d22021-09-28 13:48:21 -0400477
478// ensure BazelOutPath implements genPathProvider
479var _ genPathProvider = BazelOutPath{}
480
481// ensure BazelOutPath implements objPathProvider
Liz Kammer620dea62021-04-14 17:36:10 -0400482var _ objPathProvider = BazelOutPath{}
483
Liz Kammer0f3b7d22021-09-28 13:48:21 -0400484func (p BazelOutPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
485 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
486}
487
Liz Kammer620dea62021-04-14 17:36:10 -0400488func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
489 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
490}
491
Cole Faust9a06d252022-06-03 16:00:11 -0700492// PathForBazelOutRelative returns a BazelOutPath representing the path under an output directory dedicated to
493// bazel-owned outputs. Calling .Rel() on the result will give the input path as relative to the given
494// relativeRoot.
495func PathForBazelOutRelative(ctx PathContext, relativeRoot string, path string) BazelOutPath {
496 validatedPath, err := validatePath(filepath.Join("execroot", "__main__", path))
Liz Kammer620dea62021-04-14 17:36:10 -0400497 if err != nil {
498 reportPathError(ctx, err)
499 }
Cole Faust0abd4b42023-01-10 10:49:18 -0800500 var relativeRootPath string
501 if pathComponents := strings.SplitN(path, "/", 4); len(pathComponents) >= 3 &&
Cole Faust9a06d252022-06-03 16:00:11 -0700502 pathComponents[0] == "bazel-out" && pathComponents[2] == "bin" {
503 // If the path starts with something like: bazel-out/linux_x86_64-fastbuild-ST-b4ef1c4402f9/bin/
504 // make it relative to that folder. bazel-out/volatile-status.txt is an example
505 // of something that starts with bazel-out but is not relative to the bin folder
506 relativeRootPath = filepath.Join("execroot", "__main__", pathComponents[0], pathComponents[1], pathComponents[2], relativeRoot)
Cole Faust0abd4b42023-01-10 10:49:18 -0800507 } else {
508 relativeRootPath = filepath.Join("execroot", "__main__", relativeRoot)
Cole Faust9a06d252022-06-03 16:00:11 -0700509 }
Liz Kammer620dea62021-04-14 17:36:10 -0400510
Cole Faust9a06d252022-06-03 16:00:11 -0700511 var relPath string
512 if relPath, err = filepath.Rel(relativeRootPath, validatedPath); err != nil || strings.HasPrefix(relPath, "../") {
513 // We failed to make this path relative to execroot/__main__, fall back to a non-relative path
514 // One case where this happens is when path is ../bazel_tools/something
515 relativeRootPath = ""
516 relPath = validatedPath
517 }
518
519 outputPath := OutputPath{
520 basePath{"", ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200521 ctx.Config().soongOutDir,
Cole Faust9a06d252022-06-03 16:00:11 -0700522 ctx.Config().BazelContext.OutputBase(),
523 }
Liz Kammer620dea62021-04-14 17:36:10 -0400524
525 return BazelOutPath{
Cole Faust9a06d252022-06-03 16:00:11 -0700526 // .withRel() appends its argument onto the current path, and only the most
527 // recently appended part is returned by outputPath.rel().
528 // So outputPath.rel() will return relPath.
529 OutputPath: outputPath.withRel(relativeRootPath).withRel(relPath),
Liz Kammer620dea62021-04-14 17:36:10 -0400530 }
531}
Liz Kammerb6a55bf2021-04-12 15:42:51 -0400532
Cole Faust9a06d252022-06-03 16:00:11 -0700533// PathForBazelOut returns a BazelOutPath representing the path under an output directory dedicated to
534// bazel-owned outputs.
535func PathForBazelOut(ctx PathContext, path string) BazelOutPath {
536 return PathForBazelOutRelative(ctx, "", path)
537}
538
Liz Kammerb6a55bf2021-04-12 15:42:51 -0400539// PathsForBazelOut returns a list of paths representing the paths under an output directory
540// dedicated to Bazel-owned outputs.
541func PathsForBazelOut(ctx PathContext, paths []string) Paths {
542 outs := make(Paths, 0, len(paths))
543 for _, p := range paths {
544 outs = append(outs, PathForBazelOut(ctx, p))
545 }
546 return outs
547}
Jingwen Chen6817bbb2022-10-14 09:56:07 +0000548
549// BazelStringOrLabelFromProp splits a Soong module property that can be
550// either a string literal, path (with android:path tag) or a module reference
551// into separate bazel string or label attributes. Bazel treats string and label
552// attributes as distinct types, so this function categorizes a string property
553// into either one of them.
554//
555// e.g. apex.private_key = "foo.pem" can either refer to:
556//
557// 1. "foo.pem" in the current directory -> file target
558// 2. "foo.pem" module -> rule target
559// 3. "foo.pem" file in a different directory, prefixed by a product variable handled
560// in a bazel macro. -> string literal
561//
562// For the first two cases, they are defined using the label attribute. For the third case,
563// it's defined with the string attribute.
564func BazelStringOrLabelFromProp(
565 ctx TopDownMutatorContext,
566 propToDistinguish *string) (bazel.LabelAttribute, bazel.StringAttribute) {
567
568 var labelAttr bazel.LabelAttribute
569 var strAttr bazel.StringAttribute
570
571 if propToDistinguish == nil {
572 // nil pointer
573 return labelAttr, strAttr
574 }
575
576 prop := String(propToDistinguish)
577 if SrcIsModule(prop) != "" {
578 // If it's a module (SrcIsModule will return the module name), set the
579 // resolved label to the label attribute.
580 labelAttr.SetValue(BazelLabelForModuleDepSingle(ctx, prop))
581 } else {
582 // Not a module name. This could be a string literal or a file target in
583 // the current dir. Check if the path exists:
584 path := ExistentPathForSource(ctx, ctx.ModuleDir(), prop)
585
586 if path.Valid() && parentDir(path.String()) == ctx.ModuleDir() {
587 // If it exists and the path is relative to the current dir, resolve the bazel label
588 // for the _file target_ and set it to the label attribute.
589 //
590 // Resolution is necessary because this could be a file in a subpackage.
591 labelAttr.SetValue(BazelLabelForModuleSrcSingle(ctx, prop))
592 } else {
593 // Otherwise, treat it as a string literal and assign to the string attribute.
594 strAttr.Value = propToDistinguish
595 }
596 }
597
598 return labelAttr, strAttr
599}