blob: 375297f6a7cd56cfb2f814ebb78bd83f23cf3a12 [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 (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000019 "io/ioutil"
20 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070021 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070022 "reflect"
Chris Wailesb2703ad2021-07-30 13:25:42 -070023 "regexp"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070024 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070025 "strings"
26
27 "github.com/google/blueprint"
Colin Cross0e446152021-05-03 13:35:32 -070028 "github.com/google/blueprint/bootstrap"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070029 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080030)
31
Colin Cross988414c2020-01-11 01:11:46 +000032var absSrcDir string
33
Dan Willemsen34cc69e2015-09-23 15:26:20 -070034// PathContext is the subset of a (Module|Singleton)Context required by the
35// Path methods.
36type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080037 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080038 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080039}
40
Colin Cross7f19f372016-11-01 11:10:25 -070041type PathGlobContext interface {
42 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
43}
44
Colin Crossaabf6792017-11-29 00:27:14 -080045var _ PathContext = SingletonContext(nil)
46var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070047
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010048// "Null" path context is a minimal path context for a given config.
49type NullPathContext struct {
50 config Config
51}
52
53func (NullPathContext) AddNinjaFileDeps(...string) {}
54func (ctx NullPathContext) Config() Config { return ctx.config }
55
Liz Kammera830f3a2020-11-10 10:50:34 -080056// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
57// Path methods. These path methods can be called before any mutators have run.
58type EarlyModulePathContext interface {
59 PathContext
60 PathGlobContext
61
62 ModuleDir() string
63 ModuleErrorf(fmt string, args ...interface{})
64}
65
66var _ EarlyModulePathContext = ModuleContext(nil)
67
68// Glob globs files and directories matching globPattern relative to ModuleDir(),
69// paths in the excludes parameter will be omitted.
70func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
71 ret, err := ctx.GlobWithDeps(globPattern, excludes)
72 if err != nil {
73 ctx.ModuleErrorf("glob: %s", err.Error())
74 }
75 return pathsForModuleSrcFromFullPath(ctx, ret, true)
76}
77
78// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
79// Paths in the excludes parameter will be omitted.
80func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
81 ret, err := ctx.GlobWithDeps(globPattern, excludes)
82 if err != nil {
83 ctx.ModuleErrorf("glob: %s", err.Error())
84 }
85 return pathsForModuleSrcFromFullPath(ctx, ret, false)
86}
87
88// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
89// the Path methods that rely on module dependencies having been resolved.
90type ModuleWithDepsPathContext interface {
91 EarlyModulePathContext
Paul Duffin40131a32021-07-09 17:10:35 +010092 VisitDirectDepsBlueprint(visit func(blueprint.Module))
93 OtherModuleDependencyTag(m blueprint.Module) blueprint.DependencyTag
Liz Kammera830f3a2020-11-10 10:50:34 -080094}
95
96// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
97// the Path methods that rely on module dependencies having been resolved and ability to report
98// missing dependency errors.
99type ModuleMissingDepsPathContext interface {
100 ModuleWithDepsPathContext
101 AddMissingDependencies(missingDeps []string)
102}
103
Dan Willemsen00269f22017-07-06 16:59:48 -0700104type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700105 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700106
107 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700108 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700109 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800110 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700111 InstallInVendorRamdisk() bool
Inseob Kim08758f02021-04-08 21:13:22 +0900112 InstallInDebugRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900113 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700114 InstallInRoot() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900115 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700116}
117
118var _ ModuleInstallPathContext = ModuleContext(nil)
119
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700120// errorfContext is the interface containing the Errorf method matching the
121// Errorf method in blueprint.SingletonContext.
122type errorfContext interface {
123 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800124}
125
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700126var _ errorfContext = blueprint.SingletonContext(nil)
127
128// moduleErrorf is the interface containing the ModuleErrorf method matching
129// the ModuleErrorf method in blueprint.ModuleContext.
130type moduleErrorf interface {
131 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800132}
133
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700134var _ moduleErrorf = blueprint.ModuleContext(nil)
135
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700136// reportPathError will register an error with the attached context. It
137// attempts ctx.ModuleErrorf for a better error message first, then falls
138// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800139func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100140 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800141}
142
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100143// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800144// attempts ctx.ModuleErrorf for a better error message first, then falls
145// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100146func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700147 if mctx, ok := ctx.(moduleErrorf); ok {
148 mctx.ModuleErrorf(format, args...)
149 } else if ectx, ok := ctx.(errorfContext); ok {
150 ectx.Errorf(format, args...)
151 } else {
152 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700153 }
154}
155
Colin Cross5e708052019-08-06 13:59:50 -0700156func pathContextName(ctx PathContext, module blueprint.Module) string {
157 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
158 return x.ModuleName(module)
159 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
160 return x.OtherModuleName(module)
161 }
162 return "unknown"
163}
164
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700165type Path interface {
166 // Returns the path in string form
167 String() string
168
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700169 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700170 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700171
172 // Base returns the last element of the path
173 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800174
175 // Rel returns the portion of the path relative to the directory it was created from. For
176 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800177 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800178 Rel() string
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000179
180 // RelativeToTop returns a new path relative to the top, it is provided solely for use in tests.
181 //
182 // It is guaranteed to always return the same type as it is called on, e.g. if called on an
183 // InstallPath then the returned value can be converted to an InstallPath.
184 //
185 // A standard build has the following structure:
186 // ../top/
187 // out/ - make install files go here.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200188 // out/soong - this is the soongOutDir passed to NewTestConfig()
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000189 // ... - the source files
190 //
191 // This function converts a path so that it appears relative to the ../top/ directory, i.e.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200192 // * Make install paths, which have the pattern "soongOutDir/../<path>" are converted into the top
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000193 // relative path "out/<path>"
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200194 // * Soong install paths and other writable paths, which have the pattern "soongOutDir/<path>" are
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000195 // converted into the top relative path "out/soong/<path>".
196 // * Source paths are already relative to the top.
197 // * Phony paths are not relative to anything.
198 // * toolDepPath have an absolute but known value in so don't need making relative to anything in
199 // order to test.
200 RelativeToTop() Path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700201}
202
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000203const (
204 OutDir = "out"
205 OutSoongDir = OutDir + "/soong"
206)
207
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700208// WritablePath is a type of path that can be used as an output for build rules.
209type WritablePath interface {
210 Path
211
Paul Duffin9b478b02019-12-10 13:41:51 +0000212 // return the path to the build directory.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200213 getSoongOutDir() string
Paul Duffin9b478b02019-12-10 13:41:51 +0000214
Jeff Gaston734e3802017-04-10 15:47:24 -0700215 // the writablePath method doesn't directly do anything,
216 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700217 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100218
219 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700220}
221
222type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800223 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700224}
225type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800226 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700227}
228type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800229 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700230}
231
232// GenPathWithExt derives a new file path in ctx's generated sources directory
233// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800234func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700235 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700236 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700237 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100238 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700239 return PathForModuleGen(ctx)
240}
241
242// ObjPathWithExt derives a new file path in ctx's object directory from the
243// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800244func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700245 if path, ok := p.(objPathProvider); ok {
246 return path.objPathWithExt(ctx, subdir, ext)
247 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100248 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700249 return PathForModuleObj(ctx)
250}
251
252// ResPathWithName derives a new path in ctx's output resource directory, using
253// the current path to create the directory name, and the `name` argument for
254// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800255func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700256 if path, ok := p.(resPathProvider); ok {
257 return path.resPathWithName(ctx, name)
258 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100259 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700260 return PathForModuleRes(ctx)
261}
262
263// OptionalPath is a container that may or may not contain a valid Path.
264type OptionalPath struct {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100265 path Path // nil if invalid.
266 invalidReason string // Not applicable if path != nil. "" if the reason is unknown.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700267}
268
269// OptionalPathForPath returns an OptionalPath containing the path.
270func OptionalPathForPath(path Path) OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100271 return OptionalPath{path: path}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700272}
273
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100274// InvalidOptionalPath returns an OptionalPath that is invalid with the given reason.
275func InvalidOptionalPath(reason string) OptionalPath {
276
277 return OptionalPath{invalidReason: reason}
278}
279
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700280// Valid returns whether there is a valid path
281func (p OptionalPath) Valid() bool {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100282 return p.path != nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700283}
284
285// Path returns the Path embedded in this OptionalPath. You must be sure that
286// there is a valid path, since this method will panic if there is not.
287func (p OptionalPath) Path() Path {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100288 if p.path == nil {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100289 msg := "Requesting an invalid path"
290 if p.invalidReason != "" {
291 msg += ": " + p.invalidReason
292 }
293 panic(msg)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700294 }
295 return p.path
296}
297
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +0100298// InvalidReason returns the reason that the optional path is invalid, or "" if it is valid.
299func (p OptionalPath) InvalidReason() string {
300 if p.path != nil {
301 return ""
302 }
303 if p.invalidReason == "" {
304 return "unknown"
305 }
306 return p.invalidReason
307}
308
Paul Duffinef081852021-05-13 11:11:15 +0100309// AsPaths converts the OptionalPath into Paths.
310//
311// It returns nil if this is not valid, or a single length slice containing the Path embedded in
312// this OptionalPath.
313func (p OptionalPath) AsPaths() Paths {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100314 if p.path == nil {
Paul Duffinef081852021-05-13 11:11:15 +0100315 return nil
316 }
317 return Paths{p.path}
318}
319
Paul Duffinafdd4062021-03-30 19:44:07 +0100320// RelativeToTop returns an OptionalPath with the path that was embedded having been replaced by the
321// result of calling Path.RelativeToTop on it.
322func (p OptionalPath) RelativeToTop() OptionalPath {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100323 if p.path == nil {
Paul Duffina5b81352021-03-28 23:57:19 +0100324 return p
325 }
326 p.path = p.path.RelativeToTop()
327 return p
328}
329
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700330// String returns the string version of the Path, or "" if it isn't valid.
331func (p OptionalPath) String() string {
Martin Stjernholm2fee27f2021-09-16 14:11:12 +0100332 if p.path != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700333 return p.path.String()
334 } else {
335 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700336 }
337}
Colin Cross6e18ca42015-07-14 18:55:36 -0700338
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700339// Paths is a slice of Path objects, with helpers to operate on the collection.
340type Paths []Path
341
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000342// RelativeToTop creates a new Paths containing the result of calling Path.RelativeToTop on each
343// item in this slice.
344func (p Paths) RelativeToTop() Paths {
345 ensureTestOnly()
346 if p == nil {
347 return p
348 }
349 ret := make(Paths, len(p))
350 for i, path := range p {
351 ret[i] = path.RelativeToTop()
352 }
353 return ret
354}
355
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000356func (paths Paths) containsPath(path Path) bool {
357 for _, p := range paths {
358 if p == path {
359 return true
360 }
361 }
362 return false
363}
364
Liz Kammer7aa52882021-02-11 09:16:14 -0500365// PathsForSource returns Paths rooted from SrcDir, *not* rooted from the module's local source
366// directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700367func PathsForSource(ctx PathContext, paths []string) Paths {
368 ret := make(Paths, len(paths))
369 for i, path := range paths {
370 ret[i] = PathForSource(ctx, path)
371 }
372 return ret
373}
374
Liz Kammer7aa52882021-02-11 09:16:14 -0500375// ExistentPathsForSources returns a list of Paths rooted from SrcDir, *not* rooted from the
376// module's local source directory, that are found in the tree. If any are not found, they are
377// 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 -0800378func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800379 ret := make(Paths, 0, len(paths))
380 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800381 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800382 if p.Valid() {
383 ret = append(ret, p.Path())
384 }
385 }
386 return ret
387}
388
Liz Kammer620dea62021-04-14 17:36:10 -0400389// PathsForModuleSrc returns a Paths{} containing the resolved references in paths:
Colin Crossd079e0b2022-08-16 10:27:33 -0700390// - filepath, relative to local module directory, resolves as a filepath relative to the local
391// source directory
392// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
393// source directory.
394// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
395// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
396// filepath.
397//
Liz Kammer620dea62021-04-14 17:36:10 -0400398// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700399// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400400// path_deps mutator.
401// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700402// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400403// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700404// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800405func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800406 return PathsForModuleSrcExcludes(ctx, paths, nil)
407}
408
Liz Kammer619be462022-01-28 15:13:39 -0500409type SourceInput struct {
410 Context ModuleMissingDepsPathContext
411 Paths []string
412 ExcludePaths []string
413 IncludeDirs bool
414}
415
Liz Kammer620dea62021-04-14 17:36:10 -0400416// PathsForModuleSrcExcludes returns a Paths{} containing the resolved references in paths, minus
417// those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700418// - filepath, relative to local module directory, resolves as a filepath relative to the local
419// source directory
420// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
421// source directory. Not valid in excludes.
422// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
423// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
424// filepath.
425//
Liz Kammer620dea62021-04-14 17:36:10 -0400426// excluding the items (similarly resolved
427// Properties passed as the paths argument must have been annotated with struct tag
428// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
429// path_deps mutator.
430// If a requested module is not found as a dependency:
Colin Crossd079e0b2022-08-16 10:27:33 -0700431// - if ctx.Config().AllowMissingDependencies() is true, this module to be marked as having
Liz Kammer620dea62021-04-14 17:36:10 -0400432// missing dependencies
Colin Crossd079e0b2022-08-16 10:27:33 -0700433// - otherwise, a ModuleError is thrown.
Liz Kammera830f3a2020-11-10 10:50:34 -0800434func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500435 return PathsRelativeToModuleSourceDir(SourceInput{
436 Context: ctx,
437 Paths: paths,
438 ExcludePaths: excludes,
439 IncludeDirs: true,
440 })
441}
442
443func PathsRelativeToModuleSourceDir(input SourceInput) Paths {
444 ret, missingDeps := PathsAndMissingDepsRelativeToModuleSourceDir(input)
445 if input.Context.Config().AllowMissingDependencies() {
446 input.Context.AddMissingDependencies(missingDeps)
Colin Crossba71a3f2019-03-18 12:12:48 -0700447 } else {
448 for _, m := range missingDeps {
Liz Kammer619be462022-01-28 15:13:39 -0500449 input.Context.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
Colin Crossba71a3f2019-03-18 12:12:48 -0700450 }
451 }
452 return ret
453}
454
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000455// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
456type OutputPaths []OutputPath
457
458// Paths returns the OutputPaths as a Paths
459func (p OutputPaths) Paths() Paths {
460 if p == nil {
461 return nil
462 }
463 ret := make(Paths, len(p))
464 for i, path := range p {
465 ret[i] = path
466 }
467 return ret
468}
469
470// Strings returns the string forms of the writable paths.
471func (p OutputPaths) Strings() []string {
472 if p == nil {
473 return nil
474 }
475 ret := make([]string, len(p))
476 for i, path := range p {
477 ret[i] = path.String()
478 }
479 return ret
480}
481
Colin Crossa44551f2021-10-25 15:36:21 -0700482// PathForGoBinary returns the path to the installed location of a bootstrap_go_binary module.
483func PathForGoBinary(ctx PathContext, goBinary bootstrap.GoBinaryTool) Path {
484 goBinaryInstallDir := pathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "bin", false)
485 rel := Rel(ctx, goBinaryInstallDir.String(), goBinary.InstallPath())
486 return goBinaryInstallDir.Join(ctx, rel)
487}
488
Liz Kammera830f3a2020-11-10 10:50:34 -0800489// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
490// If the dependency is not found, a missingErrorDependency is returned.
491// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
492func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
Paul Duffind5cf92e2021-07-09 17:38:55 +0100493 module := GetModuleFromPathDep(ctx, moduleName, tag)
Liz Kammera830f3a2020-11-10 10:50:34 -0800494 if module == nil {
495 return nil, missingDependencyError{[]string{moduleName}}
496 }
Colin Crossfa65cee2021-03-22 17:05:59 -0700497 if aModule, ok := module.(Module); ok && !aModule.Enabled() {
498 return nil, missingDependencyError{[]string{moduleName}}
499 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800500 if outProducer, ok := module.(OutputFileProducer); ok {
501 outputFiles, err := outProducer.OutputFiles(tag)
502 if err != nil {
503 return nil, fmt.Errorf("path dependency %q: %s", path, err)
504 }
505 return outputFiles, nil
506 } else if tag != "" {
507 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
Colin Cross0e446152021-05-03 13:35:32 -0700508 } else if goBinary, ok := module.(bootstrap.GoBinaryTool); ok {
Colin Crossa44551f2021-10-25 15:36:21 -0700509 goBinaryPath := PathForGoBinary(ctx, goBinary)
510 return Paths{goBinaryPath}, nil
Liz Kammera830f3a2020-11-10 10:50:34 -0800511 } else if srcProducer, ok := module.(SourceFileProducer); ok {
512 return srcProducer.Srcs(), nil
513 } else {
514 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
515 }
516}
517
Paul Duffind5cf92e2021-07-09 17:38:55 +0100518// GetModuleFromPathDep will return the module that was added as a dependency automatically for
519// properties tagged with `android:"path"` or manually using ExtractSourceDeps or
520// ExtractSourcesDeps.
521//
522// The moduleName and tag supplied to this should be the values returned from SrcIsModuleWithTag.
523// Or, if no tag is expected then the moduleName should be the value returned by SrcIsModule and
524// the tag must be "".
525//
526// If tag is "" then the returned module will be the dependency that was added for ":moduleName".
527// Otherwise, it is the dependency that was added for ":moduleName{tag}".
Paul Duffind5cf92e2021-07-09 17:38:55 +0100528func GetModuleFromPathDep(ctx ModuleWithDepsPathContext, moduleName, tag string) blueprint.Module {
Paul Duffin40131a32021-07-09 17:10:35 +0100529 var found blueprint.Module
530 // The sourceOrOutputDepTag uniquely identifies the module dependency as it contains both the
531 // module name and the tag. Dependencies added automatically for properties tagged with
532 // `android:"path"` are deduped so are guaranteed to be unique. It is possible for duplicate
533 // dependencies to be added manually using ExtractSourcesDeps or ExtractSourceDeps but even then
534 // it will always be the case that the dependencies will be identical, i.e. the same tag and same
535 // moduleName referring to the same dependency module.
536 //
537 // It does not matter whether the moduleName is a fully qualified name or if the module
538 // dependency is a prebuilt module. All that matters is the same information is supplied to
539 // create the tag here as was supplied to create the tag when the dependency was added so that
540 // this finds the matching dependency module.
541 expectedTag := sourceOrOutputDepTag(moduleName, tag)
542 ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
543 depTag := ctx.OtherModuleDependencyTag(module)
544 if depTag == expectedTag {
545 found = module
546 }
547 })
548 return found
Paul Duffind5cf92e2021-07-09 17:38:55 +0100549}
550
Liz Kammer620dea62021-04-14 17:36:10 -0400551// PathsAndMissingDepsForModuleSrcExcludes returns a Paths{} containing the resolved references in
552// paths, minus those listed in excludes. Elements of paths and excludes are resolved as:
Colin Crossd079e0b2022-08-16 10:27:33 -0700553// - filepath, relative to local module directory, resolves as a filepath relative to the local
554// source directory
555// - glob, relative to the local module directory, resolves as filepath(s), relative to the local
556// source directory. Not valid in excludes.
557// - other modules using the ":name{.tag}" syntax. These modules must implement SourceFileProducer
558// or OutputFileProducer. These resolve as a filepath to an output filepath or generated source
559// filepath.
560//
Liz Kammer620dea62021-04-14 17:36:10 -0400561// and a list of the module names of missing module dependencies are returned as the second return.
562// Properties passed as the paths argument must have been annotated with struct tag
Colin Cross41955e82019-05-29 14:40:35 -0700563// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
Liz Kammer620dea62021-04-14 17:36:10 -0400564// path_deps mutator.
Liz Kammer619be462022-01-28 15:13:39 -0500565func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) (Paths, []string) {
566 return PathsAndMissingDepsRelativeToModuleSourceDir(SourceInput{
567 Context: ctx,
568 Paths: paths,
569 ExcludePaths: excludes,
570 IncludeDirs: true,
571 })
572}
573
574func PathsAndMissingDepsRelativeToModuleSourceDir(input SourceInput) (Paths, []string) {
575 prefix := pathForModuleSrc(input.Context).String()
Colin Cross8a497952019-03-05 22:25:09 -0800576
577 var expandedExcludes []string
Liz Kammer619be462022-01-28 15:13:39 -0500578 if input.ExcludePaths != nil {
579 expandedExcludes = make([]string, 0, len(input.ExcludePaths))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700580 }
Colin Cross8a497952019-03-05 22:25:09 -0800581
Colin Crossba71a3f2019-03-18 12:12:48 -0700582 var missingExcludeDeps []string
Liz Kammer619be462022-01-28 15:13:39 -0500583 for _, e := range input.ExcludePaths {
Colin Cross41955e82019-05-29 14:40:35 -0700584 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammer619be462022-01-28 15:13:39 -0500585 modulePaths, err := getPathsFromModuleDep(input.Context, e, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800586 if m, ok := err.(missingDependencyError); ok {
587 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
588 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500589 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800590 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800591 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800592 }
593 } else {
594 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
595 }
596 }
597
Liz Kammer619be462022-01-28 15:13:39 -0500598 if input.Paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700599 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800600 }
601
Colin Crossba71a3f2019-03-18 12:12:48 -0700602 var missingDeps []string
603
Liz Kammer619be462022-01-28 15:13:39 -0500604 expandedSrcFiles := make(Paths, 0, len(input.Paths))
605 for _, s := range input.Paths {
606 srcFiles, err := expandOneSrcPath(sourcePathInput{
607 context: input.Context,
608 path: s,
609 expandedExcludes: expandedExcludes,
610 includeDirs: input.IncludeDirs,
611 })
Colin Cross8a497952019-03-05 22:25:09 -0800612 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700613 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800614 } else if err != nil {
Liz Kammer619be462022-01-28 15:13:39 -0500615 reportPathError(input.Context, err)
Colin Cross8a497952019-03-05 22:25:09 -0800616 }
617 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
618 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700619
620 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800621}
622
623type missingDependencyError struct {
624 missingDeps []string
625}
626
627func (e missingDependencyError) Error() string {
628 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
629}
630
Liz Kammer619be462022-01-28 15:13:39 -0500631type sourcePathInput struct {
632 context ModuleWithDepsPathContext
633 path string
634 expandedExcludes []string
635 includeDirs bool
636}
637
Liz Kammera830f3a2020-11-10 10:50:34 -0800638// Expands one path string to Paths rooted from the module's local source
639// directory, excluding those listed in the expandedExcludes.
640// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
Liz Kammer619be462022-01-28 15:13:39 -0500641func expandOneSrcPath(input sourcePathInput) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900642 excludePaths := func(paths Paths) Paths {
Liz Kammer619be462022-01-28 15:13:39 -0500643 if len(input.expandedExcludes) == 0 {
Jooyung Han7607dd32020-07-05 10:23:14 +0900644 return paths
645 }
646 remainder := make(Paths, 0, len(paths))
647 for _, p := range paths {
Liz Kammer619be462022-01-28 15:13:39 -0500648 if !InList(p.String(), input.expandedExcludes) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900649 remainder = append(remainder, p)
650 }
651 }
652 return remainder
653 }
Liz Kammer619be462022-01-28 15:13:39 -0500654 if m, t := SrcIsModuleWithTag(input.path); m != "" {
655 modulePaths, err := getPathsFromModuleDep(input.context, input.path, m, t)
Liz Kammera830f3a2020-11-10 10:50:34 -0800656 if err != nil {
657 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800658 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800659 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800660 }
Colin Cross8a497952019-03-05 22:25:09 -0800661 } else {
Liz Kammer619be462022-01-28 15:13:39 -0500662 p := pathForModuleSrc(input.context, input.path)
663 if pathtools.IsGlob(input.path) {
664 paths := GlobFiles(input.context, p.String(), input.expandedExcludes)
665 return PathsWithModuleSrcSubDir(input.context, paths, ""), nil
666 } else {
667 if exists, _, err := input.context.Config().fs.Exists(p.String()); err != nil {
668 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
669 } else if !exists && !input.context.Config().TestAllowNonExistentPaths {
670 ReportPathErrorf(input.context, "module source path %q does not exist", p)
671 } else if !input.includeDirs {
672 if isDir, err := input.context.Config().fs.IsDir(p.String()); exists && err != nil {
673 ReportPathErrorf(input.context, "%s: %s", p, err.Error())
674 } else if isDir {
675 ReportPathErrorf(input.context, "module source path %q is a directory", p)
676 }
677 }
Colin Cross8a497952019-03-05 22:25:09 -0800678
Liz Kammer619be462022-01-28 15:13:39 -0500679 if InList(p.String(), input.expandedExcludes) {
680 return nil, nil
681 }
682 return Paths{p}, nil
Colin Cross8a497952019-03-05 22:25:09 -0800683 }
Colin Cross8a497952019-03-05 22:25:09 -0800684 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700685}
686
687// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
688// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800689// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700690// It intended for use in globs that only list files that exist, so it allows '$' in
691// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800692func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200693 prefix := ctx.ModuleDir() + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700694 if prefix == "./" {
695 prefix = ""
696 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700697 ret := make(Paths, 0, len(paths))
698 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800699 if !incDirs && strings.HasSuffix(p, "/") {
700 continue
701 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700702 path := filepath.Clean(p)
703 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100704 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700705 continue
706 }
Colin Crosse3924e12018-08-15 20:18:53 -0700707
Colin Crossfe4bc362018-09-12 10:02:13 -0700708 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700709 if err != nil {
710 reportPathError(ctx, err)
711 continue
712 }
713
Colin Cross07e51612019-03-05 12:46:40 -0800714 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700715
Colin Cross07e51612019-03-05 12:46:40 -0800716 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700717 }
718 return ret
719}
720
Liz Kammera830f3a2020-11-10 10:50:34 -0800721// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
722// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
723func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800724 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700725 return PathsForModuleSrc(ctx, input)
726 }
727 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
728 // is created, we're run again.
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +0200729 path := filepath.Join(ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800730 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700731}
732
733// Strings returns the Paths in string form
734func (p Paths) Strings() []string {
735 if p == nil {
736 return nil
737 }
738 ret := make([]string, len(p))
739 for i, path := range p {
740 ret[i] = path.String()
741 }
742 return ret
743}
744
Colin Crossc0efd1d2020-07-03 11:56:24 -0700745func CopyOfPaths(paths Paths) Paths {
746 return append(Paths(nil), paths...)
747}
748
Colin Crossb6715442017-10-24 11:13:31 -0700749// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
750// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700751func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800752 // 128 was chosen based on BenchmarkFirstUniquePaths results.
753 if len(list) > 128 {
754 return firstUniquePathsMap(list)
755 }
756 return firstUniquePathsList(list)
757}
758
Colin Crossc0efd1d2020-07-03 11:56:24 -0700759// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
760// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900761func SortedUniquePaths(list Paths) Paths {
762 unique := FirstUniquePaths(list)
763 sort.Slice(unique, func(i, j int) bool {
764 return unique[i].String() < unique[j].String()
765 })
766 return unique
767}
768
Colin Cross27027c72020-02-28 15:34:17 -0800769func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700770 k := 0
771outer:
772 for i := 0; i < len(list); i++ {
773 for j := 0; j < k; j++ {
774 if list[i] == list[j] {
775 continue outer
776 }
777 }
778 list[k] = list[i]
779 k++
780 }
781 return list[:k]
782}
783
Colin Cross27027c72020-02-28 15:34:17 -0800784func firstUniquePathsMap(list Paths) Paths {
785 k := 0
786 seen := make(map[Path]bool, len(list))
787 for i := 0; i < len(list); i++ {
788 if seen[list[i]] {
789 continue
790 }
791 seen[list[i]] = true
792 list[k] = list[i]
793 k++
794 }
795 return list[:k]
796}
797
Colin Cross5d583952020-11-24 16:21:24 -0800798// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
799// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
800func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
801 // 128 was chosen based on BenchmarkFirstUniquePaths results.
802 if len(list) > 128 {
803 return firstUniqueInstallPathsMap(list)
804 }
805 return firstUniqueInstallPathsList(list)
806}
807
808func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
809 k := 0
810outer:
811 for i := 0; i < len(list); i++ {
812 for j := 0; j < k; j++ {
813 if list[i] == list[j] {
814 continue outer
815 }
816 }
817 list[k] = list[i]
818 k++
819 }
820 return list[:k]
821}
822
823func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
824 k := 0
825 seen := make(map[InstallPath]bool, len(list))
826 for i := 0; i < len(list); i++ {
827 if seen[list[i]] {
828 continue
829 }
830 seen[list[i]] = true
831 list[k] = list[i]
832 k++
833 }
834 return list[:k]
835}
836
Colin Crossb6715442017-10-24 11:13:31 -0700837// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
838// modifies the Paths slice contents in place, and returns a subslice of the original slice.
839func LastUniquePaths(list Paths) Paths {
840 totalSkip := 0
841 for i := len(list) - 1; i >= totalSkip; i-- {
842 skip := 0
843 for j := i - 1; j >= totalSkip; j-- {
844 if list[i] == list[j] {
845 skip++
846 } else {
847 list[j+skip] = list[j]
848 }
849 }
850 totalSkip += skip
851 }
852 return list[totalSkip:]
853}
854
Colin Crossa140bb02018-04-17 10:52:26 -0700855// ReversePaths returns a copy of a Paths in reverse order.
856func ReversePaths(list Paths) Paths {
857 if list == nil {
858 return nil
859 }
860 ret := make(Paths, len(list))
861 for i := range list {
862 ret[i] = list[len(list)-1-i]
863 }
864 return ret
865}
866
Jeff Gaston294356f2017-09-27 17:05:30 -0700867func indexPathList(s Path, list []Path) int {
868 for i, l := range list {
869 if l == s {
870 return i
871 }
872 }
873
874 return -1
875}
876
877func inPathList(p Path, list []Path) bool {
878 return indexPathList(p, list) != -1
879}
880
881func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000882 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
883}
884
885func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700886 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000887 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700888 filtered = append(filtered, l)
889 } else {
890 remainder = append(remainder, l)
891 }
892 }
893
894 return
895}
896
Colin Cross93e85952017-08-15 13:34:18 -0700897// HasExt returns true of any of the paths have extension ext, otherwise false
898func (p Paths) HasExt(ext string) bool {
899 for _, path := range p {
900 if path.Ext() == ext {
901 return true
902 }
903 }
904
905 return false
906}
907
908// FilterByExt returns the subset of the paths that have extension ext
909func (p Paths) FilterByExt(ext string) Paths {
910 ret := make(Paths, 0, len(p))
911 for _, path := range p {
912 if path.Ext() == ext {
913 ret = append(ret, path)
914 }
915 }
916 return ret
917}
918
919// FilterOutByExt returns the subset of the paths that do not have extension ext
920func (p Paths) FilterOutByExt(ext string) Paths {
921 ret := make(Paths, 0, len(p))
922 for _, path := range p {
923 if path.Ext() != ext {
924 ret = append(ret, path)
925 }
926 }
927 return ret
928}
929
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700930// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
931// (including subdirectories) are in a contiguous subslice of the list, and can be found in
932// O(log(N)) time using a binary search on the directory prefix.
933type DirectorySortedPaths Paths
934
935func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
936 ret := append(DirectorySortedPaths(nil), paths...)
937 sort.Slice(ret, func(i, j int) bool {
938 return ret[i].String() < ret[j].String()
939 })
940 return ret
941}
942
943// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
944// that are in the specified directory and its subdirectories.
945func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
946 prefix := filepath.Clean(dir) + "/"
947 start := sort.Search(len(p), func(i int) bool {
948 return prefix < p[i].String()
949 })
950
951 ret := p[start:]
952
953 end := sort.Search(len(ret), func(i int) bool {
954 return !strings.HasPrefix(ret[i].String(), prefix)
955 })
956
957 ret = ret[:end]
958
959 return Paths(ret)
960}
961
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500962// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700963type WritablePaths []WritablePath
964
Paul Duffin85d8f0d2021-03-24 10:18:18 +0000965// RelativeToTop creates a new WritablePaths containing the result of calling Path.RelativeToTop on
966// each item in this slice.
967func (p WritablePaths) RelativeToTop() WritablePaths {
968 ensureTestOnly()
969 if p == nil {
970 return p
971 }
972 ret := make(WritablePaths, len(p))
973 for i, path := range p {
974 ret[i] = path.RelativeToTop().(WritablePath)
975 }
976 return ret
977}
978
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700979// Strings returns the string forms of the writable paths.
980func (p WritablePaths) Strings() []string {
981 if p == nil {
982 return nil
983 }
984 ret := make([]string, len(p))
985 for i, path := range p {
986 ret[i] = path.String()
987 }
988 return ret
989}
990
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800991// Paths returns the WritablePaths as a Paths
992func (p WritablePaths) Paths() Paths {
993 if p == nil {
994 return nil
995 }
996 ret := make(Paths, len(p))
997 for i, path := range p {
998 ret[i] = path
999 }
1000 return ret
1001}
1002
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001003type basePath struct {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001004 path string
1005 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001006}
1007
1008func (p basePath) Ext() string {
1009 return filepath.Ext(p.path)
1010}
1011
Colin Cross4f6fc9c2016-10-26 10:05:25 -07001012func (p basePath) Base() string {
1013 return filepath.Base(p.path)
1014}
1015
Colin Crossfaeb7aa2017-02-01 14:12:44 -08001016func (p basePath) Rel() string {
1017 if p.rel != "" {
1018 return p.rel
1019 }
1020 return p.path
1021}
1022
Colin Cross0875c522017-11-28 17:34:01 -08001023func (p basePath) String() string {
1024 return p.path
1025}
1026
Colin Cross0db55682017-12-05 15:36:55 -08001027func (p basePath) withRel(rel string) basePath {
1028 p.path = filepath.Join(p.path, rel)
1029 p.rel = rel
1030 return p
1031}
1032
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001033// SourcePath is a Path representing a file path rooted from SrcDir
1034type SourcePath struct {
1035 basePath
Paul Duffin580efc82021-03-24 09:04:03 +00001036
1037 // The sources root, i.e. Config.SrcDir()
1038 srcDir string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001039}
1040
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001041func (p SourcePath) RelativeToTop() Path {
1042 ensureTestOnly()
1043 return p
1044}
1045
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001046var _ Path = SourcePath{}
1047
Colin Cross0db55682017-12-05 15:36:55 -08001048func (p SourcePath) withRel(rel string) SourcePath {
1049 p.basePath = p.basePath.withRel(rel)
1050 return p
1051}
1052
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001053// safePathForSource is for paths that we expect are safe -- only for use by go
1054// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -07001055func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
1056 p, err := validateSafePath(pathComponents...)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +02001057 ret := SourcePath{basePath{p, ""}, "."}
Colin Crossfe4bc362018-09-12 10:02:13 -07001058 if err != nil {
1059 return ret, err
1060 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001061
Colin Cross7b3dcc32019-01-24 13:14:39 -08001062 // absolute path already checked by validateSafePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001063 // special-case api surface gen files for now
1064 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001065 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -07001066 }
1067
Colin Crossfe4bc362018-09-12 10:02:13 -07001068 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001069}
1070
Colin Cross192e97a2018-02-22 14:21:02 -08001071// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
1072func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +00001073 p, err := validatePath(pathComponents...)
Lukacs T. Berkif7e36d82021-08-16 17:05:09 +02001074 ret := SourcePath{basePath{p, ""}, "."}
Colin Cross94a32102018-02-22 14:21:02 -08001075 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -08001076 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -08001077 }
1078
Colin Cross7b3dcc32019-01-24 13:14:39 -08001079 // absolute path already checked by validatePath
Inseob Kim5eb7ee92022-04-27 10:30:34 +09001080 // special-case for now
1081 if strings.HasPrefix(ret.String(), ctx.Config().soongOutDir) && !strings.Contains(ret.String(), ctx.Config().soongOutDir+"/.export") {
Mikhail Naganovab1f5182019-02-08 13:17:55 -08001082 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +00001083 }
1084
Colin Cross192e97a2018-02-22 14:21:02 -08001085 return ret, nil
1086}
1087
1088// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
1089// path does not exist.
1090func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
1091 var files []string
1092
1093 if gctx, ok := ctx.(PathGlobContext); ok {
1094 // Use glob to produce proper dependencies, even though we only want
1095 // a single file.
1096 files, err = gctx.GlobWithDeps(path.String(), nil)
1097 } else {
Colin Cross82ea3fb2021-04-05 17:48:26 -07001098 var result pathtools.GlobResult
Colin Cross192e97a2018-02-22 14:21:02 -08001099 // We cannot add build statements in this context, so we fall back to
1100 // AddNinjaFileDeps
Colin Cross82ea3fb2021-04-05 17:48:26 -07001101 result, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
1102 ctx.AddNinjaFileDeps(result.Deps...)
1103 files = result.Matches
Colin Cross192e97a2018-02-22 14:21:02 -08001104 }
1105
1106 if err != nil {
1107 return false, fmt.Errorf("glob: %s", err.Error())
1108 }
1109
1110 return len(files) > 0, nil
1111}
1112
1113// PathForSource joins the provided path components and validates that the result
1114// neither escapes the source dir nor is in the out dir.
1115// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
1116func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1117 path, err := pathForSource(ctx, pathComponents...)
1118 if err != nil {
1119 reportPathError(ctx, err)
1120 }
1121
Colin Crosse3924e12018-08-15 20:18:53 -07001122 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001123 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001124 }
1125
Liz Kammera830f3a2020-11-10 10:50:34 -08001126 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -08001127 exists, err := existsWithDependencies(ctx, path)
1128 if err != nil {
1129 reportPathError(ctx, err)
1130 }
1131 if !exists {
1132 modCtx.AddMissingDependencies([]string{path.String()})
1133 }
Colin Cross988414c2020-01-11 01:11:46 +00001134 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001135 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Pedro Loureiro5d190cc2021-02-15 15:41:33 +00001136 } else if !exists && !ctx.Config().TestAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001137 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -08001138 }
1139 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001140}
1141
Spandan Dasc6c10fa2022-10-21 21:52:13 +00001142// MaybeExistentPathForSource joins the provided path components and validates that the result
1143// neither escapes the source dir nor is in the out dir.
1144// It does not validate whether the path exists.
1145func MaybeExistentPathForSource(ctx PathContext, pathComponents ...string) SourcePath {
1146 path, err := pathForSource(ctx, pathComponents...)
1147 if err != nil {
1148 reportPathError(ctx, err)
1149 }
1150
1151 if pathtools.IsGlob(path.String()) {
1152 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
1153 }
1154 return path
1155}
1156
Liz Kammer7aa52882021-02-11 09:16:14 -05001157// ExistentPathForSource returns an OptionalPath with the SourcePath, rooted from SrcDir, *not*
1158// rooted from the module's local source directory, if the path exists, or an empty OptionalPath if
1159// it doesn't exist. Dependencies are added so that the ninja file will be regenerated if the state
1160// of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -08001161func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -08001162 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -08001163 if err != nil {
1164 reportPathError(ctx, err)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001165 // No need to put the error message into the returned path since it has been reported already.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001166 return OptionalPath{}
1167 }
Colin Crossc48c1432018-02-23 07:09:01 +00001168
Colin Crosse3924e12018-08-15 20:18:53 -07001169 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001170 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -07001171 return OptionalPath{}
1172 }
1173
Colin Cross192e97a2018-02-22 14:21:02 -08001174 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +00001175 if err != nil {
1176 reportPathError(ctx, err)
1177 return OptionalPath{}
1178 }
Colin Cross192e97a2018-02-22 14:21:02 -08001179 if !exists {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001180 return InvalidOptionalPath(path.String() + " does not exist")
Colin Crossc48c1432018-02-23 07:09:01 +00001181 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001182 return OptionalPathForPath(path)
1183}
1184
1185func (p SourcePath) String() string {
Paul Duffin580efc82021-03-24 09:04:03 +00001186 return filepath.Join(p.srcDir, p.path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001187}
1188
1189// Join creates a new SourcePath with paths... joined with the current path. The
1190// provided paths... may not use '..' to escape from the current path.
1191func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001192 path, err := validatePath(paths...)
1193 if err != nil {
1194 reportPathError(ctx, err)
1195 }
Colin Cross0db55682017-12-05 15:36:55 -08001196 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001197}
1198
Colin Cross2fafa3e2019-03-05 12:39:51 -08001199// join is like Join but does less path validation.
1200func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
1201 path, err := validateSafePath(paths...)
1202 if err != nil {
1203 reportPathError(ctx, err)
1204 }
1205 return p.withRel(path)
1206}
1207
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001208// OverlayPath returns the overlay for `path' if it exists. This assumes that the
1209// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001210func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001211 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -08001212 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001213 relDir = srcPath.path
1214 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001215 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001216 // No need to put the error message into the returned path since it has been reported already.
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001217 return OptionalPath{}
1218 }
Paul Duffin580efc82021-03-24 09:04:03 +00001219 dir := filepath.Join(p.srcDir, p.path, relDir)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001220 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -07001221 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001222 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -08001223 }
Colin Cross461b4452018-02-23 09:22:42 -08001224 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001225 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001226 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001227 return OptionalPath{}
1228 }
1229 if len(paths) == 0 {
Martin Stjernholmc32dd1c2021-09-15 02:39:00 +01001230 return InvalidOptionalPath(dir + " does not exist")
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001231 }
Paul Duffin580efc82021-03-24 09:04:03 +00001232 relPath := Rel(ctx, p.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001233 return OptionalPathForPath(PathForSource(ctx, relPath))
1234}
1235
Colin Cross70dda7e2019-10-01 22:05:35 -07001236// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001237type OutputPath struct {
1238 basePath
Paul Duffind65c58b2021-03-24 09:22:07 +00001239
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001240 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001241 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001242
Colin Crossd63c9a72020-01-29 16:52:50 -08001243 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001244}
1245
Colin Cross702e0f82017-10-18 17:27:54 -07001246func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001247 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001248 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001249 return p
1250}
1251
Colin Cross3063b782018-08-15 11:19:12 -07001252func (p OutputPath) WithoutRel() OutputPath {
1253 p.basePath.rel = filepath.Base(p.basePath.path)
1254 return p
1255}
1256
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001257func (p OutputPath) getSoongOutDir() string {
1258 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001259}
1260
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001261func (p OutputPath) RelativeToTop() Path {
1262 return p.outputPathRelativeToTop()
1263}
1264
1265func (p OutputPath) outputPathRelativeToTop() OutputPath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001266 p.fullPath = StringPathRelativeToTop(p.soongOutDir, p.fullPath)
1267 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001268 return p
1269}
1270
Paul Duffin0267d492021-02-02 10:05:52 +00001271func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1272 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1273}
1274
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001275var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001276var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001277var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001278
Chris Parsons8f232a22020-06-23 17:37:05 -04001279// toolDepPath is a Path representing a dependency of the build tool.
1280type toolDepPath struct {
1281 basePath
1282}
1283
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001284func (t toolDepPath) RelativeToTop() Path {
1285 ensureTestOnly()
1286 return t
1287}
1288
Chris Parsons8f232a22020-06-23 17:37:05 -04001289var _ Path = toolDepPath{}
1290
1291// pathForBuildToolDep returns a toolDepPath representing the given path string.
1292// There is no validation for the path, as it is "trusted": It may fail
1293// normal validation checks. For example, it may be an absolute path.
1294// Only use this function to construct paths for dependencies of the build
1295// tool invocation.
1296func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
Paul Duffin74abc5d2021-03-24 09:24:59 +00001297 return toolDepPath{basePath{path, ""}}
Chris Parsons8f232a22020-06-23 17:37:05 -04001298}
1299
Jeff Gaston734e3802017-04-10 15:47:24 -07001300// PathForOutput joins the provided paths and returns an OutputPath that is
1301// validated to not escape the build dir.
1302// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1303func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001304 path, err := validatePath(pathComponents...)
1305 if err != nil {
1306 reportPathError(ctx, err)
1307 }
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001308 fullPath := filepath.Join(ctx.Config().soongOutDir, path)
Colin Crossd63c9a72020-01-29 16:52:50 -08001309 path = fullPath[len(fullPath)-len(path):]
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001310 return OutputPath{basePath{path, ""}, ctx.Config().soongOutDir, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001311}
1312
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001313// PathsForOutput returns Paths rooted from soongOutDir
Colin Cross40e33732019-02-15 11:08:35 -08001314func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1315 ret := make(WritablePaths, len(paths))
1316 for i, path := range paths {
1317 ret[i] = PathForOutput(ctx, path)
1318 }
1319 return ret
1320}
1321
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001322func (p OutputPath) writablePath() {}
1323
1324func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001325 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001326}
1327
1328// Join creates a new OutputPath with paths... joined with the current path. The
1329// provided paths... may not use '..' to escape from the current path.
1330func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001331 path, err := validatePath(paths...)
1332 if err != nil {
1333 reportPathError(ctx, err)
1334 }
Colin Cross0db55682017-12-05 15:36:55 -08001335 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001336}
1337
Colin Cross8854a5a2019-02-11 14:14:16 -08001338// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1339func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1340 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001341 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001342 }
1343 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001344 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001345 return ret
1346}
1347
Colin Cross40e33732019-02-15 11:08:35 -08001348// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1349func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1350 path, err := validatePath(paths...)
1351 if err != nil {
1352 reportPathError(ctx, err)
1353 }
1354
1355 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001356 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001357 return ret
1358}
1359
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001360// PathForIntermediates returns an OutputPath representing the top-level
1361// intermediates directory.
1362func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001363 path, err := validatePath(paths...)
1364 if err != nil {
1365 reportPathError(ctx, err)
1366 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001367 return PathForOutput(ctx, ".intermediates", path)
1368}
1369
Colin Cross07e51612019-03-05 12:46:40 -08001370var _ genPathProvider = SourcePath{}
1371var _ objPathProvider = SourcePath{}
1372var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001373
Colin Cross07e51612019-03-05 12:46:40 -08001374// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001375// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001376func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Paul Duffin407501b2021-07-09 16:56:35 +01001377 // Just join the components textually just to make sure that it does not corrupt a fully qualified
1378 // module reference, e.g. if the pathComponents is "://other:foo" then using filepath.Join() or
1379 // validatePath() will corrupt it, e.g. replace "//" with "/". If the path is not a module
1380 // reference then it will be validated by expandOneSrcPath anyway when it calls expandOneSrcPath.
1381 p := strings.Join(pathComponents, string(filepath.Separator))
Liz Kammer619be462022-01-28 15:13:39 -05001382 paths, err := expandOneSrcPath(sourcePathInput{context: ctx, path: p, includeDirs: true})
Colin Cross8a497952019-03-05 22:25:09 -08001383 if err != nil {
1384 if depErr, ok := err.(missingDependencyError); ok {
1385 if ctx.Config().AllowMissingDependencies() {
1386 ctx.AddMissingDependencies(depErr.missingDeps)
1387 } else {
1388 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1389 }
1390 } else {
1391 reportPathError(ctx, err)
1392 }
1393 return nil
1394 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001395 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001396 return nil
1397 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001398 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001399 }
1400 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001401}
1402
Liz Kammera830f3a2020-11-10 10:50:34 -08001403func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001404 p, err := validatePath(paths...)
1405 if err != nil {
1406 reportPathError(ctx, err)
1407 }
1408
1409 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1410 if err != nil {
1411 reportPathError(ctx, err)
1412 }
1413
1414 path.basePath.rel = p
1415
1416 return path
1417}
1418
Colin Cross2fafa3e2019-03-05 12:39:51 -08001419// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1420// will return the path relative to subDir in the module's source directory. If any input paths are not located
1421// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001422func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001423 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001424 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001425 for i, path := range paths {
1426 rel := Rel(ctx, subDirFullPath.String(), path.String())
1427 paths[i] = subDirFullPath.join(ctx, rel)
1428 }
1429 return paths
1430}
1431
1432// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1433// 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 -08001434func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001435 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001436 rel := Rel(ctx, subDirFullPath.String(), path.String())
1437 return subDirFullPath.Join(ctx, rel)
1438}
1439
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001440// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1441// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001442func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001443 if p == nil {
1444 return OptionalPath{}
1445 }
1446 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1447}
1448
Liz Kammera830f3a2020-11-10 10:50:34 -08001449func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001450 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001451}
1452
Liz Kammera830f3a2020-11-10 10:50:34 -08001453func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001454 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001455}
1456
Liz Kammera830f3a2020-11-10 10:50:34 -08001457func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001458 // TODO: Use full directory if the new ctx is not the current ctx?
1459 return PathForModuleRes(ctx, p.path, name)
1460}
1461
1462// ModuleOutPath is a Path representing a module's output directory.
1463type ModuleOutPath struct {
1464 OutputPath
1465}
1466
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001467func (p ModuleOutPath) RelativeToTop() Path {
1468 p.OutputPath = p.outputPathRelativeToTop()
1469 return p
1470}
1471
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001472var _ Path = ModuleOutPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001473var _ WritablePath = ModuleOutPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001474
Liz Kammera830f3a2020-11-10 10:50:34 -08001475func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001476 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1477}
1478
Liz Kammera830f3a2020-11-10 10:50:34 -08001479// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1480type ModuleOutPathContext interface {
1481 PathContext
1482
1483 ModuleName() string
1484 ModuleDir() string
1485 ModuleSubDir() string
1486}
1487
1488func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001489 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1490}
1491
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001492// PathForModuleOut returns a Path representing the paths... under the module's
1493// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001494func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001495 p, err := validatePath(paths...)
1496 if err != nil {
1497 reportPathError(ctx, err)
1498 }
Colin Cross702e0f82017-10-18 17:27:54 -07001499 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001500 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001501 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001502}
1503
1504// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1505// directory. Mainly used for generated sources.
1506type ModuleGenPath struct {
1507 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001508}
1509
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001510func (p ModuleGenPath) RelativeToTop() Path {
1511 p.OutputPath = p.outputPathRelativeToTop()
1512 return p
1513}
1514
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001515var _ Path = ModuleGenPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001516var _ WritablePath = ModuleGenPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001517var _ genPathProvider = ModuleGenPath{}
1518var _ objPathProvider = ModuleGenPath{}
1519
1520// PathForModuleGen returns a Path representing the paths... under the module's
1521// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001522func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001523 p, err := validatePath(paths...)
1524 if err != nil {
1525 reportPathError(ctx, err)
1526 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001527 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001528 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001529 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001530 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001531 }
1532}
1533
Liz Kammera830f3a2020-11-10 10:50:34 -08001534func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001535 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001536 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001537}
1538
Liz Kammera830f3a2020-11-10 10:50:34 -08001539func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001540 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1541}
1542
1543// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1544// directory. Used for compiled objects.
1545type ModuleObjPath struct {
1546 ModuleOutPath
1547}
1548
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001549func (p ModuleObjPath) RelativeToTop() Path {
1550 p.OutputPath = p.outputPathRelativeToTop()
1551 return p
1552}
1553
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001554var _ Path = ModuleObjPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001555var _ WritablePath = ModuleObjPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001556
1557// PathForModuleObj returns a Path representing the paths... under the module's
1558// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001559func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001560 p, err := validatePath(pathComponents...)
1561 if err != nil {
1562 reportPathError(ctx, err)
1563 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001564 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1565}
1566
1567// ModuleResPath is a a Path representing the 'res' directory in a module's
1568// output directory.
1569type ModuleResPath struct {
1570 ModuleOutPath
1571}
1572
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001573func (p ModuleResPath) RelativeToTop() Path {
1574 p.OutputPath = p.outputPathRelativeToTop()
1575 return p
1576}
1577
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001578var _ Path = ModuleResPath{}
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001579var _ WritablePath = ModuleResPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001580
1581// PathForModuleRes returns a Path representing the paths... under the module's
1582// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001583func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001584 p, err := validatePath(pathComponents...)
1585 if err != nil {
1586 reportPathError(ctx, err)
1587 }
1588
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001589 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1590}
1591
Colin Cross70dda7e2019-10-01 22:05:35 -07001592// InstallPath is a Path representing a installed file path rooted from the build directory
1593type InstallPath struct {
1594 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001595
Lukacs T. Berkib078ade2021-08-31 10:42:08 +02001596 // The soong build directory, i.e. Config.SoongOutDir()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001597 soongOutDir string
Paul Duffind65c58b2021-03-24 09:22:07 +00001598
Jiyong Park957bcd92020-10-20 18:23:33 +09001599 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1600 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1601 partitionDir string
1602
Colin Crossb1692a32021-10-25 15:39:01 -07001603 partition string
1604
Jiyong Park957bcd92020-10-20 18:23:33 +09001605 // makePath indicates whether this path is for Soong (false) or Make (true).
1606 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001607}
1608
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001609// Will panic if called from outside a test environment.
1610func ensureTestOnly() {
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001611 if PrefixInList(os.Args, "-test.") {
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001612 return
1613 }
Martin Stjernholm32312eb2021-03-27 18:54:49 +00001614 panic(fmt.Errorf("Not in test. Command line:\n %s", strings.Join(os.Args, "\n ")))
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001615}
1616
1617func (p InstallPath) RelativeToTop() Path {
1618 ensureTestOnly()
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001619 p.soongOutDir = OutSoongDir
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001620 return p
1621}
1622
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001623func (p InstallPath) getSoongOutDir() string {
1624 return p.soongOutDir
Paul Duffin9b478b02019-12-10 13:41:51 +00001625}
1626
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001627func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1628 panic("Not implemented")
1629}
1630
Paul Duffin9b478b02019-12-10 13:41:51 +00001631var _ Path = InstallPath{}
1632var _ WritablePath = InstallPath{}
1633
Colin Cross70dda7e2019-10-01 22:05:35 -07001634func (p InstallPath) writablePath() {}
1635
1636func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001637 if p.makePath {
1638 // Make path starts with out/ instead of out/soong.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001639 return filepath.Join(p.soongOutDir, "../", p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001640 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001641 return filepath.Join(p.soongOutDir, p.path)
Jiyong Park957bcd92020-10-20 18:23:33 +09001642 }
1643}
1644
1645// PartitionDir returns the path to the partition where the install path is rooted at. It is
1646// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1647// The ./soong is dropped if the install path is for Make.
1648func (p InstallPath) PartitionDir() string {
1649 if p.makePath {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001650 return filepath.Join(p.soongOutDir, "../", p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001651 } else {
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001652 return filepath.Join(p.soongOutDir, p.partitionDir)
Jiyong Park957bcd92020-10-20 18:23:33 +09001653 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001654}
1655
Jihoon Kangf78a8902022-09-01 22:47:07 +00001656func (p InstallPath) Partition() string {
1657 return p.partition
1658}
1659
Colin Cross70dda7e2019-10-01 22:05:35 -07001660// Join creates a new InstallPath with paths... joined with the current path. The
1661// provided paths... may not use '..' to escape from the current path.
1662func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1663 path, err := validatePath(paths...)
1664 if err != nil {
1665 reportPathError(ctx, err)
1666 }
1667 return p.withRel(path)
1668}
1669
1670func (p InstallPath) withRel(rel string) InstallPath {
1671 p.basePath = p.basePath.withRel(rel)
1672 return p
1673}
1674
Colin Crossc68db4b2021-11-11 18:59:15 -08001675// Deprecated: ToMakePath is a noop, PathForModuleInstall always returns Make paths when building
1676// embedded in Make.
Colin Crossff6c33d2019-10-02 16:01:35 -07001677func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001678 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001679 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001680}
1681
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001682// PathForModuleInstall returns a Path representing the install path for the
1683// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001684func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Spandan Das5d1b9292021-06-03 19:36:41 +00001685 os, arch := osAndArch(ctx)
1686 partition := modulePartition(ctx, os)
1687 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1688}
1689
Colin Cross1d0eb7a2021-11-03 14:08:20 -07001690// PathForHostDexInstall returns an InstallPath representing the install path for the
1691// module appended with paths...
1692func PathForHostDexInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
1693 return makePathForInstall(ctx, ctx.Config().BuildOS, ctx.Config().BuildArch, "", ctx.Debug(), pathComponents...)
1694}
1695
Spandan Das5d1b9292021-06-03 19:36:41 +00001696// PathForModuleInPartitionInstall is similar to PathForModuleInstall but partition is provided by the caller
1697func PathForModuleInPartitionInstall(ctx ModuleInstallPathContext, partition string, pathComponents ...string) InstallPath {
1698 os, arch := osAndArch(ctx)
1699 return makePathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
1700}
1701
1702func osAndArch(ctx ModuleInstallPathContext) (OsType, ArchType) {
Colin Cross6e359402020-02-10 15:29:54 -08001703 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001704 arch := ctx.Arch().ArchType
1705 forceOS, forceArch := ctx.InstallForceOS()
1706 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001707 os = *forceOS
1708 }
Jiyong Park87788b52020-09-01 12:37:45 +09001709 if forceArch != nil {
1710 arch = *forceArch
1711 }
Spandan Das5d1b9292021-06-03 19:36:41 +00001712 return os, arch
1713}
Colin Cross609c49a2020-02-13 13:20:11 -08001714
Spandan Das5d1b9292021-06-03 19:36:41 +00001715func makePathForInstall(ctx ModuleInstallPathContext, os OsType, arch ArchType, partition string, debug bool, pathComponents ...string) InstallPath {
1716 ret := pathForInstall(ctx, os, arch, partition, debug, pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001717 return ret
1718}
1719
Jiyong Park87788b52020-09-01 12:37:45 +09001720func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001721 pathComponents ...string) InstallPath {
1722
Jiyong Park957bcd92020-10-20 18:23:33 +09001723 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001724
Colin Cross6e359402020-02-10 15:29:54 -08001725 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001726 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001727 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001728 osName := os.String()
Colin Crossa9b2aac2022-06-15 17:25:51 -07001729 if os == Linux {
Jiyong Park87788b52020-09-01 12:37:45 +09001730 // instead of linux_glibc
1731 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001732 }
Colin Crossa9b2aac2022-06-15 17:25:51 -07001733 if os == LinuxMusl && ctx.Config().UseHostMusl() {
1734 // When using musl instead of glibc, use "linux" instead of "linux_musl". When cross
1735 // compiling we will still use "linux_musl".
1736 osName = "linux"
1737 }
1738
Jiyong Park87788b52020-09-01 12:37:45 +09001739 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1740 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1741 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1742 // Let's keep using x86 for the existing cases until we have a need to support
1743 // other architectures.
1744 archName := arch.String()
1745 if os.Class == Host && (arch == X86_64 || arch == Common) {
1746 archName = "x86"
1747 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001748 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001749 }
Colin Cross609c49a2020-02-13 13:20:11 -08001750 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001751 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001752 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001753
Jiyong Park957bcd92020-10-20 18:23:33 +09001754 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001755 if err != nil {
1756 reportPathError(ctx, err)
1757 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001758
Jiyong Park957bcd92020-10-20 18:23:33 +09001759 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001760 basePath: basePath{partionPath, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001761 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001762 partitionDir: partionPath,
Colin Crossb1692a32021-10-25 15:39:01 -07001763 partition: partition,
Colin Crossc68db4b2021-11-11 18:59:15 -08001764 }
1765
1766 if ctx.Config().KatiEnabled() {
1767 base.makePath = true
Jiyong Park957bcd92020-10-20 18:23:33 +09001768 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001769
Jiyong Park957bcd92020-10-20 18:23:33 +09001770 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001771}
1772
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001773func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001774 base := InstallPath{
Paul Duffin74abc5d2021-03-24 09:24:59 +00001775 basePath: basePath{prefix, ""},
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001776 soongOutDir: ctx.Config().soongOutDir,
Jiyong Park957bcd92020-10-20 18:23:33 +09001777 partitionDir: prefix,
1778 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001779 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001780 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001781}
1782
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001783func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1784 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1785}
1786
1787func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1788 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1789}
1790
Colin Cross70dda7e2019-10-01 22:05:35 -07001791func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Crossb1692a32021-10-25 15:39:01 -07001792 rel := Rel(ctx, strings.TrimSuffix(path.PartitionDir(), path.partition), path.String())
Colin Cross43f08db2018-11-12 10:13:39 -08001793 return "/" + rel
1794}
1795
Colin Cross6e359402020-02-10 15:29:54 -08001796func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001797 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001798 if ctx.InstallInTestcases() {
1799 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001800 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001801 } else if os.Class == Device {
1802 if ctx.InstallInData() {
1803 partition = "data"
1804 } else if ctx.InstallInRamdisk() {
1805 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1806 partition = "recovery/root/first_stage_ramdisk"
1807 } else {
1808 partition = "ramdisk"
1809 }
1810 if !ctx.InstallInRoot() {
1811 partition += "/system"
1812 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001813 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001814 // The module is only available after switching root into
1815 // /first_stage_ramdisk. To expose the module before switching root
1816 // on a device without a dedicated recovery partition, install the
1817 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001818 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Petri Gyntherac229562021-03-02 23:44:02 -08001819 partition = "vendor_ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001820 } else {
Petri Gyntherac229562021-03-02 23:44:02 -08001821 partition = "vendor_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001822 }
1823 if !ctx.InstallInRoot() {
1824 partition += "/system"
1825 }
Inseob Kim08758f02021-04-08 21:13:22 +09001826 } else if ctx.InstallInDebugRamdisk() {
1827 partition = "debug_ramdisk"
Colin Cross6e359402020-02-10 15:29:54 -08001828 } else if ctx.InstallInRecovery() {
1829 if ctx.InstallInRoot() {
1830 partition = "recovery/root"
1831 } else {
1832 // the layout of recovery partion is the same as that of system partition
1833 partition = "recovery/root/system"
1834 }
1835 } else if ctx.SocSpecific() {
1836 partition = ctx.DeviceConfig().VendorPath()
1837 } else if ctx.DeviceSpecific() {
1838 partition = ctx.DeviceConfig().OdmPath()
1839 } else if ctx.ProductSpecific() {
1840 partition = ctx.DeviceConfig().ProductPath()
1841 } else if ctx.SystemExtSpecific() {
1842 partition = ctx.DeviceConfig().SystemExtPath()
1843 } else if ctx.InstallInRoot() {
1844 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001845 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001846 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001847 }
Colin Cross6e359402020-02-10 15:29:54 -08001848 if ctx.InstallInSanitizerDir() {
1849 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001850 }
Colin Cross43f08db2018-11-12 10:13:39 -08001851 }
1852 return partition
1853}
1854
Colin Cross609c49a2020-02-13 13:20:11 -08001855type InstallPaths []InstallPath
1856
1857// Paths returns the InstallPaths as a Paths
1858func (p InstallPaths) Paths() Paths {
1859 if p == nil {
1860 return nil
1861 }
1862 ret := make(Paths, len(p))
1863 for i, path := range p {
1864 ret[i] = path
1865 }
1866 return ret
1867}
1868
1869// Strings returns the string forms of the install paths.
1870func (p InstallPaths) Strings() []string {
1871 if p == nil {
1872 return nil
1873 }
1874 ret := make([]string, len(p))
1875 for i, path := range p {
1876 ret[i] = path.String()
1877 }
1878 return ret
1879}
1880
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001881// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001882// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001883func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001884 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001885 path := filepath.Clean(path)
1886 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001887 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001888 }
1889 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001890 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1891 // variables. '..' may remove the entire ninja variable, even if it
1892 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001893 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001894}
1895
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001896// validatePath validates that a path does not include ninja variables, and that
1897// each path component does not attempt to leave its component. Returns a joined
1898// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001899func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001900 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001901 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001902 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001903 }
1904 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001905 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001906}
Colin Cross5b529592017-05-09 13:34:34 -07001907
Colin Cross0875c522017-11-28 17:34:01 -08001908func PathForPhony(ctx PathContext, phony string) WritablePath {
1909 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001910 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001911 }
Paul Duffin74abc5d2021-03-24 09:24:59 +00001912 return PhonyPath{basePath{phony, ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001913}
1914
Colin Cross74e3fe42017-12-11 15:51:44 -08001915type PhonyPath struct {
1916 basePath
1917}
1918
1919func (p PhonyPath) writablePath() {}
1920
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +02001921func (p PhonyPath) getSoongOutDir() string {
Paul Duffind65c58b2021-03-24 09:22:07 +00001922 // A phone path cannot contain any / so cannot be relative to the build directory.
1923 return ""
Paul Duffin9b478b02019-12-10 13:41:51 +00001924}
1925
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001926func (p PhonyPath) RelativeToTop() Path {
1927 ensureTestOnly()
1928 // A phony path cannot contain any / so does not have a build directory so switching to a new
1929 // build directory has no effect so just return this path.
1930 return p
1931}
1932
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001933func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1934 panic("Not implemented")
1935}
1936
Colin Cross74e3fe42017-12-11 15:51:44 -08001937var _ Path = PhonyPath{}
1938var _ WritablePath = PhonyPath{}
1939
Colin Cross5b529592017-05-09 13:34:34 -07001940type testPath struct {
1941 basePath
1942}
1943
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001944func (p testPath) RelativeToTop() Path {
1945 ensureTestOnly()
1946 return p
1947}
1948
Colin Cross5b529592017-05-09 13:34:34 -07001949func (p testPath) String() string {
1950 return p.path
1951}
1952
Paul Duffin85d8f0d2021-03-24 10:18:18 +00001953var _ Path = testPath{}
1954
Colin Cross40e33732019-02-15 11:08:35 -08001955// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1956// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001957func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001958 p, err := validateSafePath(paths...)
1959 if err != nil {
1960 panic(err)
1961 }
Colin Cross5b529592017-05-09 13:34:34 -07001962 return testPath{basePath{path: p, rel: p}}
1963}
1964
Sam Delmerico2351eac2022-05-24 17:10:02 +00001965func PathForTestingWithRel(path, rel string) Path {
1966 p, err := validateSafePath(path, rel)
1967 if err != nil {
1968 panic(err)
1969 }
1970 r, err := validatePath(rel)
1971 if err != nil {
1972 panic(err)
1973 }
1974 return testPath{basePath{path: p, rel: r}}
1975}
1976
Colin Cross40e33732019-02-15 11:08:35 -08001977// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1978func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001979 p := make(Paths, len(strs))
1980 for i, s := range strs {
1981 p[i] = PathForTesting(s)
1982 }
1983
1984 return p
1985}
Colin Cross43f08db2018-11-12 10:13:39 -08001986
Colin Cross40e33732019-02-15 11:08:35 -08001987type testPathContext struct {
1988 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001989}
1990
Colin Cross40e33732019-02-15 11:08:35 -08001991func (x *testPathContext) Config() Config { return x.config }
1992func (x *testPathContext) AddNinjaFileDeps(...string) {}
1993
1994// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1995// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001996func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001997 return &testPathContext{
1998 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001999 }
2000}
2001
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002002type testModuleInstallPathContext struct {
2003 baseModuleContext
2004
2005 inData bool
2006 inTestcases bool
2007 inSanitizerDir bool
2008 inRamdisk bool
2009 inVendorRamdisk bool
Inseob Kim08758f02021-04-08 21:13:22 +09002010 inDebugRamdisk bool
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002011 inRecovery bool
2012 inRoot bool
2013 forceOS *OsType
2014 forceArch *ArchType
2015}
2016
2017func (m testModuleInstallPathContext) Config() Config {
2018 return m.baseModuleContext.config
2019}
2020
2021func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
2022
2023func (m testModuleInstallPathContext) InstallInData() bool {
2024 return m.inData
2025}
2026
2027func (m testModuleInstallPathContext) InstallInTestcases() bool {
2028 return m.inTestcases
2029}
2030
2031func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
2032 return m.inSanitizerDir
2033}
2034
2035func (m testModuleInstallPathContext) InstallInRamdisk() bool {
2036 return m.inRamdisk
2037}
2038
2039func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
2040 return m.inVendorRamdisk
2041}
2042
Inseob Kim08758f02021-04-08 21:13:22 +09002043func (m testModuleInstallPathContext) InstallInDebugRamdisk() bool {
2044 return m.inDebugRamdisk
2045}
2046
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002047func (m testModuleInstallPathContext) InstallInRecovery() bool {
2048 return m.inRecovery
2049}
2050
2051func (m testModuleInstallPathContext) InstallInRoot() bool {
2052 return m.inRoot
2053}
2054
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01002055func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
2056 return m.forceOS, m.forceArch
2057}
2058
2059// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
2060// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
2061// delegated to it will panic.
2062func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
2063 ctx := &testModuleInstallPathContext{}
2064 ctx.config = config
2065 ctx.os = Android
2066 return ctx
2067}
2068
Colin Cross43f08db2018-11-12 10:13:39 -08002069// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
2070// targetPath is not inside basePath.
2071func Rel(ctx PathContext, basePath string, targetPath string) string {
2072 rel, isRel := MaybeRel(ctx, basePath, targetPath)
2073 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01002074 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08002075 return ""
2076 }
2077 return rel
2078}
2079
2080// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
2081// targetPath is not inside basePath.
2082func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002083 rel, isRel, err := maybeRelErr(basePath, targetPath)
2084 if err != nil {
2085 reportPathError(ctx, err)
2086 }
2087 return rel, isRel
2088}
2089
2090func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08002091 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
2092 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07002093 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002094 }
2095 rel, err := filepath.Rel(basePath, targetPath)
2096 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07002097 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08002098 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07002099 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002100 }
Dan Willemsen633c5022019-04-12 11:11:38 -07002101 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08002102}
Colin Cross988414c2020-01-11 01:11:46 +00002103
2104// Writes a file to the output directory. Attempting to write directly to the output directory
2105// will fail due to the sandbox of the soong_build process.
2106func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
Colin Crossd6421132021-11-09 12:32:34 -08002107 absPath := absolutePath(path.String())
2108 err := os.MkdirAll(filepath.Dir(absPath), 0777)
2109 if err != nil {
2110 return err
2111 }
2112 return ioutil.WriteFile(absPath, data, perm)
Colin Cross988414c2020-01-11 01:11:46 +00002113}
2114
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002115func RemoveAllOutputDir(path WritablePath) error {
2116 return os.RemoveAll(absolutePath(path.String()))
2117}
2118
2119func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
2120 dir := absolutePath(path.String())
Liz Kammer09f947d2021-05-12 14:51:49 -04002121 return createDirIfNonexistent(dir, perm)
2122}
2123
2124func createDirIfNonexistent(dir string, perm os.FileMode) error {
Liz Kammer2dd9ca42020-11-25 16:06:39 -08002125 if _, err := os.Stat(dir); os.IsNotExist(err) {
2126 return os.MkdirAll(dir, os.ModePerm)
2127 } else {
2128 return err
2129 }
2130}
2131
Jingwen Chen78257e52021-05-21 02:34:24 +00002132// absolutePath is deliberately private so that Soong's Go plugins can't use it to find and
2133// read arbitrary files without going through the methods in the current package that track
2134// dependencies.
Colin Cross988414c2020-01-11 01:11:46 +00002135func absolutePath(path string) string {
2136 if filepath.IsAbs(path) {
2137 return path
2138 }
2139 return filepath.Join(absSrcDir, path)
2140}
Chris Parsons216e10a2020-07-09 17:12:52 -04002141
2142// A DataPath represents the path of a file to be used as data, for example
2143// a test library to be installed alongside a test.
2144// The data file should be installed (copied from `<SrcPath>`) to
2145// `<install_root>/<RelativeInstallPath>/<filename>`, or
2146// `<install_root>/<filename>` if RelativeInstallPath is empty.
2147type DataPath struct {
2148 // The path of the data file that should be copied into the data directory
2149 SrcPath Path
2150 // The install path of the data file, relative to the install root.
2151 RelativeInstallPath string
2152}
Colin Crossdcf71b22021-02-01 13:59:03 -08002153
2154// PathsIfNonNil returns a Paths containing only the non-nil input arguments.
2155func PathsIfNonNil(paths ...Path) Paths {
2156 if len(paths) == 0 {
2157 // Fast path for empty argument list
2158 return nil
2159 } else if len(paths) == 1 {
2160 // Fast path for a single argument
2161 if paths[0] != nil {
2162 return paths
2163 } else {
2164 return nil
2165 }
2166 }
2167 ret := make(Paths, 0, len(paths))
2168 for _, path := range paths {
2169 if path != nil {
2170 ret = append(ret, path)
2171 }
2172 }
2173 if len(ret) == 0 {
2174 return nil
2175 }
2176 return ret
2177}
Chris Wailesb2703ad2021-07-30 13:25:42 -07002178
2179var thirdPartyDirPrefixExceptions = []*regexp.Regexp{
2180 regexp.MustCompile("^vendor/[^/]*google[^/]*/"),
2181 regexp.MustCompile("^hardware/google/"),
2182 regexp.MustCompile("^hardware/interfaces/"),
2183 regexp.MustCompile("^hardware/libhardware[^/]*/"),
2184 regexp.MustCompile("^hardware/ril/"),
2185}
2186
2187func IsThirdPartyPath(path string) bool {
2188 thirdPartyDirPrefixes := []string{"external/", "vendor/", "hardware/"}
2189
2190 if HasAnyPrefix(path, thirdPartyDirPrefixes) {
2191 for _, prefix := range thirdPartyDirPrefixExceptions {
2192 if prefix.MatchString(path) {
2193 return false
2194 }
2195 }
2196 return true
2197 }
2198 return false
2199}
Colin Crossaff21fb2022-01-12 10:57:57 -08002200
2201// PathsDepSet is a thin type-safe wrapper around the generic depSet. It always uses
2202// topological order.
2203type PathsDepSet struct {
2204 depSet
2205}
2206
2207// newPathsDepSet returns an immutable PathsDepSet with the given direct and
2208// transitive contents.
2209func newPathsDepSet(direct Paths, transitive []*PathsDepSet) *PathsDepSet {
2210 return &PathsDepSet{*newDepSet(TOPOLOGICAL, direct, transitive)}
2211}
2212
2213// ToList returns the PathsDepSet flattened to a list in topological order.
2214func (d *PathsDepSet) ToList() Paths {
2215 if d == nil {
2216 return nil
2217 }
2218 return d.depSet.ToList().(Paths)
2219}