blob: c841372dca9ecceab11c43853400ff87cf7a4c23 [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
Paul Duffin9b478b02019-12-10 13:41:51 +0000121 // return the path to the build directory.
122 buildDir() string
123
Jeff Gaston734e3802017-04-10 15:47:24 -0700124 // the writablePath method doesn't directly do anything,
125 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700126 writablePath()
127}
128
129type genPathProvider interface {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700130 genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700131}
132type objPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700133 objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700134}
135type resPathProvider interface {
Colin Cross635c3b02016-05-18 15:37:25 -0700136 resPathWithName(ctx ModuleContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700137}
138
139// GenPathWithExt derives a new file path in ctx's generated sources directory
140// from the current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700141func GenPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700142 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700143 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700144 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800145 reportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700146 return PathForModuleGen(ctx)
147}
148
149// ObjPathWithExt derives a new file path in ctx's object directory from the
150// current path, but with the new extension.
Dan Willemsen21ec4902016-11-02 20:43:13 -0700151func ObjPathWithExt(ctx ModuleContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700152 if path, ok := p.(objPathProvider); ok {
153 return path.objPathWithExt(ctx, subdir, ext)
154 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800155 reportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700156 return PathForModuleObj(ctx)
157}
158
159// ResPathWithName derives a new path in ctx's output resource directory, using
160// the current path to create the directory name, and the `name` argument for
161// the filename.
Colin Cross635c3b02016-05-18 15:37:25 -0700162func ResPathWithName(ctx ModuleContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700163 if path, ok := p.(resPathProvider); ok {
164 return path.resPathWithName(ctx, name)
165 }
Colin Cross1ccfcc32018-02-22 13:54:26 -0800166 reportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700167 return PathForModuleRes(ctx)
168}
169
170// OptionalPath is a container that may or may not contain a valid Path.
171type OptionalPath struct {
172 valid bool
173 path Path
174}
175
176// OptionalPathForPath returns an OptionalPath containing the path.
177func OptionalPathForPath(path Path) OptionalPath {
178 if path == nil {
179 return OptionalPath{}
180 }
181 return OptionalPath{valid: true, path: path}
182}
183
184// Valid returns whether there is a valid path
185func (p OptionalPath) Valid() bool {
186 return p.valid
187}
188
189// Path returns the Path embedded in this OptionalPath. You must be sure that
190// there is a valid path, since this method will panic if there is not.
191func (p OptionalPath) Path() Path {
192 if !p.valid {
193 panic("Requesting an invalid path")
194 }
195 return p.path
196}
197
198// String returns the string version of the Path, or "" if it isn't valid.
199func (p OptionalPath) String() string {
200 if p.valid {
201 return p.path.String()
202 } else {
203 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700204 }
205}
Colin Cross6e18ca42015-07-14 18:55:36 -0700206
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700207// Paths is a slice of Path objects, with helpers to operate on the collection.
208type Paths []Path
209
210// PathsForSource returns Paths rooted from SrcDir
211func PathsForSource(ctx PathContext, paths []string) Paths {
212 ret := make(Paths, len(paths))
213 for i, path := range paths {
214 ret[i] = PathForSource(ctx, path)
215 }
216 return ret
217}
218
Jeff Gaston734e3802017-04-10 15:47:24 -0700219// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800220// found in the tree. If any are not found, they are omitted from the list,
221// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800222func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800223 ret := make(Paths, 0, len(paths))
224 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800225 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800226 if p.Valid() {
227 ret = append(ret, p.Path())
228 }
229 }
230 return ret
231}
232
Colin Cross41955e82019-05-29 14:40:35 -0700233// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
234// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
235// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
236// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
237// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
238// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Colin Cross635c3b02016-05-18 15:37:25 -0700239func PathsForModuleSrc(ctx ModuleContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800240 return PathsForModuleSrcExcludes(ctx, paths, nil)
241}
242
Colin Crossba71a3f2019-03-18 12:12:48 -0700243// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700244// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
245// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
246// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
247// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100248// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700249// having missing dependencies.
Colin Cross8a497952019-03-05 22:25:09 -0800250func PathsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700251 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
252 if ctx.Config().AllowMissingDependencies() {
253 ctx.AddMissingDependencies(missingDeps)
254 } else {
255 for _, m := range missingDeps {
256 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
257 }
258 }
259 return ret
260}
261
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000262// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
263type OutputPaths []OutputPath
264
265// Paths returns the OutputPaths as a Paths
266func (p OutputPaths) Paths() Paths {
267 if p == nil {
268 return nil
269 }
270 ret := make(Paths, len(p))
271 for i, path := range p {
272 ret[i] = path
273 }
274 return ret
275}
276
277// Strings returns the string forms of the writable paths.
278func (p OutputPaths) Strings() []string {
279 if p == nil {
280 return nil
281 }
282 ret := make([]string, len(p))
283 for i, path := range p {
284 ret[i] = path.String()
285 }
286 return ret
287}
288
Colin Crossba71a3f2019-03-18 12:12:48 -0700289// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700290// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
291// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
292// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
293// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
294// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
295// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
296// dependencies.
Colin Crossba71a3f2019-03-18 12:12:48 -0700297func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800298 prefix := pathForModuleSrc(ctx).String()
299
300 var expandedExcludes []string
301 if excludes != nil {
302 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700303 }
Colin Cross8a497952019-03-05 22:25:09 -0800304
Colin Crossba71a3f2019-03-18 12:12:48 -0700305 var missingExcludeDeps []string
306
Colin Cross8a497952019-03-05 22:25:09 -0800307 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700308 if m, t := SrcIsModuleWithTag(e); m != "" {
309 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800310 if module == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700311 missingExcludeDeps = append(missingExcludeDeps, m)
Colin Cross8a497952019-03-05 22:25:09 -0800312 continue
313 }
Colin Cross41955e82019-05-29 14:40:35 -0700314 if outProducer, ok := module.(OutputFileProducer); ok {
315 outputFiles, err := outProducer.OutputFiles(t)
316 if err != nil {
317 ctx.ModuleErrorf("path dependency %q: %s", e, err)
318 }
319 expandedExcludes = append(expandedExcludes, outputFiles.Strings()...)
320 } else if t != "" {
321 ctx.ModuleErrorf("path dependency %q is not an output file producing module", e)
322 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800323 expandedExcludes = append(expandedExcludes, srcProducer.Srcs().Strings()...)
324 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700325 ctx.ModuleErrorf("path dependency %q is not a source file producing module", e)
Colin Cross8a497952019-03-05 22:25:09 -0800326 }
327 } else {
328 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
329 }
330 }
331
332 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700333 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800334 }
335
Colin Crossba71a3f2019-03-18 12:12:48 -0700336 var missingDeps []string
337
Colin Cross8a497952019-03-05 22:25:09 -0800338 expandedSrcFiles := make(Paths, 0, len(paths))
339 for _, s := range paths {
340 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
341 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700342 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800343 } else if err != nil {
344 reportPathError(ctx, err)
345 }
346 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
347 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700348
349 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800350}
351
352type missingDependencyError struct {
353 missingDeps []string
354}
355
356func (e missingDependencyError) Error() string {
357 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
358}
359
360func expandOneSrcPath(ctx ModuleContext, s string, expandedExcludes []string) (Paths, error) {
Colin Cross41955e82019-05-29 14:40:35 -0700361 if m, t := SrcIsModuleWithTag(s); m != "" {
362 module := ctx.GetDirectDepWithTag(m, sourceOrOutputDepTag(t))
Colin Cross8a497952019-03-05 22:25:09 -0800363 if module == nil {
364 return nil, missingDependencyError{[]string{m}}
365 }
Colin Cross41955e82019-05-29 14:40:35 -0700366 if outProducer, ok := module.(OutputFileProducer); ok {
367 outputFiles, err := outProducer.OutputFiles(t)
368 if err != nil {
369 return nil, fmt.Errorf("path dependency %q: %s", s, err)
370 }
371 return outputFiles, nil
372 } else if t != "" {
373 return nil, fmt.Errorf("path dependency %q is not an output file producing module", s)
374 } else if srcProducer, ok := module.(SourceFileProducer); ok {
Colin Cross8a497952019-03-05 22:25:09 -0800375 moduleSrcs := srcProducer.Srcs()
376 for _, e := range expandedExcludes {
377 for j := 0; j < len(moduleSrcs); j++ {
378 if moduleSrcs[j].String() == e {
379 moduleSrcs = append(moduleSrcs[:j], moduleSrcs[j+1:]...)
380 j--
381 }
382 }
383 }
384 return moduleSrcs, nil
385 } else {
Colin Cross41955e82019-05-29 14:40:35 -0700386 return nil, fmt.Errorf("path dependency %q is not a source file producing module", s)
Colin Cross8a497952019-03-05 22:25:09 -0800387 }
388 } else if pathtools.IsGlob(s) {
389 paths := ctx.GlobFiles(pathForModuleSrc(ctx, s).String(), expandedExcludes)
390 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
391 } else {
392 p := pathForModuleSrc(ctx, s)
393 if exists, _, err := ctx.Fs().Exists(p.String()); err != nil {
394 reportPathErrorf(ctx, "%s: %s", p, err.Error())
395 } else if !exists {
396 reportPathErrorf(ctx, "module source path %q does not exist", p)
397 }
398
399 j := findStringInSlice(p.String(), expandedExcludes)
400 if j >= 0 {
401 return nil, nil
402 }
403 return Paths{p}, nil
404 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700405}
406
407// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
408// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800409// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700410// It intended for use in globs that only list files that exist, so it allows '$' in
411// filenames.
Colin Crossdc35e212019-06-06 16:13:11 -0700412func pathsForModuleSrcFromFullPath(ctx BaseModuleContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800413 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700414 if prefix == "./" {
415 prefix = ""
416 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700417 ret := make(Paths, 0, len(paths))
418 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800419 if !incDirs && strings.HasSuffix(p, "/") {
420 continue
421 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700422 path := filepath.Clean(p)
423 if !strings.HasPrefix(path, prefix) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800424 reportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700425 continue
426 }
Colin Crosse3924e12018-08-15 20:18:53 -0700427
Colin Crossfe4bc362018-09-12 10:02:13 -0700428 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700429 if err != nil {
430 reportPathError(ctx, err)
431 continue
432 }
433
Colin Cross07e51612019-03-05 12:46:40 -0800434 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700435
Colin Cross07e51612019-03-05 12:46:40 -0800436 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700437 }
438 return ret
439}
440
441// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's
Colin Cross0ddae7f2019-02-07 15:30:01 -0800442// 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 -0700443func PathsWithOptionalDefaultForModuleSrc(ctx ModuleContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800444 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700445 return PathsForModuleSrc(ctx, input)
446 }
447 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
448 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800449 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Colin Cross461b4452018-02-23 09:22:42 -0800450 return ctx.Glob(path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700451}
452
453// Strings returns the Paths in string form
454func (p Paths) Strings() []string {
455 if p == nil {
456 return nil
457 }
458 ret := make([]string, len(p))
459 for i, path := range p {
460 ret[i] = path.String()
461 }
462 return ret
463}
464
Colin Crossb6715442017-10-24 11:13:31 -0700465// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
466// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700467func FirstUniquePaths(list Paths) Paths {
468 k := 0
469outer:
470 for i := 0; i < len(list); i++ {
471 for j := 0; j < k; j++ {
472 if list[i] == list[j] {
473 continue outer
474 }
475 }
476 list[k] = list[i]
477 k++
478 }
479 return list[:k]
480}
481
Colin Crossb6715442017-10-24 11:13:31 -0700482// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
483// modifies the Paths slice contents in place, and returns a subslice of the original slice.
484func LastUniquePaths(list Paths) Paths {
485 totalSkip := 0
486 for i := len(list) - 1; i >= totalSkip; i-- {
487 skip := 0
488 for j := i - 1; j >= totalSkip; j-- {
489 if list[i] == list[j] {
490 skip++
491 } else {
492 list[j+skip] = list[j]
493 }
494 }
495 totalSkip += skip
496 }
497 return list[totalSkip:]
498}
499
Colin Crossa140bb02018-04-17 10:52:26 -0700500// ReversePaths returns a copy of a Paths in reverse order.
501func ReversePaths(list Paths) Paths {
502 if list == nil {
503 return nil
504 }
505 ret := make(Paths, len(list))
506 for i := range list {
507 ret[i] = list[len(list)-1-i]
508 }
509 return ret
510}
511
Jeff Gaston294356f2017-09-27 17:05:30 -0700512func indexPathList(s Path, list []Path) int {
513 for i, l := range list {
514 if l == s {
515 return i
516 }
517 }
518
519 return -1
520}
521
522func inPathList(p Path, list []Path) bool {
523 return indexPathList(p, list) != -1
524}
525
526func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000527 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
528}
529
530func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700531 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000532 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700533 filtered = append(filtered, l)
534 } else {
535 remainder = append(remainder, l)
536 }
537 }
538
539 return
540}
541
Colin Cross93e85952017-08-15 13:34:18 -0700542// HasExt returns true of any of the paths have extension ext, otherwise false
543func (p Paths) HasExt(ext string) bool {
544 for _, path := range p {
545 if path.Ext() == ext {
546 return true
547 }
548 }
549
550 return false
551}
552
553// FilterByExt returns the subset of the paths that have extension ext
554func (p Paths) FilterByExt(ext string) Paths {
555 ret := make(Paths, 0, len(p))
556 for _, path := range p {
557 if path.Ext() == ext {
558 ret = append(ret, path)
559 }
560 }
561 return ret
562}
563
564// FilterOutByExt returns the subset of the paths that do not have extension ext
565func (p Paths) FilterOutByExt(ext string) Paths {
566 ret := make(Paths, 0, len(p))
567 for _, path := range p {
568 if path.Ext() != ext {
569 ret = append(ret, path)
570 }
571 }
572 return ret
573}
574
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700575// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
576// (including subdirectories) are in a contiguous subslice of the list, and can be found in
577// O(log(N)) time using a binary search on the directory prefix.
578type DirectorySortedPaths Paths
579
580func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
581 ret := append(DirectorySortedPaths(nil), paths...)
582 sort.Slice(ret, func(i, j int) bool {
583 return ret[i].String() < ret[j].String()
584 })
585 return ret
586}
587
588// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
589// that are in the specified directory and its subdirectories.
590func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
591 prefix := filepath.Clean(dir) + "/"
592 start := sort.Search(len(p), func(i int) bool {
593 return prefix < p[i].String()
594 })
595
596 ret := p[start:]
597
598 end := sort.Search(len(ret), func(i int) bool {
599 return !strings.HasPrefix(ret[i].String(), prefix)
600 })
601
602 ret = ret[:end]
603
604 return Paths(ret)
605}
606
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700607// WritablePaths is a slice of WritablePaths, used for multiple outputs.
608type WritablePaths []WritablePath
609
610// Strings returns the string forms of the writable paths.
611func (p WritablePaths) Strings() []string {
612 if p == nil {
613 return nil
614 }
615 ret := make([]string, len(p))
616 for i, path := range p {
617 ret[i] = path.String()
618 }
619 return ret
620}
621
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800622// Paths returns the WritablePaths as a Paths
623func (p WritablePaths) Paths() Paths {
624 if p == nil {
625 return nil
626 }
627 ret := make(Paths, len(p))
628 for i, path := range p {
629 ret[i] = path
630 }
631 return ret
632}
633
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700634type basePath struct {
635 path string
636 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800637 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700638}
639
640func (p basePath) Ext() string {
641 return filepath.Ext(p.path)
642}
643
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700644func (p basePath) Base() string {
645 return filepath.Base(p.path)
646}
647
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800648func (p basePath) Rel() string {
649 if p.rel != "" {
650 return p.rel
651 }
652 return p.path
653}
654
Colin Cross0875c522017-11-28 17:34:01 -0800655func (p basePath) String() string {
656 return p.path
657}
658
Colin Cross0db55682017-12-05 15:36:55 -0800659func (p basePath) withRel(rel string) basePath {
660 p.path = filepath.Join(p.path, rel)
661 p.rel = rel
662 return p
663}
664
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700665// SourcePath is a Path representing a file path rooted from SrcDir
666type SourcePath struct {
667 basePath
668}
669
670var _ Path = SourcePath{}
671
Colin Cross0db55682017-12-05 15:36:55 -0800672func (p SourcePath) withRel(rel string) SourcePath {
673 p.basePath = p.basePath.withRel(rel)
674 return p
675}
676
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700677// safePathForSource is for paths that we expect are safe -- only for use by go
678// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700679func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
680 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800681 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700682 if err != nil {
683 return ret, err
684 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700685
Colin Cross7b3dcc32019-01-24 13:14:39 -0800686 // absolute path already checked by validateSafePath
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 Cross6e18ca42015-07-14 18:55:36 -0700689 }
690
Colin Crossfe4bc362018-09-12 10:02:13 -0700691 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700692}
693
Colin Cross192e97a2018-02-22 14:21:02 -0800694// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
695func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000696 p, err := validatePath(pathComponents...)
697 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800698 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800699 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800700 }
701
Colin Cross7b3dcc32019-01-24 13:14:39 -0800702 // absolute path already checked by validatePath
703 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800704 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000705 }
706
Colin Cross192e97a2018-02-22 14:21:02 -0800707 return ret, nil
708}
709
710// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
711// path does not exist.
712func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
713 var files []string
714
715 if gctx, ok := ctx.(PathGlobContext); ok {
716 // Use glob to produce proper dependencies, even though we only want
717 // a single file.
718 files, err = gctx.GlobWithDeps(path.String(), nil)
719 } else {
720 var deps []string
721 // We cannot add build statements in this context, so we fall back to
722 // AddNinjaFileDeps
Colin Cross3f4d1162018-09-21 15:11:48 -0700723 files, deps, err = pathtools.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800724 ctx.AddNinjaFileDeps(deps...)
725 }
726
727 if err != nil {
728 return false, fmt.Errorf("glob: %s", err.Error())
729 }
730
731 return len(files) > 0, nil
732}
733
734// PathForSource joins the provided path components and validates that the result
735// neither escapes the source dir nor is in the out dir.
736// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
737func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
738 path, err := pathForSource(ctx, pathComponents...)
739 if err != nil {
740 reportPathError(ctx, err)
741 }
742
Colin Crosse3924e12018-08-15 20:18:53 -0700743 if pathtools.IsGlob(path.String()) {
744 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
745 }
746
Colin Cross192e97a2018-02-22 14:21:02 -0800747 if modCtx, ok := ctx.(ModuleContext); ok && ctx.Config().AllowMissingDependencies() {
748 exists, err := existsWithDependencies(ctx, path)
749 if err != nil {
750 reportPathError(ctx, err)
751 }
752 if !exists {
753 modCtx.AddMissingDependencies([]string{path.String()})
754 }
755 } else if exists, _, err := ctx.Fs().Exists(path.String()); err != nil {
756 reportPathErrorf(ctx, "%s: %s", path, err.Error())
757 } else if !exists {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800758 reportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800759 }
760 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700761}
762
Jeff Gaston734e3802017-04-10 15:47:24 -0700763// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700764// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
765// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800766func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800767 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800768 if err != nil {
769 reportPathError(ctx, err)
770 return OptionalPath{}
771 }
Colin Crossc48c1432018-02-23 07:09:01 +0000772
Colin Crosse3924e12018-08-15 20:18:53 -0700773 if pathtools.IsGlob(path.String()) {
774 reportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
775 return OptionalPath{}
776 }
777
Colin Cross192e97a2018-02-22 14:21:02 -0800778 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000779 if err != nil {
780 reportPathError(ctx, err)
781 return OptionalPath{}
782 }
Colin Cross192e97a2018-02-22 14:21:02 -0800783 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000784 return OptionalPath{}
785 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700786 return OptionalPathForPath(path)
787}
788
789func (p SourcePath) String() string {
790 return filepath.Join(p.config.srcDir, p.path)
791}
792
793// Join creates a new SourcePath with paths... joined with the current path. The
794// provided paths... may not use '..' to escape from the current path.
795func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800796 path, err := validatePath(paths...)
797 if err != nil {
798 reportPathError(ctx, err)
799 }
Colin Cross0db55682017-12-05 15:36:55 -0800800 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700801}
802
Colin Cross2fafa3e2019-03-05 12:39:51 -0800803// join is like Join but does less path validation.
804func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
805 path, err := validateSafePath(paths...)
806 if err != nil {
807 reportPathError(ctx, err)
808 }
809 return p.withRel(path)
810}
811
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700812// OverlayPath returns the overlay for `path' if it exists. This assumes that the
813// SourcePath is the path to a resource overlay directory.
Colin Cross635c3b02016-05-18 15:37:25 -0700814func (p SourcePath) OverlayPath(ctx ModuleContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700815 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800816 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700817 relDir = srcPath.path
818 } else {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800819 reportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700820 return OptionalPath{}
821 }
822 dir := filepath.Join(p.config.srcDir, p.path, relDir)
823 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700824 if pathtools.IsGlob(dir) {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800825 reportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800826 }
Colin Cross461b4452018-02-23 09:22:42 -0800827 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700828 if err != nil {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800829 reportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700830 return OptionalPath{}
831 }
832 if len(paths) == 0 {
833 return OptionalPath{}
834 }
Colin Cross43f08db2018-11-12 10:13:39 -0800835 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700836 return OptionalPathForPath(PathForSource(ctx, relPath))
837}
838
Colin Cross70dda7e2019-10-01 22:05:35 -0700839// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700840type OutputPath struct {
841 basePath
842}
843
Colin Cross702e0f82017-10-18 17:27:54 -0700844func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -0800845 p.basePath = p.basePath.withRel(rel)
Colin Cross702e0f82017-10-18 17:27:54 -0700846 return p
847}
848
Colin Cross3063b782018-08-15 11:19:12 -0700849func (p OutputPath) WithoutRel() OutputPath {
850 p.basePath.rel = filepath.Base(p.basePath.path)
851 return p
852}
853
Paul Duffin9b478b02019-12-10 13:41:51 +0000854func (p OutputPath) buildDir() string {
855 return p.config.buildDir
856}
857
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700858var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +0000859var _ WritablePath = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700860
Jeff Gaston734e3802017-04-10 15:47:24 -0700861// PathForOutput joins the provided paths and returns an OutputPath that is
862// validated to not escape the build dir.
863// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
864func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800865 path, err := validatePath(pathComponents...)
866 if err != nil {
867 reportPathError(ctx, err)
868 }
Colin Crossaabf6792017-11-29 00:27:14 -0800869 return OutputPath{basePath{path, ctx.Config(), ""}}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700870}
871
Colin Cross40e33732019-02-15 11:08:35 -0800872// PathsForOutput returns Paths rooted from buildDir
873func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
874 ret := make(WritablePaths, len(paths))
875 for i, path := range paths {
876 ret[i] = PathForOutput(ctx, path)
877 }
878 return ret
879}
880
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700881func (p OutputPath) writablePath() {}
882
883func (p OutputPath) String() string {
884 return filepath.Join(p.config.buildDir, p.path)
885}
886
887// Join creates a new OutputPath with paths... joined with the current path. The
888// provided paths... may not use '..' to escape from the current path.
889func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800890 path, err := validatePath(paths...)
891 if err != nil {
892 reportPathError(ctx, err)
893 }
Colin Cross0db55682017-12-05 15:36:55 -0800894 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700895}
896
Colin Cross8854a5a2019-02-11 14:14:16 -0800897// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
898func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
899 if strings.Contains(ext, "/") {
900 reportPathErrorf(ctx, "extension %q cannot contain /", ext)
901 }
902 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -0800903 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -0800904 return ret
905}
906
Colin Cross40e33732019-02-15 11:08:35 -0800907// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
908func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
909 path, err := validatePath(paths...)
910 if err != nil {
911 reportPathError(ctx, err)
912 }
913
914 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -0800915 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -0800916 return ret
917}
918
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700919// PathForIntermediates returns an OutputPath representing the top-level
920// intermediates directory.
921func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800922 path, err := validatePath(paths...)
923 if err != nil {
924 reportPathError(ctx, err)
925 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700926 return PathForOutput(ctx, ".intermediates", path)
927}
928
Colin Cross07e51612019-03-05 12:46:40 -0800929var _ genPathProvider = SourcePath{}
930var _ objPathProvider = SourcePath{}
931var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700932
Colin Cross07e51612019-03-05 12:46:40 -0800933// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700934// module's local source directory.
Colin Cross8a497952019-03-05 22:25:09 -0800935func PathForModuleSrc(ctx ModuleContext, pathComponents ...string) Path {
936 p, err := validatePath(pathComponents...)
937 if err != nil {
938 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -0800939 }
Colin Cross8a497952019-03-05 22:25:09 -0800940 paths, err := expandOneSrcPath(ctx, p, nil)
941 if err != nil {
942 if depErr, ok := err.(missingDependencyError); ok {
943 if ctx.Config().AllowMissingDependencies() {
944 ctx.AddMissingDependencies(depErr.missingDeps)
945 } else {
946 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
947 }
948 } else {
949 reportPathError(ctx, err)
950 }
951 return nil
952 } else if len(paths) == 0 {
953 reportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
954 return nil
955 } else if len(paths) > 1 {
956 reportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
957 }
958 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700959}
960
Colin Cross07e51612019-03-05 12:46:40 -0800961func pathForModuleSrc(ctx ModuleContext, paths ...string) SourcePath {
962 p, err := validatePath(paths...)
963 if err != nil {
964 reportPathError(ctx, err)
965 }
966
967 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
968 if err != nil {
969 reportPathError(ctx, err)
970 }
971
972 path.basePath.rel = p
973
974 return path
975}
976
Colin Cross2fafa3e2019-03-05 12:39:51 -0800977// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
978// will return the path relative to subDir in the module's source directory. If any input paths are not located
979// inside subDir then a path error will be reported.
980func PathsWithModuleSrcSubDir(ctx ModuleContext, paths Paths, subDir string) Paths {
981 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -0800982 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800983 for i, path := range paths {
984 rel := Rel(ctx, subDirFullPath.String(), path.String())
985 paths[i] = subDirFullPath.join(ctx, rel)
986 }
987 return paths
988}
989
990// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
991// module's source directory. If the input path is not located inside subDir then a path error will be reported.
992func PathWithModuleSrcSubDir(ctx ModuleContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -0800993 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -0800994 rel := Rel(ctx, subDirFullPath.String(), path.String())
995 return subDirFullPath.Join(ctx, rel)
996}
997
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700998// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
999// valid path if p is non-nil.
Colin Cross635c3b02016-05-18 15:37:25 -07001000func OptionalPathForModuleSrc(ctx ModuleContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001001 if p == nil {
1002 return OptionalPath{}
1003 }
1004 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1005}
1006
Colin Cross07e51612019-03-05 12:46:40 -08001007func (p SourcePath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001008 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001009}
1010
Colin Cross07e51612019-03-05 12:46:40 -08001011func (p SourcePath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001012 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001013}
1014
Colin Cross07e51612019-03-05 12:46:40 -08001015func (p SourcePath) resPathWithName(ctx ModuleContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001016 // TODO: Use full directory if the new ctx is not the current ctx?
1017 return PathForModuleRes(ctx, p.path, name)
1018}
1019
1020// ModuleOutPath is a Path representing a module's output directory.
1021type ModuleOutPath struct {
1022 OutputPath
1023}
1024
1025var _ Path = ModuleOutPath{}
1026
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001027func (p ModuleOutPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
1028 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1029}
1030
Colin Cross702e0f82017-10-18 17:27:54 -07001031func pathForModule(ctx ModuleContext) OutputPath {
1032 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1033}
1034
Logan Chien7eefdc42018-07-11 18:10:41 +08001035// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1036// reference abi dump for the given module. This is not guaranteed to be valid.
1037func PathForVndkRefAbiDump(ctx ModuleContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001038 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001039
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001040 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001041 if len(arches) == 0 {
1042 panic("device build with no primary arch")
1043 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001044 currentArch := ctx.Arch()
1045 archNameAndVariant := currentArch.ArchType.String()
1046 if currentArch.ArchVariant != "" {
1047 archNameAndVariant += "_" + currentArch.ArchVariant
1048 }
Logan Chien5237bed2018-07-11 17:15:57 +08001049
1050 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001051 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001052 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001053 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001054 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001055 } else {
1056 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001057 }
Logan Chien5237bed2018-07-11 17:15:57 +08001058
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001059 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001060
1061 var ext string
1062 if isGzip {
1063 ext = ".lsdump.gz"
1064 } else {
1065 ext = ".lsdump"
1066 }
1067
1068 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1069 version, binderBitness, archNameAndVariant, "source-based",
1070 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001071}
1072
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001073// PathForModuleOut returns a Path representing the paths... under the module's
1074// output directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001075func PathForModuleOut(ctx ModuleContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001076 p, err := validatePath(paths...)
1077 if err != nil {
1078 reportPathError(ctx, err)
1079 }
Colin Cross702e0f82017-10-18 17:27:54 -07001080 return ModuleOutPath{
1081 OutputPath: pathForModule(ctx).withRel(p),
1082 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001083}
1084
1085// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1086// directory. Mainly used for generated sources.
1087type ModuleGenPath struct {
1088 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001089}
1090
1091var _ Path = ModuleGenPath{}
1092var _ genPathProvider = ModuleGenPath{}
1093var _ objPathProvider = ModuleGenPath{}
1094
1095// PathForModuleGen returns a Path representing the paths... under the module's
1096// `gen' directory.
Colin Cross635c3b02016-05-18 15:37:25 -07001097func PathForModuleGen(ctx ModuleContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001098 p, err := validatePath(paths...)
1099 if err != nil {
1100 reportPathError(ctx, err)
1101 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001102 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001103 ModuleOutPath: ModuleOutPath{
1104 OutputPath: pathForModule(ctx).withRel("gen").withRel(p),
1105 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001106 }
1107}
1108
Dan Willemsen21ec4902016-11-02 20:43:13 -07001109func (p ModuleGenPath) genPathWithExt(ctx ModuleContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001110 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001111 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001112}
1113
Colin Cross635c3b02016-05-18 15:37:25 -07001114func (p ModuleGenPath) objPathWithExt(ctx ModuleContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001115 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1116}
1117
1118// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1119// directory. Used for compiled objects.
1120type ModuleObjPath struct {
1121 ModuleOutPath
1122}
1123
1124var _ Path = ModuleObjPath{}
1125
1126// PathForModuleObj returns a Path representing the paths... under the module's
1127// 'obj' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001128func PathForModuleObj(ctx ModuleContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001129 p, err := validatePath(pathComponents...)
1130 if err != nil {
1131 reportPathError(ctx, err)
1132 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001133 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1134}
1135
1136// ModuleResPath is a a Path representing the 'res' directory in a module's
1137// output directory.
1138type ModuleResPath struct {
1139 ModuleOutPath
1140}
1141
1142var _ Path = ModuleResPath{}
1143
1144// PathForModuleRes returns a Path representing the paths... under the module's
1145// 'res' directory.
Jeff Gaston734e3802017-04-10 15:47:24 -07001146func PathForModuleRes(ctx ModuleContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001147 p, err := validatePath(pathComponents...)
1148 if err != nil {
1149 reportPathError(ctx, err)
1150 }
1151
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001152 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1153}
1154
Colin Cross70dda7e2019-10-01 22:05:35 -07001155// InstallPath is a Path representing a installed file path rooted from the build directory
1156type InstallPath struct {
1157 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001158
1159 baseDir string // "../" for Make paths to convert "out/soong" to "out", "" for Soong paths
Colin Cross70dda7e2019-10-01 22:05:35 -07001160}
1161
Paul Duffin9b478b02019-12-10 13:41:51 +00001162func (p InstallPath) buildDir() string {
1163 return p.config.buildDir
1164}
1165
1166var _ Path = InstallPath{}
1167var _ WritablePath = InstallPath{}
1168
Colin Cross70dda7e2019-10-01 22:05:35 -07001169func (p InstallPath) writablePath() {}
1170
1171func (p InstallPath) String() string {
Colin Crossff6c33d2019-10-02 16:01:35 -07001172 return filepath.Join(p.config.buildDir, p.baseDir, p.path)
Colin Cross70dda7e2019-10-01 22:05:35 -07001173}
1174
1175// Join creates a new InstallPath with paths... joined with the current path. The
1176// provided paths... may not use '..' to escape from the current path.
1177func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1178 path, err := validatePath(paths...)
1179 if err != nil {
1180 reportPathError(ctx, err)
1181 }
1182 return p.withRel(path)
1183}
1184
1185func (p InstallPath) withRel(rel string) InstallPath {
1186 p.basePath = p.basePath.withRel(rel)
1187 return p
1188}
1189
Colin Crossff6c33d2019-10-02 16:01:35 -07001190// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1191// i.e. out/ instead of out/soong/.
1192func (p InstallPath) ToMakePath() InstallPath {
1193 p.baseDir = "../"
1194 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001195}
1196
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001197// PathForModuleInstall returns a Path representing the install path for the
1198// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001199func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001200 var outPaths []string
1201 if ctx.Device() {
Colin Cross43f08db2018-11-12 10:13:39 -08001202 partition := modulePartition(ctx)
Colin Cross6510f912017-11-29 00:27:14 -08001203 outPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001204 } else {
Dan Willemsen866b5632017-09-22 12:28:24 -07001205 switch ctx.Os() {
1206 case Linux:
1207 outPaths = []string{"host", "linux-x86"}
1208 case LinuxBionic:
1209 // TODO: should this be a separate top level, or shared with linux-x86?
1210 outPaths = []string{"host", "linux_bionic-x86"}
1211 default:
1212 outPaths = []string{"host", ctx.Os().String() + "-x86"}
1213 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001214 }
Dan Willemsen782a2d12015-12-21 14:55:28 -08001215 if ctx.Debug() {
1216 outPaths = append([]string{"debug"}, outPaths...)
1217 }
Jeff Gaston734e3802017-04-10 15:47:24 -07001218 outPaths = append(outPaths, pathComponents...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001219
1220 path, err := validatePath(outPaths...)
1221 if err != nil {
1222 reportPathError(ctx, err)
1223 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001224
1225 ret := InstallPath{basePath{path, ctx.Config(), ""}, ""}
1226 if ctx.InstallBypassMake() && ctx.Config().EmbeddedInMake() {
1227 ret = ret.ToMakePath()
1228 }
1229
1230 return ret
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001231}
1232
Colin Cross70dda7e2019-10-01 22:05:35 -07001233func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1234 paths = append([]string{"ndk"}, paths...)
1235 path, err := validatePath(paths...)
1236 if err != nil {
1237 reportPathError(ctx, err)
1238 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001239 return InstallPath{basePath{path, ctx.Config(), ""}, ""}
Colin Cross70dda7e2019-10-01 22:05:35 -07001240}
1241
1242func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001243 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1244
1245 return "/" + rel
1246}
1247
1248func modulePartition(ctx ModuleInstallPathContext) string {
1249 var partition string
1250 if ctx.InstallInData() {
1251 partition = "data"
Jaewoong Jung0949f312019-09-11 10:25:18 -07001252 } else if ctx.InstallInTestcases() {
1253 partition = "testcases"
Colin Cross43f08db2018-11-12 10:13:39 -08001254 } else if ctx.InstallInRecovery() {
Colin Cross90ba5f42019-10-02 11:10:58 -07001255 if ctx.InstallInRoot() {
1256 partition = "recovery/root"
1257 } else {
1258 // the layout of recovery partion is the same as that of system partition
1259 partition = "recovery/root/system"
1260 }
Colin Cross43f08db2018-11-12 10:13:39 -08001261 } else if ctx.SocSpecific() {
1262 partition = ctx.DeviceConfig().VendorPath()
1263 } else if ctx.DeviceSpecific() {
1264 partition = ctx.DeviceConfig().OdmPath()
1265 } else if ctx.ProductSpecific() {
1266 partition = ctx.DeviceConfig().ProductPath()
Justin Yund5f6c822019-06-25 16:47:17 +09001267 } else if ctx.SystemExtSpecific() {
1268 partition = ctx.DeviceConfig().SystemExtPath()
Colin Cross90ba5f42019-10-02 11:10:58 -07001269 } else if ctx.InstallInRoot() {
1270 partition = "root"
Colin Cross43f08db2018-11-12 10:13:39 -08001271 } else {
1272 partition = "system"
1273 }
1274 if ctx.InstallInSanitizerDir() {
1275 partition = "data/asan/" + partition
1276 }
1277 return partition
1278}
1279
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001280// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001281// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001282func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001283 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001284 path := filepath.Clean(path)
1285 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001286 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001287 }
1288 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001289 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1290 // variables. '..' may remove the entire ninja variable, even if it
1291 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001292 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001293}
1294
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001295// validatePath validates that a path does not include ninja variables, and that
1296// each path component does not attempt to leave its component. Returns a joined
1297// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001298func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001299 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001300 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001301 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001302 }
1303 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001304 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001305}
Colin Cross5b529592017-05-09 13:34:34 -07001306
Colin Cross0875c522017-11-28 17:34:01 -08001307func PathForPhony(ctx PathContext, phony string) WritablePath {
1308 if strings.ContainsAny(phony, "$/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001309 reportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001310 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001311 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001312}
1313
Colin Cross74e3fe42017-12-11 15:51:44 -08001314type PhonyPath struct {
1315 basePath
1316}
1317
1318func (p PhonyPath) writablePath() {}
1319
Paul Duffin9b478b02019-12-10 13:41:51 +00001320func (p PhonyPath) buildDir() string {
1321 return p.config.buildDir
1322}
1323
Colin Cross74e3fe42017-12-11 15:51:44 -08001324var _ Path = PhonyPath{}
1325var _ WritablePath = PhonyPath{}
1326
Colin Cross5b529592017-05-09 13:34:34 -07001327type testPath struct {
1328 basePath
1329}
1330
1331func (p testPath) String() string {
1332 return p.path
1333}
1334
Colin Cross40e33732019-02-15 11:08:35 -08001335// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1336// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001337func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001338 p, err := validateSafePath(paths...)
1339 if err != nil {
1340 panic(err)
1341 }
Colin Cross5b529592017-05-09 13:34:34 -07001342 return testPath{basePath{path: p, rel: p}}
1343}
1344
Colin Cross40e33732019-02-15 11:08:35 -08001345// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1346func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001347 p := make(Paths, len(strs))
1348 for i, s := range strs {
1349 p[i] = PathForTesting(s)
1350 }
1351
1352 return p
1353}
Colin Cross43f08db2018-11-12 10:13:39 -08001354
Colin Cross40e33732019-02-15 11:08:35 -08001355type testPathContext struct {
1356 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001357}
1358
Colin Cross98be1bb2019-12-13 20:41:13 -08001359func (x *testPathContext) Fs() pathtools.FileSystem { return x.config.fs }
Colin Cross40e33732019-02-15 11:08:35 -08001360func (x *testPathContext) Config() Config { return x.config }
1361func (x *testPathContext) AddNinjaFileDeps(...string) {}
1362
1363// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1364// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001365func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001366 return &testPathContext{
1367 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001368 }
1369}
1370
Colin Cross43f08db2018-11-12 10:13:39 -08001371// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1372// targetPath is not inside basePath.
1373func Rel(ctx PathContext, basePath string, targetPath string) string {
1374 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1375 if !isRel {
1376 reportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
1377 return ""
1378 }
1379 return rel
1380}
1381
1382// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1383// targetPath is not inside basePath.
1384func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001385 rel, isRel, err := maybeRelErr(basePath, targetPath)
1386 if err != nil {
1387 reportPathError(ctx, err)
1388 }
1389 return rel, isRel
1390}
1391
1392func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001393 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1394 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001395 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001396 }
1397 rel, err := filepath.Rel(basePath, targetPath)
1398 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001399 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001400 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001401 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001402 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001403 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001404}