blob: 1a37a34f03b6b597ebd8cdc6c5113daaadd7c8b0 [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 Cross6a745c62015-06-16 16:38:10 -070019 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070020 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070021 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070022 "strings"
23
24 "github.com/google/blueprint"
25 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080026)
27
Dan Willemsen34cc69e2015-09-23 15:26:20 -070028// PathContext is the subset of a (Module|Singleton)Context required by the
29// Path methods.
30type PathContext interface {
Colin Cross294941b2017-02-01 14:10:36 -080031 Fs() pathtools.FileSystem
Colin Crossaabf6792017-11-29 00:27:14 -080032 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080033 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080034}
35
Colin Cross7f19f372016-11-01 11:10:25 -070036type PathGlobContext interface {
37 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
38}
39
Colin Crossaabf6792017-11-29 00:27:14 -080040var _ PathContext = SingletonContext(nil)
41var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070042
Dan Willemsen00269f22017-07-06 16:59:48 -070043type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -070044 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -070045
46 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -070047 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070048 InstallInSanitizerDir() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +090049 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -070050 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -070051 InstallBypassMake() bool
Dan Willemsen00269f22017-07-06 16:59:48 -070052}
53
54var _ ModuleInstallPathContext = ModuleContext(nil)
55
Dan Willemsen34cc69e2015-09-23 15:26:20 -070056// errorfContext is the interface containing the Errorf method matching the
57// Errorf method in blueprint.SingletonContext.
58type errorfContext interface {
59 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080060}
61
Dan Willemsen34cc69e2015-09-23 15:26:20 -070062var _ errorfContext = blueprint.SingletonContext(nil)
63
64// moduleErrorf is the interface containing the ModuleErrorf method matching
65// the ModuleErrorf method in blueprint.ModuleContext.
66type moduleErrorf interface {
67 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -080068}
69
Dan Willemsen34cc69e2015-09-23 15:26:20 -070070var _ moduleErrorf = blueprint.ModuleContext(nil)
71
Dan Willemsen34cc69e2015-09-23 15:26:20 -070072// reportPathError will register an error with the attached context. It
73// attempts ctx.ModuleErrorf for a better error message first, then falls
74// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -080075func reportPathError(ctx PathContext, err error) {
76 reportPathErrorf(ctx, "%s", err.Error())
77}
78
79// reportPathErrorf will register an error with the attached context. It
80// attempts ctx.ModuleErrorf for a better error message first, then falls
81// back to ctx.Errorf.
82func reportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -070083 if mctx, ok := ctx.(moduleErrorf); ok {
84 mctx.ModuleErrorf(format, args...)
85 } else if ectx, ok := ctx.(errorfContext); ok {
86 ectx.Errorf(format, args...)
87 } else {
88 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -070089 }
90}
91
Dan Willemsen34cc69e2015-09-23 15:26:20 -070092type Path interface {
93 // Returns the path in string form
94 String() string
95
Colin Cross4f6fc9c2016-10-26 10:05:25 -070096 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -070097 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -070098
99 // Base returns the last element of the path
100 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800101
102 // Rel returns the portion of the path relative to the directory it was created from. For
103 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800104 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800105 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700106}
107
108// WritablePath is a type of path that can be used as an output for build rules.
109type WritablePath interface {
110 Path
111
Jeff Gaston734e3802017-04-10 15:47:24 -0700112 // the writablePath method doesn't directly do anything,
113 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700114 writablePath()
115}
116
117type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700118 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700119}
120type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700121 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700122}
123type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700124 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700125}
126
127// GenPathWithExt derives a new file path in ctx's generated sources directory
128// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700129func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700130 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700131 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700132 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800133 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700134 return PathForModuleGen(ctx)
135}
136
137// ObjPathWithExt derives a new file path in ctx's object directory from the
138// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700139func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700140 if path, ok := p.(objPathProvider); ok {
141 return path.objPathWithExt(ctx, subdir, ext)
142 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800143 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700144 return PathForModuleObj(ctx)
145}
146
147// ResPathWithName derives a new path in ctx's output resource directory, using
148// the current path to create the directory name, and the `name` argument for
149// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700150func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700151 if path, ok := p.(resPathProvider); ok {
152 return path.resPathWithName(ctx, name)
153 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800154 reportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700155 return PathForModuleRes(ctx)
156}
157
158// OptionalPath is a container that may or may not contain a valid Path.
159type OptionalPath struct {
160 valid bool
161 path Path
162}
163
164// OptionalPathForPath returns an OptionalPath containing the path.
165func OptionalPathForPath(path Path) OptionalPath {
166 if path == nil {
167 return OptionalPath{}
168 }
169 return OptionalPath{valid: true, path: path}
170}
171
172// Valid returns whether there is a valid path
173func (p OptionalPath) Valid() bool {
174 return p.valid
175}
176
177// Path returns the Path embedded in this OptionalPath. You must be sure that
178// there is a valid path, since this method will panic if there is not.
179func (p OptionalPath) Path() Path {
180 if !p.valid {
181 panic("Requesting an invalid path")
182 }
183 return p.path
184}
185
186// String returns the string version of the Path, or "" if it isn't valid.
187func (p OptionalPath) String() string {
188 if p.valid {
189 return p.path.String()
190 } else {
191 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700192 }
193}
Colin Cross6e18ca42015-07-14 18:55:36 -0700194
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700195// Paths is a slice of Path objects, with helpers to operate on the collection.
196type Paths []Path
197
198// PathsForSource returns Paths rooted from SrcDir
199func PathsForSource(ctx PathContext, paths []string) Paths {
200 ret := make(Paths, len(paths))
201 for i, path := range paths {
202 ret[i] = PathForSource(ctx, path)
203 }
204 return ret
205}
206
Jeff Gaston734e3802017-04-10 15:47:24 -0700207// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800208// found in the tree. If any are not found, they are omitted from the list,
209// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800210func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800211 ret := make(Paths, 0, len(paths))
212 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800213 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800214 if p.Valid() {
215 ret = append(ret, p.Path())
216 }
217 }
218 return ret
219}
220
Colin Cross41955e82019-05-29 14:40:35 -0700221// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
222// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
223// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
224// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
225// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
226// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700227func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800228 return PathsForModuleSrcExcludes(ctx, paths, nil)
229}
230
Colin Crossba71a3f2019-03-18 12:12:48 -0700231// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700232// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
233// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
234// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
235// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100236// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700237// having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800238func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700239 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
240 if ctx.Config().AllowMissingDependencies() {
241 ctx.AddMissingDependencies(missingDeps)
242 } else {
243 for _, m := range missingDeps {
244 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
245 }
246 }
247 return ret
248}
249
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000250// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
251type OutputPaths []OutputPath
252
253// Paths returns the OutputPaths as a Paths
254func (p OutputPaths) Paths() Paths {
255 if p == nil {
256 return nil
257 }
258 ret := make(Paths, len(p))
259 for i, path := range p {
260 ret[i] = path
261 }
262 return ret
263}
264
265// Strings returns the string forms of the writable paths.
266func (p OutputPaths) Strings() []string {
267 if p == nil {
268 return nil
269 }
270 ret := make([]string, len(p))
271 for i, path := range p {
272 ret[i] = path.String()
273 }
274 return ret
275}
276
Colin Crossba71a3f2019-03-18 12:12:48 -0700277// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700278// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
279// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
280// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
281// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
282// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
283// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
284// dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700285func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800286 prefix := pathForModuleSrc(ctx).String()
287
288 var expandedExcludes []string
289 if excludes != nil {
290 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700291 }
Colin Cross8a497952019-03-05 22:25:09 -0800292
Colin Crossba71a3f2019-03-18 12:12:48 -0700293 var missingExcludeDeps []string
294
Colin Cross8a497952019-03-05 22:25:09 -0800295 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700296 if m, t := SrcIsModuleWithTag(e); m != "" {
297 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800298 if module == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700299 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800300 continue
301 }
Colin Cross41955e82019-05-29 14:40:35 -0700302 if outProducer, ok := module.(OutputFileProducer); ok {
303 outputFiles, err := outProducer.OutputFiles(t)
304 if err != nil {
305 ctx.ModuleErrorf("path dependency %q: %s", e, err)
306 }
307 expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
308 } else if t != "" {
309 ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
310 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800311 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
312 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700313 ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
Colin Cross8a497952019-03-05 22:25:09 -0800314 }
315 } else {
316 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
317 }
318 }
319
320 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700321 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800322 }
323
Colin Crossba71a3f2019-03-18 12:12:48 -0700324 var missingDeps []string
325
Colin Cross8a497952019-03-05 22:25:09 -0800326 expandedSrcFiles := make(Paths, 0, len(paths))
327 for _, s := range paths {
328 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
329 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700330 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800331 } else if err != nil {
332 reportPathError(ctx, err)
333 }
334 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
335 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700336
337 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800338}
339
340type missingDependencyError struct {
341 missingDeps []string
342}
343
344func (e missingDependencyError) Error() string {
345 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
346}
347
348func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
Colin Cross41955e82019-05-29 14:40:35 -0700349 if m, t := SrcIsModuleWithTag(s); m != "" {
350 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800351 if module == nil {
352 return nil, missingDependencyError{[]string{m}}
353 }
Colin Cross41955e82019-05-29 14:40:35 -0700354 if outProducer, ok := module.(OutputFileProducer); ok {
355 outputFiles, err := outProducer.OutputFiles(t)
356 if err != nil {
357 return nil, fmt.Errorf("path dependency %q: %s", s, err)
358 }
359 return outputFiles, nil
360 } else if t != "" {
361 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
362 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800363 moduleSrcs := srcProducer.Srcs()
364 for _, e := range expandedExcludes {
365 for j := 0; j < len(moduleSrcs); j++ {
366 if moduleSrcs[j].String() == e {
367 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
368 j--
369 }
370 }
371 }
372 return moduleSrcs, nil
373 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700374 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800375 }
376 } else if pathtools.IsGlob(s) {
377 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
378 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
379 } else {
380 p := pathForModuleSrc(ctx, s)
381 if exists, _, err := ctx.Fs().Exists(p.String()); err != nil {
382 reportPathErrorf(ctx, "%s: %s", p, err.Error())
383 } else if !exists {
384 reportPathErrorf(ctx, "module source path %q does not exist", p)
385 }
386
387 j := findStringInSlice(p.String(), expandedExcludes)
388 if j >= 0 {
389 return nil, nil
390 }
391 return Paths{p}, nil
392 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700393}
394
395// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
396// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800397// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700398// It intended for use in globs that only list files that exist, so it allows '$' in
399// filenames.
Colin Crossdc35e212019-06-06 16:13:11 -0700400func pathsForModuleSrcFromFullPath(ctx BaseModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800401 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700402 if prefix == "./" {
403 prefix = ""
404 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700405 ret := make(Paths, 0, len(paths))
406 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800407 if !incDirs && strings.HasSuffix(p, "/") {
408 continue
409 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700410 path := filepath.Clean(p)
411 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800412 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700413 continue
414 }
Colin Crosse3924e12018-08-15 20:18:53 -0700415
Colin Crossfe4bc362018-09-12 10:02:13 -0700416 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700417 if err != nil {
418 reportPathError(ctx, err)
419 continue
420 }
421
Colin Cross07e51612019-03-05 12:46:40 -0800422 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700423
Colin Cross07e51612019-03-05 12:46:40 -0800424 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700425 }
426 return ret
427}
428
429// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800430// local source directory. If input is nil, use the default if it exists. If input is empty, returns nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700431func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800432 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700433 return PathsForModuleSrc(ctx, input)
434 }
435 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
436 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800437 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800438 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700439}
440
441// Strings returns the Paths in string form
442func (p Paths) Strings() []string {
443 if p == nil {
444 return nil
445 }
446 ret := make([]string, len(p))
447 for i, path := range p {
448 ret[i] = path.String()
449 }
450 return ret
451}
452
Colin Crossb6715442017-10-24 11:13:31 -0700453// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
454// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700455func FirstUniquePaths(list Paths) Paths {
456 k := 0
457outer:
458 for i := 0; i < len(list); i++ {
459 for j := 0; j < k; j++ {
460 if list[i] == list[j] {
461 continue outer
462 }
463 }
464 list[k] = list[i]
465 k++
466 }
467 return list[:k]
468}
469
Colin Crossb6715442017-10-24 11:13:31 -0700470// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
471// modifies the Paths slice contents in place, and returns a subslice of the original slice.
472func LastUniquePaths(list Paths) Paths {
473 totalSkip := 0
474 for i := len(list) - 1; i >= totalSkip; i-- {
475 skip := 0
476 for j := i - 1; j >= totalSkip; j-- {
477 if list[i] == list[j] {
478 skip++
479 } else {
480 list[j+skip] = list[j]
481 }
482 }
483 totalSkip += skip
484 }
485 return list[totalSkip:]
486}
487
Colin Crossa140bb02018-04-17 10:52:26 -0700488// ReversePaths returns a copy of a Paths in reverse order.
489func ReversePaths(list Paths) Paths {
490 if list == nil {
491 return nil
492 }
493 ret := make(Paths, len(list))
494 for i := range list {
495 ret[i] = list[len(list)-1-i]
496 }
497 return ret
498}
499
Jeff Gaston294356f2017-09-27 17:05:30 -0700500func indexPathList(s Path, list []Path) int {
501 for i, l := range list {
502 if l == s {
503 return i
504 }
505 }
506
507 return -1
508}
509
510func inPathList(p Path, list []Path) bool {
511 return indexPathList(p, list) != -1
512}
513
514func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
515 for _, l := range list {
516 if inPathList(l, filter) {
517 filtered = append(filtered, l)
518 } else {
519 remainder = append(remainder, l)
520 }
521 }
522
523 return
524}
525
Colin Cross93e85952017-08-15 13:34:18 -0700526// HasExt returns true of any of the paths have extension ext, otherwise false
527func (p Paths) HasExt(ext string) bool {
528 for _, path := range p {
529 if path.Ext() == ext {
530 return true
531 }
532 }
533
534 return false
535}
536
537// FilterByExt returns the subset of the paths that have extension ext
538func (p Paths) FilterByExt(ext string) Paths {
539 ret := make(Paths, 0, len(p))
540 for _, path := range p {
541 if path.Ext() == ext {
542 ret = append(ret, path)
543 }
544 }
545 return ret
546}
547
548// FilterOutByExt returns the subset of the paths that do not have extension ext
549func (p Paths) FilterOutByExt(ext string) Paths {
550 ret := make(Paths, 0, len(p))
551 for _, path := range p {
552 if path.Ext() != ext {
553 ret = append(ret, path)
554 }
555 }
556 return ret
557}
558
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700559// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
560// (including subdirectories) are in a contiguous subslice of the list, and can be found in
561// O(log(N)) time using a binary search on the directory prefix.
562type DirectorySortedPaths Paths
563
564func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
565 ret := append(DirectorySortedPaths(nil), paths...)
566 sort.Slice(ret, func(i, j int) bool {
567 return ret[i].String() < ret[j].String()
568 })
569 return ret
570}
571
572// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
573// that are in the specified directory and its subdirectories.
574func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
575 prefix := filepath.Clean(dir) + "/"
576 start := sort.Search(len(p), func(i int) bool {
577 return prefix < p[i].String()
578 })
579
580 ret := p[start:]
581
582 end := sort.Search(len(ret), func(i int) bool {
583 return !strings.HasPrefix(ret[i].String(), prefix)
584 })
585
586 ret = ret[:end]
587
588 return Paths(ret)
589}
590
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700591// WritablePaths is a slice of WritablePaths, used for multiple outputs.
592type WritablePaths []WritablePath
593
594// Strings returns the string forms of the writable paths.
595func (p WritablePaths) Strings() []string {
596 if p == nil {
597 return nil
598 }
599 ret := make([]string, len(p))
600 for i, path := range p {
601 ret[i] = path.String()
602 }
603 return ret
604}
605
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800606// Paths returns the WritablePaths as a Paths
607func (p WritablePaths) Paths() Paths {
608 if p == nil {
609 return nil
610 }
611 ret := make(Paths, len(p))
612 for i, path := range p {
613 ret[i] = path
614 }
615 return ret
616}
617
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700618type basePath struct {
619 path string
620 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800621 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700622}
623
624func (p basePath) Ext() string {
625 return filepath.Ext(p.path)
626}
627
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700628func (p basePath) Base() string {
629 return filepath.Base(p.path)
630}
631
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800632func (p basePath) Rel() string {
633 if p.rel != "" {
634 return p.rel
635 }
636 return p.path
637}
638
Colin Cross0875c522017-11-28 17:34:01 -0800639func (p basePath) String() string {
640 return p.path
641}
642
Colin Cross0db55682017-12-05 15:36:55 -0800643func (p basePath) withRel(rel string) basePath {
644 p.path = filepath.Join(p.path, rel)
645 p.rel = rel
646 return p
647}
648
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700649// SourcePath is a Path representing a file path rooted from SrcDir
650type SourcePath struct {
651 basePath
652}
653
654var _ Path = SourcePath{}
655
Colin Cross0db55682017-12-05 15:36:55 -0800656func (p SourcePath) withRel(rel string) SourcePath {
657 p.basePath = p.basePath.withRel(rel)
658 return p
659}
660
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700661// safePathForSource is for paths that we expect are safe -- only for use by go
662// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700663func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
664 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800665 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700666 if err != nil {
667 return ret, err
668 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700669
Colin Cross7b3dcc32019-01-24 13:14:39 -0800670 // absolute path already checked by validateSafePath
671 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800672 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700673 }
674
Colin Crossfe4bc362018-09-12 10:02:13 -0700675 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700676}
677
Colin Cross192e97a2018-02-22 14:21:02 -0800678// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
679func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000680 p, err := validatePath(pathComponents...)
681 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800682 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800683 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800684 }
685
Colin Cross7b3dcc32019-01-24 13:14:39 -0800686 // absolute path already checked by validatePath
687 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800688 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000689 }
690
Colin Cross192e97a2018-02-22 14:21:02 -0800691 return ret, nil
692}
693
694// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
695// path does not exist.
696func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
697 var files []string
698
699 if gctx, ok := ctx.(PathGlobContext); ok {
700 // Use glob to produce proper dependencies, even though we only want
701 // a single file.
702 files, err = gctx.GlobWithDeps(path.String(), nil)
703 } else {
704 var deps []string
705 // We cannot add build statements in this context, so we fall back to
706 // AddNinjaFileDeps
Colin Cross3f4d1162018-09-21 15:11:48 -0700707 files, deps, err = pathtools.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800708 ctx.AddNinjaFileDeps(deps...)
709 }
710
711 if err != nil {
712 return false, fmt.Errorf("glob: %s", err.Error())
713 }
714
715 return len(files) > 0, nil
716}
717
718// PathForSource joins the provided path components and validates that the result
719// neither escapes the source dir nor is in the out dir.
720// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
721func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
722 path, err := pathForSource(ctx, pathComponents...)
723 if err != nil {
724 reportPathError(ctx, err)
725 }
726
Colin Crosse3924e12018-08-15 20:18:53 -0700727 if pathtools.IsGlob(path.String()) {
728 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
729 }
730
Colin Cross192e97a2018-02-22 14:21:02 -0800731 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
732 exists, err := existsWithDependencies(ctx, path)
733 if err != nil {
734 reportPathError(ctx, err)
735 }
736 if !exists {
737 modCtx.AddMissingDependencies([]string{path.String()})
738 }
739 } else if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
740 reportPathErrorf(ctx, "%s: %s", path, err.Error())
741 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800742 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800743 }
744 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700745}
746
Jeff Gaston734e3802017-04-10 15:47:24 -0700747// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700748// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
749// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800750func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800751 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800752 if err != nil {
753 reportPathError(ctx, err)
754 return OptionalPath{}
755 }
Colin Crossc48c1432018-02-23 07:09:01 +0000756
Colin Crosse3924e12018-08-15 20:18:53 -0700757 if pathtools.IsGlob(path.String()) {
758 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
759 return OptionalPath{}
760 }
761
Colin Cross192e97a2018-02-22 14:21:02 -0800762 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000763 if err != nil {
764 reportPathError(ctx, err)
765 return OptionalPath{}
766 }
Colin Cross192e97a2018-02-22 14:21:02 -0800767 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000768 return OptionalPath{}
769 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700770 return OptionalPathForPath(path)
771}
772
773func (p SourcePath) String() string {
774 return filepath.Join(p.config.srcDir, p.path)
775}
776
777// Join creates a new SourcePath with paths... joined with the current path. The
778// provided paths... may not use '..' to escape from the current path.
779func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800780 path, err := validatePath(paths...)
781 if err != nil {
782 reportPathError(ctx, err)
783 }
Colin Cross0db55682017-12-05 15:36:55 -0800784 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700785}
786
Colin Cross2fafa3e2019-03-05 12:39:51 -0800787// join is like Join but does less path validation.
788func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
789 path, err := validateSafePath(paths...)
790 if err != nil {
791 reportPathError(ctx, err)
792 }
793 return p.withRel(path)
794}
795
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700796// OverlayPath returns the overlay for `path' if it exists. This assumes that the
797// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700798func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700799 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800800 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700801 relDir = srcPath.path
802 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800803 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700804 return OptionalPath{}
805 }
806 dir := filepath.Join(p.config.srcDir, p.path, relDir)
807 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700808 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800809 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800810 }
Colin Cross461b4452018-02-23 09:22:42 -0800811 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700812 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800813 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700814 return OptionalPath{}
815 }
816 if len(paths) == 0 {
817 return OptionalPath{}
818 }
Colin Cross43f08db2018-11-12 10:13:39 -0800819 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700820 return OptionalPathForPath(PathForSource(ctx, relPath))
821}
822
Colin Cross70dda7e2019-10-01 22:05:35 -0700823// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700824type OutputPath struct {
825 basePath
826}
827
Colin Cross702e0f82017-10-18 17:27:54 -0700828func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800829 p.basePath = p.basePath.withRel(rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700830 return p
831}
832
Colin Cross3063b782018-08-15 11:19:12 -0700833func (p OutputPath) WithoutRel() OutputPath {
834 p.basePath.rel = filepath.Base(p.basePath.path)
835 return p
836}
837
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700838var _ Path = OutputPath{}
839
Jeff Gaston734e3802017-04-10 15:47:24 -0700840// PathForOutput joins the provided paths and returns an OutputPath that is
841// validated to not escape the build dir.
842// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
843func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800844 path, err := validatePath(pathComponents...)
845 if err != nil {
846 reportPathError(ctx, err)
847 }
Colin Crossaabf6792017-11-29 00:27:14 -0800848 return OutputPath{basePath{path, ctx.Config(), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700849}
850
Colin Cross40e33732019-02-15 11:08:35 -0800851// PathsForOutput returns Paths rooted from buildDir
852func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
853 ret := make(WritablePaths, len(paths))
854 for i, path := range paths {
855 ret[i] = PathForOutput(ctx, path)
856 }
857 return ret
858}
859
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700860func (p OutputPath) writablePath() {}
861
862func (p OutputPath) String() string {
863 return filepath.Join(p.config.buildDir, p.path)
864}
865
866// Join creates a new OutputPath with paths... joined with the current path. The
867// provided paths... may not use '..' to escape from the current path.
868func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800869 path, err := validatePath(paths...)
870 if err != nil {
871 reportPathError(ctx, err)
872 }
Colin Cross0db55682017-12-05 15:36:55 -0800873 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700874}
875
Colin Cross8854a5a2019-02-11 14:14:16 -0800876// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
877func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
878 if strings.Contains(ext, "/") {
879 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
880 }
881 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800882 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800883 return ret
884}
885
Colin Cross40e33732019-02-15 11:08:35 -0800886// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
887func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
888 path, err := validatePath(paths...)
889 if err != nil {
890 reportPathError(ctx, err)
891 }
892
893 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800894 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800895 return ret
896}
897
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700898// PathForIntermediates returns an OutputPath representing the top-level
899// intermediates directory.
900func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800901 path, err := validatePath(paths...)
902 if err != nil {
903 reportPathError(ctx, err)
904 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700905 return PathForOutput(ctx, ".intermediates", path)
906}
907
Colin Cross07e51612019-03-05 12:46:40 -0800908var _ genPathProvider = SourcePath{}
909var _ objPathProvider = SourcePath{}
910var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700911
Colin Cross07e51612019-03-05 12:46:40 -0800912// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700913// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800914func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
915 p, err := validatePath(pathComponents...)
916 if err != nil {
917 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800918 }
Colin Cross8a497952019-03-05 22:25:09 -0800919 paths, err := expandOneSrcPath(ctx, p, nil)
920 if err != nil {
921 if depErr, ok := err.(missingDependencyError); ok {
922 if ctx.Config().AllowMissingDependencies() {
923 ctx.AddMissingDependencies(depErr.missingDeps)
924 } else {
925 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
926 }
927 } else {
928 reportPathError(ctx, err)
929 }
930 return nil
931 } else if len(paths) == 0 {
932 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
933 return nil
934 } else if len(paths) > 1 {
935 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
936 }
937 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700938}
939
Colin Cross07e51612019-03-05 12:46:40 -0800940func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
941 p, err := validatePath(paths...)
942 if err != nil {
943 reportPathError(ctx, err)
944 }
945
946 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
947 if err != nil {
948 reportPathError(ctx, err)
949 }
950
951 path.basePath.rel = p
952
953 return path
954}
955
Colin Cross2fafa3e2019-03-05 12:39:51 -0800956// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
957// will return the path relative to subDir in the module's source directory. If any input paths are not located
958// inside subDir then a path error will be reported.
959func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
960 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -0800961 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800962 for i, path := range paths {
963 rel := Rel(ctx, subDirFullPath.String(), path.String())
964 paths[i] = subDirFullPath.join(ctx, rel)
965 }
966 return paths
967}
968
969// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
970// module's source directory. If the input path is not located inside subDir then a path error will be reported.
971func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -0800972 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800973 rel := Rel(ctx, subDirFullPath.String(), path.String())
974 return subDirFullPath.Join(ctx, rel)
975}
976
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700977// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
978// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700979func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700980 if p == nil {
981 return OptionalPath{}
982 }
983 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
984}
985
Colin Cross07e51612019-03-05 12:46:40 -0800986func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800987 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700988}
989
Colin Cross07e51612019-03-05 12:46:40 -0800990func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -0800991 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700992}
993
Colin Cross07e51612019-03-05 12:46:40 -0800994func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700995 // TODO: Use full directory if the new ctx is not the current ctx?
996 return PathForModuleRes(ctx, p.path, name)
997}
998
999// ModuleOutPath is a Path representing a module's output directory.
1000type ModuleOutPath struct {
1001 OutputPath
1002}
1003
1004var _ Path = ModuleOutPath{}
1005
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001006func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
1007 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1008}
1009
Colin Cross702e0f82017-10-18 17:27:54 -07001010func pathForModule(ctx ModuleContext) OutputPath {
1011 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1012}
1013
Logan Chien7eefdc42018-07-11 18:10:41 +08001014// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1015// reference abi dump for the given module. This is not guaranteed to be valid.
1016func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001017 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001018
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001019 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001020 if len(arches) == 0 {
1021 panic("device build with no primary arch")
1022 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001023 currentArch := ctx.Arch()
1024 archNameAndVariant := currentArch.ArchType.String()
1025 if currentArch.ArchVariant != "" {
1026 archNameAndVariant += "_" + currentArch.ArchVariant
1027 }
Logan Chien5237bed2018-07-11 17:15:57 +08001028
1029 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001030 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001031 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001032 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001033 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001034 } else {
1035 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001036 }
Logan Chien5237bed2018-07-11 17:15:57 +08001037
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001038 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001039
1040 var ext string
1041 if isGzip {
1042 ext = ".lsdump.gz"
1043 } else {
1044 ext = ".lsdump"
1045 }
1046
1047 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1048 version, binderBitness, archNameAndVariant, "source-based",
1049 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001050}
1051
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001052// PathForModuleOut returns a Path representing the paths... under the module's
1053// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001054func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001055 p, err := validatePath(paths...)
1056 if err != nil {
1057 reportPathError(ctx, err)
1058 }
Colin Cross702e0f82017-10-18 17:27:54 -07001059 return ModuleOutPath{
1060 OutputPath: pathForModule(ctx).withRel(p),
1061 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001062}
1063
1064// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1065// directory. Mainly used for generated sources.
1066type ModuleGenPath struct {
1067 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001068}
1069
1070var _ Path = ModuleGenPath{}
1071var _ genPathProvider = ModuleGenPath{}
1072var _ objPathProvider = ModuleGenPath{}
1073
1074// PathForModuleGen returns a Path representing the paths... under the module's
1075// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001076func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001077 p, err := validatePath(paths...)
1078 if err != nil {
1079 reportPathError(ctx, err)
1080 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001081 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001082 ModuleOutPath: ModuleOutPath{
1083 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1084 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001085 }
1086}
1087
Dan Willemsen21ec4902016-11-02 20:43:13 -07001088func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001089 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001090 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001091}
1092
Colin Cross635c3b02016-05-18 15:37:25 -07001093func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001094 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1095}
1096
1097// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1098// directory. Used for compiled objects.
1099type ModuleObjPath struct {
1100 ModuleOutPath
1101}
1102
1103var _ Path = ModuleObjPath{}
1104
1105// PathForModuleObj returns a Path representing the paths... under the module's
1106// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001107func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001108 p, err := validatePath(pathComponents...)
1109 if err != nil {
1110 reportPathError(ctx, err)
1111 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001112 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1113}
1114
1115// ModuleResPath is a a Path representing the 'res' directory in a module's
1116// output directory.
1117type ModuleResPath struct {
1118 ModuleOutPath
1119}
1120
1121var _ Path = ModuleResPath{}
1122
1123// PathForModuleRes returns a Path representing the paths... under the module's
1124// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001125func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001126 p, err := validatePath(pathComponents...)
1127 if err != nil {
1128 reportPathError(ctx, err)
1129 }
1130
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001131 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1132}
1133
Colin Cross70dda7e2019-10-01 22:05:35 -07001134// InstallPath is a Path representing a installed file path rooted from the build directory
1135type InstallPath struct {
1136 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001137
1138 baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
Colin Cross70dda7e2019-10-01 22:05:35 -07001139}
1140
1141func (p InstallPath) writablePath() {}
1142
1143func (p InstallPath) String() string {
Colin Crossff6c33d2019-10-02 16:01:35 -07001144 return filepath.Join(p.config.buildDir, p.baseDir, p.path)
Colin Cross70dda7e2019-10-01 22:05:35 -07001145}
1146
1147// Join creates a new InstallPath with paths... joined with the current path. The
1148// provided paths... may not use '..' to escape from the current path.
1149func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1150 path, err := validatePath(paths...)
1151 if err != nil {
1152 reportPathError(ctx, err)
1153 }
1154 return p.withRel(path)
1155}
1156
1157func (p InstallPath) withRel(rel string) InstallPath {
1158 p.basePath = p.basePath.withRel(rel)
1159 return p
1160}
1161
Colin Crossff6c33d2019-10-02 16:01:35 -07001162// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1163// i.e. out/ instead of out/soong/.
1164func (p InstallPath) ToMakePath() InstallPath {
1165 p.baseDir = "../"
1166 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001167}
1168
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001169// PathForModuleInstall returns a Path representing the install path for the
1170// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001171func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001172 var outPaths []string
1173 if ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -08001174 partition := modulePartition(ctx)
Colin Cross6510f912017-11-29 00:27:14 -08001175 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001176 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -07001177 switch ctx.Os() {
1178 case Linux:
1179 outPaths = []string{"host", "linux-x86"}
1180 case LinuxBionic:
1181 // TODO: should this be a separate top level, or shared with linux-x86?
1182 outPaths = []string{"host", "linux_bionic-x86"}
1183 default:
1184 outPaths = []string{"host", ctx.Os().String() + "-x86"}
1185 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001186 }
Dan Willemsen782a2d12015-12-21 14:55:28 -08001187 if ctx.Debug() {
1188 outPaths = append([]string{"debug"}, outPaths...)
1189 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001190 outPaths = append(outPaths, pathComponents...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001191
1192 path, err := validatePath(outPaths...)
1193 if err != nil {
1194 reportPathError(ctx, err)
1195 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001196
1197 ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
1198 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1199 ret = ret.ToMakePath()
1200 }
1201
1202 return ret
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001203}
1204
Colin Cross70dda7e2019-10-01 22:05:35 -07001205func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1206 paths = append([]string{"ndk"}, paths...)
1207 path, err := validatePath(paths...)
1208 if err != nil {
1209 reportPathError(ctx, err)
1210 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001211 return InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Cross70dda7e2019-10-01 22:05:35 -07001212}
1213
1214func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001215 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1216
1217 return "/" + rel
1218}
1219
1220func modulePartition(ctx ModuleInstallPathContext) string {
1221 var partition string
1222 if ctx.InstallInData() {
1223 partition = "data"
Jaewoong Jung0949f312019-09-11 10:25:18 -07001224 } else if ctx.InstallInTestcases() {
1225 partition = "testcases"
Colin Cross43f08db2018-11-12 10:13:39 -08001226 } else if ctx.InstallInRecovery() {
Colin Cross90ba5f42019-10-02 11:10:58 -07001227 if ctx.InstallInRoot() {
1228 partition = "recovery/root"
1229 } else {
1230 // the layout of recovery partion is the same as that of system partition
1231 partition = "recovery/root/system"
1232 }
Colin Cross43f08db2018-11-12 10:13:39 -08001233 } else if ctx.SocSpecific() {
1234 partition = ctx.DeviceConfig().VendorPath()
1235 } else if ctx.DeviceSpecific() {
1236 partition = ctx.DeviceConfig().OdmPath()
1237 } else if ctx.ProductSpecific() {
1238 partition = ctx.DeviceConfig().ProductPath()
Justin Yund5f6c822019-06-25 16:47:17 +09001239 } else if ctx.SystemExtSpecific() {
1240 partition = ctx.DeviceConfig().SystemExtPath()
Colin Cross90ba5f42019-10-02 11:10:58 -07001241 } else if ctx.InstallInRoot() {
1242 partition = "root"
Colin Cross43f08db2018-11-12 10:13:39 -08001243 } else {
1244 partition = "system"
1245 }
1246 if ctx.InstallInSanitizerDir() {
1247 partition = "data/asan/" + partition
1248 }
1249 return partition
1250}
1251
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001252// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001253// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001254func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001255 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001256 path := filepath.Clean(path)
1257 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001258 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001259 }
1260 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001261 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1262 // variables. '..' may remove the entire ninja variable, even if it
1263 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001264 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001265}
1266
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001267// validatePath validates that a path does not include ninja variables, and that
1268// each path component does not attempt to leave its component. Returns a joined
1269// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001270func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001271 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001272 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001273 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001274 }
1275 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001276 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001277}
Colin Cross5b529592017-05-09 13:34:34 -07001278
Colin Cross0875c522017-11-28 17:34:01 -08001279func PathForPhony(ctx PathContext, phony string) WritablePath {
1280 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001281 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001282 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001283 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001284}
1285
Colin Cross74e3fe42017-12-11 15:51:44 -08001286type PhonyPath struct {
1287 basePath
1288}
1289
1290func (p PhonyPath) writablePath() {}
1291
1292var _ Path = PhonyPath{}
1293var _ WritablePath = PhonyPath{}
1294
Colin Cross5b529592017-05-09 13:34:34 -07001295type testPath struct {
1296 basePath
1297}
1298
1299func (p testPath) String() string {
1300 return p.path
1301}
1302
Colin Cross40e33732019-02-15 11:08:35 -08001303type testWritablePath struct {
1304 testPath
1305}
1306
1307func (p testPath) writablePath() {}
1308
1309// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1310// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001311func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001312 p, err := validateSafePath(paths...)
1313 if err != nil {
1314 panic(err)
1315 }
Colin Cross5b529592017-05-09 13:34:34 -07001316 return testPath{basePath{path: p, rel: p}}
1317}
1318
Colin Cross40e33732019-02-15 11:08:35 -08001319// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1320func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001321 p := make(Paths, len(strs))
1322 for i, s := range strs {
1323 p[i] = PathForTesting(s)
1324 }
1325
1326 return p
1327}
Colin Cross43f08db2018-11-12 10:13:39 -08001328
Colin Cross40e33732019-02-15 11:08:35 -08001329// WritablePathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be
1330// used from within tests.
1331func WritablePathForTesting(paths ...string) WritablePath {
1332 p, err := validateSafePath(paths...)
1333 if err != nil {
1334 panic(err)
1335 }
1336 return testWritablePath{testPath{basePath{path: p, rel: p}}}
1337}
1338
1339// WritablePathsForTesting returns a Path constructed from each element in strs. It should only be used from within
1340// tests.
1341func WritablePathsForTesting(strs ...string) WritablePaths {
1342 p := make(WritablePaths, len(strs))
1343 for i, s := range strs {
1344 p[i] = WritablePathForTesting(s)
1345 }
1346
1347 return p
1348}
1349
1350type testPathContext struct {
1351 config Config
1352 fs pathtools.FileSystem
1353}
1354
1355func (x *testPathContext) Fs() pathtools.FileSystem { return x.fs }
1356func (x *testPathContext) Config() Config { return x.config }
1357func (x *testPathContext) AddNinjaFileDeps(...string) {}
1358
1359// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1360// PathForOutput.
1361func PathContextForTesting(config Config, fs map[string][]byte) PathContext {
1362 return &testPathContext{
1363 config: config,
1364 fs: pathtools.MockFs(fs),
1365 }
1366}
1367
Colin Cross43f08db2018-11-12 10:13:39 -08001368// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1369// targetPath is not inside basePath.
1370func Rel(ctx PathContext, basePath string, targetPath string) string {
1371 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1372 if !isRel {
1373 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1374 return ""
1375 }
1376 return rel
1377}
1378
1379// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1380// targetPath is not inside basePath.
1381func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001382 rel, isRel, err := maybeRelErr(basePath, targetPath)
1383 if err != nil {
1384 reportPathError(ctx, err)
1385 }
1386 return rel, isRel
1387}
1388
1389func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001390 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1391 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001392 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001393 }
1394 rel, err := filepath.Rel(basePath, targetPath)
1395 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001396 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001397 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001398 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001399 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001400 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001401}