blob: d181b75b404216f6fb918e6fbfd3366c56c4b153 [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
Colin Cross5e708052019-08-06 13:59:50 -070092func pathContextName(ctx PathContext, module blueprint.Module) string {
93 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
94 return x.ModuleName(module)
95 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
96 return x.OtherModuleName(module)
97 }
98 return "unknown"
99}
100
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700101type Path interface {
102 // Returns the path in string form
103 String() string
104
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700105 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700106 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700107
108 // Base returns the last element of the path
109 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800110
111 // Rel returns the portion of the path relative to the directory it was created from. For
112 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800113 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800114 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700115}
116
117// WritablePath is a type of path that can be used as an output for build rules.
118type WritablePath interface {
119 Path
120
Jeff Gaston734e3802017-04-10 15:47:24 -0700121 // the writablePath method doesn't directly do anything,
122 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700123 writablePath()
124}
125
126type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700127 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700128}
129type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700130 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700131}
132type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700133 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700134}
135
136// GenPathWithExt derives a new file path in ctx's generated sources directory
137// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700138func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700139 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700140 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700141 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800142 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700143 return PathForModuleGen(ctx)
144}
145
146// ObjPathWithExt derives a new file path in ctx's object directory from the
147// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700148func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700149 if path, ok := p.(objPathProvider); ok {
150 return path.objPathWithExt(ctx, subdir, ext)
151 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800152 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700153 return PathForModuleObj(ctx)
154}
155
156// ResPathWithName derives a new path in ctx's output resource directory, using
157// the current path to create the directory name, and the `name` argument for
158// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700159func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700160 if path, ok := p.(resPathProvider); ok {
161 return path.resPathWithName(ctx, name)
162 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800163 reportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700164 return PathForModuleRes(ctx)
165}
166
167// OptionalPath is a container that may or may not contain a valid Path.
168type OptionalPath struct {
169 valid bool
170 path Path
171}
172
173// OptionalPathForPath returns an OptionalPath containing the path.
174func OptionalPathForPath(path Path) OptionalPath {
175 if path == nil {
176 return OptionalPath{}
177 }
178 return OptionalPath{valid: true, path: path}
179}
180
181// Valid returns whether there is a valid path
182func (p OptionalPath) Valid() bool {
183 return p.valid
184}
185
186// Path returns the Path embedded in this OptionalPath. You must be sure that
187// there is a valid path, since this method will panic if there is not.
188func (p OptionalPath) Path() Path {
189 if !p.valid {
190 panic("Requesting an invalid path")
191 }
192 return p.path
193}
194
195// String returns the string version of the Path, or "" if it isn't valid.
196func (p OptionalPath) String() string {
197 if p.valid {
198 return p.path.String()
199 } else {
200 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700201 }
202}
Colin Cross6e18ca42015-07-14 18:55:36 -0700203
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700204// Paths is a slice of Path objects, with helpers to operate on the collection.
205type Paths []Path
206
207// PathsForSource returns Paths rooted from SrcDir
208func PathsForSource(ctx PathContext, paths []string) Paths {
209 ret := make(Paths, len(paths))
210 for i, path := range paths {
211 ret[i] = PathForSource(ctx, path)
212 }
213 return ret
214}
215
Jeff Gaston734e3802017-04-10 15:47:24 -0700216// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800217// found in the tree. If any are not found, they are omitted from the list,
218// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800219func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800220 ret := make(Paths, 0, len(paths))
221 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800222 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800223 if p.Valid() {
224 ret = append(ret, p.Path())
225 }
226 }
227 return ret
228}
229
Colin Cross41955e82019-05-29 14:40:35 -0700230// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
231// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
232// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
233// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
234// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
235// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700236func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800237 return PathsForModuleSrcExcludes(ctx, paths, nil)
238}
239
Colin Crossba71a3f2019-03-18 12:12:48 -0700240// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700241// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
242// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
243// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
244// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100245// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700246// having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800247func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700248 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
249 if ctx.Config().AllowMissingDependencies() {
250 ctx.AddMissingDependencies(missingDeps)
251 } else {
252 for _, m := range missingDeps {
253 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
254 }
255 }
256 return ret
257}
258
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000259// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
260type OutputPaths []OutputPath
261
262// Paths returns the OutputPaths as a Paths
263func (p OutputPaths) Paths() Paths {
264 if p == nil {
265 return nil
266 }
267 ret := make(Paths, len(p))
268 for i, path := range p {
269 ret[i] = path
270 }
271 return ret
272}
273
274// Strings returns the string forms of the writable paths.
275func (p OutputPaths) Strings() []string {
276 if p == nil {
277 return nil
278 }
279 ret := make([]string, len(p))
280 for i, path := range p {
281 ret[i] = path.String()
282 }
283 return ret
284}
285
Colin Crossba71a3f2019-03-18 12:12:48 -0700286// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700287// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
288// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
289// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
290// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
291// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
292// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
293// dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700294func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800295 prefix := pathForModuleSrc(ctx).String()
296
297 var expandedExcludes []string
298 if excludes != nil {
299 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700300 }
Colin Cross8a497952019-03-05 22:25:09 -0800301
Colin Crossba71a3f2019-03-18 12:12:48 -0700302 var missingExcludeDeps []string
303
Colin Cross8a497952019-03-05 22:25:09 -0800304 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700305 if m, t := SrcIsModuleWithTag(e); m != "" {
306 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800307 if module == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700308 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800309 continue
310 }
Colin Cross41955e82019-05-29 14:40:35 -0700311 if outProducer, ok := module.(OutputFileProducer); ok {
312 outputFiles, err := outProducer.OutputFiles(t)
313 if err != nil {
314 ctx.ModuleErrorf("path dependency %q: %s", e, err)
315 }
316 expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
317 } else if t != "" {
318 ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
319 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800320 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
321 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700322 ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
Colin Cross8a497952019-03-05 22:25:09 -0800323 }
324 } else {
325 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
326 }
327 }
328
329 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700330 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800331 }
332
Colin Crossba71a3f2019-03-18 12:12:48 -0700333 var missingDeps []string
334
Colin Cross8a497952019-03-05 22:25:09 -0800335 expandedSrcFiles := make(Paths, 0, len(paths))
336 for _, s := range paths {
337 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
338 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700339 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800340 } else if err != nil {
341 reportPathError(ctx, err)
342 }
343 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
344 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700345
346 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800347}
348
349type missingDependencyError struct {
350 missingDeps []string
351}
352
353func (e missingDependencyError) Error() string {
354 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
355}
356
357func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
Colin Cross41955e82019-05-29 14:40:35 -0700358 if m, t := SrcIsModuleWithTag(s); m != "" {
359 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800360 if module == nil {
361 return nil, missingDependencyError{[]string{m}}
362 }
Colin Cross41955e82019-05-29 14:40:35 -0700363 if outProducer, ok := module.(OutputFileProducer); ok {
364 outputFiles, err := outProducer.OutputFiles(t)
365 if err != nil {
366 return nil, fmt.Errorf("path dependency %q: %s", s, err)
367 }
368 return outputFiles, nil
369 } else if t != "" {
370 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
371 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800372 moduleSrcs := srcProducer.Srcs()
373 for _, e := range expandedExcludes {
374 for j := 0; j < len(moduleSrcs); j++ {
375 if moduleSrcs[j].String() == e {
376 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
377 j--
378 }
379 }
380 }
381 return moduleSrcs, nil
382 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700383 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800384 }
385 } else if pathtools.IsGlob(s) {
386 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
387 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
388 } else {
389 p := pathForModuleSrc(ctx, s)
390 if exists, _, err := ctx.Fs().Exists(p.String()); err != nil {
391 reportPathErrorf(ctx, "%s: %s", p, err.Error())
392 } else if !exists {
393 reportPathErrorf(ctx, "module source path %q does not exist", p)
394 }
395
396 j := findStringInSlice(p.String(), expandedExcludes)
397 if j >= 0 {
398 return nil, nil
399 }
400 return Paths{p}, nil
401 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700402}
403
404// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
405// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800406// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700407// It intended for use in globs that only list files that exist, so it allows '$' in
408// filenames.
Colin Crossdc35e212019-06-06 16:13:11 -0700409func pathsForModuleSrcFromFullPath(ctx BaseModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800410 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700411 if prefix == "./" {
412 prefix = ""
413 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700414 ret := make(Paths, 0, len(paths))
415 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800416 if !incDirs && strings.HasSuffix(p, "/") {
417 continue
418 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700419 path := filepath.Clean(p)
420 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800421 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700422 continue
423 }
Colin Crosse3924e12018-08-15 20:18:53 -0700424
Colin Crossfe4bc362018-09-12 10:02:13 -0700425 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700426 if err != nil {
427 reportPathError(ctx, err)
428 continue
429 }
430
Colin Cross07e51612019-03-05 12:46:40 -0800431 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700432
Colin Cross07e51612019-03-05 12:46:40 -0800433 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700434 }
435 return ret
436}
437
438// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800439// 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 -0700440func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800441 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700442 return PathsForModuleSrc(ctx, input)
443 }
444 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
445 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800446 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800447 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700448}
449
450// Strings returns the Paths in string form
451func (p Paths) Strings() []string {
452 if p == nil {
453 return nil
454 }
455 ret := make([]string, len(p))
456 for i, path := range p {
457 ret[i] = path.String()
458 }
459 return ret
460}
461
Colin Crossb6715442017-10-24 11:13:31 -0700462// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
463// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700464func FirstUniquePaths(list Paths) Paths {
465 k := 0
466outer:
467 for i := 0; i < len(list); i++ {
468 for j := 0; j < k; j++ {
469 if list[i] == list[j] {
470 continue outer
471 }
472 }
473 list[k] = list[i]
474 k++
475 }
476 return list[:k]
477}
478
Colin Crossb6715442017-10-24 11:13:31 -0700479// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
480// modifies the Paths slice contents in place, and returns a subslice of the original slice.
481func LastUniquePaths(list Paths) Paths {
482 totalSkip := 0
483 for i := len(list) - 1; i >= totalSkip; i-- {
484 skip := 0
485 for j := i - 1; j >= totalSkip; j-- {
486 if list[i] == list[j] {
487 skip++
488 } else {
489 list[j+skip] = list[j]
490 }
491 }
492 totalSkip += skip
493 }
494 return list[totalSkip:]
495}
496
Colin Crossa140bb02018-04-17 10:52:26 -0700497// ReversePaths returns a copy of a Paths in reverse order.
498func ReversePaths(list Paths) Paths {
499 if list == nil {
500 return nil
501 }
502 ret := make(Paths, len(list))
503 for i := range list {
504 ret[i] = list[len(list)-1-i]
505 }
506 return ret
507}
508
Jeff Gaston294356f2017-09-27 17:05:30 -0700509func indexPathList(s Path, list []Path) int {
510 for i, l := range list {
511 if l == s {
512 return i
513 }
514 }
515
516 return -1
517}
518
519func inPathList(p Path, list []Path) bool {
520 return indexPathList(p, list) != -1
521}
522
523func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000524 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
525}
526
527func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700528 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000529 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700530 filtered = append(filtered, l)
531 } else {
532 remainder = append(remainder, l)
533 }
534 }
535
536 return
537}
538
Colin Cross93e85952017-08-15 13:34:18 -0700539// HasExt returns true of any of the paths have extension ext, otherwise false
540func (p Paths) HasExt(ext string) bool {
541 for _, path := range p {
542 if path.Ext() == ext {
543 return true
544 }
545 }
546
547 return false
548}
549
550// FilterByExt returns the subset of the paths that have extension ext
551func (p Paths) FilterByExt(ext string) Paths {
552 ret := make(Paths, 0, len(p))
553 for _, path := range p {
554 if path.Ext() == ext {
555 ret = append(ret, path)
556 }
557 }
558 return ret
559}
560
561// FilterOutByExt returns the subset of the paths that do not have extension ext
562func (p Paths) FilterOutByExt(ext string) Paths {
563 ret := make(Paths, 0, len(p))
564 for _, path := range p {
565 if path.Ext() != ext {
566 ret = append(ret, path)
567 }
568 }
569 return ret
570}
571
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700572// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
573// (including subdirectories) are in a contiguous subslice of the list, and can be found in
574// O(log(N)) time using a binary search on the directory prefix.
575type DirectorySortedPaths Paths
576
577func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
578 ret := append(DirectorySortedPaths(nil), paths...)
579 sort.Slice(ret, func(i, j int) bool {
580 return ret[i].String() < ret[j].String()
581 })
582 return ret
583}
584
585// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
586// that are in the specified directory and its subdirectories.
587func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
588 prefix := filepath.Clean(dir) + "/"
589 start := sort.Search(len(p), func(i int) bool {
590 return prefix < p[i].String()
591 })
592
593 ret := p[start:]
594
595 end := sort.Search(len(ret), func(i int) bool {
596 return !strings.HasPrefix(ret[i].String(), prefix)
597 })
598
599 ret = ret[:end]
600
601 return Paths(ret)
602}
603
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700604// WritablePaths is a slice of WritablePaths, used for multiple outputs.
605type WritablePaths []WritablePath
606
607// Strings returns the string forms of the writable paths.
608func (p WritablePaths) Strings() []string {
609 if p == nil {
610 return nil
611 }
612 ret := make([]string, len(p))
613 for i, path := range p {
614 ret[i] = path.String()
615 }
616 return ret
617}
618
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800619// Paths returns the WritablePaths as a Paths
620func (p WritablePaths) Paths() Paths {
621 if p == nil {
622 return nil
623 }
624 ret := make(Paths, len(p))
625 for i, path := range p {
626 ret[i] = path
627 }
628 return ret
629}
630
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700631type basePath struct {
632 path string
633 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800634 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700635}
636
637func (p basePath) Ext() string {
638 return filepath.Ext(p.path)
639}
640
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700641func (p basePath) Base() string {
642 return filepath.Base(p.path)
643}
644
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800645func (p basePath) Rel() string {
646 if p.rel != "" {
647 return p.rel
648 }
649 return p.path
650}
651
Colin Cross0875c522017-11-28 17:34:01 -0800652func (p basePath) String() string {
653 return p.path
654}
655
Colin Cross0db55682017-12-05 15:36:55 -0800656func (p basePath) withRel(rel string) basePath {
657 p.path = filepath.Join(p.path, rel)
658 p.rel = rel
659 return p
660}
661
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700662// SourcePath is a Path representing a file path rooted from SrcDir
663type SourcePath struct {
664 basePath
665}
666
667var _ Path = SourcePath{}
668
Colin Cross0db55682017-12-05 15:36:55 -0800669func (p SourcePath) withRel(rel string) SourcePath {
670 p.basePath = p.basePath.withRel(rel)
671 return p
672}
673
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700674// safePathForSource is for paths that we expect are safe -- only for use by go
675// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700676func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
677 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800678 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700679 if err != nil {
680 return ret, err
681 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700682
Colin Cross7b3dcc32019-01-24 13:14:39 -0800683 // absolute path already checked by validateSafePath
684 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800685 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700686 }
687
Colin Crossfe4bc362018-09-12 10:02:13 -0700688 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700689}
690
Colin Cross192e97a2018-02-22 14:21:02 -0800691// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
692func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000693 p, err := validatePath(pathComponents...)
694 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800695 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800696 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800697 }
698
Colin Cross7b3dcc32019-01-24 13:14:39 -0800699 // absolute path already checked by validatePath
700 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800701 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000702 }
703
Colin Cross192e97a2018-02-22 14:21:02 -0800704 return ret, nil
705}
706
707// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
708// path does not exist.
709func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
710 var files []string
711
712 if gctx, ok := ctx.(PathGlobContext); ok {
713 // Use glob to produce proper dependencies, even though we only want
714 // a single file.
715 files, err = gctx.GlobWithDeps(path.String(), nil)
716 } else {
717 var deps []string
718 // We cannot add build statements in this context, so we fall back to
719 // AddNinjaFileDeps
Colin Cross3f4d1162018-09-21 15:11:48 -0700720 files, deps, err = pathtools.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800721 ctx.AddNinjaFileDeps(deps...)
722 }
723
724 if err != nil {
725 return false, fmt.Errorf("glob: %s", err.Error())
726 }
727
728 return len(files) > 0, nil
729}
730
731// PathForSource joins the provided path components and validates that the result
732// neither escapes the source dir nor is in the out dir.
733// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
734func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
735 path, err := pathForSource(ctx, pathComponents...)
736 if err != nil {
737 reportPathError(ctx, err)
738 }
739
Colin Crosse3924e12018-08-15 20:18:53 -0700740 if pathtools.IsGlob(path.String()) {
741 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
742 }
743
Colin Cross192e97a2018-02-22 14:21:02 -0800744 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
745 exists, err := existsWithDependencies(ctx, path)
746 if err != nil {
747 reportPathError(ctx, err)
748 }
749 if !exists {
750 modCtx.AddMissingDependencies([]string{path.String()})
751 }
752 } else if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
753 reportPathErrorf(ctx, "%s: %s", path, err.Error())
754 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800755 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800756 }
757 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700758}
759
Jeff Gaston734e3802017-04-10 15:47:24 -0700760// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700761// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
762// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800763func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800764 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800765 if err != nil {
766 reportPathError(ctx, err)
767 return OptionalPath{}
768 }
Colin Crossc48c1432018-02-23 07:09:01 +0000769
Colin Crosse3924e12018-08-15 20:18:53 -0700770 if pathtools.IsGlob(path.String()) {
771 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
772 return OptionalPath{}
773 }
774
Colin Cross192e97a2018-02-22 14:21:02 -0800775 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000776 if err != nil {
777 reportPathError(ctx, err)
778 return OptionalPath{}
779 }
Colin Cross192e97a2018-02-22 14:21:02 -0800780 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000781 return OptionalPath{}
782 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700783 return OptionalPathForPath(path)
784}
785
786func (p SourcePath) String() string {
787 return filepath.Join(p.config.srcDir, p.path)
788}
789
790// Join creates a new SourcePath with paths... joined with the current path. The
791// provided paths... may not use '..' to escape from the current path.
792func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800793 path, err := validatePath(paths...)
794 if err != nil {
795 reportPathError(ctx, err)
796 }
Colin Cross0db55682017-12-05 15:36:55 -0800797 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700798}
799
Colin Cross2fafa3e2019-03-05 12:39:51 -0800800// join is like Join but does less path validation.
801func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
802 path, err := validateSafePath(paths...)
803 if err != nil {
804 reportPathError(ctx, err)
805 }
806 return p.withRel(path)
807}
808
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700809// OverlayPath returns the overlay for `path' if it exists. This assumes that the
810// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700811func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700812 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800813 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700814 relDir = srcPath.path
815 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800816 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700817 return OptionalPath{}
818 }
819 dir := filepath.Join(p.config.srcDir, p.path, relDir)
820 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700821 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800822 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800823 }
Colin Cross461b4452018-02-23 09:22:42 -0800824 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700825 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800826 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700827 return OptionalPath{}
828 }
829 if len(paths) == 0 {
830 return OptionalPath{}
831 }
Colin Cross43f08db2018-11-12 10:13:39 -0800832 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700833 return OptionalPathForPath(PathForSource(ctx, relPath))
834}
835
Colin Cross70dda7e2019-10-01 22:05:35 -0700836// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700837type OutputPath struct {
838 basePath
839}
840
Colin Cross702e0f82017-10-18 17:27:54 -0700841func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800842 p.basePath = p.basePath.withRel(rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700843 return p
844}
845
Colin Cross3063b782018-08-15 11:19:12 -0700846func (p OutputPath) WithoutRel() OutputPath {
847 p.basePath.rel = filepath.Base(p.basePath.path)
848 return p
849}
850
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700851var _ Path = OutputPath{}
852
Jeff Gaston734e3802017-04-10 15:47:24 -0700853// PathForOutput joins the provided paths and returns an OutputPath that is
854// validated to not escape the build dir.
855// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
856func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800857 path, err := validatePath(pathComponents...)
858 if err != nil {
859 reportPathError(ctx, err)
860 }
Colin Crossaabf6792017-11-29 00:27:14 -0800861 return OutputPath{basePath{path, ctx.Config(), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700862}
863
Colin Cross40e33732019-02-15 11:08:35 -0800864// PathsForOutput returns Paths rooted from buildDir
865func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
866 ret := make(WritablePaths, len(paths))
867 for i, path := range paths {
868 ret[i] = PathForOutput(ctx, path)
869 }
870 return ret
871}
872
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700873func (p OutputPath) writablePath() {}
874
875func (p OutputPath) String() string {
876 return filepath.Join(p.config.buildDir, p.path)
877}
878
879// Join creates a new OutputPath with paths... joined with the current path. The
880// provided paths... may not use '..' to escape from the current path.
881func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800882 path, err := validatePath(paths...)
883 if err != nil {
884 reportPathError(ctx, err)
885 }
Colin Cross0db55682017-12-05 15:36:55 -0800886 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700887}
888
Colin Cross8854a5a2019-02-11 14:14:16 -0800889// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
890func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
891 if strings.Contains(ext, "/") {
892 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
893 }
894 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800895 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800896 return ret
897}
898
Colin Cross40e33732019-02-15 11:08:35 -0800899// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
900func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
901 path, err := validatePath(paths...)
902 if err != nil {
903 reportPathError(ctx, err)
904 }
905
906 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800907 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800908 return ret
909}
910
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700911// PathForIntermediates returns an OutputPath representing the top-level
912// intermediates directory.
913func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800914 path, err := validatePath(paths...)
915 if err != nil {
916 reportPathError(ctx, err)
917 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700918 return PathForOutput(ctx, ".intermediates", path)
919}
920
Colin Cross07e51612019-03-05 12:46:40 -0800921var _ genPathProvider = SourcePath{}
922var _ objPathProvider = SourcePath{}
923var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700924
Colin Cross07e51612019-03-05 12:46:40 -0800925// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700926// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800927func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
928 p, err := validatePath(pathComponents...)
929 if err != nil {
930 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800931 }
Colin Cross8a497952019-03-05 22:25:09 -0800932 paths, err := expandOneSrcPath(ctx, p, nil)
933 if err != nil {
934 if depErr, ok := err.(missingDependencyError); ok {
935 if ctx.Config().AllowMissingDependencies() {
936 ctx.AddMissingDependencies(depErr.missingDeps)
937 } else {
938 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
939 }
940 } else {
941 reportPathError(ctx, err)
942 }
943 return nil
944 } else if len(paths) == 0 {
945 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
946 return nil
947 } else if len(paths) > 1 {
948 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
949 }
950 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700951}
952
Colin Cross07e51612019-03-05 12:46:40 -0800953func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
954 p, err := validatePath(paths...)
955 if err != nil {
956 reportPathError(ctx, err)
957 }
958
959 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
960 if err != nil {
961 reportPathError(ctx, err)
962 }
963
964 path.basePath.rel = p
965
966 return path
967}
968
Colin Cross2fafa3e2019-03-05 12:39:51 -0800969// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
970// will return the path relative to subDir in the module's source directory. If any input paths are not located
971// inside subDir then a path error will be reported.
972func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
973 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -0800974 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800975 for i, path := range paths {
976 rel := Rel(ctx, subDirFullPath.String(), path.String())
977 paths[i] = subDirFullPath.join(ctx, rel)
978 }
979 return paths
980}
981
982// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
983// module's source directory. If the input path is not located inside subDir then a path error will be reported.
984func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -0800985 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800986 rel := Rel(ctx, subDirFullPath.String(), path.String())
987 return subDirFullPath.Join(ctx, rel)
988}
989
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700990// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
991// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -0700992func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700993 if p == nil {
994 return OptionalPath{}
995 }
996 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
997}
998
Colin Cross07e51612019-03-05 12:46:40 -0800999func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001000 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001001}
1002
Colin Cross07e51612019-03-05 12:46:40 -08001003func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001004 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001005}
1006
Colin Cross07e51612019-03-05 12:46:40 -08001007func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001008 // TODO: Use full directory if the new ctx is not the current ctx?
1009 return PathForModuleRes(ctx, p.path, name)
1010}
1011
1012// ModuleOutPath is a Path representing a module's output directory.
1013type ModuleOutPath struct {
1014 OutputPath
1015}
1016
1017var _ Path = ModuleOutPath{}
1018
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001019func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
1020 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1021}
1022
Colin Cross702e0f82017-10-18 17:27:54 -07001023func pathForModule(ctx ModuleContext) OutputPath {
1024 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1025}
1026
Logan Chien7eefdc42018-07-11 18:10:41 +08001027// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1028// reference abi dump for the given module. This is not guaranteed to be valid.
1029func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001030 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001031
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001032 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001033 if len(arches) == 0 {
1034 panic("device build with no primary arch")
1035 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001036 currentArch := ctx.Arch()
1037 archNameAndVariant := currentArch.ArchType.String()
1038 if currentArch.ArchVariant != "" {
1039 archNameAndVariant += "_" + currentArch.ArchVariant
1040 }
Logan Chien5237bed2018-07-11 17:15:57 +08001041
1042 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001043 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001044 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001045 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001046 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001047 } else {
1048 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001049 }
Logan Chien5237bed2018-07-11 17:15:57 +08001050
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001051 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001052
1053 var ext string
1054 if isGzip {
1055 ext = ".lsdump.gz"
1056 } else {
1057 ext = ".lsdump"
1058 }
1059
1060 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1061 version, binderBitness, archNameAndVariant, "source-based",
1062 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001063}
1064
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001065// PathForModuleOut returns a Path representing the paths... under the module's
1066// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001067func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001068 p, err := validatePath(paths...)
1069 if err != nil {
1070 reportPathError(ctx, err)
1071 }
Colin Cross702e0f82017-10-18 17:27:54 -07001072 return ModuleOutPath{
1073 OutputPath: pathForModule(ctx).withRel(p),
1074 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001075}
1076
1077// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1078// directory. Mainly used for generated sources.
1079type ModuleGenPath struct {
1080 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001081}
1082
1083var _ Path = ModuleGenPath{}
1084var _ genPathProvider = ModuleGenPath{}
1085var _ objPathProvider = ModuleGenPath{}
1086
1087// PathForModuleGen returns a Path representing the paths... under the module's
1088// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001089func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001090 p, err := validatePath(paths...)
1091 if err != nil {
1092 reportPathError(ctx, err)
1093 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001094 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001095 ModuleOutPath: ModuleOutPath{
1096 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1097 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001098 }
1099}
1100
Dan Willemsen21ec4902016-11-02 20:43:13 -07001101func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001102 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001103 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001104}
1105
Colin Cross635c3b02016-05-18 15:37:25 -07001106func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001107 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1108}
1109
1110// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1111// directory. Used for compiled objects.
1112type ModuleObjPath struct {
1113 ModuleOutPath
1114}
1115
1116var _ Path = ModuleObjPath{}
1117
1118// PathForModuleObj returns a Path representing the paths... under the module's
1119// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001120func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001121 p, err := validatePath(pathComponents...)
1122 if err != nil {
1123 reportPathError(ctx, err)
1124 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001125 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1126}
1127
1128// ModuleResPath is a a Path representing the 'res' directory in a module's
1129// output directory.
1130type ModuleResPath struct {
1131 ModuleOutPath
1132}
1133
1134var _ Path = ModuleResPath{}
1135
1136// PathForModuleRes returns a Path representing the paths... under the module's
1137// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001138func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001139 p, err := validatePath(pathComponents...)
1140 if err != nil {
1141 reportPathError(ctx, err)
1142 }
1143
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001144 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1145}
1146
Colin Cross70dda7e2019-10-01 22:05:35 -07001147// InstallPath is a Path representing a installed file path rooted from the build directory
1148type InstallPath struct {
1149 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001150
1151 baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
Colin Cross70dda7e2019-10-01 22:05:35 -07001152}
1153
1154func (p InstallPath) writablePath() {}
1155
1156func (p InstallPath) String() string {
Colin Crossff6c33d2019-10-02 16:01:35 -07001157 return filepath.Join(p.config.buildDir, p.baseDir, p.path)
Colin Cross70dda7e2019-10-01 22:05:35 -07001158}
1159
1160// Join creates a new InstallPath with paths... joined with the current path. The
1161// provided paths... may not use '..' to escape from the current path.
1162func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1163 path, err := validatePath(paths...)
1164 if err != nil {
1165 reportPathError(ctx, err)
1166 }
1167 return p.withRel(path)
1168}
1169
1170func (p InstallPath) withRel(rel string) InstallPath {
1171 p.basePath = p.basePath.withRel(rel)
1172 return p
1173}
1174
Colin Crossff6c33d2019-10-02 16:01:35 -07001175// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1176// i.e. out/ instead of out/soong/.
1177func (p InstallPath) ToMakePath() InstallPath {
1178 p.baseDir = "../"
1179 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001180}
1181
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001182// PathForModuleInstall returns a Path representing the install path for the
1183// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001184func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001185 var outPaths []string
1186 if ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -08001187 partition := modulePartition(ctx)
Colin Cross6510f912017-11-29 00:27:14 -08001188 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001189 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -07001190 switch ctx.Os() {
1191 case Linux:
1192 outPaths = []string{"host", "linux-x86"}
1193 case LinuxBionic:
1194 // TODO: should this be a separate top level, or shared with linux-x86?
1195 outPaths = []string{"host", "linux_bionic-x86"}
1196 default:
1197 outPaths = []string{"host", ctx.Os().String() + "-x86"}
1198 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001199 }
Dan Willemsen782a2d12015-12-21 14:55:28 -08001200 if ctx.Debug() {
1201 outPaths = append([]string{"debug"}, outPaths...)
1202 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001203 outPaths = append(outPaths, pathComponents...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001204
1205 path, err := validatePath(outPaths...)
1206 if err != nil {
1207 reportPathError(ctx, err)
1208 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001209
1210 ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
1211 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1212 ret = ret.ToMakePath()
1213 }
1214
1215 return ret
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001216}
1217
Colin Cross70dda7e2019-10-01 22:05:35 -07001218func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1219 paths = append([]string{"ndk"}, paths...)
1220 path, err := validatePath(paths...)
1221 if err != nil {
1222 reportPathError(ctx, err)
1223 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001224 return InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Cross70dda7e2019-10-01 22:05:35 -07001225}
1226
1227func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001228 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1229
1230 return "/" + rel
1231}
1232
1233func modulePartition(ctx ModuleInstallPathContext) string {
1234 var partition string
1235 if ctx.InstallInData() {
1236 partition = "data"
Jaewoong Jung0949f312019-09-11 10:25:18 -07001237 } else if ctx.InstallInTestcases() {
1238 partition = "testcases"
Colin Cross43f08db2018-11-12 10:13:39 -08001239 } else if ctx.InstallInRecovery() {
Colin Cross90ba5f42019-10-02 11:10:58 -07001240 if ctx.InstallInRoot() {
1241 partition = "recovery/root"
1242 } else {
1243 // the layout of recovery partion is the same as that of system partition
1244 partition = "recovery/root/system"
1245 }
Colin Cross43f08db2018-11-12 10:13:39 -08001246 } else if ctx.SocSpecific() {
1247 partition = ctx.DeviceConfig().VendorPath()
1248 } else if ctx.DeviceSpecific() {
1249 partition = ctx.DeviceConfig().OdmPath()
1250 } else if ctx.ProductSpecific() {
1251 partition = ctx.DeviceConfig().ProductPath()
Justin Yund5f6c822019-06-25 16:47:17 +09001252 } else if ctx.SystemExtSpecific() {
1253 partition = ctx.DeviceConfig().SystemExtPath()
Colin Cross90ba5f42019-10-02 11:10:58 -07001254 } else if ctx.InstallInRoot() {
1255 partition = "root"
Colin Cross43f08db2018-11-12 10:13:39 -08001256 } else {
1257 partition = "system"
1258 }
1259 if ctx.InstallInSanitizerDir() {
1260 partition = "data/asan/" + partition
1261 }
1262 return partition
1263}
1264
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001265// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001266// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001267func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001268 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001269 path := filepath.Clean(path)
1270 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001271 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001272 }
1273 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001274 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1275 // variables. '..' may remove the entire ninja variable, even if it
1276 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001277 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001278}
1279
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001280// validatePath validates that a path does not include ninja variables, and that
1281// each path component does not attempt to leave its component. Returns a joined
1282// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001283func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001284 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001285 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001286 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001287 }
1288 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001289 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001290}
Colin Cross5b529592017-05-09 13:34:34 -07001291
Colin Cross0875c522017-11-28 17:34:01 -08001292func PathForPhony(ctx PathContext, phony string) WritablePath {
1293 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001294 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001295 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001296 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001297}
1298
Colin Cross74e3fe42017-12-11 15:51:44 -08001299type PhonyPath struct {
1300 basePath
1301}
1302
1303func (p PhonyPath) writablePath() {}
1304
1305var _ Path = PhonyPath{}
1306var _ WritablePath = PhonyPath{}
1307
Colin Cross5b529592017-05-09 13:34:34 -07001308type testPath struct {
1309 basePath
1310}
1311
1312func (p testPath) String() string {
1313 return p.path
1314}
1315
Colin Cross40e33732019-02-15 11:08:35 -08001316type testWritablePath struct {
1317 testPath
1318}
1319
1320func (p testPath) writablePath() {}
1321
1322// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1323// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001324func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001325 p, err := validateSafePath(paths...)
1326 if err != nil {
1327 panic(err)
1328 }
Colin Cross5b529592017-05-09 13:34:34 -07001329 return testPath{basePath{path: p, rel: p}}
1330}
1331
Colin Cross40e33732019-02-15 11:08:35 -08001332// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1333func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001334 p := make(Paths, len(strs))
1335 for i, s := range strs {
1336 p[i] = PathForTesting(s)
1337 }
1338
1339 return p
1340}
Colin Cross43f08db2018-11-12 10:13:39 -08001341
Colin Cross40e33732019-02-15 11:08:35 -08001342// WritablePathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be
1343// used from within tests.
1344func WritablePathForTesting(paths ...string) WritablePath {
1345 p, err := validateSafePath(paths...)
1346 if err != nil {
1347 panic(err)
1348 }
1349 return testWritablePath{testPath{basePath{path: p, rel: p}}}
1350}
1351
1352// WritablePathsForTesting returns a Path constructed from each element in strs. It should only be used from within
1353// tests.
1354func WritablePathsForTesting(strs ...string) WritablePaths {
1355 p := make(WritablePaths, len(strs))
1356 for i, s := range strs {
1357 p[i] = WritablePathForTesting(s)
1358 }
1359
1360 return p
1361}
1362
1363type testPathContext struct {
1364 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001365}
1366
Colin Cross98be1bb2019-12-13 20:41:13 -08001367func (x *testPathContext) Fs() pathtools.FileSystem { return x.config.fs }
Colin Cross40e33732019-02-15 11:08:35 -08001368func (x *testPathContext) Config() Config { return x.config }
1369func (x *testPathContext) AddNinjaFileDeps(...string) {}
1370
1371// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1372// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001373func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001374 return &testPathContext{
1375 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001376 }
1377}
1378
Colin Cross43f08db2018-11-12 10:13:39 -08001379// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1380// targetPath is not inside basePath.
1381func Rel(ctx PathContext, basePath string, targetPath string) string {
1382 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1383 if !isRel {
1384 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1385 return ""
1386 }
1387 return rel
1388}
1389
1390// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1391// targetPath is not inside basePath.
1392func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001393 rel, isRel, err := maybeRelErr(basePath, targetPath)
1394 if err != nil {
1395 reportPathError(ctx, err)
1396 }
1397 return rel, isRel
1398}
1399
1400func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001401 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1402 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001403 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001404 }
1405 rel, err := filepath.Rel(basePath, targetPath)
1406 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001407 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001408 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001409 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001410 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001411 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001412}