blob: b5a14016fe7193cd4fd94e58e7b3ce5c7e43c3cb [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Colin Cross635c3b02016-05-18 15:37:25 -070015package android
Colin Cross3f40fa42015-01-30 17:27:36 -080016
17import (
Colin Cross6e18ca42015-07-14 18:55:36 -070018 "fmt"
Colin Cross988414c2020-01-11 01:11:46 +000019 "io/ioutil"
20 "os"
Colin Cross6a745c62015-06-16 16:38:10 -070021 "path/filepath"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070022 "reflect"
Colin Cross5e6cfbe2017-11-03 15:20:35 -070023 "sort"
Dan Willemsen34cc69e2015-09-23 15:26:20 -070024 "strings"
25
26 "github.com/google/blueprint"
27 "github.com/google/blueprint/pathtools"
Colin Cross3f40fa42015-01-30 17:27:36 -080028)
29
Colin Cross988414c2020-01-11 01:11:46 +000030var absSrcDir string
31
Dan Willemsen34cc69e2015-09-23 15:26:20 -070032// PathContext is the subset of a (Module|Singleton)Context required by the
33// Path methods.
34type PathContext interface {
Colin Crossaabf6792017-11-29 00:27:14 -080035 Config() Config
Dan Willemsen7b310ee2015-12-18 15:11:17 -080036 AddNinjaFileDeps(deps ...string)
Colin Cross3f40fa42015-01-30 17:27:36 -080037}
38
Colin Cross7f19f372016-11-01 11:10:25 -070039type PathGlobContext interface {
40 GlobWithDeps(globPattern string, excludes []string) ([]string, error)
41}
42
Colin Crossaabf6792017-11-29 00:27:14 -080043var _ PathContext = SingletonContext(nil)
44var _ PathContext = ModuleContext(nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -070045
Ulya Trafimovich8640ab92020-05-11 18:06:15 +010046// "Null" path context is a minimal path context for a given config.
47type NullPathContext struct {
48 config Config
49}
50
51func (NullPathContext) AddNinjaFileDeps(...string) {}
52func (ctx NullPathContext) Config() Config { return ctx.config }
53
Liz Kammera830f3a2020-11-10 10:50:34 -080054// EarlyModulePathContext is a subset of EarlyModuleContext methods required by the
55// Path methods. These path methods can be called before any mutators have run.
56type EarlyModulePathContext interface {
57 PathContext
58 PathGlobContext
59
60 ModuleDir() string
61 ModuleErrorf(fmt string, args ...interface{})
62}
63
64var _ EarlyModulePathContext = ModuleContext(nil)
65
66// Glob globs files and directories matching globPattern relative to ModuleDir(),
67// paths in the excludes parameter will be omitted.
68func Glob(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
69 ret, err := ctx.GlobWithDeps(globPattern, excludes)
70 if err != nil {
71 ctx.ModuleErrorf("glob: %s", err.Error())
72 }
73 return pathsForModuleSrcFromFullPath(ctx, ret, true)
74}
75
76// GlobFiles globs *only* files (not directories) matching globPattern relative to ModuleDir().
77// Paths in the excludes parameter will be omitted.
78func GlobFiles(ctx EarlyModulePathContext, globPattern string, excludes []string) Paths {
79 ret, err := ctx.GlobWithDeps(globPattern, excludes)
80 if err != nil {
81 ctx.ModuleErrorf("glob: %s", err.Error())
82 }
83 return pathsForModuleSrcFromFullPath(ctx, ret, false)
84}
85
86// ModuleWithDepsPathContext is a subset of *ModuleContext methods required by
87// the Path methods that rely on module dependencies having been resolved.
88type ModuleWithDepsPathContext interface {
89 EarlyModulePathContext
90 GetDirectDepWithTag(name string, tag blueprint.DependencyTag) blueprint.Module
91}
92
93// ModuleMissingDepsPathContext is a subset of *ModuleContext methods required by
94// the Path methods that rely on module dependencies having been resolved and ability to report
95// missing dependency errors.
96type ModuleMissingDepsPathContext interface {
97 ModuleWithDepsPathContext
98 AddMissingDependencies(missingDeps []string)
99}
100
Dan Willemsen00269f22017-07-06 16:59:48 -0700101type ModuleInstallPathContext interface {
Colin Cross0ea8ba82019-06-06 14:33:29 -0700102 BaseModuleContext
Dan Willemsen00269f22017-07-06 16:59:48 -0700103
104 InstallInData() bool
Jaewoong Jung0949f312019-09-11 10:25:18 -0700105 InstallInTestcases() bool
Dan Willemsen00269f22017-07-06 16:59:48 -0700106 InstallInSanitizerDir() bool
Yifan Hong1b3348d2020-01-21 15:53:22 -0800107 InstallInRamdisk() bool
Yifan Hong60e0cfb2020-10-21 15:17:56 -0700108 InstallInVendorRamdisk() bool
Jiyong Parkf9332f12018-02-01 00:54:12 +0900109 InstallInRecovery() bool
Colin Cross90ba5f42019-10-02 11:10:58 -0700110 InstallInRoot() bool
Colin Cross607d8582019-07-29 16:44:46 -0700111 InstallBypassMake() bool
Jiyong Park87788b52020-09-01 12:37:45 +0900112 InstallForceOS() (*OsType, *ArchType)
Dan Willemsen00269f22017-07-06 16:59:48 -0700113}
114
115var _ ModuleInstallPathContext = ModuleContext(nil)
116
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700117// errorfContext is the interface containing the Errorf method matching the
118// Errorf method in blueprint.SingletonContext.
119type errorfContext interface {
120 Errorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800121}
122
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700123var _ errorfContext = blueprint.SingletonContext(nil)
124
125// moduleErrorf is the interface containing the ModuleErrorf method matching
126// the ModuleErrorf method in blueprint.ModuleContext.
127type moduleErrorf interface {
128 ModuleErrorf(format string, args ...interface{})
Colin Cross3f40fa42015-01-30 17:27:36 -0800129}
130
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700131var _ moduleErrorf = blueprint.ModuleContext(nil)
132
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700133// reportPathError will register an error with the attached context. It
134// attempts ctx.ModuleErrorf for a better error message first, then falls
135// back to ctx.Errorf.
Colin Cross1ccfcc32018-02-22 13:54:26 -0800136func reportPathError(ctx PathContext, err error) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100137 ReportPathErrorf(ctx, "%s", err.Error())
Colin Cross1ccfcc32018-02-22 13:54:26 -0800138}
139
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100140// ReportPathErrorf will register an error with the attached context. It
Colin Cross1ccfcc32018-02-22 13:54:26 -0800141// attempts ctx.ModuleErrorf for a better error message first, then falls
142// back to ctx.Errorf.
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100143func ReportPathErrorf(ctx PathContext, format string, args ...interface{}) {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700144 if mctx, ok := ctx.(moduleErrorf); ok {
145 mctx.ModuleErrorf(format, args...)
146 } else if ectx, ok := ctx.(errorfContext); ok {
147 ectx.Errorf(format, args...)
148 } else {
149 panic(fmt.Sprintf(format, args...))
Colin Crossf2298272015-05-12 11:36:53 -0700150 }
151}
152
Colin Cross5e708052019-08-06 13:59:50 -0700153func pathContextName(ctx PathContext, module blueprint.Module) string {
154 if x, ok := ctx.(interface{ ModuleName(blueprint.Module) string }); ok {
155 return x.ModuleName(module)
156 } else if x, ok := ctx.(interface{ OtherModuleName(blueprint.Module) string }); ok {
157 return x.OtherModuleName(module)
158 }
159 return "unknown"
160}
161
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700162type Path interface {
163 // Returns the path in string form
164 String() string
165
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700166 // Ext returns the extension of the last element of the path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700167 Ext() string
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700168
169 // Base returns the last element of the path
170 Base() string
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800171
172 // Rel returns the portion of the path relative to the directory it was created from. For
173 // example, Rel on a PathsForModuleSrc would return the path relative to the module source
Colin Cross0db55682017-12-05 15:36:55 -0800174 // directory, and OutputPath.Join("foo").Rel() would return "foo".
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800175 Rel() string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700176}
177
178// WritablePath is a type of path that can be used as an output for build rules.
179type WritablePath interface {
180 Path
181
Paul Duffin9b478b02019-12-10 13:41:51 +0000182 // return the path to the build directory.
183 buildDir() string
184
Jeff Gaston734e3802017-04-10 15:47:24 -0700185 // the writablePath method doesn't directly do anything,
186 // but it allows a struct to distinguish between whether or not it implements the WritablePath interface
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700187 writablePath()
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +0100188
189 ReplaceExtension(ctx PathContext, ext string) OutputPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700190}
191
192type genPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800193 genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700194}
195type objPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800196 objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700197}
198type resPathProvider interface {
Liz Kammera830f3a2020-11-10 10:50:34 -0800199 resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700200}
201
202// GenPathWithExt derives a new file path in ctx's generated sources directory
203// from the current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800204func GenPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700205 if path, ok := p.(genPathProvider); ok {
Dan Willemsen21ec4902016-11-02 20:43:13 -0700206 return path.genPathWithExt(ctx, subdir, ext)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700207 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100208 ReportPathErrorf(ctx, "Tried to create generated file from unsupported path: %s(%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700209 return PathForModuleGen(ctx)
210}
211
212// ObjPathWithExt derives a new file path in ctx's object directory from the
213// current path, but with the new extension.
Liz Kammera830f3a2020-11-10 10:50:34 -0800214func ObjPathWithExt(ctx ModuleOutPathContext, subdir string, p Path, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700215 if path, ok := p.(objPathProvider); ok {
216 return path.objPathWithExt(ctx, subdir, ext)
217 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100218 ReportPathErrorf(ctx, "Tried to create object file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700219 return PathForModuleObj(ctx)
220}
221
222// ResPathWithName derives a new path in ctx's output resource directory, using
223// the current path to create the directory name, and the `name` argument for
224// the filename.
Liz Kammera830f3a2020-11-10 10:50:34 -0800225func ResPathWithName(ctx ModuleOutPathContext, p Path, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700226 if path, ok := p.(resPathProvider); ok {
227 return path.resPathWithName(ctx, name)
228 }
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100229 ReportPathErrorf(ctx, "Tried to create res file from unsupported path: %s (%s)", reflect.TypeOf(p).Name(), p)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700230 return PathForModuleRes(ctx)
231}
232
233// OptionalPath is a container that may or may not contain a valid Path.
234type OptionalPath struct {
235 valid bool
236 path Path
237}
238
239// OptionalPathForPath returns an OptionalPath containing the path.
240func OptionalPathForPath(path Path) OptionalPath {
241 if path == nil {
242 return OptionalPath{}
243 }
244 return OptionalPath{valid: true, path: path}
245}
246
247// Valid returns whether there is a valid path
248func (p OptionalPath) Valid() bool {
249 return p.valid
250}
251
252// Path returns the Path embedded in this OptionalPath. You must be sure that
253// there is a valid path, since this method will panic if there is not.
254func (p OptionalPath) Path() Path {
255 if !p.valid {
256 panic("Requesting an invalid path")
257 }
258 return p.path
259}
260
261// String returns the string version of the Path, or "" if it isn't valid.
262func (p OptionalPath) String() string {
263 if p.valid {
264 return p.path.String()
265 } else {
266 return ""
Colin Crossf2298272015-05-12 11:36:53 -0700267 }
268}
Colin Cross6e18ca42015-07-14 18:55:36 -0700269
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700270// Paths is a slice of Path objects, with helpers to operate on the collection.
271type Paths []Path
272
Jingwen Chen40fd90a2020-06-15 05:24:19 +0000273func (paths Paths) containsPath(path Path) bool {
274 for _, p := range paths {
275 if p == path {
276 return true
277 }
278 }
279 return false
280}
281
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700282// PathsForSource returns Paths rooted from SrcDir
283func PathsForSource(ctx PathContext, paths []string) Paths {
284 ret := make(Paths, len(paths))
285 for i, path := range paths {
286 ret[i] = PathForSource(ctx, path)
287 }
288 return ret
289}
290
Jeff Gaston734e3802017-04-10 15:47:24 -0700291// ExistentPathsForSources returns a list of Paths rooted from SrcDir that are
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800292// found in the tree. If any are not found, they are omitted from the list,
293// and dependencies are added so that we're re-run when they are added.
Colin Cross32f38982018-02-22 11:47:25 -0800294func ExistentPathsForSources(ctx PathContext, paths []string) Paths {
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800295 ret := make(Paths, 0, len(paths))
296 for _, path := range paths {
Colin Cross32f38982018-02-22 11:47:25 -0800297 p := ExistentPathForSource(ctx, path)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800298 if p.Valid() {
299 ret = append(ret, p.Path())
300 }
301 }
302 return ret
303}
304
Colin Cross41955e82019-05-29 14:40:35 -0700305// PathsForModuleSrc returns Paths rooted from the module's local source directory. It expands globs, references to
306// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
307// ":name{.tag}" syntax. Properties passed as the paths argument must have been annotated with struct tag
308// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
309// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
310// OutputFileProducer dependencies will cause the module to be marked as having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800311func PathsForModuleSrc(ctx ModuleMissingDepsPathContext, paths []string) Paths {
Colin Cross8a497952019-03-05 22:25:09 -0800312 return PathsForModuleSrcExcludes(ctx, paths, nil)
313}
314
Colin Crossba71a3f2019-03-18 12:12:48 -0700315// PathsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding paths listed in
Colin Cross41955e82019-05-29 14:40:35 -0700316// the excludes arguments. It expands globs, references to SourceFileProducer modules using the ":name" syntax, and
317// references to OutputFileProducer modules using the ":name{.tag}" syntax. Properties passed as the paths or excludes
318// argument must have been annotated with struct tag `android:"path"` so that dependencies on SourceFileProducer modules
319// will have already been handled by the path_properties mutator. If ctx.Config().AllowMissingDependencies() is
Paul Duffin036cace2019-07-25 14:44:56 +0100320// true then any missing SourceFileProducer or OutputFileProducer dependencies will cause the module to be marked as
Colin Cross41955e82019-05-29 14:40:35 -0700321// having missing dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800322func PathsForModuleSrcExcludes(ctx ModuleMissingDepsPathContext, paths, excludes []string) Paths {
Colin Crossba71a3f2019-03-18 12:12:48 -0700323 ret, missingDeps := PathsAndMissingDepsForModuleSrcExcludes(ctx, paths, excludes)
324 if ctx.Config().AllowMissingDependencies() {
325 ctx.AddMissingDependencies(missingDeps)
326 } else {
327 for _, m := range missingDeps {
328 ctx.ModuleErrorf(`missing dependency on %q, is the property annotated with android:"path"?`, m)
329 }
330 }
331 return ret
332}
333
Ulya Trafimovich4d2eeed2019-11-08 10:54:21 +0000334// OutputPaths is a slice of OutputPath objects, with helpers to operate on the collection.
335type OutputPaths []OutputPath
336
337// Paths returns the OutputPaths as a Paths
338func (p OutputPaths) Paths() Paths {
339 if p == nil {
340 return nil
341 }
342 ret := make(Paths, len(p))
343 for i, path := range p {
344 ret[i] = path
345 }
346 return ret
347}
348
349// Strings returns the string forms of the writable paths.
350func (p OutputPaths) Strings() []string {
351 if p == nil {
352 return nil
353 }
354 ret := make([]string, len(p))
355 for i, path := range p {
356 ret[i] = path.String()
357 }
358 return ret
359}
360
Liz Kammera830f3a2020-11-10 10:50:34 -0800361// Expands Paths to a SourceFileProducer or OutputFileProducer module dependency referenced via ":name" or ":name{.tag}" syntax.
362// If the dependency is not found, a missingErrorDependency is returned.
363// If the module dependency is not a SourceFileProducer or OutputFileProducer, appropriate errors will be returned.
364func getPathsFromModuleDep(ctx ModuleWithDepsPathContext, path, moduleName, tag string) (Paths, error) {
365 module := ctx.GetDirectDepWithTag(moduleName, sourceOrOutputDepTag(tag))
366 if module == nil {
367 return nil, missingDependencyError{[]string{moduleName}}
368 }
369 if outProducer, ok := module.(OutputFileProducer); ok {
370 outputFiles, err := outProducer.OutputFiles(tag)
371 if err != nil {
372 return nil, fmt.Errorf("path dependency %q: %s", path, err)
373 }
374 return outputFiles, nil
375 } else if tag != "" {
376 return nil, fmt.Errorf("path dependency %q is not an output file producing module", path)
377 } else if srcProducer, ok := module.(SourceFileProducer); ok {
378 return srcProducer.Srcs(), nil
379 } else {
380 return nil, fmt.Errorf("path dependency %q is not a source file producing module", path)
381 }
382}
383
Colin Crossba71a3f2019-03-18 12:12:48 -0700384// PathsAndMissingDepsForModuleSrcExcludes returns Paths rooted from the module's local source directory, excluding
Colin Cross41955e82019-05-29 14:40:35 -0700385// paths listed in the excludes arguments, and a list of missing dependencies. It expands globs, references to
386// SourceFileProducer modules using the ":name" syntax, and references to OutputFileProducer modules using the
387// ":name{.tag}" syntax. Properties passed as the paths or excludes argument must have been annotated with struct tag
388// `android:"path"` so that dependencies on SourceFileProducer modules will have already been handled by the
389// path_properties mutator. If ctx.Config().AllowMissingDependencies() is true then any missing SourceFileProducer or
390// OutputFileProducer dependencies will be returned, and they will NOT cause the module to be marked as having missing
391// dependencies.
Liz Kammera830f3a2020-11-10 10:50:34 -0800392func PathsAndMissingDepsForModuleSrcExcludes(ctx ModuleWithDepsPathContext, paths, excludes []string) (Paths, []string) {
Colin Cross8a497952019-03-05 22:25:09 -0800393 prefix := pathForModuleSrc(ctx).String()
394
395 var expandedExcludes []string
396 if excludes != nil {
397 expandedExcludes = make([]string, 0, len(excludes))
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700398 }
Colin Cross8a497952019-03-05 22:25:09 -0800399
Colin Crossba71a3f2019-03-18 12:12:48 -0700400 var missingExcludeDeps []string
401
Colin Cross8a497952019-03-05 22:25:09 -0800402 for _, e := range excludes {
Colin Cross41955e82019-05-29 14:40:35 -0700403 if m, t := SrcIsModuleWithTag(e); m != "" {
Liz Kammera830f3a2020-11-10 10:50:34 -0800404 modulePaths, err := getPathsFromModuleDep(ctx, e, m, t)
405 if m, ok := err.(missingDependencyError); ok {
406 missingExcludeDeps = append(missingExcludeDeps, m.missingDeps...)
407 } else if err != nil {
408 reportPathError(ctx, err)
Colin Cross8a497952019-03-05 22:25:09 -0800409 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800410 expandedExcludes = append(expandedExcludes, modulePaths.Strings()...)
Colin Cross8a497952019-03-05 22:25:09 -0800411 }
412 } else {
413 expandedExcludes = append(expandedExcludes, filepath.Join(prefix, e))
414 }
415 }
416
417 if paths == nil {
Colin Crossba71a3f2019-03-18 12:12:48 -0700418 return nil, missingExcludeDeps
Colin Cross8a497952019-03-05 22:25:09 -0800419 }
420
Colin Crossba71a3f2019-03-18 12:12:48 -0700421 var missingDeps []string
422
Colin Cross8a497952019-03-05 22:25:09 -0800423 expandedSrcFiles := make(Paths, 0, len(paths))
424 for _, s := range paths {
425 srcFiles, err := expandOneSrcPath(ctx, s, expandedExcludes)
426 if depErr, ok := err.(missingDependencyError); ok {
Colin Crossba71a3f2019-03-18 12:12:48 -0700427 missingDeps = append(missingDeps, depErr.missingDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800428 } else if err != nil {
429 reportPathError(ctx, err)
430 }
431 expandedSrcFiles = append(expandedSrcFiles, srcFiles...)
432 }
Colin Crossba71a3f2019-03-18 12:12:48 -0700433
434 return expandedSrcFiles, append(missingDeps, missingExcludeDeps...)
Colin Cross8a497952019-03-05 22:25:09 -0800435}
436
437type missingDependencyError struct {
438 missingDeps []string
439}
440
441func (e missingDependencyError) Error() string {
442 return "missing dependencies: " + strings.Join(e.missingDeps, ", ")
443}
444
Liz Kammera830f3a2020-11-10 10:50:34 -0800445// Expands one path string to Paths rooted from the module's local source
446// directory, excluding those listed in the expandedExcludes.
447// Expands globs, references to SourceFileProducer or OutputFileProducer modules using the ":name" and ":name{.tag}" syntax.
448func expandOneSrcPath(ctx ModuleWithDepsPathContext, sPath string, expandedExcludes []string) (Paths, error) {
Jooyung Han7607dd32020-07-05 10:23:14 +0900449 excludePaths := func(paths Paths) Paths {
450 if len(expandedExcludes) == 0 {
451 return paths
452 }
453 remainder := make(Paths, 0, len(paths))
454 for _, p := range paths {
455 if !InList(p.String(), expandedExcludes) {
456 remainder = append(remainder, p)
457 }
458 }
459 return remainder
460 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800461 if m, t := SrcIsModuleWithTag(sPath); m != "" {
462 modulePaths, err := getPathsFromModuleDep(ctx, sPath, m, t)
463 if err != nil {
464 return nil, err
Colin Cross8a497952019-03-05 22:25:09 -0800465 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800466 return excludePaths(modulePaths), nil
Colin Cross8a497952019-03-05 22:25:09 -0800467 }
Liz Kammera830f3a2020-11-10 10:50:34 -0800468 } else if pathtools.IsGlob(sPath) {
469 paths := GlobFiles(ctx, pathForModuleSrc(ctx, sPath).String(), expandedExcludes)
Colin Cross8a497952019-03-05 22:25:09 -0800470 return PathsWithModuleSrcSubDir(ctx, paths, ""), nil
471 } else {
Liz Kammera830f3a2020-11-10 10:50:34 -0800472 p := pathForModuleSrc(ctx, sPath)
Colin Cross988414c2020-01-11 01:11:46 +0000473 if exists, _, err := ctx.Config().fs.Exists(p.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100474 ReportPathErrorf(ctx, "%s: %s", p, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -0700475 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100476 ReportPathErrorf(ctx, "module source path %q does not exist", p)
Colin Cross8a497952019-03-05 22:25:09 -0800477 }
478
Jooyung Han7607dd32020-07-05 10:23:14 +0900479 if InList(p.String(), expandedExcludes) {
Colin Cross8a497952019-03-05 22:25:09 -0800480 return nil, nil
481 }
482 return Paths{p}, nil
483 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700484}
485
486// pathsForModuleSrcFromFullPath returns Paths rooted from the module's local
487// source directory, but strip the local source directory from the beginning of
Dan Willemsen540a78c2018-02-26 21:50:08 -0800488// each string. If incDirs is false, strip paths with a trailing '/' from the list.
Colin Crossfe4bc362018-09-12 10:02:13 -0700489// It intended for use in globs that only list files that exist, so it allows '$' in
490// filenames.
Liz Kammera830f3a2020-11-10 10:50:34 -0800491func pathsForModuleSrcFromFullPath(ctx EarlyModulePathContext, paths []string, incDirs bool) Paths {
Colin Cross6510f912017-11-29 00:27:14 -0800492 prefix := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir()) + "/"
Colin Cross0f37af02017-09-27 17:42:05 -0700493 if prefix == "./" {
494 prefix = ""
495 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700496 ret := make(Paths, 0, len(paths))
497 for _, p := range paths {
Dan Willemsen540a78c2018-02-26 21:50:08 -0800498 if !incDirs && strings.HasSuffix(p, "/") {
499 continue
500 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700501 path := filepath.Clean(p)
502 if !strings.HasPrefix(path, prefix) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100503 ReportPathErrorf(ctx, "Path %q is not in module source directory %q", p, prefix)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700504 continue
505 }
Colin Crosse3924e12018-08-15 20:18:53 -0700506
Colin Crossfe4bc362018-09-12 10:02:13 -0700507 srcPath, err := safePathForSource(ctx, ctx.ModuleDir(), path[len(prefix):])
Colin Crosse3924e12018-08-15 20:18:53 -0700508 if err != nil {
509 reportPathError(ctx, err)
510 continue
511 }
512
Colin Cross07e51612019-03-05 12:46:40 -0800513 srcPath.basePath.rel = srcPath.path
Colin Crosse3924e12018-08-15 20:18:53 -0700514
Colin Cross07e51612019-03-05 12:46:40 -0800515 ret = append(ret, srcPath)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700516 }
517 return ret
518}
519
Liz Kammera830f3a2020-11-10 10:50:34 -0800520// PathsWithOptionalDefaultForModuleSrc returns Paths rooted from the module's local source
521// directory. If input is nil, use the default if it exists. If input is empty, returns nil.
522func PathsWithOptionalDefaultForModuleSrc(ctx ModuleMissingDepsPathContext, input []string, def string) Paths {
Colin Cross0ddae7f2019-02-07 15:30:01 -0800523 if input != nil {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700524 return PathsForModuleSrc(ctx, input)
525 }
526 // Use Glob so that if the default doesn't exist, a dependency is added so that when it
527 // is created, we're run again.
Colin Cross6510f912017-11-29 00:27:14 -0800528 path := filepath.Join(ctx.Config().srcDir, ctx.ModuleDir(), def)
Liz Kammera830f3a2020-11-10 10:50:34 -0800529 return Glob(ctx, path, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700530}
531
532// Strings returns the Paths in string form
533func (p Paths) Strings() []string {
534 if p == nil {
535 return nil
536 }
537 ret := make([]string, len(p))
538 for i, path := range p {
539 ret[i] = path.String()
540 }
541 return ret
542}
543
Colin Crossc0efd1d2020-07-03 11:56:24 -0700544func CopyOfPaths(paths Paths) Paths {
545 return append(Paths(nil), paths...)
546}
547
Colin Crossb6715442017-10-24 11:13:31 -0700548// FirstUniquePaths returns all unique elements of a Paths, keeping the first copy of each. It
549// modifies the Paths slice contents in place, and returns a subslice of the original slice.
Dan Willemsenfe92c962017-08-29 12:28:37 -0700550func FirstUniquePaths(list Paths) Paths {
Colin Cross27027c72020-02-28 15:34:17 -0800551 // 128 was chosen based on BenchmarkFirstUniquePaths results.
552 if len(list) > 128 {
553 return firstUniquePathsMap(list)
554 }
555 return firstUniquePathsList(list)
556}
557
Colin Crossc0efd1d2020-07-03 11:56:24 -0700558// SortedUniquePaths returns all unique elements of a Paths in sorted order. It modifies the
559// Paths slice contents in place, and returns a subslice of the original slice.
Jiyong Park33c77362020-05-29 22:00:16 +0900560func SortedUniquePaths(list Paths) Paths {
561 unique := FirstUniquePaths(list)
562 sort.Slice(unique, func(i, j int) bool {
563 return unique[i].String() < unique[j].String()
564 })
565 return unique
566}
567
Colin Cross27027c72020-02-28 15:34:17 -0800568func firstUniquePathsList(list Paths) Paths {
Dan Willemsenfe92c962017-08-29 12:28:37 -0700569 k := 0
570outer:
571 for i := 0; i < len(list); i++ {
572 for j := 0; j < k; j++ {
573 if list[i] == list[j] {
574 continue outer
575 }
576 }
577 list[k] = list[i]
578 k++
579 }
580 return list[:k]
581}
582
Colin Cross27027c72020-02-28 15:34:17 -0800583func firstUniquePathsMap(list Paths) Paths {
584 k := 0
585 seen := make(map[Path]bool, len(list))
586 for i := 0; i < len(list); i++ {
587 if seen[list[i]] {
588 continue
589 }
590 seen[list[i]] = true
591 list[k] = list[i]
592 k++
593 }
594 return list[:k]
595}
596
Colin Cross5d583952020-11-24 16:21:24 -0800597// FirstUniqueInstallPaths returns all unique elements of an InstallPaths, keeping the first copy of each. It
598// modifies the InstallPaths slice contents in place, and returns a subslice of the original slice.
599func FirstUniqueInstallPaths(list InstallPaths) InstallPaths {
600 // 128 was chosen based on BenchmarkFirstUniquePaths results.
601 if len(list) > 128 {
602 return firstUniqueInstallPathsMap(list)
603 }
604 return firstUniqueInstallPathsList(list)
605}
606
607func firstUniqueInstallPathsList(list InstallPaths) InstallPaths {
608 k := 0
609outer:
610 for i := 0; i < len(list); i++ {
611 for j := 0; j < k; j++ {
612 if list[i] == list[j] {
613 continue outer
614 }
615 }
616 list[k] = list[i]
617 k++
618 }
619 return list[:k]
620}
621
622func firstUniqueInstallPathsMap(list InstallPaths) InstallPaths {
623 k := 0
624 seen := make(map[InstallPath]bool, len(list))
625 for i := 0; i < len(list); i++ {
626 if seen[list[i]] {
627 continue
628 }
629 seen[list[i]] = true
630 list[k] = list[i]
631 k++
632 }
633 return list[:k]
634}
635
Colin Crossb6715442017-10-24 11:13:31 -0700636// LastUniquePaths returns all unique elements of a Paths, keeping the last copy of each. It
637// modifies the Paths slice contents in place, and returns a subslice of the original slice.
638func LastUniquePaths(list Paths) Paths {
639 totalSkip := 0
640 for i := len(list) - 1; i >= totalSkip; i-- {
641 skip := 0
642 for j := i - 1; j >= totalSkip; j-- {
643 if list[i] == list[j] {
644 skip++
645 } else {
646 list[j+skip] = list[j]
647 }
648 }
649 totalSkip += skip
650 }
651 return list[totalSkip:]
652}
653
Colin Crossa140bb02018-04-17 10:52:26 -0700654// ReversePaths returns a copy of a Paths in reverse order.
655func ReversePaths(list Paths) Paths {
656 if list == nil {
657 return nil
658 }
659 ret := make(Paths, len(list))
660 for i := range list {
661 ret[i] = list[len(list)-1-i]
662 }
663 return ret
664}
665
Jeff Gaston294356f2017-09-27 17:05:30 -0700666func indexPathList(s Path, list []Path) int {
667 for i, l := range list {
668 if l == s {
669 return i
670 }
671 }
672
673 return -1
674}
675
676func inPathList(p Path, list []Path) bool {
677 return indexPathList(p, list) != -1
678}
679
680func FilterPathList(list []Path, filter []Path) (remainder []Path, filtered []Path) {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000681 return FilterPathListPredicate(list, func(p Path) bool { return inPathList(p, filter) })
682}
683
684func FilterPathListPredicate(list []Path, predicate func(Path) bool) (remainder []Path, filtered []Path) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700685 for _, l := range list {
Paul Duffin57b9e1d2019-12-13 00:03:35 +0000686 if predicate(l) {
Jeff Gaston294356f2017-09-27 17:05:30 -0700687 filtered = append(filtered, l)
688 } else {
689 remainder = append(remainder, l)
690 }
691 }
692
693 return
694}
695
Colin Cross93e85952017-08-15 13:34:18 -0700696// HasExt returns true of any of the paths have extension ext, otherwise false
697func (p Paths) HasExt(ext string) bool {
698 for _, path := range p {
699 if path.Ext() == ext {
700 return true
701 }
702 }
703
704 return false
705}
706
707// FilterByExt returns the subset of the paths that have extension ext
708func (p Paths) FilterByExt(ext string) Paths {
709 ret := make(Paths, 0, len(p))
710 for _, path := range p {
711 if path.Ext() == ext {
712 ret = append(ret, path)
713 }
714 }
715 return ret
716}
717
718// FilterOutByExt returns the subset of the paths that do not have extension ext
719func (p Paths) FilterOutByExt(ext string) Paths {
720 ret := make(Paths, 0, len(p))
721 for _, path := range p {
722 if path.Ext() != ext {
723 ret = append(ret, path)
724 }
725 }
726 return ret
727}
728
Colin Cross5e6cfbe2017-11-03 15:20:35 -0700729// DirectorySortedPaths is a slice of paths that are sorted such that all files in a directory
730// (including subdirectories) are in a contiguous subslice of the list, and can be found in
731// O(log(N)) time using a binary search on the directory prefix.
732type DirectorySortedPaths Paths
733
734func PathsToDirectorySortedPaths(paths Paths) DirectorySortedPaths {
735 ret := append(DirectorySortedPaths(nil), paths...)
736 sort.Slice(ret, func(i, j int) bool {
737 return ret[i].String() < ret[j].String()
738 })
739 return ret
740}
741
742// PathsInDirectory returns a subslice of the DirectorySortedPaths as a Paths that contains all entries
743// that are in the specified directory and its subdirectories.
744func (p DirectorySortedPaths) PathsInDirectory(dir string) Paths {
745 prefix := filepath.Clean(dir) + "/"
746 start := sort.Search(len(p), func(i int) bool {
747 return prefix < p[i].String()
748 })
749
750 ret := p[start:]
751
752 end := sort.Search(len(ret), func(i int) bool {
753 return !strings.HasPrefix(ret[i].String(), prefix)
754 })
755
756 ret = ret[:end]
757
758 return Paths(ret)
759}
760
Alex Humesky29e3bbe2020-11-20 21:30:13 -0500761// WritablePaths is a slice of WritablePath, used for multiple outputs.
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700762type WritablePaths []WritablePath
763
764// Strings returns the string forms of the writable paths.
765func (p WritablePaths) Strings() []string {
766 if p == nil {
767 return nil
768 }
769 ret := make([]string, len(p))
770 for i, path := range p {
771 ret[i] = path.String()
772 }
773 return ret
774}
775
Colin Cross3bc7ffa2017-11-22 16:19:37 -0800776// Paths returns the WritablePaths as a Paths
777func (p WritablePaths) Paths() Paths {
778 if p == nil {
779 return nil
780 }
781 ret := make(Paths, len(p))
782 for i, path := range p {
783 ret[i] = path
784 }
785 return ret
786}
787
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700788type basePath struct {
789 path string
790 config Config
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800791 rel string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700792}
793
794func (p basePath) Ext() string {
795 return filepath.Ext(p.path)
796}
797
Colin Cross4f6fc9c2016-10-26 10:05:25 -0700798func (p basePath) Base() string {
799 return filepath.Base(p.path)
800}
801
Colin Crossfaeb7aa2017-02-01 14:12:44 -0800802func (p basePath) Rel() string {
803 if p.rel != "" {
804 return p.rel
805 }
806 return p.path
807}
808
Colin Cross0875c522017-11-28 17:34:01 -0800809func (p basePath) String() string {
810 return p.path
811}
812
Colin Cross0db55682017-12-05 15:36:55 -0800813func (p basePath) withRel(rel string) basePath {
814 p.path = filepath.Join(p.path, rel)
815 p.rel = rel
816 return p
817}
818
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700819// SourcePath is a Path representing a file path rooted from SrcDir
820type SourcePath struct {
821 basePath
822}
823
824var _ Path = SourcePath{}
825
Colin Cross0db55682017-12-05 15:36:55 -0800826func (p SourcePath) withRel(rel string) SourcePath {
827 p.basePath = p.basePath.withRel(rel)
828 return p
829}
830
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700831// safePathForSource is for paths that we expect are safe -- only for use by go
832// code that is embedding ninja variables in paths
Colin Crossfe4bc362018-09-12 10:02:13 -0700833func safePathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
834 p, err := validateSafePath(pathComponents...)
Colin Crossaabf6792017-11-29 00:27:14 -0800835 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Crossfe4bc362018-09-12 10:02:13 -0700836 if err != nil {
837 return ret, err
838 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700839
Colin Cross7b3dcc32019-01-24 13:14:39 -0800840 // absolute path already checked by validateSafePath
841 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800842 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Cross6e18ca42015-07-14 18:55:36 -0700843 }
844
Colin Crossfe4bc362018-09-12 10:02:13 -0700845 return ret, err
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700846}
847
Colin Cross192e97a2018-02-22 14:21:02 -0800848// pathForSource creates a SourcePath from pathComponents, but does not check that it exists.
849func pathForSource(ctx PathContext, pathComponents ...string) (SourcePath, error) {
Colin Crossc48c1432018-02-23 07:09:01 +0000850 p, err := validatePath(pathComponents...)
851 ret := SourcePath{basePath{p, ctx.Config(), ""}}
Colin Cross94a32102018-02-22 14:21:02 -0800852 if err != nil {
Colin Cross192e97a2018-02-22 14:21:02 -0800853 return ret, err
Colin Cross94a32102018-02-22 14:21:02 -0800854 }
855
Colin Cross7b3dcc32019-01-24 13:14:39 -0800856 // absolute path already checked by validatePath
857 if strings.HasPrefix(ret.String(), ctx.Config().buildDir) {
Mikhail Naganovab1f5182019-02-08 13:17:55 -0800858 return ret, fmt.Errorf("source path %q is in output", ret.String())
Colin Crossc48c1432018-02-23 07:09:01 +0000859 }
860
Colin Cross192e97a2018-02-22 14:21:02 -0800861 return ret, nil
862}
863
864// existsWithDependencies returns true if the path exists, and adds appropriate dependencies to rerun if the
865// path does not exist.
866func existsWithDependencies(ctx PathContext, path SourcePath) (exists bool, err error) {
867 var files []string
868
869 if gctx, ok := ctx.(PathGlobContext); ok {
870 // Use glob to produce proper dependencies, even though we only want
871 // a single file.
872 files, err = gctx.GlobWithDeps(path.String(), nil)
873 } else {
874 var deps []string
875 // We cannot add build statements in this context, so we fall back to
876 // AddNinjaFileDeps
Colin Cross988414c2020-01-11 01:11:46 +0000877 files, deps, err = ctx.Config().fs.Glob(path.String(), nil, pathtools.FollowSymlinks)
Colin Cross192e97a2018-02-22 14:21:02 -0800878 ctx.AddNinjaFileDeps(deps...)
879 }
880
881 if err != nil {
882 return false, fmt.Errorf("glob: %s", err.Error())
883 }
884
885 return len(files) > 0, nil
886}
887
888// PathForSource joins the provided path components and validates that the result
889// neither escapes the source dir nor is in the out dir.
890// On error, it will return a usable, but invalid SourcePath, and report a ModuleError.
891func PathForSource(ctx PathContext, pathComponents ...string) SourcePath {
892 path, err := pathForSource(ctx, pathComponents...)
893 if err != nil {
894 reportPathError(ctx, err)
895 }
896
Colin Crosse3924e12018-08-15 20:18:53 -0700897 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100898 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -0700899 }
900
Liz Kammera830f3a2020-11-10 10:50:34 -0800901 if modCtx, ok := ctx.(ModuleMissingDepsPathContext); ok && ctx.Config().AllowMissingDependencies() {
Colin Cross192e97a2018-02-22 14:21:02 -0800902 exists, err := existsWithDependencies(ctx, path)
903 if err != nil {
904 reportPathError(ctx, err)
905 }
906 if !exists {
907 modCtx.AddMissingDependencies([]string{path.String()})
908 }
Colin Cross988414c2020-01-11 01:11:46 +0000909 } else if exists, _, err := ctx.Config().fs.Exists(path.String()); err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100910 ReportPathErrorf(ctx, "%s: %s", path, err.Error())
Colin Cross5e6a7972020-06-07 16:56:32 -0700911 } else if !exists && !ctx.Config().testAllowNonExistentPaths {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100912 ReportPathErrorf(ctx, "source path %q does not exist", path)
Colin Cross192e97a2018-02-22 14:21:02 -0800913 }
914 return path
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700915}
916
Jeff Gaston734e3802017-04-10 15:47:24 -0700917// ExistentPathForSource returns an OptionalPath with the SourcePath if the
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700918// path exists, or an empty OptionalPath if it doesn't exist. Dependencies are added
919// so that the ninja file will be regenerated if the state of the path changes.
Colin Cross32f38982018-02-22 11:47:25 -0800920func ExistentPathForSource(ctx PathContext, pathComponents ...string) OptionalPath {
Colin Cross192e97a2018-02-22 14:21:02 -0800921 path, err := pathForSource(ctx, pathComponents...)
Colin Cross1ccfcc32018-02-22 13:54:26 -0800922 if err != nil {
923 reportPathError(ctx, err)
924 return OptionalPath{}
925 }
Colin Crossc48c1432018-02-23 07:09:01 +0000926
Colin Crosse3924e12018-08-15 20:18:53 -0700927 if pathtools.IsGlob(path.String()) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100928 ReportPathErrorf(ctx, "path may not contain a glob: %s", path.String())
Colin Crosse3924e12018-08-15 20:18:53 -0700929 return OptionalPath{}
930 }
931
Colin Cross192e97a2018-02-22 14:21:02 -0800932 exists, err := existsWithDependencies(ctx, path)
Colin Crossc48c1432018-02-23 07:09:01 +0000933 if err != nil {
934 reportPathError(ctx, err)
935 return OptionalPath{}
936 }
Colin Cross192e97a2018-02-22 14:21:02 -0800937 if !exists {
Colin Crossc48c1432018-02-23 07:09:01 +0000938 return OptionalPath{}
939 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700940 return OptionalPathForPath(path)
941}
942
943func (p SourcePath) String() string {
944 return filepath.Join(p.config.srcDir, p.path)
945}
946
947// Join creates a new SourcePath with paths... joined with the current path. The
948// provided paths... may not use '..' to escape from the current path.
949func (p SourcePath) Join(ctx PathContext, paths ...string) SourcePath {
Colin Cross1ccfcc32018-02-22 13:54:26 -0800950 path, err := validatePath(paths...)
951 if err != nil {
952 reportPathError(ctx, err)
953 }
Colin Cross0db55682017-12-05 15:36:55 -0800954 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700955}
956
Colin Cross2fafa3e2019-03-05 12:39:51 -0800957// join is like Join but does less path validation.
958func (p SourcePath) join(ctx PathContext, paths ...string) SourcePath {
959 path, err := validateSafePath(paths...)
960 if err != nil {
961 reportPathError(ctx, err)
962 }
963 return p.withRel(path)
964}
965
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700966// OverlayPath returns the overlay for `path' if it exists. This assumes that the
967// SourcePath is the path to a resource overlay directory.
Liz Kammera830f3a2020-11-10 10:50:34 -0800968func (p SourcePath) OverlayPath(ctx ModuleMissingDepsPathContext, path Path) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700969 var relDir string
Colin Cross07e51612019-03-05 12:46:40 -0800970 if srcPath, ok := path.(SourcePath); ok {
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700971 relDir = srcPath.path
972 } else {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100973 ReportPathErrorf(ctx, "Cannot find relative path for %s(%s)", reflect.TypeOf(path).Name(), path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700974 return OptionalPath{}
975 }
976 dir := filepath.Join(p.config.srcDir, p.path, relDir)
977 // Use Glob so that we are run again if the directory is added.
Colin Cross7f19f372016-11-01 11:10:25 -0700978 if pathtools.IsGlob(dir) {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100979 ReportPathErrorf(ctx, "Path may not contain a glob: %s", dir)
Dan Willemsen7b310ee2015-12-18 15:11:17 -0800980 }
Colin Cross461b4452018-02-23 09:22:42 -0800981 paths, err := ctx.GlobWithDeps(dir, nil)
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700982 if err != nil {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +0100983 ReportPathErrorf(ctx, "glob: %s", err.Error())
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700984 return OptionalPath{}
985 }
986 if len(paths) == 0 {
987 return OptionalPath{}
988 }
Colin Cross43f08db2018-11-12 10:13:39 -0800989 relPath := Rel(ctx, p.config.srcDir, paths[0])
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700990 return OptionalPathForPath(PathForSource(ctx, relPath))
991}
992
Colin Cross70dda7e2019-10-01 22:05:35 -0700993// OutputPath is a Path representing an intermediates file path rooted from the build directory
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700994type OutputPath struct {
995 basePath
Colin Crossd63c9a72020-01-29 16:52:50 -0800996 fullPath string
Dan Willemsen34cc69e2015-09-23 15:26:20 -0700997}
998
Colin Cross702e0f82017-10-18 17:27:54 -0700999func (p OutputPath) withRel(rel string) OutputPath {
Colin Cross0db55682017-12-05 15:36:55 -08001000 p.basePath = p.basePath.withRel(rel)
Colin Crossd63c9a72020-01-29 16:52:50 -08001001 p.fullPath = filepath.Join(p.fullPath, rel)
Colin Cross702e0f82017-10-18 17:27:54 -07001002 return p
1003}
1004
Colin Cross3063b782018-08-15 11:19:12 -07001005func (p OutputPath) WithoutRel() OutputPath {
1006 p.basePath.rel = filepath.Base(p.basePath.path)
1007 return p
1008}
1009
Paul Duffin9b478b02019-12-10 13:41:51 +00001010func (p OutputPath) buildDir() string {
1011 return p.config.buildDir
1012}
1013
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001014var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001015var _ WritablePath = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001016
Chris Parsons8f232a22020-06-23 17:37:05 -04001017// toolDepPath is a Path representing a dependency of the build tool.
1018type toolDepPath struct {
1019 basePath
1020}
1021
1022var _ Path = toolDepPath{}
1023
1024// pathForBuildToolDep returns a toolDepPath representing the given path string.
1025// There is no validation for the path, as it is "trusted": It may fail
1026// normal validation checks. For example, it may be an absolute path.
1027// Only use this function to construct paths for dependencies of the build
1028// tool invocation.
1029func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
1030 return toolDepPath{basePath{path, ctx.Config(), ""}}
1031}
1032
Jeff Gaston734e3802017-04-10 15:47:24 -07001033// PathForOutput joins the provided paths and returns an OutputPath that is
1034// validated to not escape the build dir.
1035// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1036func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001037 path, err := validatePath(pathComponents...)
1038 if err != nil {
1039 reportPathError(ctx, err)
1040 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001041 fullPath := filepath.Join(ctx.Config().buildDir, path)
1042 path = fullPath[len(fullPath)-len(path):]
1043 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001044}
1045
Colin Cross40e33732019-02-15 11:08:35 -08001046// PathsForOutput returns Paths rooted from buildDir
1047func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1048 ret := make(WritablePaths, len(paths))
1049 for i, path := range paths {
1050 ret[i] = PathForOutput(ctx, path)
1051 }
1052 return ret
1053}
1054
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001055func (p OutputPath) writablePath() {}
1056
1057func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001058 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001059}
1060
1061// Join creates a new OutputPath with paths... joined with the current path. The
1062// provided paths... may not use '..' to escape from the current path.
1063func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001064 path, err := validatePath(paths...)
1065 if err != nil {
1066 reportPathError(ctx, err)
1067 }
Colin Cross0db55682017-12-05 15:36:55 -08001068 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001069}
1070
Colin Cross8854a5a2019-02-11 14:14:16 -08001071// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1072func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1073 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001074 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001075 }
1076 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001077 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001078 return ret
1079}
1080
Colin Cross40e33732019-02-15 11:08:35 -08001081// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1082func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1083 path, err := validatePath(paths...)
1084 if err != nil {
1085 reportPathError(ctx, err)
1086 }
1087
1088 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001089 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001090 return ret
1091}
1092
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001093// PathForIntermediates returns an OutputPath representing the top-level
1094// intermediates directory.
1095func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001096 path, err := validatePath(paths...)
1097 if err != nil {
1098 reportPathError(ctx, err)
1099 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001100 return PathForOutput(ctx, ".intermediates", path)
1101}
1102
Colin Cross07e51612019-03-05 12:46:40 -08001103var _ genPathProvider = SourcePath{}
1104var _ objPathProvider = SourcePath{}
1105var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001106
Colin Cross07e51612019-03-05 12:46:40 -08001107// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001108// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001109func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001110 p, err := validatePath(pathComponents...)
1111 if err != nil {
1112 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001113 }
Colin Cross8a497952019-03-05 22:25:09 -08001114 paths, err := expandOneSrcPath(ctx, p, nil)
1115 if err != nil {
1116 if depErr, ok := err.(missingDependencyError); ok {
1117 if ctx.Config().AllowMissingDependencies() {
1118 ctx.AddMissingDependencies(depErr.missingDeps)
1119 } else {
1120 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1121 }
1122 } else {
1123 reportPathError(ctx, err)
1124 }
1125 return nil
1126 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001127 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001128 return nil
1129 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001130 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001131 }
1132 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001133}
1134
Liz Kammera830f3a2020-11-10 10:50:34 -08001135func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001136 p, err := validatePath(paths...)
1137 if err != nil {
1138 reportPathError(ctx, err)
1139 }
1140
1141 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1142 if err != nil {
1143 reportPathError(ctx, err)
1144 }
1145
1146 path.basePath.rel = p
1147
1148 return path
1149}
1150
Colin Cross2fafa3e2019-03-05 12:39:51 -08001151// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1152// will return the path relative to subDir in the module's source directory. If any input paths are not located
1153// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001154func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001155 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001156 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001157 for i, path := range paths {
1158 rel := Rel(ctx, subDirFullPath.String(), path.String())
1159 paths[i] = subDirFullPath.join(ctx, rel)
1160 }
1161 return paths
1162}
1163
1164// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1165// module's source directory. If the input path is not located inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001166func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001167 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001168 rel := Rel(ctx, subDirFullPath.String(), path.String())
1169 return subDirFullPath.Join(ctx, rel)
1170}
1171
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001172// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1173// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001174func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001175 if p == nil {
1176 return OptionalPath{}
1177 }
1178 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1179}
1180
Liz Kammera830f3a2020-11-10 10:50:34 -08001181func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001182 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001183}
1184
Liz Kammera830f3a2020-11-10 10:50:34 -08001185func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001186 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001187}
1188
Liz Kammera830f3a2020-11-10 10:50:34 -08001189func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001190 // TODO: Use full directory if the new ctx is not the current ctx?
1191 return PathForModuleRes(ctx, p.path, name)
1192}
1193
1194// ModuleOutPath is a Path representing a module's output directory.
1195type ModuleOutPath struct {
1196 OutputPath
1197}
1198
1199var _ Path = ModuleOutPath{}
1200
Liz Kammera830f3a2020-11-10 10:50:34 -08001201func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001202 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1203}
1204
Liz Kammera830f3a2020-11-10 10:50:34 -08001205// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1206type ModuleOutPathContext interface {
1207 PathContext
1208
1209 ModuleName() string
1210 ModuleDir() string
1211 ModuleSubDir() string
1212}
1213
1214func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001215 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1216}
1217
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001218type BazelOutPath struct {
1219 OutputPath
1220}
1221
1222var _ Path = BazelOutPath{}
1223var _ objPathProvider = BazelOutPath{}
1224
Liz Kammera830f3a2020-11-10 10:50:34 -08001225func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001226 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1227}
1228
Logan Chien7eefdc42018-07-11 18:10:41 +08001229// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1230// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001231func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001232 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001233
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001234 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001235 if len(arches) == 0 {
1236 panic("device build with no primary arch")
1237 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001238 currentArch := ctx.Arch()
1239 archNameAndVariant := currentArch.ArchType.String()
1240 if currentArch.ArchVariant != "" {
1241 archNameAndVariant += "_" + currentArch.ArchVariant
1242 }
Logan Chien5237bed2018-07-11 17:15:57 +08001243
1244 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001245 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001246 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001247 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001248 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001249 } else {
1250 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001251 }
Logan Chien5237bed2018-07-11 17:15:57 +08001252
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001253 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001254
1255 var ext string
1256 if isGzip {
1257 ext = ".lsdump.gz"
1258 } else {
1259 ext = ".lsdump"
1260 }
1261
1262 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1263 version, binderBitness, archNameAndVariant, "source-based",
1264 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001265}
1266
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001267// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1268// bazel-owned outputs.
1269func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1270 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1271 execRootPath := filepath.Join(execRootPathComponents...)
1272 validatedExecRootPath, err := validatePath(execRootPath)
1273 if err != nil {
1274 reportPathError(ctx, err)
1275 }
1276
1277 outputPath := OutputPath{basePath{"", ctx.Config(), ""},
1278 ctx.Config().BazelContext.OutputBase()}
1279
1280 return BazelOutPath{
1281 OutputPath: outputPath.withRel(validatedExecRootPath),
1282 }
1283}
1284
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001285// PathForModuleOut returns a Path representing the paths... under the module's
1286// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001287func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001288 p, err := validatePath(paths...)
1289 if err != nil {
1290 reportPathError(ctx, err)
1291 }
Colin Cross702e0f82017-10-18 17:27:54 -07001292 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001293 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001294 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001295}
1296
1297// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1298// directory. Mainly used for generated sources.
1299type ModuleGenPath struct {
1300 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001301}
1302
1303var _ Path = ModuleGenPath{}
1304var _ genPathProvider = ModuleGenPath{}
1305var _ objPathProvider = ModuleGenPath{}
1306
1307// PathForModuleGen returns a Path representing the paths... under the module's
1308// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001309func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001310 p, err := validatePath(paths...)
1311 if err != nil {
1312 reportPathError(ctx, err)
1313 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001314 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001315 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001316 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001317 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001318 }
1319}
1320
Liz Kammera830f3a2020-11-10 10:50:34 -08001321func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001322 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001323 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001324}
1325
Liz Kammera830f3a2020-11-10 10:50:34 -08001326func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001327 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1328}
1329
1330// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1331// directory. Used for compiled objects.
1332type ModuleObjPath struct {
1333 ModuleOutPath
1334}
1335
1336var _ Path = ModuleObjPath{}
1337
1338// PathForModuleObj returns a Path representing the paths... under the module's
1339// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001340func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001341 p, err := validatePath(pathComponents...)
1342 if err != nil {
1343 reportPathError(ctx, err)
1344 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001345 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1346}
1347
1348// ModuleResPath is a a Path representing the 'res' directory in a module's
1349// output directory.
1350type ModuleResPath struct {
1351 ModuleOutPath
1352}
1353
1354var _ Path = ModuleResPath{}
1355
1356// PathForModuleRes returns a Path representing the paths... under the module's
1357// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001358func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001359 p, err := validatePath(pathComponents...)
1360 if err != nil {
1361 reportPathError(ctx, err)
1362 }
1363
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001364 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1365}
1366
Colin Cross70dda7e2019-10-01 22:05:35 -07001367// InstallPath is a Path representing a installed file path rooted from the build directory
1368type InstallPath struct {
1369 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001370
Jiyong Park957bcd92020-10-20 18:23:33 +09001371 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1372 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1373 partitionDir string
1374
1375 // makePath indicates whether this path is for Soong (false) or Make (true).
1376 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001377}
1378
Paul Duffin9b478b02019-12-10 13:41:51 +00001379func (p InstallPath) buildDir() string {
1380 return p.config.buildDir
1381}
1382
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001383func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1384 panic("Not implemented")
1385}
1386
Paul Duffin9b478b02019-12-10 13:41:51 +00001387var _ Path = InstallPath{}
1388var _ WritablePath = InstallPath{}
1389
Colin Cross70dda7e2019-10-01 22:05:35 -07001390func (p InstallPath) writablePath() {}
1391
1392func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001393 if p.makePath {
1394 // Make path starts with out/ instead of out/soong.
1395 return filepath.Join(p.config.buildDir, "../", p.path)
1396 } else {
1397 return filepath.Join(p.config.buildDir, p.path)
1398 }
1399}
1400
1401// PartitionDir returns the path to the partition where the install path is rooted at. It is
1402// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1403// The ./soong is dropped if the install path is for Make.
1404func (p InstallPath) PartitionDir() string {
1405 if p.makePath {
1406 return filepath.Join(p.config.buildDir, "../", p.partitionDir)
1407 } else {
1408 return filepath.Join(p.config.buildDir, p.partitionDir)
1409 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001410}
1411
1412// Join creates a new InstallPath with paths... joined with the current path. The
1413// provided paths... may not use '..' to escape from the current path.
1414func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1415 path, err := validatePath(paths...)
1416 if err != nil {
1417 reportPathError(ctx, err)
1418 }
1419 return p.withRel(path)
1420}
1421
1422func (p InstallPath) withRel(rel string) InstallPath {
1423 p.basePath = p.basePath.withRel(rel)
1424 return p
1425}
1426
Colin Crossff6c33d2019-10-02 16:01:35 -07001427// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1428// i.e. out/ instead of out/soong/.
1429func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001430 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001431 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001432}
1433
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001434// PathForModuleInstall returns a Path representing the install path for the
1435// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001436func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001437 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001438 arch := ctx.Arch().ArchType
1439 forceOS, forceArch := ctx.InstallForceOS()
1440 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001441 os = *forceOS
1442 }
Jiyong Park87788b52020-09-01 12:37:45 +09001443 if forceArch != nil {
1444 arch = *forceArch
1445 }
Colin Cross6e359402020-02-10 15:29:54 -08001446 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001447
Jiyong Park87788b52020-09-01 12:37:45 +09001448 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001449
Jingwen Chencda22c92020-11-23 00:22:30 -05001450 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001451 ret = ret.ToMakePath()
1452 }
1453
1454 return ret
1455}
1456
Jiyong Park87788b52020-09-01 12:37:45 +09001457func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001458 pathComponents ...string) InstallPath {
1459
Jiyong Park957bcd92020-10-20 18:23:33 +09001460 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001461
Colin Cross6e359402020-02-10 15:29:54 -08001462 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001463 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001464 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001465 osName := os.String()
1466 if os == Linux {
1467 // instead of linux_glibc
1468 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001469 }
Jiyong Park87788b52020-09-01 12:37:45 +09001470 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1471 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1472 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1473 // Let's keep using x86 for the existing cases until we have a need to support
1474 // other architectures.
1475 archName := arch.String()
1476 if os.Class == Host && (arch == X86_64 || arch == Common) {
1477 archName = "x86"
1478 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001479 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001480 }
Colin Cross609c49a2020-02-13 13:20:11 -08001481 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001482 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001483 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001484
Jiyong Park957bcd92020-10-20 18:23:33 +09001485 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001486 if err != nil {
1487 reportPathError(ctx, err)
1488 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001489
Jiyong Park957bcd92020-10-20 18:23:33 +09001490 base := InstallPath{
1491 basePath: basePath{partionPath, ctx.Config(), ""},
1492 partitionDir: partionPath,
1493 makePath: false,
1494 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001495
Jiyong Park957bcd92020-10-20 18:23:33 +09001496 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001497}
1498
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001499func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001500 base := InstallPath{
1501 basePath: basePath{prefix, ctx.Config(), ""},
1502 partitionDir: prefix,
1503 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001504 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001505 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001506}
1507
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001508func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1509 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1510}
1511
1512func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1513 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1514}
1515
Colin Cross70dda7e2019-10-01 22:05:35 -07001516func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001517 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1518
1519 return "/" + rel
1520}
1521
Colin Cross6e359402020-02-10 15:29:54 -08001522func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001523 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001524 if ctx.InstallInTestcases() {
1525 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001526 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001527 } else if os.Class == Device {
1528 if ctx.InstallInData() {
1529 partition = "data"
1530 } else if ctx.InstallInRamdisk() {
1531 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1532 partition = "recovery/root/first_stage_ramdisk"
1533 } else {
1534 partition = "ramdisk"
1535 }
1536 if !ctx.InstallInRoot() {
1537 partition += "/system"
1538 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001539 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001540 // The module is only available after switching root into
1541 // /first_stage_ramdisk. To expose the module before switching root
1542 // on a device without a dedicated recovery partition, install the
1543 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001544 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Yifan Hong39143a92020-10-26 12:43:12 -07001545 partition = "vendor-ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001546 } else {
1547 partition = "vendor-ramdisk"
1548 }
1549 if !ctx.InstallInRoot() {
1550 partition += "/system"
1551 }
Colin Cross6e359402020-02-10 15:29:54 -08001552 } else if ctx.InstallInRecovery() {
1553 if ctx.InstallInRoot() {
1554 partition = "recovery/root"
1555 } else {
1556 // the layout of recovery partion is the same as that of system partition
1557 partition = "recovery/root/system"
1558 }
1559 } else if ctx.SocSpecific() {
1560 partition = ctx.DeviceConfig().VendorPath()
1561 } else if ctx.DeviceSpecific() {
1562 partition = ctx.DeviceConfig().OdmPath()
1563 } else if ctx.ProductSpecific() {
1564 partition = ctx.DeviceConfig().ProductPath()
1565 } else if ctx.SystemExtSpecific() {
1566 partition = ctx.DeviceConfig().SystemExtPath()
1567 } else if ctx.InstallInRoot() {
1568 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001569 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001570 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001571 }
Colin Cross6e359402020-02-10 15:29:54 -08001572 if ctx.InstallInSanitizerDir() {
1573 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001574 }
Colin Cross43f08db2018-11-12 10:13:39 -08001575 }
1576 return partition
1577}
1578
Colin Cross609c49a2020-02-13 13:20:11 -08001579type InstallPaths []InstallPath
1580
1581// Paths returns the InstallPaths as a Paths
1582func (p InstallPaths) Paths() Paths {
1583 if p == nil {
1584 return nil
1585 }
1586 ret := make(Paths, len(p))
1587 for i, path := range p {
1588 ret[i] = path
1589 }
1590 return ret
1591}
1592
1593// Strings returns the string forms of the install paths.
1594func (p InstallPaths) Strings() []string {
1595 if p == nil {
1596 return nil
1597 }
1598 ret := make([]string, len(p))
1599 for i, path := range p {
1600 ret[i] = path.String()
1601 }
1602 return ret
1603}
1604
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001605// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001606// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001607func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001608 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001609 path := filepath.Clean(path)
1610 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001611 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001612 }
1613 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001614 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1615 // variables. '..' may remove the entire ninja variable, even if it
1616 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001617 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001618}
1619
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001620// validatePath validates that a path does not include ninja variables, and that
1621// each path component does not attempt to leave its component. Returns a joined
1622// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001623func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001624 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001625 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001626 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001627 }
1628 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001629 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001630}
Colin Cross5b529592017-05-09 13:34:34 -07001631
Colin Cross0875c522017-11-28 17:34:01 -08001632func PathForPhony(ctx PathContext, phony string) WritablePath {
1633 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001634 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001635 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001636 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001637}
1638
Colin Cross74e3fe42017-12-11 15:51:44 -08001639type PhonyPath struct {
1640 basePath
1641}
1642
1643func (p PhonyPath) writablePath() {}
1644
Paul Duffin9b478b02019-12-10 13:41:51 +00001645func (p PhonyPath) buildDir() string {
1646 return p.config.buildDir
1647}
1648
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001649func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1650 panic("Not implemented")
1651}
1652
Colin Cross74e3fe42017-12-11 15:51:44 -08001653var _ Path = PhonyPath{}
1654var _ WritablePath = PhonyPath{}
1655
Colin Cross5b529592017-05-09 13:34:34 -07001656type testPath struct {
1657 basePath
1658}
1659
1660func (p testPath) String() string {
1661 return p.path
1662}
1663
Colin Cross40e33732019-02-15 11:08:35 -08001664// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1665// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001666func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001667 p, err := validateSafePath(paths...)
1668 if err != nil {
1669 panic(err)
1670 }
Colin Cross5b529592017-05-09 13:34:34 -07001671 return testPath{basePath{path: p, rel: p}}
1672}
1673
Colin Cross40e33732019-02-15 11:08:35 -08001674// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1675func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001676 p := make(Paths, len(strs))
1677 for i, s := range strs {
1678 p[i] = PathForTesting(s)
1679 }
1680
1681 return p
1682}
Colin Cross43f08db2018-11-12 10:13:39 -08001683
Colin Cross40e33732019-02-15 11:08:35 -08001684type testPathContext struct {
1685 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001686}
1687
Colin Cross40e33732019-02-15 11:08:35 -08001688func (x *testPathContext) Config() Config { return x.config }
1689func (x *testPathContext) AddNinjaFileDeps(...string) {}
1690
1691// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1692// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001693func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001694 return &testPathContext{
1695 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001696 }
1697}
1698
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001699type testModuleInstallPathContext struct {
1700 baseModuleContext
1701
1702 inData bool
1703 inTestcases bool
1704 inSanitizerDir bool
1705 inRamdisk bool
1706 inVendorRamdisk bool
1707 inRecovery bool
1708 inRoot bool
1709 forceOS *OsType
1710 forceArch *ArchType
1711}
1712
1713func (m testModuleInstallPathContext) Config() Config {
1714 return m.baseModuleContext.config
1715}
1716
1717func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1718
1719func (m testModuleInstallPathContext) InstallInData() bool {
1720 return m.inData
1721}
1722
1723func (m testModuleInstallPathContext) InstallInTestcases() bool {
1724 return m.inTestcases
1725}
1726
1727func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1728 return m.inSanitizerDir
1729}
1730
1731func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1732 return m.inRamdisk
1733}
1734
1735func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1736 return m.inVendorRamdisk
1737}
1738
1739func (m testModuleInstallPathContext) InstallInRecovery() bool {
1740 return m.inRecovery
1741}
1742
1743func (m testModuleInstallPathContext) InstallInRoot() bool {
1744 return m.inRoot
1745}
1746
1747func (m testModuleInstallPathContext) InstallBypassMake() bool {
1748 return false
1749}
1750
1751func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1752 return m.forceOS, m.forceArch
1753}
1754
1755// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1756// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1757// delegated to it will panic.
1758func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1759 ctx := &testModuleInstallPathContext{}
1760 ctx.config = config
1761 ctx.os = Android
1762 return ctx
1763}
1764
Colin Cross43f08db2018-11-12 10:13:39 -08001765// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1766// targetPath is not inside basePath.
1767func Rel(ctx PathContext, basePath string, targetPath string) string {
1768 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1769 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001770 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001771 return ""
1772 }
1773 return rel
1774}
1775
1776// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1777// targetPath is not inside basePath.
1778func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001779 rel, isRel, err := maybeRelErr(basePath, targetPath)
1780 if err != nil {
1781 reportPathError(ctx, err)
1782 }
1783 return rel, isRel
1784}
1785
1786func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001787 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1788 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001789 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001790 }
1791 rel, err := filepath.Rel(basePath, targetPath)
1792 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001793 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001794 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001795 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001796 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001797 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001798}
Colin Cross988414c2020-01-11 01:11:46 +00001799
1800// Writes a file to the output directory. Attempting to write directly to the output directory
1801// will fail due to the sandbox of the soong_build process.
1802func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1803 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1804}
1805
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001806func RemoveAllOutputDir(path WritablePath) error {
1807 return os.RemoveAll(absolutePath(path.String()))
1808}
1809
1810func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1811 dir := absolutePath(path.String())
1812 if _, err := os.Stat(dir); os.IsNotExist(err) {
1813 return os.MkdirAll(dir, os.ModePerm)
1814 } else {
1815 return err
1816 }
1817}
1818
Colin Cross988414c2020-01-11 01:11:46 +00001819func absolutePath(path string) string {
1820 if filepath.IsAbs(path) {
1821 return path
1822 }
1823 return filepath.Join(absSrcDir, path)
1824}
Chris Parsons216e10a2020-07-09 17:12:52 -04001825
1826// A DataPath represents the path of a file to be used as data, for example
1827// a test library to be installed alongside a test.
1828// The data file should be installed (copied from `<SrcPath>`) to
1829// `<install_root>/<RelativeInstallPath>/<filename>`, or
1830// `<install_root>/<filename>` if RelativeInstallPath is empty.
1831type DataPath struct {
1832 // The path of the data file that should be copied into the data directory
1833 SrcPath Path
1834 // The install path of the data file, relative to the install root.
1835 RelativeInstallPath string
1836}