blob: c303c38f555f1950cf38f9555c7092a9051bbec4 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// 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
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Liz Kammer356f7d42021-01-26 09:18:53 -050018 "android/soong/bazel"
Colin Cross6e18ca42015-07-14 18:55:36 -070019 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000020 "io/ioutil"
21 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070022 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070023 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070024 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070025 "strings"
26
27 "github.com/google/blueprint"
28 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080029)
30
Colin Cross988414c2020-01-11 01:11:46 +000031var absSrcDir string
32
Dan Willemsen34cc69e2015-09-23 15:26:20 -070033// PathContext is the subset of a (Module|Singleton)Context required by the
34// Path methods.
35type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080036 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080037 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080038}
39
Colin Cross7f19f372016-11-01 11:10:25 -070040type PathGlobContext interface {
41 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
42}
43
Colin Crossaabf6792017-11-29 00:27:14 -080044var _ PathContext = SingletonContext(nil)
45var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070046
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010047// "Null" path context is a minimal path context for a given config.
48type NullPathContext struct {
49 config Config
50}
51
52func (NullPathContext) AddNinjaFileDeps(...string) {}
53func (ctx NullPathContext) Config() Config { return ctx.config }
54
Liz Kammera830f3a2020-11-10 10:50:34 -080055// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
56// Path methods. These path methods can be called before any mutators have run.
57type EarlyModulePathContext interface {
58 PathContext
59 PathGlobContext
60
61 ModuleDir() string
62 ModuleErrorf(fmt string, args ...interface{})
63}
64
65var _ EarlyModulePathContext = ModuleContext(nil)
66
67// Glob globs files and directories matching globPattern relative to ModuleDir(),
68// paths in the excludes parameter will be omitted.
69func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
70 ret, err := ctx.GlobWithDeps(globPattern, excludes)
71 if err != nil {
72 ctx.ModuleErrorf("glob: %s", err.Error())
73 }
74 return pathsForModuleSrcFromFullPath(ctx, ret, true)
75}
76
77// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
78// Paths in the excludes parameter will be omitted.
79func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
80 ret, err := ctx.GlobWithDeps(globPattern, excludes)
81 if err != nil {
82 ctx.ModuleErrorf("glob: %s", err.Error())
83 }
84 return pathsForModuleSrcFromFullPath(ctx, ret, false)
85}
86
87// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
88// the Path methods that rely on module dependencies having been resolved.
89type ModuleWithDepsPathContext interface {
90 EarlyModulePathContext
91 GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
92}
93
94// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
95// the Path methods that rely on module dependencies having been resolved and ability to report
96// missing dependency errors.
97type ModuleMissingDepsPathContext interface {
98 ModuleWithDepsPathContext
99 AddMissingDependencies(missingDeps []string)
100}
101
Dan Willemsen00269f22017-07-06 16:59:48 -0700102type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700103 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700104
105 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700106 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700107 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800108 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700109 InstallInVendorRamdisk() bool
Inseob Kimf84e9c02021-04-08 21:13:22 +0900110 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900111 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700112 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -0700113 InstallBypassMake() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900114 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700115}
116
117var _ ModuleInstallPathContext = ModuleContext(nil)
118
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700119// errorfContext is the interface containing the Errorf method matching the
120// Errorf method in blueprint.SingletonContext.
121type errorfContext interface {
122 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800123}
124
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700125var _ errorfContext = blueprint.SingletonContext(nil)
126
127// moduleErrorf is the interface containing the ModuleErrorf method matching
128// the ModuleErrorf method in blueprint.ModuleContext.
129type moduleErrorf interface {
130 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800131}
132
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700133var _ moduleErrorf = blueprint.ModuleContext(nil)
134
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700135// reportPathError will register an error with the attached context. It
136// attempts ctx.ModuleErrorf for a better error message first, then falls
137// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800138func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100139 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800140}
141
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100142// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800143// attempts ctx.ModuleErrorf for a better error message first, then falls
144// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100145func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700146 if mctx, ok := ctx.(moduleErrorf); ok {
147 mctx.ModuleErrorf(format, args...)
148 } else if ectx, ok := ctx.(errorfContext); ok {
149 ectx.Errorf(format, args...)
150 } else {
151 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700152 }
153}
154
Colin Cross5e708052019-08-06 13:59:50 -0700155func pathContextName(ctx PathContext, module blueprint.Module) string {
156 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
157 return x.ModuleName(module)
158 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
159 return x.OtherModuleName(module)
160 }
161 return "unknown"
162}
163
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700164type Path interface {
165 // Returns the path in string form
166 String() string
167
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700168 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700169 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700170
171 // Base returns the last element of the path
172 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800173
174 // Rel returns the portion of the path relative to the directory it was created from. For
175 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800176 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800177 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000178
179 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
180 //
181 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
182 // InstallPath then the returned value can be converted to an InstallPath.
183 //
184 // A standard build has the following structure:
185 // ../top/
186 // out/ - make install files go here.
187 // out/soong - this is the buildDir passed to NewTestConfig()
188 // ... - the source files
189 //
190 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
191 // * Make install paths, which have the pattern "buildDir/../<path>" are converted into the top
192 // relative path "out/<path>"
193 // * Soong install paths and other writable paths, which have the pattern "buildDir/<path>" are
194 // converted into the top relative path "out/soong/<path>".
195 // * Source paths are already relative to the top.
196 // * Phony paths are not relative to anything.
197 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
198 // order to test.
199 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700200}
201
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000202const (
203 OutDir = "out"
204 OutSoongDir = OutDir + "/soong"
205)
206
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700207// WritablePath is a type of path that can be used as an output for build rules.
208type WritablePath interface {
209 Path
210
Paul Duffin9b478b02019-12-10 13:41:51 +0000211 // return the path to the build directory.
Paul Duffind65c58b2021-03-24 09:22:07 +0000212 getBuildDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000213
Jeff Gaston734e3802017-04-10 15:47:24 -0700214 // the writablePath method doesn't directly do anything,
215 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700216 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100217
218 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700219}
220
221type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800222 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700223}
224type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800225 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700226}
227type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800228 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700229}
230
231// GenPathWithExt derives a new file path in ctx's generated sources directory
232// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800233func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700234 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700235 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700236 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100237 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700238 return PathForModuleGen(ctx)
239}
240
241// ObjPathWithExt derives a new file path in ctx's object directory from the
242// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800243func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700244 if path, ok := p.(objPathProvider); ok {
245 return path.objPathWithExt(ctx, subdir, ext)
246 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100247 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700248 return PathForModuleObj(ctx)
249}
250
251// ResPathWithName derives a new path in ctx's output resource directory, using
252// the current path to create the directory name, and the `name` argument for
253// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800254func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700255 if path, ok := p.(resPathProvider); ok {
256 return path.resPathWithName(ctx, name)
257 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100258 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700259 return PathForModuleRes(ctx)
260}
261
262// OptionalPath is a container that may or may not contain a valid Path.
263type OptionalPath struct {
264 valid bool
265 path Path
266}
267
268// OptionalPathForPath returns an OptionalPath containing the path.
269func OptionalPathForPath(path Path) OptionalPath {
270 if path == nil {
271 return OptionalPath{}
272 }
273 return OptionalPath{valid: true, path: path}
274}
275
276// Valid returns whether there is a valid path
277func (p OptionalPath) Valid() bool {
278 return p.valid
279}
280
281// Path returns the Path embedded in this OptionalPath. You must be sure that
282// there is a valid path, since this method will panic if there is not.
283func (p OptionalPath) Path() Path {
284 if !p.valid {
285 panic("Requesting an invalid path")
286 }
287 return p.path
288}
289
Paul Duffinafdd4062021-03-30 19:44:07 +0100290// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
291// result of calling Path.RelativeToTop on it.
292func (p OptionalPath) RelativeToTop() OptionalPath {
Paul Duffina5b81352021-03-28 23:57:19 +0100293 if !p.valid {
294 return p
295 }
296 p.path = p.path.RelativeToTop()
297 return p
298}
299
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700300// String returns the string version of the Path, or "" if it isn't valid.
301func (p OptionalPath) String() string {
302 if p.valid {
303 return p.path.String()
304 } else {
305 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700306 }
307}
Colin Cross6e18ca42015-07-14 18:55:36 -0700308
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700309// Paths is a slice of Path objects, with helpers to operate on the collection.
310type Paths []Path
311
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000312// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
313// item in this slice.
314func (p Paths) RelativeToTop() Paths {
315 ensureTestOnly()
316 if p == nil {
317 return p
318 }
319 ret := make(Paths, len(p))
320 for i, path := range p {
321 ret[i] = path.RelativeToTop()
322 }
323 return ret
324}
325
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000326func (paths Paths) containsPath(path Path) bool {
327 for _, p := range paths {
328 if p == path {
329 return true
330 }
331 }
332 return false
333}
334
Liz Kammer7aa52882021-02-11 09:16:14 -0500335// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
336// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700337func PathsForSource(ctx PathContext, paths []string) Paths {
338 ret := make(Paths, len(paths))
339 for i, path := range paths {
340 ret[i] = PathForSource(ctx, path)
341 }
342 return ret
343}
344
Liz Kammer7aa52882021-02-11 09:16:14 -0500345// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
346// module's local source directory, that are found in the tree. If any are not found, they are
347// omitted from the list, and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800348func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800349 ret := make(Paths, 0, len(paths))
350 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800351 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800352 if p.Valid() {
353 ret = append(ret, p.Path())
354 }
355 }
356 return ret
357}
358
Colin Cross41955e82019-05-29 14:40:35 -0700359// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
360// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
361// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
362// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
363// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
364// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800365func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800366 return PathsForModuleSrcExcludes(ctx, paths, nil)
367}
368
Colin Crossba71a3f2019-03-18 12:12:48 -0700369// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700370// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
371// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
372// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
373// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100374// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700375// having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800376func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700377 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
378 if ctx.Config().AllowMissingDependencies() {
379 ctx.AddMissingDependencies(missingDeps)
380 } else {
381 for _, m := range missingDeps {
382 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
383 }
384 }
385 return ret
386}
387
Liz Kammer356f7d42021-01-26 09:18:53 -0500388// A subset of the ModuleContext methods which are sufficient to resolve references to paths/deps in
389// order to form a Bazel-compatible label for conversion.
390type BazelConversionPathContext interface {
391 EarlyModulePathContext
392
393 GetDirectDep(name string) (blueprint.Module, blueprint.DependencyTag)
Liz Kammerbdc60992021-02-24 16:55:11 -0500394 Module() Module
Jingwen Chen12b4c272021-03-10 02:05:59 -0500395 ModuleType() string
Liz Kammer356f7d42021-01-26 09:18:53 -0500396 OtherModuleName(m blueprint.Module) string
397 OtherModuleDir(m blueprint.Module) string
398}
399
400// BazelLabelForModuleDeps returns a Bazel-compatible label for the requested modules which
401// correspond to dependencies on the module within the given ctx.
402func BazelLabelForModuleDeps(ctx BazelConversionPathContext, modules []string) bazel.LabelList {
403 var labels bazel.LabelList
404 for _, module := range modules {
405 bpText := module
406 if m := SrcIsModule(module); m == "" {
407 module = ":" + module
408 }
409 if m, t := SrcIsModuleWithTag(module); m != "" {
410 l := getOtherModuleLabel(ctx, m, t)
411 l.Bp_text = bpText
412 labels.Includes = append(labels.Includes, l)
413 } else {
414 ctx.ModuleErrorf("%q, is not a module reference", module)
415 }
416 }
417 return labels
418}
419
Rupert Shuttleworthc143cc52021-04-13 13:08:04 -0400420// Returns true if a prefix + components[:i] + /Android.bp exists
421// TODO(b/185358476) Could check for BUILD file instead of checking for Android.bp file, or ensure BUILD is always generated?
422func directoryHasBlueprint(fs pathtools.FileSystem, prefix string, components []string, componentIndex int) bool {
423 blueprintPath := prefix
424 if blueprintPath != "" {
425 blueprintPath = blueprintPath + "/"
426 }
427 blueprintPath = blueprintPath + strings.Join(components[:componentIndex+1], "/")
428 blueprintPath = blueprintPath + "/Android.bp"
429 if exists, _, _ := fs.Exists(blueprintPath); exists {
430 return true
431 } else {
432 return false
433 }
434}
435
436// Transform a path (if necessary) to acknowledge package boundaries
437//
438// e.g. something like
439// async_safe/include/async_safe/CHECK.h
440// might become
441// //bionic/libc/async_safe:include/async_safe/CHECK.h
442// if the "async_safe" directory is actually a package and not just a directory.
443//
444// In particular, paths that extend into packages are transformed into absolute labels beginning with //.
445func transformSubpackagePath(ctx BazelConversionPathContext, path bazel.Label) bazel.Label {
446 var newPath bazel.Label
447
448 // Don't transform Bp_text
449 newPath.Bp_text = path.Bp_text
450
451 if strings.HasPrefix(path.Label, "//") {
452 // Assume absolute labels are already correct (e.g. //path/to/some/package:foo.h)
453 newPath.Label = path.Label
454 return newPath
455 }
456
457 newLabel := ""
458 pathComponents := strings.Split(path.Label, "/")
459 foundBlueprint := false
460 // Check the deepest subdirectory first and work upwards
461 for i := len(pathComponents) - 1; i >= 0; i-- {
462 pathComponent := pathComponents[i]
463 var sep string
464 if !foundBlueprint && directoryHasBlueprint(ctx.Config().fs, ctx.ModuleDir(), pathComponents, i) {
465 sep = ":"
466 foundBlueprint = true
467 } else {
468 sep = "/"
469 }
470 if newLabel == "" {
471 newLabel = pathComponent
472 } else {
473 newLabel = pathComponent + sep + newLabel
474 }
475 }
476 if foundBlueprint {
477 // Ensure paths end up looking like //bionic/... instead of //./bionic/...
478 moduleDir := ctx.ModuleDir()
479 if strings.HasPrefix(moduleDir, ".") {
480 moduleDir = moduleDir[1:]
481 }
482 // Make the path into an absolute label (e.g. //bionic/libc/foo:bar.h instead of just foo:bar.h)
483 if moduleDir == "" {
484 newLabel = "//" + newLabel
485 } else {
486 newLabel = "//" + moduleDir + "/" + newLabel
487 }
488 }
489 newPath.Label = newLabel
490
491 return newPath
492}
493
494// Transform paths to acknowledge package boundaries
495// See transformSubpackagePath() for more information
496func transformSubpackagePaths(ctx BazelConversionPathContext, paths bazel.LabelList) bazel.LabelList {
497 var newPaths bazel.LabelList
498 for _, include := range paths.Includes {
499 newPaths.Includes = append(newPaths.Includes, transformSubpackagePath(ctx, include))
500 }
501 for _, exclude := range paths.Excludes {
502 newPaths.Excludes = append(newPaths.Excludes, transformSubpackagePath(ctx, exclude))
503 }
504 return newPaths
505}
506
Liz Kammer356f7d42021-01-26 09:18:53 -0500507// BazelLabelForModuleSrc returns bazel.LabelList with paths rooted from the module's local source
508// directory. It expands globs, and resolves references to modules using the ":name" syntax to
509// bazel-compatible labels. Properties passed as the paths or excludes argument must have been
510// annotated with struct tag `android:"path"` so that dependencies on other modules will have
511// already been handled by the path_properties mutator.
Jingwen Chen63930982021-03-24 10:04:33 -0400512//
513// With expanded globs, we can catch package boundaries problem instead of
514// silently failing to potentially missing files from Bazel's globs.
Liz Kammer356f7d42021-01-26 09:18:53 -0500515func BazelLabelForModuleSrc(ctx BazelConversionPathContext, paths []string) bazel.LabelList {
516 return BazelLabelForModuleSrcExcludes(ctx, paths, []string(nil))
517}
518
519// BazelLabelForModuleSrcExcludes returns bazel.LabelList with paths rooted from the module's local
520// source directory, excluding labels included in the excludes argument. It expands globs, and
521// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
522// passed as the paths or excludes argument must have been annotated with struct tag
523// `android:"path"` so that dependencies on other modules will have already been handled by the
524// path_properties mutator.
Jingwen Chen63930982021-03-24 10:04:33 -0400525//
526// With expanded globs, we can catch package boundaries problem instead of
527// silently failing to potentially missing files from Bazel's globs.
Liz Kammer356f7d42021-01-26 09:18:53 -0500528func BazelLabelForModuleSrcExcludes(ctx BazelConversionPathContext, paths, excludes []string) bazel.LabelList {
529 excludeLabels := expandSrcsForBazel(ctx, excludes, []string(nil))
530 excluded := make([]string, 0, len(excludeLabels.Includes))
531 for _, e := range excludeLabels.Includes {
532 excluded = append(excluded, e.Label)
533 }
534 labels := expandSrcsForBazel(ctx, paths, excluded)
535 labels.Excludes = excludeLabels.Includes
Rupert Shuttleworthc143cc52021-04-13 13:08:04 -0400536 labels = transformSubpackagePaths(ctx, labels)
Liz Kammer356f7d42021-01-26 09:18:53 -0500537 return labels
538}
539
540// expandSrcsForBazel returns bazel.LabelList with paths rooted from the module's local
541// source directory, excluding labels included in the excludes argument. It expands globs, and
542// resolves references to modules using the ":name" syntax to bazel-compatible labels. Properties
543// passed as the paths or excludes argument must have been annotated with struct tag
544// `android:"path"` so that dependencies on other modules will have already been handled by the
545// path_properties mutator.
546func expandSrcsForBazel(ctx BazelConversionPathContext, paths, expandedExcludes []string) bazel.LabelList {
Liz Kammerebfcf672021-02-16 15:00:05 -0500547 if paths == nil {
548 return bazel.LabelList{}
549 }
Liz Kammer356f7d42021-01-26 09:18:53 -0500550 labels := bazel.LabelList{
551 Includes: []bazel.Label{},
552 }
553 for _, p := range paths {
554 if m, tag := SrcIsModuleWithTag(p); m != "" {
555 l := getOtherModuleLabel(ctx, m, tag)
556 if !InList(l.Label, expandedExcludes) {
557 l.Bp_text = fmt.Sprintf(":%s", m)
558 labels.Includes = append(labels.Includes, l)
559 }
560 } else {
561 var expandedPaths []bazel.Label
562 if pathtools.IsGlob(p) {
563 globbedPaths := GlobFiles(ctx, pathForModuleSrc(ctx, p).String(), expandedExcludes)
564 globbedPaths = PathsWithModuleSrcSubDir(ctx, globbedPaths, "")
565 for _, path := range globbedPaths {
566 s := path.Rel()
567 expandedPaths = append(expandedPaths, bazel.Label{Label: s})
568 }
569 } else {
570 if !InList(p, expandedExcludes) {
571 expandedPaths = append(expandedPaths, bazel.Label{Label: p})
572 }
573 }
574 labels.Includes = append(labels.Includes, expandedPaths...)
575 }
576 }
577 return labels
578}
579
580// getOtherModuleLabel returns a bazel.Label for the given dependency/tag combination for the
581// module. The label will be relative to the current directory if appropriate. The dependency must
582// already be resolved by either deps mutator or path deps mutator.
583func getOtherModuleLabel(ctx BazelConversionPathContext, dep, tag string) bazel.Label {
584 m, _ := ctx.GetDirectDep(dep)
Jingwen Chen07027912021-03-15 06:02:43 -0400585 if m == nil {
586 panic(fmt.Errorf("cannot get direct dep %s of %s", dep, ctx.Module().Name()))
587 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500588 otherLabel := bazelModuleLabel(ctx, m, tag)
589 label := bazelModuleLabel(ctx, ctx.Module(), "")
590 if samePackage(label, otherLabel) {
591 otherLabel = bazelShortLabel(otherLabel)
Liz Kammer356f7d42021-01-26 09:18:53 -0500592 }
Liz Kammerbdc60992021-02-24 16:55:11 -0500593
594 return bazel.Label{
595 Label: otherLabel,
596 }
597}
598
599func bazelModuleLabel(ctx BazelConversionPathContext, module blueprint.Module, tag string) string {
600 // TODO(b/165114590): Convert tag (":name{.tag}") to corresponding Bazel implicit output targets.
601 b, ok := module.(Bazelable)
602 // TODO(b/181155349): perhaps return an error here if the module can't be/isn't being converted
Jingwen Chen12b4c272021-03-10 02:05:59 -0500603 if !ok || !b.ConvertedToBazel(ctx) {
Liz Kammerbdc60992021-02-24 16:55:11 -0500604 return bp2buildModuleLabel(ctx, module)
605 }
606 return b.GetBazelLabel(ctx, module)
607}
608
609func bazelShortLabel(label string) string {
610 i := strings.Index(label, ":")
611 return label[i:]
612}
613
614func bazelPackage(label string) string {
615 i := strings.Index(label, ":")
616 return label[0:i]
617}
618
619func samePackage(label1, label2 string) bool {
620 return bazelPackage(label1) == bazelPackage(label2)
621}
622
623func bp2buildModuleLabel(ctx BazelConversionPathContext, module blueprint.Module) string {
624 moduleName := ctx.OtherModuleName(module)
625 moduleDir := ctx.OtherModuleDir(module)
626 return fmt.Sprintf("//%s:%s", moduleDir, moduleName)
Liz Kammer356f7d42021-01-26 09:18:53 -0500627}
628
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000629// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
630type OutputPaths []OutputPath
631
632// Paths returns the OutputPaths as a Paths
633func (p OutputPaths) Paths() Paths {
634 if p == nil {
635 return nil
636 }
637 ret := make(Paths, len(p))
638 for i, path := range p {
639 ret[i] = path
640 }
641 return ret
642}
643
644// Strings returns the string forms of the writable paths.
645func (p OutputPaths) Strings() []string {
646 if p == nil {
647 return nil
648 }
649 ret := make([]string, len(p))
650 for i, path := range p {
651 ret[i] = path.String()
652 }
653 return ret
654}
655
Liz Kammera830f3a2020-11-10 10:50:34 -0800656// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
657// If the dependency is not found, a missingErrorDependency is returned.
658// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
659func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
660 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
661 if module == nil {
662 return nil, missingDependencyError{[]string{moduleName}}
663 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700664 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
665 return nil, missingDependencyError{[]string{moduleName}}
666 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800667 if outProducer, ok := module.(OutputFileProducer); ok {
668 outputFiles, err := outProducer.OutputFiles(tag)
669 if err != nil {
670 return nil, fmt.Errorf("path dependency %q: %s", path, err)
671 }
672 return outputFiles, nil
673 } else if tag != "" {
674 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
675 } else if srcProducer, ok := module.(SourceFileProducer); ok {
676 return srcProducer.Srcs(), nil
677 } else {
678 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
679 }
680}
681
Colin Crossba71a3f2019-03-18 12:12:48 -0700682// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700683// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
684// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
685// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
686// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
687// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
688// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
689// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800690func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800691 prefix := pathForModuleSrc(ctx).String()
692
693 var expandedExcludes []string
694 if excludes != nil {
695 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700696 }
Colin Cross8a497952019-03-05 22:25:09 -0800697
Colin Crossba71a3f2019-03-18 12:12:48 -0700698 var missingExcludeDeps []string
699
Colin Cross8a497952019-03-05 22:25:09 -0800700 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700701 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800702 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
703 if m, ok := err.(missingDependencyError); ok {
704 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
705 } else if err != nil {
706 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800707 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800708 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800709 }
710 } else {
711 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
712 }
713 }
714
715 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700716 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800717 }
718
Colin Crossba71a3f2019-03-18 12:12:48 -0700719 var missingDeps []string
720
Colin Cross8a497952019-03-05 22:25:09 -0800721 expandedSrcFiles := make(Paths, 0, len(paths))
722 for _, s := range paths {
723 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
724 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700725 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800726 } else if err != nil {
727 reportPathError(ctx, err)
728 }
729 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
730 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700731
732 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800733}
734
735type missingDependencyError struct {
736 missingDeps []string
737}
738
739func (e missingDependencyError) Error() string {
740 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
741}
742
Liz Kammera830f3a2020-11-10 10:50:34 -0800743// Expands one path string to Paths rooted from the module's local source
744// directory, excluding those listed in the expandedExcludes.
745// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
746func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900747 excludePaths := func(paths Paths) Paths {
748 if len(expandedExcludes) == 0 {
749 return paths
750 }
751 remainder := make(Paths, 0, len(paths))
752 for _, p := range paths {
753 if !InList(p.String(), expandedExcludes) {
754 remainder = append(remainder, p)
755 }
756 }
757 return remainder
758 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800759 if m, t := SrcIsModuleWithTag(sPath); m != "" {
760 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
761 if err != nil {
762 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800763 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800764 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800765 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800766 } else if pathtools.IsGlob(sPath) {
767 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800768 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
769 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800770 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000771 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100772 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +0000773 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100774 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800775 }
776
Jooyung Han7607dd32020-07-05 10:23:14 +0900777 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800778 return nil, nil
779 }
780 return Paths{p}, nil
781 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700782}
783
784// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
785// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800786// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700787// It intended for use in globs that only list files that exist, so it allows '$' in
788// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800789func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800790 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700791 if prefix == "./" {
792 prefix = ""
793 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700794 ret := make(Paths, 0, len(paths))
795 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800796 if !incDirs && strings.HasSuffix(p, "/") {
797 continue
798 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700799 path := filepath.Clean(p)
800 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100801 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700802 continue
803 }
Colin Crosse3924e12018-08-15 20:18:53 -0700804
Colin Crossfe4bc362018-09-12 10:02:13 -0700805 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700806 if err != nil {
807 reportPathError(ctx, err)
808 continue
809 }
810
Colin Cross07e51612019-03-05 12:46:40 -0800811 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700812
Colin Cross07e51612019-03-05 12:46:40 -0800813 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700814 }
815 return ret
816}
817
Liz Kammera830f3a2020-11-10 10:50:34 -0800818// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
819// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
820func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800821 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700822 return PathsForModuleSrc(ctx, input)
823 }
824 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
825 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800826 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800827 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700828}
829
830// Strings returns the Paths in string form
831func (p Paths) Strings() []string {
832 if p == nil {
833 return nil
834 }
835 ret := make([]string, len(p))
836 for i, path := range p {
837 ret[i] = path.String()
838 }
839 return ret
840}
841
Colin Crossc0efd1d2020-07-03 11:56:24 -0700842func CopyOfPaths(paths Paths) Paths {
843 return append(Paths(nil), paths...)
844}
845
Colin Crossb6715442017-10-24 11:13:31 -0700846// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
847// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700848func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800849 // 128 was chosen based on BenchmarkFirstUniquePaths results.
850 if len(list) > 128 {
851 return firstUniquePathsMap(list)
852 }
853 return firstUniquePathsList(list)
854}
855
Colin Crossc0efd1d2020-07-03 11:56:24 -0700856// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
857// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900858func SortedUniquePaths(list Paths) Paths {
859 unique := FirstUniquePaths(list)
860 sort.Slice(unique, func(i, j int) bool {
861 return unique[i].String() < unique[j].String()
862 })
863 return unique
864}
865
Colin Cross27027c72020-02-28 15:34:17 -0800866func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700867 k := 0
868outer:
869 for i := 0; i < len(list); i++ {
870 for j := 0; j < k; j++ {
871 if list[i] == list[j] {
872 continue outer
873 }
874 }
875 list[k] = list[i]
876 k++
877 }
878 return list[:k]
879}
880
Colin Cross27027c72020-02-28 15:34:17 -0800881func firstUniquePathsMap(list Paths) Paths {
882 k := 0
883 seen := make(map[Path]bool, len(list))
884 for i := 0; i < len(list); i++ {
885 if seen[list[i]] {
886 continue
887 }
888 seen[list[i]] = true
889 list[k] = list[i]
890 k++
891 }
892 return list[:k]
893}
894
Colin Cross5d583952020-11-24 16:21:24 -0800895// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
896// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
897func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
898 // 128 was chosen based on BenchmarkFirstUniquePaths results.
899 if len(list) > 128 {
900 return firstUniqueInstallPathsMap(list)
901 }
902 return firstUniqueInstallPathsList(list)
903}
904
905func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
906 k := 0
907outer:
908 for i := 0; i < len(list); i++ {
909 for j := 0; j < k; j++ {
910 if list[i] == list[j] {
911 continue outer
912 }
913 }
914 list[k] = list[i]
915 k++
916 }
917 return list[:k]
918}
919
920func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
921 k := 0
922 seen := make(map[InstallPath]bool, len(list))
923 for i := 0; i < len(list); i++ {
924 if seen[list[i]] {
925 continue
926 }
927 seen[list[i]] = true
928 list[k] = list[i]
929 k++
930 }
931 return list[:k]
932}
933
Colin Crossb6715442017-10-24 11:13:31 -0700934// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
935// modifies the Paths slice contents in place, and returns a subslice of the original slice.
936func LastUniquePaths(list Paths) Paths {
937 totalSkip := 0
938 for i := len(list) - 1; i >= totalSkip; i-- {
939 skip := 0
940 for j := i - 1; j >= totalSkip; j-- {
941 if list[i] == list[j] {
942 skip++
943 } else {
944 list[j+skip] = list[j]
945 }
946 }
947 totalSkip += skip
948 }
949 return list[totalSkip:]
950}
951
Colin Crossa140bb02018-04-17 10:52:26 -0700952// ReversePaths returns a copy of a Paths in reverse order.
953func ReversePaths(list Paths) Paths {
954 if list == nil {
955 return nil
956 }
957 ret := make(Paths, len(list))
958 for i := range list {
959 ret[i] = list[len(list)-1-i]
960 }
961 return ret
962}
963
Jeff Gaston294356f2017-09-27 17:05:30 -0700964func indexPathList(s Path, list []Path) int {
965 for i, l := range list {
966 if l == s {
967 return i
968 }
969 }
970
971 return -1
972}
973
974func inPathList(p Path, list []Path) bool {
975 return indexPathList(p, list) != -1
976}
977
978func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000979 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
980}
981
982func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700983 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000984 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700985 filtered = append(filtered, l)
986 } else {
987 remainder = append(remainder, l)
988 }
989 }
990
991 return
992}
993
Colin Cross93e85952017-08-15 13:34:18 -0700994// HasExt returns true of any of the paths have extension ext, otherwise false
995func (p Paths) HasExt(ext string) bool {
996 for _, path := range p {
997 if path.Ext() == ext {
998 return true
999 }
1000 }
1001
1002 return false
1003}
1004
1005// FilterByExt returns the subset of the paths that have extension ext
1006func (p Paths) FilterByExt(ext string) Paths {
1007 ret := make(Paths, 0, len(p))
1008 for _, path := range p {
1009 if path.Ext() == ext {
1010 ret = append(ret, path)
1011 }
1012 }
1013 return ret
1014}
1015
1016// FilterOutByExt returns the subset of the paths that do not have extension ext
1017func (p Paths) FilterOutByExt(ext string) Paths {
1018 ret := make(Paths, 0, len(p))
1019 for _, path := range p {
1020 if path.Ext() != ext {
1021 ret = append(ret, path)
1022 }
1023 }
1024 return ret
1025}
1026
Colin Cross5e6cfbe2017-11-03 15:20:35 -07001027// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
1028// (including subdirectories) are in a contiguous subslice of the list, and can be found in
1029// O(log(N)) time using a binary search on the directory prefix.
1030type DirectorySortedPaths Paths
1031
1032func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
1033 ret := append(DirectorySortedPaths(nil), paths...)
1034 sort.Slice(ret, func(i, j int) bool {
1035 return ret[i].String() < ret[j].String()
1036 })
1037 return ret
1038}
1039
1040// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
1041// that are in the specified directory and its subdirectories.
1042func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
1043 prefix := filepath.Clean(dir) + "/"
1044 start := sort.Search(len(p), func(i int) bool {
1045 return prefix < p[i].String()
1046 })
1047
1048 ret := p[start:]
1049
1050 end := sort.Search(len(ret), func(i int) bool {
1051 return !strings.HasPrefix(ret[i].String(), prefix)
1052 })
1053
1054 ret = ret[:end]
1055
1056 return Paths(ret)
1057}
1058
Alex Humesky29e3bbe2020-11-20 21:30:13 -05001059// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001060type WritablePaths []WritablePath
1061
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001062// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
1063// each item in this slice.
1064func (p WritablePaths) RelativeToTop() WritablePaths {
1065 ensureTestOnly()
1066 if p == nil {
1067 return p
1068 }
1069 ret := make(WritablePaths, len(p))
1070 for i, path := range p {
1071 ret[i] = path.RelativeToTop().(WritablePath)
1072 }
1073 return ret
1074}
1075
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001076// Strings returns the string forms of the writable paths.
1077func (p WritablePaths) Strings() []string {
1078 if p == nil {
1079 return nil
1080 }
1081 ret := make([]string, len(p))
1082 for i, path := range p {
1083 ret[i] = path.String()
1084 }
1085 return ret
1086}
1087
Colin Cross3bc7ffa2017-11-22 16:19:37 -08001088// Paths returns the WritablePaths as a Paths
1089func (p WritablePaths) Paths() Paths {
1090 if p == nil {
1091 return nil
1092 }
1093 ret := make(Paths, len(p))
1094 for i, path := range p {
1095 ret[i] = path
1096 }
1097 return ret
1098}
1099
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001100type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001101 path string
1102 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001103}
1104
1105func (p basePath) Ext() string {
1106 return filepath.Ext(p.path)
1107}
1108
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001109func (p basePath) Base() string {
1110 return filepath.Base(p.path)
1111}
1112
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001113func (p basePath) Rel() string {
1114 if p.rel != "" {
1115 return p.rel
1116 }
1117 return p.path
1118}
1119
Colin Cross0875c522017-11-28 17:34:01 -08001120func (p basePath) String() string {
1121 return p.path
1122}
1123
Colin Cross0db55682017-12-05 15:36:55 -08001124func (p basePath) withRel(rel string) basePath {
1125 p.path = filepath.Join(p.path, rel)
1126 p.rel = rel
1127 return p
1128}
1129
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001130// SourcePath is a Path representing a file path rooted from SrcDir
1131type SourcePath struct {
1132 basePath
Paul Duffin580efc82021-03-24 09:04:03 +00001133
1134 // The sources root, i.e. Config.SrcDir()
1135 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001136}
1137
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001138func (p SourcePath) RelativeToTop() Path {
1139 ensureTestOnly()
1140 return p
1141}
1142
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001143var _ Path = SourcePath{}
1144
Colin Cross0db55682017-12-05 15:36:55 -08001145func (p SourcePath) withRel(rel string) SourcePath {
1146 p.basePath = p.basePath.withRel(rel)
1147 return p
1148}
1149
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001150// safePathForSource is for paths that we expect are safe -- only for use by go
1151// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001152func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1153 p, err := validateSafePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001154 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Crossfe4bc362018-09-12 10:02:13 -07001155 if err != nil {
1156 return ret, err
1157 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001158
Colin Cross7b3dcc32019-01-24 13:14:39 -08001159 // absolute path already checked by validateSafePath
1160 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001161 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001162 }
1163
Colin Crossfe4bc362018-09-12 10:02:13 -07001164 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001165}
1166
Colin Cross192e97a2018-02-22 14:21:02 -08001167// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1168func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001169 p, err := validatePath(pathComponents...)
Paul Duffin74abc5d2021-03-24 09:24:59 +00001170 ret := SourcePath{basePath{p, ""}, ctx.Config().srcDir}
Colin Cross94a32102018-02-22 14:21:02 -08001171 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001172 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001173 }
1174
Colin Cross7b3dcc32019-01-24 13:14:39 -08001175 // absolute path already checked by validatePath
1176 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001177 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001178 }
1179
Colin Cross192e97a2018-02-22 14:21:02 -08001180 return ret, nil
1181}
1182
1183// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1184// path does not exist.
1185func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1186 var files []string
1187
1188 if gctx, ok := ctx.(PathGlobContext); ok {
1189 // Use glob to produce proper dependencies, even though we only want
1190 // a single file.
1191 files, err = gctx.GlobWithDeps(path.String(), nil)
1192 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -07001193 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -08001194 // We cannot add build statements in this context, so we fall back to
1195 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -07001196 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
1197 ctx.AddNinjaFileDeps(result.Deps...)
1198 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -08001199 }
1200
1201 if err != nil {
1202 return false, fmt.Errorf("glob: %s", err.Error())
1203 }
1204
1205 return len(files) > 0, nil
1206}
1207
1208// PathForSource joins the provided path components and validates that the result
1209// neither escapes the source dir nor is in the out dir.
1210// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1211func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1212 path, err := pathForSource(ctx, pathComponents...)
1213 if err != nil {
1214 reportPathError(ctx, err)
1215 }
1216
Colin Crosse3924e12018-08-15 20:18:53 -07001217 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001218 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001219 }
1220
Liz Kammera830f3a2020-11-10 10:50:34 -08001221 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001222 exists, err := existsWithDependencies(ctx, path)
1223 if err != nil {
1224 reportPathError(ctx, err)
1225 }
1226 if !exists {
1227 modCtx.AddMissingDependencies([]string{path.String()})
1228 }
Colin Cross988414c2020-01-11 01:11:46 +00001229 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001230 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001231 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001232 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001233 }
1234 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001235}
1236
Liz Kammer7aa52882021-02-11 09:16:14 -05001237// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1238// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1239// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1240// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001241func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001242 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001243 if err != nil {
1244 reportPathError(ctx, err)
1245 return OptionalPath{}
1246 }
Colin Crossc48c1432018-02-23 07:09:01 +00001247
Colin Crosse3924e12018-08-15 20:18:53 -07001248 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001249 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001250 return OptionalPath{}
1251 }
1252
Colin Cross192e97a2018-02-22 14:21:02 -08001253 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001254 if err != nil {
1255 reportPathError(ctx, err)
1256 return OptionalPath{}
1257 }
Colin Cross192e97a2018-02-22 14:21:02 -08001258 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +00001259 return OptionalPath{}
1260 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001261 return OptionalPathForPath(path)
1262}
1263
1264func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001265 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001266}
1267
1268// Join creates a new SourcePath with paths... joined with the current path. The
1269// provided paths... may not use '..' to escape from the current path.
1270func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001271 path, err := validatePath(paths...)
1272 if err != nil {
1273 reportPathError(ctx, err)
1274 }
Colin Cross0db55682017-12-05 15:36:55 -08001275 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001276}
1277
Colin Cross2fafa3e2019-03-05 12:39:51 -08001278// join is like Join but does less path validation.
1279func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1280 path, err := validateSafePath(paths...)
1281 if err != nil {
1282 reportPathError(ctx, err)
1283 }
1284 return p.withRel(path)
1285}
1286
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001287// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1288// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001289func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001290 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001291 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001292 relDir = srcPath.path
1293 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001294 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001295 return OptionalPath{}
1296 }
Paul Duffin580efc82021-03-24 09:04:03 +00001297 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001298 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001299 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001300 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001301 }
Colin Cross461b4452018-02-23 09:22:42 -08001302 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001303 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001304 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001305 return OptionalPath{}
1306 }
1307 if len(paths) == 0 {
1308 return OptionalPath{}
1309 }
Paul Duffin580efc82021-03-24 09:04:03 +00001310 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001311 return OptionalPathForPath(PathForSource(ctx, relPath))
1312}
1313
Colin Cross70dda7e2019-10-01 22:05:35 -07001314// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001315type OutputPath struct {
1316 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001317
1318 // The soong build directory, i.e. Config.BuildDir()
1319 buildDir string
1320
Colin Crossd63c9a72020-01-29 16:52:50 -08001321 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001322}
1323
Colin Cross702e0f82017-10-18 17:27:54 -07001324func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001325 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001326 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001327 return p
1328}
1329
Colin Cross3063b782018-08-15 11:19:12 -07001330func (p OutputPath) WithoutRel() OutputPath {
1331 p.basePath.rel = filepath.Base(p.basePath.path)
1332 return p
1333}
1334
Paul Duffind65c58b2021-03-24 09:22:07 +00001335func (p OutputPath) getBuildDir() string {
1336 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001337}
1338
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001339func (p OutputPath) RelativeToTop() Path {
1340 return p.outputPathRelativeToTop()
1341}
1342
1343func (p OutputPath) outputPathRelativeToTop() OutputPath {
1344 p.fullPath = StringPathRelativeToTop(p.buildDir, p.fullPath)
1345 p.buildDir = OutSoongDir
1346 return p
1347}
1348
Paul Duffin0267d492021-02-02 10:05:52 +00001349func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1350 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1351}
1352
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001353var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001354var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001355var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001356
Chris Parsons8f232a22020-06-23 17:37:05 -04001357// toolDepPath is a Path representing a dependency of the build tool.
1358type toolDepPath struct {
1359 basePath
1360}
1361
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001362func (t toolDepPath) RelativeToTop() Path {
1363 ensureTestOnly()
1364 return t
1365}
1366
Chris Parsons8f232a22020-06-23 17:37:05 -04001367var _ Path = toolDepPath{}
1368
1369// pathForBuildToolDep returns a toolDepPath representing the given path string.
1370// There is no validation for the path, as it is "trusted": It may fail
1371// normal validation checks. For example, it may be an absolute path.
1372// Only use this function to construct paths for dependencies of the build
1373// tool invocation.
1374func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001375 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001376}
1377
Jeff Gaston734e3802017-04-10 15:47:24 -07001378// PathForOutput joins the provided paths and returns an OutputPath that is
1379// validated to not escape the build dir.
1380// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1381func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001382 path, err := validatePath(pathComponents...)
1383 if err != nil {
1384 reportPathError(ctx, err)
1385 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001386 fullPath := filepath.Join(ctx.Config().buildDir, path)
1387 path = fullPath[len(fullPath)-len(path):]
Paul Duffin74abc5d2021-03-24 09:24:59 +00001388 return OutputPath{basePath{path, ""}, ctx.Config().buildDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001389}
1390
Colin Cross40e33732019-02-15 11:08:35 -08001391// PathsForOutput returns Paths rooted from buildDir
1392func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1393 ret := make(WritablePaths, len(paths))
1394 for i, path := range paths {
1395 ret[i] = PathForOutput(ctx, path)
1396 }
1397 return ret
1398}
1399
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001400func (p OutputPath) writablePath() {}
1401
1402func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001403 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001404}
1405
1406// Join creates a new OutputPath with paths... joined with the current path. The
1407// provided paths... may not use '..' to escape from the current path.
1408func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001409 path, err := validatePath(paths...)
1410 if err != nil {
1411 reportPathError(ctx, err)
1412 }
Colin Cross0db55682017-12-05 15:36:55 -08001413 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001414}
1415
Colin Cross8854a5a2019-02-11 14:14:16 -08001416// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1417func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1418 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001419 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001420 }
1421 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001422 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001423 return ret
1424}
1425
Colin Cross40e33732019-02-15 11:08:35 -08001426// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1427func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1428 path, err := validatePath(paths...)
1429 if err != nil {
1430 reportPathError(ctx, err)
1431 }
1432
1433 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001434 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001435 return ret
1436}
1437
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001438// PathForIntermediates returns an OutputPath representing the top-level
1439// intermediates directory.
1440func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001441 path, err := validatePath(paths...)
1442 if err != nil {
1443 reportPathError(ctx, err)
1444 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001445 return PathForOutput(ctx, ".intermediates", path)
1446}
1447
Colin Cross07e51612019-03-05 12:46:40 -08001448var _ genPathProvider = SourcePath{}
1449var _ objPathProvider = SourcePath{}
1450var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001451
Colin Cross07e51612019-03-05 12:46:40 -08001452// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001453// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001454func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001455 p, err := validatePath(pathComponents...)
1456 if err != nil {
1457 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001458 }
Colin Cross8a497952019-03-05 22:25:09 -08001459 paths, err := expandOneSrcPath(ctx, p, nil)
1460 if err != nil {
1461 if depErr, ok := err.(missingDependencyError); ok {
1462 if ctx.Config().AllowMissingDependencies() {
1463 ctx.AddMissingDependencies(depErr.missingDeps)
1464 } else {
1465 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1466 }
1467 } else {
1468 reportPathError(ctx, err)
1469 }
1470 return nil
1471 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001472 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001473 return nil
1474 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001475 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001476 }
1477 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001478}
1479
Liz Kammera830f3a2020-11-10 10:50:34 -08001480func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001481 p, err := validatePath(paths...)
1482 if err != nil {
1483 reportPathError(ctx, err)
1484 }
1485
1486 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1487 if err != nil {
1488 reportPathError(ctx, err)
1489 }
1490
1491 path.basePath.rel = p
1492
1493 return path
1494}
1495
Colin Cross2fafa3e2019-03-05 12:39:51 -08001496// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1497// will return the path relative to subDir in the module's source directory. If any input paths are not located
1498// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001499func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001500 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001501 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001502 for i, path := range paths {
1503 rel := Rel(ctx, subDirFullPath.String(), path.String())
1504 paths[i] = subDirFullPath.join(ctx, rel)
1505 }
1506 return paths
1507}
1508
1509// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1510// module's source directory. If the input path is not located inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001511func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001512 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001513 rel := Rel(ctx, subDirFullPath.String(), path.String())
1514 return subDirFullPath.Join(ctx, rel)
1515}
1516
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001517// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1518// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001519func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001520 if p == nil {
1521 return OptionalPath{}
1522 }
1523 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1524}
1525
Liz Kammera830f3a2020-11-10 10:50:34 -08001526func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001527 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001528}
1529
Liz Kammera830f3a2020-11-10 10:50:34 -08001530func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001531 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001532}
1533
Liz Kammera830f3a2020-11-10 10:50:34 -08001534func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001535 // TODO: Use full directory if the new ctx is not the current ctx?
1536 return PathForModuleRes(ctx, p.path, name)
1537}
1538
1539// ModuleOutPath is a Path representing a module's output directory.
1540type ModuleOutPath struct {
1541 OutputPath
1542}
1543
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001544func (p ModuleOutPath) RelativeToTop() Path {
1545 p.OutputPath = p.outputPathRelativeToTop()
1546 return p
1547}
1548
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001549var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001550var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001551
Liz Kammera830f3a2020-11-10 10:50:34 -08001552func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001553 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1554}
1555
Liz Kammera830f3a2020-11-10 10:50:34 -08001556// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1557type ModuleOutPathContext interface {
1558 PathContext
1559
1560 ModuleName() string
1561 ModuleDir() string
1562 ModuleSubDir() string
1563}
1564
1565func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001566 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1567}
1568
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001569type BazelOutPath struct {
1570 OutputPath
1571}
1572
1573var _ Path = BazelOutPath{}
1574var _ objPathProvider = BazelOutPath{}
1575
Liz Kammera830f3a2020-11-10 10:50:34 -08001576func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001577 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1578}
1579
Logan Chien7eefdc42018-07-11 18:10:41 +08001580// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1581// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001582func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001583 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001584
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001585 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001586 if len(arches) == 0 {
1587 panic("device build with no primary arch")
1588 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001589 currentArch := ctx.Arch()
1590 archNameAndVariant := currentArch.ArchType.String()
1591 if currentArch.ArchVariant != "" {
1592 archNameAndVariant += "_" + currentArch.ArchVariant
1593 }
Logan Chien5237bed2018-07-11 17:15:57 +08001594
1595 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001596 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001597 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001598 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001599 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001600 } else {
1601 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001602 }
Logan Chien5237bed2018-07-11 17:15:57 +08001603
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001604 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001605
1606 var ext string
1607 if isGzip {
1608 ext = ".lsdump.gz"
1609 } else {
1610 ext = ".lsdump"
1611 }
1612
1613 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1614 version, binderBitness, archNameAndVariant, "source-based",
1615 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001616}
1617
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001618// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1619// bazel-owned outputs.
1620func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1621 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1622 execRootPath := filepath.Join(execRootPathComponents...)
1623 validatedExecRootPath, err := validatePath(execRootPath)
1624 if err != nil {
1625 reportPathError(ctx, err)
1626 }
1627
Paul Duffin74abc5d2021-03-24 09:24:59 +00001628 outputPath := OutputPath{basePath{"", ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001629 ctx.Config().buildDir,
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001630 ctx.Config().BazelContext.OutputBase()}
1631
1632 return BazelOutPath{
1633 OutputPath: outputPath.withRel(validatedExecRootPath),
1634 }
1635}
1636
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001637// PathForModuleOut returns a Path representing the paths... under the module's
1638// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001639func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001640 p, err := validatePath(paths...)
1641 if err != nil {
1642 reportPathError(ctx, err)
1643 }
Colin Cross702e0f82017-10-18 17:27:54 -07001644 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001645 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001646 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001647}
1648
1649// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1650// directory. Mainly used for generated sources.
1651type ModuleGenPath struct {
1652 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001653}
1654
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001655func (p ModuleGenPath) RelativeToTop() Path {
1656 p.OutputPath = p.outputPathRelativeToTop()
1657 return p
1658}
1659
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001660var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001661var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001662var _ genPathProvider = ModuleGenPath{}
1663var _ objPathProvider = ModuleGenPath{}
1664
1665// PathForModuleGen returns a Path representing the paths... under the module's
1666// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001667func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001668 p, err := validatePath(paths...)
1669 if err != nil {
1670 reportPathError(ctx, err)
1671 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001672 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001673 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001674 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001675 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001676 }
1677}
1678
Liz Kammera830f3a2020-11-10 10:50:34 -08001679func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001680 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001681 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001682}
1683
Liz Kammera830f3a2020-11-10 10:50:34 -08001684func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001685 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1686}
1687
1688// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1689// directory. Used for compiled objects.
1690type ModuleObjPath struct {
1691 ModuleOutPath
1692}
1693
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001694func (p ModuleObjPath) RelativeToTop() Path {
1695 p.OutputPath = p.outputPathRelativeToTop()
1696 return p
1697}
1698
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001699var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001700var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001701
1702// PathForModuleObj returns a Path representing the paths... under the module's
1703// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001704func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001705 p, err := validatePath(pathComponents...)
1706 if err != nil {
1707 reportPathError(ctx, err)
1708 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001709 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1710}
1711
1712// ModuleResPath is a a Path representing the 'res' directory in a module's
1713// output directory.
1714type ModuleResPath struct {
1715 ModuleOutPath
1716}
1717
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001718func (p ModuleResPath) RelativeToTop() Path {
1719 p.OutputPath = p.outputPathRelativeToTop()
1720 return p
1721}
1722
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001723var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001724var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001725
1726// PathForModuleRes returns a Path representing the paths... under the module's
1727// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001728func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001729 p, err := validatePath(pathComponents...)
1730 if err != nil {
1731 reportPathError(ctx, err)
1732 }
1733
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001734 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1735}
1736
Colin Cross70dda7e2019-10-01 22:05:35 -07001737// InstallPath is a Path representing a installed file path rooted from the build directory
1738type InstallPath struct {
1739 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001740
Paul Duffind65c58b2021-03-24 09:22:07 +00001741 // The soong build directory, i.e. Config.BuildDir()
1742 buildDir string
1743
Jiyong Park957bcd92020-10-20 18:23:33 +09001744 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1745 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1746 partitionDir string
1747
1748 // makePath indicates whether this path is for Soong (false) or Make (true).
1749 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001750}
1751
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001752// Will panic if called from outside a test environment.
1753func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001754 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001755 return
1756 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001757 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001758}
1759
1760func (p InstallPath) RelativeToTop() Path {
1761 ensureTestOnly()
1762 p.buildDir = OutSoongDir
1763 return p
1764}
1765
Paul Duffind65c58b2021-03-24 09:22:07 +00001766func (p InstallPath) getBuildDir() string {
1767 return p.buildDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001768}
1769
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001770func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1771 panic("Not implemented")
1772}
1773
Paul Duffin9b478b02019-12-10 13:41:51 +00001774var _ Path = InstallPath{}
1775var _ WritablePath = InstallPath{}
1776
Colin Cross70dda7e2019-10-01 22:05:35 -07001777func (p InstallPath) writablePath() {}
1778
1779func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001780 if p.makePath {
1781 // Make path starts with out/ instead of out/soong.
Paul Duffind65c58b2021-03-24 09:22:07 +00001782 return filepath.Join(p.buildDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001783 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001784 return filepath.Join(p.buildDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001785 }
1786}
1787
1788// PartitionDir returns the path to the partition where the install path is rooted at. It is
1789// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1790// The ./soong is dropped if the install path is for Make.
1791func (p InstallPath) PartitionDir() string {
1792 if p.makePath {
Paul Duffind65c58b2021-03-24 09:22:07 +00001793 return filepath.Join(p.buildDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001794 } else {
Paul Duffind65c58b2021-03-24 09:22:07 +00001795 return filepath.Join(p.buildDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001796 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001797}
1798
1799// Join creates a new InstallPath with paths... joined with the current path. The
1800// provided paths... may not use '..' to escape from the current path.
1801func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1802 path, err := validatePath(paths...)
1803 if err != nil {
1804 reportPathError(ctx, err)
1805 }
1806 return p.withRel(path)
1807}
1808
1809func (p InstallPath) withRel(rel string) InstallPath {
1810 p.basePath = p.basePath.withRel(rel)
1811 return p
1812}
1813
Colin Crossff6c33d2019-10-02 16:01:35 -07001814// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1815// i.e. out/ instead of out/soong/.
1816func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001817 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001818 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001819}
1820
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001821// PathForModuleInstall returns a Path representing the install path for the
1822// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001823func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001824 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001825 arch := ctx.Arch().ArchType
1826 forceOS, forceArch := ctx.InstallForceOS()
1827 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001828 os = *forceOS
1829 }
Jiyong Park87788b52020-09-01 12:37:45 +09001830 if forceArch != nil {
1831 arch = *forceArch
1832 }
Colin Cross6e359402020-02-10 15:29:54 -08001833 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001834
Jiyong Park87788b52020-09-01 12:37:45 +09001835 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001836
Jingwen Chencda22c92020-11-23 00:22:30 -05001837 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001838 ret = ret.ToMakePath()
1839 }
1840
1841 return ret
1842}
1843
Jiyong Park87788b52020-09-01 12:37:45 +09001844func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001845 pathComponents ...string) InstallPath {
1846
Jiyong Park957bcd92020-10-20 18:23:33 +09001847 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001848
Colin Cross6e359402020-02-10 15:29:54 -08001849 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001850 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001851 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001852 osName := os.String()
1853 if os == Linux {
1854 // instead of linux_glibc
1855 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001856 }
Jiyong Park87788b52020-09-01 12:37:45 +09001857 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1858 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1859 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1860 // Let's keep using x86 for the existing cases until we have a need to support
1861 // other architectures.
1862 archName := arch.String()
1863 if os.Class == Host && (arch == X86_64 || arch == Common) {
1864 archName = "x86"
1865 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001866 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001867 }
Colin Cross609c49a2020-02-13 13:20:11 -08001868 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001869 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001870 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001871
Jiyong Park957bcd92020-10-20 18:23:33 +09001872 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001873 if err != nil {
1874 reportPathError(ctx, err)
1875 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001876
Jiyong Park957bcd92020-10-20 18:23:33 +09001877 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001878 basePath: basePath{partionPath, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001879 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001880 partitionDir: partionPath,
1881 makePath: false,
1882 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001883
Jiyong Park957bcd92020-10-20 18:23:33 +09001884 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001885}
1886
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001887func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001888 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001889 basePath: basePath{prefix, ""},
Paul Duffind65c58b2021-03-24 09:22:07 +00001890 buildDir: ctx.Config().buildDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001891 partitionDir: prefix,
1892 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001893 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001894 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001895}
1896
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001897func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1898 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1899}
1900
1901func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1902 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1903}
1904
Colin Cross70dda7e2019-10-01 22:05:35 -07001905func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001906 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1907
1908 return "/" + rel
1909}
1910
Colin Cross6e359402020-02-10 15:29:54 -08001911func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001912 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001913 if ctx.InstallInTestcases() {
1914 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001915 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001916 } else if os.Class == Device {
1917 if ctx.InstallInData() {
1918 partition = "data"
1919 } else if ctx.InstallInRamdisk() {
1920 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1921 partition = "recovery/root/first_stage_ramdisk"
1922 } else {
1923 partition = "ramdisk"
1924 }
1925 if !ctx.InstallInRoot() {
1926 partition += "/system"
1927 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001928 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001929 // The module is only available after switching root into
1930 // /first_stage_ramdisk. To expose the module before switching root
1931 // on a device without a dedicated recovery partition, install the
1932 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001933 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001934 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001935 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001936 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001937 }
1938 if !ctx.InstallInRoot() {
1939 partition += "/system"
1940 }
Inseob Kimf84e9c02021-04-08 21:13:22 +09001941 } else if ctx.InstallInDebugRamdisk() {
1942 // The module is only available after switching root into
1943 // /first_stage_ramdisk. To expose the module before switching root
1944 // on a device without a dedicated recovery partition, install the
1945 // recovery variant.
1946 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1947 partition = "debug_ramdisk/first_stage_ramdisk"
1948 } else {
1949 partition = "debug_ramdisk"
1950 }
Colin Cross6e359402020-02-10 15:29:54 -08001951 } else if ctx.InstallInRecovery() {
1952 if ctx.InstallInRoot() {
1953 partition = "recovery/root"
1954 } else {
1955 // the layout of recovery partion is the same as that of system partition
1956 partition = "recovery/root/system"
1957 }
1958 } else if ctx.SocSpecific() {
1959 partition = ctx.DeviceConfig().VendorPath()
1960 } else if ctx.DeviceSpecific() {
1961 partition = ctx.DeviceConfig().OdmPath()
1962 } else if ctx.ProductSpecific() {
1963 partition = ctx.DeviceConfig().ProductPath()
1964 } else if ctx.SystemExtSpecific() {
1965 partition = ctx.DeviceConfig().SystemExtPath()
1966 } else if ctx.InstallInRoot() {
1967 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001968 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001969 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001970 }
Colin Cross6e359402020-02-10 15:29:54 -08001971 if ctx.InstallInSanitizerDir() {
1972 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001973 }
Colin Cross43f08db2018-11-12 10:13:39 -08001974 }
1975 return partition
1976}
1977
Colin Cross609c49a2020-02-13 13:20:11 -08001978type InstallPaths []InstallPath
1979
1980// Paths returns the InstallPaths as a Paths
1981func (p InstallPaths) Paths() Paths {
1982 if p == nil {
1983 return nil
1984 }
1985 ret := make(Paths, len(p))
1986 for i, path := range p {
1987 ret[i] = path
1988 }
1989 return ret
1990}
1991
1992// Strings returns the string forms of the install paths.
1993func (p InstallPaths) Strings() []string {
1994 if p == nil {
1995 return nil
1996 }
1997 ret := make([]string, len(p))
1998 for i, path := range p {
1999 ret[i] = path.String()
2000 }
2001 return ret
2002}
2003
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002004// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002005// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002006func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07002007 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002008 path := filepath.Clean(path)
2009 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002010 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002011 }
2012 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002013 // TODO: filepath.Join isn't necessarily correct with embedded ninja
2014 // variables. '..' may remove the entire ninja variable, even if it
2015 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002016 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002017}
2018
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08002019// validatePath validates that a path does not include ninja variables, and that
2020// each path component does not attempt to leave its component. Returns a joined
2021// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08002022func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07002023 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002024 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002025 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07002026 }
2027 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08002028 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07002029}
Colin Cross5b529592017-05-09 13:34:34 -07002030
Colin Cross0875c522017-11-28 17:34:01 -08002031func PathForPhony(ctx PathContext, phony string) WritablePath {
2032 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002033 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08002034 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00002035 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08002036}
2037
Colin Cross74e3fe42017-12-11 15:51:44 -08002038type PhonyPath struct {
2039 basePath
2040}
2041
2042func (p PhonyPath) writablePath() {}
2043
Paul Duffind65c58b2021-03-24 09:22:07 +00002044func (p PhonyPath) getBuildDir() string {
2045 // A phone path cannot contain any / so cannot be relative to the build directory.
2046 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00002047}
2048
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002049func (p PhonyPath) RelativeToTop() Path {
2050 ensureTestOnly()
2051 // A phony path cannot contain any / so does not have a build directory so switching to a new
2052 // build directory has no effect so just return this path.
2053 return p
2054}
2055
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01002056func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
2057 panic("Not implemented")
2058}
2059
Colin Cross74e3fe42017-12-11 15:51:44 -08002060var _ Path = PhonyPath{}
2061var _ WritablePath = PhonyPath{}
2062
Colin Cross5b529592017-05-09 13:34:34 -07002063type testPath struct {
2064 basePath
2065}
2066
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002067func (p testPath) RelativeToTop() Path {
2068 ensureTestOnly()
2069 return p
2070}
2071
Colin Cross5b529592017-05-09 13:34:34 -07002072func (p testPath) String() string {
2073 return p.path
2074}
2075
Paul Duffin85d8f0d2021-03-24 10:18:18 +00002076var _ Path = testPath{}
2077
Colin Cross40e33732019-02-15 11:08:35 -08002078// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
2079// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07002080func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08002081 p, err := validateSafePath(paths...)
2082 if err != nil {
2083 panic(err)
2084 }
Colin Cross5b529592017-05-09 13:34:34 -07002085 return testPath{basePath{path: p, rel: p}}
2086}
2087
Colin Cross40e33732019-02-15 11:08:35 -08002088// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
2089func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07002090 p := make(Paths, len(strs))
2091 for i, s := range strs {
2092 p[i] = PathForTesting(s)
2093 }
2094
2095 return p
2096}
Colin Cross43f08db2018-11-12 10:13:39 -08002097
Colin Cross40e33732019-02-15 11:08:35 -08002098type testPathContext struct {
2099 config Config
Colin Cross40e33732019-02-15 11:08:35 -08002100}
2101
Colin Cross40e33732019-02-15 11:08:35 -08002102func (x *testPathContext) Config() Config { return x.config }
2103func (x *testPathContext) AddNinjaFileDeps(...string) {}
2104
2105// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
2106// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08002107func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08002108 return &testPathContext{
2109 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08002110 }
2111}
2112
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002113type testModuleInstallPathContext struct {
2114 baseModuleContext
2115
2116 inData bool
2117 inTestcases bool
2118 inSanitizerDir bool
2119 inRamdisk bool
2120 inVendorRamdisk bool
Inseob Kimf84e9c02021-04-08 21:13:22 +09002121 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002122 inRecovery bool
2123 inRoot bool
2124 forceOS *OsType
2125 forceArch *ArchType
2126}
2127
2128func (m testModuleInstallPathContext) Config() Config {
2129 return m.baseModuleContext.config
2130}
2131
2132func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2133
2134func (m testModuleInstallPathContext) InstallInData() bool {
2135 return m.inData
2136}
2137
2138func (m testModuleInstallPathContext) InstallInTestcases() bool {
2139 return m.inTestcases
2140}
2141
2142func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2143 return m.inSanitizerDir
2144}
2145
2146func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2147 return m.inRamdisk
2148}
2149
2150func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2151 return m.inVendorRamdisk
2152}
2153
Inseob Kimf84e9c02021-04-08 21:13:22 +09002154func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2155 return m.inDebugRamdisk
2156}
2157
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002158func (m testModuleInstallPathContext) InstallInRecovery() bool {
2159 return m.inRecovery
2160}
2161
2162func (m testModuleInstallPathContext) InstallInRoot() bool {
2163 return m.inRoot
2164}
2165
2166func (m testModuleInstallPathContext) InstallBypassMake() bool {
2167 return false
2168}
2169
2170func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2171 return m.forceOS, m.forceArch
2172}
2173
2174// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2175// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2176// delegated to it will panic.
2177func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2178 ctx := &testModuleInstallPathContext{}
2179 ctx.config = config
2180 ctx.os = Android
2181 return ctx
2182}
2183
Colin Cross43f08db2018-11-12 10:13:39 -08002184// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2185// targetPath is not inside basePath.
2186func Rel(ctx PathContext, basePath string, targetPath string) string {
2187 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2188 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002189 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002190 return ""
2191 }
2192 return rel
2193}
2194
2195// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2196// targetPath is not inside basePath.
2197func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002198 rel, isRel, err := maybeRelErr(basePath, targetPath)
2199 if err != nil {
2200 reportPathError(ctx, err)
2201 }
2202 return rel, isRel
2203}
2204
2205func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002206 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2207 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002208 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002209 }
2210 rel, err := filepath.Rel(basePath, targetPath)
2211 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002212 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002213 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002214 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002215 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002216 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002217}
Colin Cross988414c2020-01-11 01:11:46 +00002218
2219// Writes a file to the output directory. Attempting to write directly to the output directory
2220// will fail due to the sandbox of the soong_build process.
2221func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
2222 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
2223}
2224
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002225func RemoveAllOutputDir(path WritablePath) error {
2226 return os.RemoveAll(absolutePath(path.String()))
2227}
2228
2229func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2230 dir := absolutePath(path.String())
2231 if _, err := os.Stat(dir); os.IsNotExist(err) {
2232 return os.MkdirAll(dir, os.ModePerm)
2233 } else {
2234 return err
2235 }
2236}
2237
Colin Cross988414c2020-01-11 01:11:46 +00002238func absolutePath(path string) string {
2239 if filepath.IsAbs(path) {
2240 return path
2241 }
2242 return filepath.Join(absSrcDir, path)
2243}
Chris Parsons216e10a2020-07-09 17:12:52 -04002244
2245// A DataPath represents the path of a file to be used as data, for example
2246// a test library to be installed alongside a test.
2247// The data file should be installed (copied from `<SrcPath>`) to
2248// `<install_root>/<RelativeInstallPath>/<filename>`, or
2249// `<install_root>/<filename>` if RelativeInstallPath is empty.
2250type DataPath struct {
2251 // The path of the data file that should be copied into the data directory
2252 SrcPath Path
2253 // The install path of the data file, relative to the install root.
2254 RelativeInstallPath string
2255}
Colin Crossdcf71b22021-02-01 13:59:03 -08002256
2257// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2258func PathsIfNonNil(paths ...Path) Paths {
2259 if len(paths) == 0 {
2260 // Fast path for empty argument list
2261 return nil
2262 } else if len(paths) == 1 {
2263 // Fast path for a single argument
2264 if paths[0] != nil {
2265 return paths
2266 } else {
2267 return nil
2268 }
2269 }
2270 ret := make(Paths, 0, len(paths))
2271 for _, path := range paths {
2272 if path != nil {
2273 ret = append(ret, path)
2274 }
2275 }
2276 if len(ret) == 0 {
2277 return nil
2278 }
2279 return ret
2280}