blob: 81069583081a44f337620df0b1f8483e0e5374a7 [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
Paul Duffin0267d492021-02-02 10:05:52 +00001014func (p OutputPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
1015 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1016}
1017
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001018var _ Path = OutputPath{}
Paul Duffin9b478b02019-12-10 13:41:51 +00001019var _ WritablePath = OutputPath{}
Paul Duffin0267d492021-02-02 10:05:52 +00001020var _ objPathProvider = OutputPath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001021
Chris Parsons8f232a22020-06-23 17:37:05 -04001022// toolDepPath is a Path representing a dependency of the build tool.
1023type toolDepPath struct {
1024 basePath
1025}
1026
1027var _ Path = toolDepPath{}
1028
1029// pathForBuildToolDep returns a toolDepPath representing the given path string.
1030// There is no validation for the path, as it is "trusted": It may fail
1031// normal validation checks. For example, it may be an absolute path.
1032// Only use this function to construct paths for dependencies of the build
1033// tool invocation.
1034func pathForBuildToolDep(ctx PathContext, path string) toolDepPath {
1035 return toolDepPath{basePath{path, ctx.Config(), ""}}
1036}
1037
Jeff Gaston734e3802017-04-10 15:47:24 -07001038// PathForOutput joins the provided paths and returns an OutputPath that is
1039// validated to not escape the build dir.
1040// On error, it will return a usable, but invalid OutputPath, and report a ModuleError.
1041func PathForOutput(ctx PathContext, pathComponents ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001042 path, err := validatePath(pathComponents...)
1043 if err != nil {
1044 reportPathError(ctx, err)
1045 }
Colin Crossd63c9a72020-01-29 16:52:50 -08001046 fullPath := filepath.Join(ctx.Config().buildDir, path)
1047 path = fullPath[len(fullPath)-len(path):]
1048 return OutputPath{basePath{path, ctx.Config(), ""}, fullPath}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001049}
1050
Colin Cross40e33732019-02-15 11:08:35 -08001051// PathsForOutput returns Paths rooted from buildDir
1052func PathsForOutput(ctx PathContext, paths []string) WritablePaths {
1053 ret := make(WritablePaths, len(paths))
1054 for i, path := range paths {
1055 ret[i] = PathForOutput(ctx, path)
1056 }
1057 return ret
1058}
1059
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001060func (p OutputPath) writablePath() {}
1061
1062func (p OutputPath) String() string {
Colin Crossd63c9a72020-01-29 16:52:50 -08001063 return p.fullPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001064}
1065
1066// Join creates a new OutputPath with paths... joined with the current path. The
1067// provided paths... may not use '..' to escape from the current path.
1068func (p OutputPath) Join(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001069 path, err := validatePath(paths...)
1070 if err != nil {
1071 reportPathError(ctx, err)
1072 }
Colin Cross0db55682017-12-05 15:36:55 -08001073 return p.withRel(path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001074}
1075
Colin Cross8854a5a2019-02-11 14:14:16 -08001076// ReplaceExtension creates a new OutputPath with the extension replaced with ext.
1077func (p OutputPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1078 if strings.Contains(ext, "/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001079 ReportPathErrorf(ctx, "extension %q cannot contain /", ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001080 }
1081 ret := PathForOutput(ctx, pathtools.ReplaceExtension(p.path, ext))
Colin Cross2cdd5df2019-02-25 10:25:24 -08001082 ret.rel = pathtools.ReplaceExtension(p.rel, ext)
Colin Cross8854a5a2019-02-11 14:14:16 -08001083 return ret
1084}
1085
Colin Cross40e33732019-02-15 11:08:35 -08001086// InSameDir creates a new OutputPath from the directory of the current OutputPath joined with the elements in paths.
1087func (p OutputPath) InSameDir(ctx PathContext, paths ...string) OutputPath {
1088 path, err := validatePath(paths...)
1089 if err != nil {
1090 reportPathError(ctx, err)
1091 }
1092
1093 ret := PathForOutput(ctx, filepath.Dir(p.path), path)
Colin Cross2cdd5df2019-02-25 10:25:24 -08001094 ret.rel = filepath.Join(filepath.Dir(p.rel), path)
Colin Cross40e33732019-02-15 11:08:35 -08001095 return ret
1096}
1097
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001098// PathForIntermediates returns an OutputPath representing the top-level
1099// intermediates directory.
1100func PathForIntermediates(ctx PathContext, paths ...string) OutputPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001101 path, err := validatePath(paths...)
1102 if err != nil {
1103 reportPathError(ctx, err)
1104 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001105 return PathForOutput(ctx, ".intermediates", path)
1106}
1107
Colin Cross07e51612019-03-05 12:46:40 -08001108var _ genPathProvider = SourcePath{}
1109var _ objPathProvider = SourcePath{}
1110var _ resPathProvider = SourcePath{}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001111
Colin Cross07e51612019-03-05 12:46:40 -08001112// PathForModuleSrc returns a Path representing the paths... under the
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001113// module's local source directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001114func PathForModuleSrc(ctx ModuleMissingDepsPathContext, pathComponents ...string) Path {
Colin Cross8a497952019-03-05 22:25:09 -08001115 p, err := validatePath(pathComponents...)
1116 if err != nil {
1117 reportPathError(ctx, err)
Colin Cross192e97a2018-02-22 14:21:02 -08001118 }
Colin Cross8a497952019-03-05 22:25:09 -08001119 paths, err := expandOneSrcPath(ctx, p, nil)
1120 if err != nil {
1121 if depErr, ok := err.(missingDependencyError); ok {
1122 if ctx.Config().AllowMissingDependencies() {
1123 ctx.AddMissingDependencies(depErr.missingDeps)
1124 } else {
1125 ctx.ModuleErrorf(`%s, is the property annotated with android:"path"?`, depErr.Error())
1126 }
1127 } else {
1128 reportPathError(ctx, err)
1129 }
1130 return nil
1131 } else if len(paths) == 0 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001132 ReportPathErrorf(ctx, "%q produced no files, expected exactly one", p)
Colin Cross8a497952019-03-05 22:25:09 -08001133 return nil
1134 } else if len(paths) > 1 {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001135 ReportPathErrorf(ctx, "%q produced %d files, expected exactly one", p, len(paths))
Colin Cross8a497952019-03-05 22:25:09 -08001136 }
1137 return paths[0]
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001138}
1139
Liz Kammera830f3a2020-11-10 10:50:34 -08001140func pathForModuleSrc(ctx EarlyModulePathContext, paths ...string) SourcePath {
Colin Cross07e51612019-03-05 12:46:40 -08001141 p, err := validatePath(paths...)
1142 if err != nil {
1143 reportPathError(ctx, err)
1144 }
1145
1146 path, err := pathForSource(ctx, ctx.ModuleDir(), p)
1147 if err != nil {
1148 reportPathError(ctx, err)
1149 }
1150
1151 path.basePath.rel = p
1152
1153 return path
1154}
1155
Colin Cross2fafa3e2019-03-05 12:39:51 -08001156// PathsWithModuleSrcSubDir takes a list of Paths and returns a new list of Paths where Rel() on each path
1157// will return the path relative to subDir in the module's source directory. If any input paths are not located
1158// inside subDir then a path error will be reported.
Liz Kammera830f3a2020-11-10 10:50:34 -08001159func PathsWithModuleSrcSubDir(ctx EarlyModulePathContext, paths Paths, subDir string) Paths {
Colin Cross2fafa3e2019-03-05 12:39:51 -08001160 paths = append(Paths(nil), paths...)
Colin Cross07e51612019-03-05 12:46:40 -08001161 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001162 for i, path := range paths {
1163 rel := Rel(ctx, subDirFullPath.String(), path.String())
1164 paths[i] = subDirFullPath.join(ctx, rel)
1165 }
1166 return paths
1167}
1168
1169// PathWithModuleSrcSubDir takes a Path and returns a Path where Rel() will return the path relative to subDir in the
1170// 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 -08001171func PathWithModuleSrcSubDir(ctx EarlyModulePathContext, path Path, subDir string) Path {
Colin Cross07e51612019-03-05 12:46:40 -08001172 subDirFullPath := pathForModuleSrc(ctx, subDir)
Colin Cross2fafa3e2019-03-05 12:39:51 -08001173 rel := Rel(ctx, subDirFullPath.String(), path.String())
1174 return subDirFullPath.Join(ctx, rel)
1175}
1176
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001177// OptionalPathForModuleSrc returns an OptionalPath. The OptionalPath contains a
1178// valid path if p is non-nil.
Liz Kammera830f3a2020-11-10 10:50:34 -08001179func OptionalPathForModuleSrc(ctx ModuleMissingDepsPathContext, p *string) OptionalPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001180 if p == nil {
1181 return OptionalPath{}
1182 }
1183 return OptionalPathForPath(PathForModuleSrc(ctx, *p))
1184}
1185
Liz Kammera830f3a2020-11-10 10:50:34 -08001186func (p SourcePath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001187 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001188}
1189
Liz Kammera830f3a2020-11-10 10:50:34 -08001190func (p SourcePath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Colin Cross7fc17db2017-02-01 14:07:55 -08001191 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001192}
1193
Liz Kammera830f3a2020-11-10 10:50:34 -08001194func (p SourcePath) resPathWithName(ctx ModuleOutPathContext, name string) ModuleResPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001195 // TODO: Use full directory if the new ctx is not the current ctx?
1196 return PathForModuleRes(ctx, p.path, name)
1197}
1198
1199// ModuleOutPath is a Path representing a module's output directory.
1200type ModuleOutPath struct {
1201 OutputPath
1202}
1203
1204var _ Path = ModuleOutPath{}
1205
Liz Kammera830f3a2020-11-10 10:50:34 -08001206func (p ModuleOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Pete Bentleyfcf55bf2019-08-16 20:14:32 +01001207 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1208}
1209
Liz Kammera830f3a2020-11-10 10:50:34 -08001210// ModuleOutPathContext Subset of ModuleContext functions necessary for output path methods.
1211type ModuleOutPathContext interface {
1212 PathContext
1213
1214 ModuleName() string
1215 ModuleDir() string
1216 ModuleSubDir() string
1217}
1218
1219func pathForModuleOut(ctx ModuleOutPathContext) OutputPath {
Colin Cross702e0f82017-10-18 17:27:54 -07001220 return PathForOutput(ctx, ".intermediates", ctx.ModuleDir(), ctx.ModuleName(), ctx.ModuleSubDir())
1221}
1222
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001223type BazelOutPath struct {
1224 OutputPath
1225}
1226
1227var _ Path = BazelOutPath{}
1228var _ objPathProvider = BazelOutPath{}
1229
Liz Kammera830f3a2020-11-10 10:50:34 -08001230func (p BazelOutPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001231 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1232}
1233
Logan Chien7eefdc42018-07-11 18:10:41 +08001234// PathForVndkRefAbiDump returns an OptionalPath representing the path of the
1235// reference abi dump for the given module. This is not guaranteed to be valid.
Liz Kammera830f3a2020-11-10 10:50:34 -08001236func PathForVndkRefAbiDump(ctx ModuleInstallPathContext, version, fileName string,
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001237 isNdk, isLlndkOrVndk, isGzip bool) OptionalPath {
Logan Chien7eefdc42018-07-11 18:10:41 +08001238
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001239 arches := ctx.DeviceConfig().Arches()
Logan Chien7eefdc42018-07-11 18:10:41 +08001240 if len(arches) == 0 {
1241 panic("device build with no primary arch")
1242 }
Jayant Chowdharyac066c62018-02-20 10:53:31 -08001243 currentArch := ctx.Arch()
1244 archNameAndVariant := currentArch.ArchType.String()
1245 if currentArch.ArchVariant != "" {
1246 archNameAndVariant += "_" + currentArch.ArchVariant
1247 }
Logan Chien5237bed2018-07-11 17:15:57 +08001248
1249 var dirName string
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001250 if isNdk {
Logan Chien5237bed2018-07-11 17:15:57 +08001251 dirName = "ndk"
Hsin-Yi Chen53489642019-07-31 17:10:45 +08001252 } else if isLlndkOrVndk {
Logan Chien5237bed2018-07-11 17:15:57 +08001253 dirName = "vndk"
Logan Chien41eabe62019-04-10 13:33:58 +08001254 } else {
1255 dirName = "platform" // opt-in libs
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001256 }
Logan Chien5237bed2018-07-11 17:15:57 +08001257
Jayant Chowdhary34ce67d2018-03-08 11:00:50 -08001258 binderBitness := ctx.DeviceConfig().BinderBitness()
Logan Chien7eefdc42018-07-11 18:10:41 +08001259
1260 var ext string
1261 if isGzip {
1262 ext = ".lsdump.gz"
1263 } else {
1264 ext = ".lsdump"
1265 }
1266
1267 return ExistentPathForSource(ctx, "prebuilts", "abi-dumps", dirName,
1268 version, binderBitness, archNameAndVariant, "source-based",
1269 fileName+ext)
Jayant Chowdhary3e231fd2017-02-08 13:45:53 -08001270}
1271
Chris Parsonsdbcb1ff2020-12-10 17:19:18 -05001272// PathForBazelOut returns a Path representing the paths... under an output directory dedicated to
1273// bazel-owned outputs.
1274func PathForBazelOut(ctx PathContext, paths ...string) BazelOutPath {
1275 execRootPathComponents := append([]string{"execroot", "__main__"}, paths...)
1276 execRootPath := filepath.Join(execRootPathComponents...)
1277 validatedExecRootPath, err := validatePath(execRootPath)
1278 if err != nil {
1279 reportPathError(ctx, err)
1280 }
1281
1282 outputPath := OutputPath{basePath{"", ctx.Config(), ""},
1283 ctx.Config().BazelContext.OutputBase()}
1284
1285 return BazelOutPath{
1286 OutputPath: outputPath.withRel(validatedExecRootPath),
1287 }
1288}
1289
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001290// PathForModuleOut returns a Path representing the paths... under the module's
1291// output directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001292func PathForModuleOut(ctx ModuleOutPathContext, paths ...string) ModuleOutPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001293 p, err := validatePath(paths...)
1294 if err != nil {
1295 reportPathError(ctx, err)
1296 }
Colin Cross702e0f82017-10-18 17:27:54 -07001297 return ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001298 OutputPath: pathForModuleOut(ctx).withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001299 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001300}
1301
1302// ModuleGenPath is a Path representing the 'gen' directory in a module's output
1303// directory. Mainly used for generated sources.
1304type ModuleGenPath struct {
1305 ModuleOutPath
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001306}
1307
1308var _ Path = ModuleGenPath{}
1309var _ genPathProvider = ModuleGenPath{}
1310var _ objPathProvider = ModuleGenPath{}
1311
1312// PathForModuleGen returns a Path representing the paths... under the module's
1313// `gen' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001314func PathForModuleGen(ctx ModuleOutPathContext, paths ...string) ModuleGenPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001315 p, err := validatePath(paths...)
1316 if err != nil {
1317 reportPathError(ctx, err)
1318 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001319 return ModuleGenPath{
Colin Cross702e0f82017-10-18 17:27:54 -07001320 ModuleOutPath: ModuleOutPath{
Liz Kammera830f3a2020-11-10 10:50:34 -08001321 OutputPath: pathForModuleOut(ctx).withRel("gen").withRel(p),
Colin Cross702e0f82017-10-18 17:27:54 -07001322 },
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001323 }
1324}
1325
Liz Kammera830f3a2020-11-10 10:50:34 -08001326func (p ModuleGenPath) genPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleGenPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001327 // TODO: make a different path for local vs remote generated files?
Dan Willemsen21ec4902016-11-02 20:43:13 -07001328 return PathForModuleGen(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001329}
1330
Liz Kammera830f3a2020-11-10 10:50:34 -08001331func (p ModuleGenPath) objPathWithExt(ctx ModuleOutPathContext, subdir, ext string) ModuleObjPath {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001332 return PathForModuleObj(ctx, subdir, pathtools.ReplaceExtension(p.path, ext))
1333}
1334
1335// ModuleObjPath is a Path representing the 'obj' directory in a module's output
1336// directory. Used for compiled objects.
1337type ModuleObjPath struct {
1338 ModuleOutPath
1339}
1340
1341var _ Path = ModuleObjPath{}
1342
1343// PathForModuleObj returns a Path representing the paths... under the module's
1344// 'obj' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001345func PathForModuleObj(ctx ModuleOutPathContext, pathComponents ...string) ModuleObjPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001346 p, err := validatePath(pathComponents...)
1347 if err != nil {
1348 reportPathError(ctx, err)
1349 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001350 return ModuleObjPath{PathForModuleOut(ctx, "obj", p)}
1351}
1352
1353// ModuleResPath is a a Path representing the 'res' directory in a module's
1354// output directory.
1355type ModuleResPath struct {
1356 ModuleOutPath
1357}
1358
1359var _ Path = ModuleResPath{}
1360
1361// PathForModuleRes returns a Path representing the paths... under the module's
1362// 'res' directory.
Liz Kammera830f3a2020-11-10 10:50:34 -08001363func PathForModuleRes(ctx ModuleOutPathContext, pathComponents ...string) ModuleResPath {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001364 p, err := validatePath(pathComponents...)
1365 if err != nil {
1366 reportPathError(ctx, err)
1367 }
1368
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001369 return ModuleResPath{PathForModuleOut(ctx, "res", p)}
1370}
1371
Colin Cross70dda7e2019-10-01 22:05:35 -07001372// InstallPath is a Path representing a installed file path rooted from the build directory
1373type InstallPath struct {
1374 basePath
Colin Crossff6c33d2019-10-02 16:01:35 -07001375
Jiyong Park957bcd92020-10-20 18:23:33 +09001376 // partitionDir is the part of the InstallPath that is automatically determined according to the context.
1377 // For example, it is host/<os>-<arch> for host modules, and target/product/<device>/<partition> for device modules.
1378 partitionDir string
1379
1380 // makePath indicates whether this path is for Soong (false) or Make (true).
1381 makePath bool
Colin Cross70dda7e2019-10-01 22:05:35 -07001382}
1383
Paul Duffin9b478b02019-12-10 13:41:51 +00001384func (p InstallPath) buildDir() string {
1385 return p.config.buildDir
1386}
1387
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001388func (p InstallPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1389 panic("Not implemented")
1390}
1391
Paul Duffin9b478b02019-12-10 13:41:51 +00001392var _ Path = InstallPath{}
1393var _ WritablePath = InstallPath{}
1394
Colin Cross70dda7e2019-10-01 22:05:35 -07001395func (p InstallPath) writablePath() {}
1396
1397func (p InstallPath) String() string {
Jiyong Park957bcd92020-10-20 18:23:33 +09001398 if p.makePath {
1399 // Make path starts with out/ instead of out/soong.
1400 return filepath.Join(p.config.buildDir, "../", p.path)
1401 } else {
1402 return filepath.Join(p.config.buildDir, p.path)
1403 }
1404}
1405
1406// PartitionDir returns the path to the partition where the install path is rooted at. It is
1407// out/soong/target/product/<device>/<partition> for device modules, and out/soong/host/<os>-<arch> for host modules.
1408// The ./soong is dropped if the install path is for Make.
1409func (p InstallPath) PartitionDir() string {
1410 if p.makePath {
1411 return filepath.Join(p.config.buildDir, "../", p.partitionDir)
1412 } else {
1413 return filepath.Join(p.config.buildDir, p.partitionDir)
1414 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001415}
1416
1417// Join creates a new InstallPath with paths... joined with the current path. The
1418// provided paths... may not use '..' to escape from the current path.
1419func (p InstallPath) Join(ctx PathContext, paths ...string) InstallPath {
1420 path, err := validatePath(paths...)
1421 if err != nil {
1422 reportPathError(ctx, err)
1423 }
1424 return p.withRel(path)
1425}
1426
1427func (p InstallPath) withRel(rel string) InstallPath {
1428 p.basePath = p.basePath.withRel(rel)
1429 return p
1430}
1431
Colin Crossff6c33d2019-10-02 16:01:35 -07001432// ToMakePath returns a new InstallPath that points to Make's install directory instead of Soong's,
1433// i.e. out/ instead of out/soong/.
1434func (p InstallPath) ToMakePath() InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001435 p.makePath = true
Colin Crossff6c33d2019-10-02 16:01:35 -07001436 return p
Colin Cross70dda7e2019-10-01 22:05:35 -07001437}
1438
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001439// PathForModuleInstall returns a Path representing the install path for the
1440// module appended with paths...
Colin Cross70dda7e2019-10-01 22:05:35 -07001441func PathForModuleInstall(ctx ModuleInstallPathContext, pathComponents ...string) InstallPath {
Colin Cross6e359402020-02-10 15:29:54 -08001442 os := ctx.Os()
Jiyong Park87788b52020-09-01 12:37:45 +09001443 arch := ctx.Arch().ArchType
1444 forceOS, forceArch := ctx.InstallForceOS()
1445 if forceOS != nil {
Colin Cross6e359402020-02-10 15:29:54 -08001446 os = *forceOS
1447 }
Jiyong Park87788b52020-09-01 12:37:45 +09001448 if forceArch != nil {
1449 arch = *forceArch
1450 }
Colin Cross6e359402020-02-10 15:29:54 -08001451 partition := modulePartition(ctx, os)
Colin Cross609c49a2020-02-13 13:20:11 -08001452
Jiyong Park87788b52020-09-01 12:37:45 +09001453 ret := pathForInstall(ctx, os, arch, partition, ctx.Debug(), pathComponents...)
Colin Cross609c49a2020-02-13 13:20:11 -08001454
Jingwen Chencda22c92020-11-23 00:22:30 -05001455 if ctx.InstallBypassMake() && ctx.Config().KatiEnabled() {
Colin Cross609c49a2020-02-13 13:20:11 -08001456 ret = ret.ToMakePath()
1457 }
1458
1459 return ret
1460}
1461
Jiyong Park87788b52020-09-01 12:37:45 +09001462func pathForInstall(ctx PathContext, os OsType, arch ArchType, partition string, debug bool,
Colin Cross609c49a2020-02-13 13:20:11 -08001463 pathComponents ...string) InstallPath {
1464
Jiyong Park957bcd92020-10-20 18:23:33 +09001465 var partionPaths []string
Colin Cross609c49a2020-02-13 13:20:11 -08001466
Colin Cross6e359402020-02-10 15:29:54 -08001467 if os.Class == Device {
Jiyong Park957bcd92020-10-20 18:23:33 +09001468 partionPaths = []string{"target", "product", ctx.Config().DeviceName(), partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001469 } else {
Jiyong Park87788b52020-09-01 12:37:45 +09001470 osName := os.String()
1471 if os == Linux {
1472 // instead of linux_glibc
1473 osName = "linux"
Dan Willemsen866b5632017-09-22 12:28:24 -07001474 }
Jiyong Park87788b52020-09-01 12:37:45 +09001475 // SOONG_HOST_OUT is set to out/host/$(HOST_OS)-$(HOST_PREBUILT_ARCH)
1476 // and HOST_PREBUILT_ARCH is forcibly set to x86 even on x86_64 hosts. We don't seem
1477 // to have a plan to fix it (see the comment in build/make/core/envsetup.mk).
1478 // Let's keep using x86 for the existing cases until we have a need to support
1479 // other architectures.
1480 archName := arch.String()
1481 if os.Class == Host && (arch == X86_64 || arch == Common) {
1482 archName = "x86"
1483 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001484 partionPaths = []string{"host", osName + "-" + archName, partition}
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001485 }
Colin Cross609c49a2020-02-13 13:20:11 -08001486 if debug {
Jiyong Park957bcd92020-10-20 18:23:33 +09001487 partionPaths = append([]string{"debug"}, partionPaths...)
Dan Willemsen782a2d12015-12-21 14:55:28 -08001488 }
Colin Cross70dda7e2019-10-01 22:05:35 -07001489
Jiyong Park957bcd92020-10-20 18:23:33 +09001490 partionPath, err := validatePath(partionPaths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001491 if err != nil {
1492 reportPathError(ctx, err)
1493 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001494
Jiyong Park957bcd92020-10-20 18:23:33 +09001495 base := InstallPath{
1496 basePath: basePath{partionPath, ctx.Config(), ""},
1497 partitionDir: partionPath,
1498 makePath: false,
1499 }
Colin Crossff6c33d2019-10-02 16:01:35 -07001500
Jiyong Park957bcd92020-10-20 18:23:33 +09001501 return base.Join(ctx, pathComponents...)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001502}
1503
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001504func pathForNdkOrSdkInstall(ctx PathContext, prefix string, paths []string) InstallPath {
Jiyong Park957bcd92020-10-20 18:23:33 +09001505 base := InstallPath{
1506 basePath: basePath{prefix, ctx.Config(), ""},
1507 partitionDir: prefix,
1508 makePath: false,
Colin Cross70dda7e2019-10-01 22:05:35 -07001509 }
Jiyong Park957bcd92020-10-20 18:23:33 +09001510 return base.Join(ctx, paths...)
Colin Cross70dda7e2019-10-01 22:05:35 -07001511}
1512
Nicolas Geoffray1228e9c2020-02-27 13:45:35 +00001513func PathForNdkInstall(ctx PathContext, paths ...string) InstallPath {
1514 return pathForNdkOrSdkInstall(ctx, "ndk", paths)
1515}
1516
1517func PathForMainlineSdksInstall(ctx PathContext, paths ...string) InstallPath {
1518 return pathForNdkOrSdkInstall(ctx, "mainline-sdks", paths)
1519}
1520
Colin Cross70dda7e2019-10-01 22:05:35 -07001521func InstallPathToOnDevicePath(ctx PathContext, path InstallPath) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001522 rel := Rel(ctx, PathForOutput(ctx, "target", "product", ctx.Config().DeviceName()).String(), path.String())
1523
1524 return "/" + rel
1525}
1526
Colin Cross6e359402020-02-10 15:29:54 -08001527func modulePartition(ctx ModuleInstallPathContext, os OsType) string {
Colin Cross43f08db2018-11-12 10:13:39 -08001528 var partition string
Colin Cross6e359402020-02-10 15:29:54 -08001529 if ctx.InstallInTestcases() {
1530 // "testcases" install directory can be used for host or device modules.
Jaewoong Jung0949f312019-09-11 10:25:18 -07001531 partition = "testcases"
Colin Cross6e359402020-02-10 15:29:54 -08001532 } else if os.Class == Device {
1533 if ctx.InstallInData() {
1534 partition = "data"
1535 } else if ctx.InstallInRamdisk() {
1536 if ctx.DeviceConfig().BoardUsesRecoveryAsBoot() {
1537 partition = "recovery/root/first_stage_ramdisk"
1538 } else {
1539 partition = "ramdisk"
1540 }
1541 if !ctx.InstallInRoot() {
1542 partition += "/system"
1543 }
Yifan Hong60e0cfb2020-10-21 15:17:56 -07001544 } else if ctx.InstallInVendorRamdisk() {
Yifan Hong39143a92020-10-26 12:43:12 -07001545 // The module is only available after switching root into
1546 // /first_stage_ramdisk. To expose the module before switching root
1547 // on a device without a dedicated recovery partition, install the
1548 // recovery variant.
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001549 if ctx.DeviceConfig().BoardMoveRecoveryResourcesToVendorBoot() {
Yifan Hong39143a92020-10-26 12:43:12 -07001550 partition = "vendor-ramdisk/first_stage_ramdisk"
Yifan Hongdd8dacc2020-10-21 15:40:17 -07001551 } else {
1552 partition = "vendor-ramdisk"
1553 }
1554 if !ctx.InstallInRoot() {
1555 partition += "/system"
1556 }
Colin Cross6e359402020-02-10 15:29:54 -08001557 } else if ctx.InstallInRecovery() {
1558 if ctx.InstallInRoot() {
1559 partition = "recovery/root"
1560 } else {
1561 // the layout of recovery partion is the same as that of system partition
1562 partition = "recovery/root/system"
1563 }
1564 } else if ctx.SocSpecific() {
1565 partition = ctx.DeviceConfig().VendorPath()
1566 } else if ctx.DeviceSpecific() {
1567 partition = ctx.DeviceConfig().OdmPath()
1568 } else if ctx.ProductSpecific() {
1569 partition = ctx.DeviceConfig().ProductPath()
1570 } else if ctx.SystemExtSpecific() {
1571 partition = ctx.DeviceConfig().SystemExtPath()
1572 } else if ctx.InstallInRoot() {
1573 partition = "root"
Yifan Hong82db7352020-01-21 16:12:26 -08001574 } else {
Colin Cross6e359402020-02-10 15:29:54 -08001575 partition = "system"
Yifan Hong82db7352020-01-21 16:12:26 -08001576 }
Colin Cross6e359402020-02-10 15:29:54 -08001577 if ctx.InstallInSanitizerDir() {
1578 partition = "data/asan/" + partition
Yifan Hong82db7352020-01-21 16:12:26 -08001579 }
Colin Cross43f08db2018-11-12 10:13:39 -08001580 }
1581 return partition
1582}
1583
Colin Cross609c49a2020-02-13 13:20:11 -08001584type InstallPaths []InstallPath
1585
1586// Paths returns the InstallPaths as a Paths
1587func (p InstallPaths) Paths() Paths {
1588 if p == nil {
1589 return nil
1590 }
1591 ret := make(Paths, len(p))
1592 for i, path := range p {
1593 ret[i] = path
1594 }
1595 return ret
1596}
1597
1598// Strings returns the string forms of the install paths.
1599func (p InstallPaths) Strings() []string {
1600 if p == nil {
1601 return nil
1602 }
1603 ret := make([]string, len(p))
1604 for i, path := range p {
1605 ret[i] = path.String()
1606 }
1607 return ret
1608}
1609
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001610// validateSafePath validates a path that we trust (may contain ninja variables).
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001611// Ensures that each path component does not attempt to leave its component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001612func validateSafePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001613 for _, path := range pathComponents {
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001614 path := filepath.Clean(path)
1615 if path == ".." || strings.HasPrefix(path, "../") || strings.HasPrefix(path, "/") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001616 return "", fmt.Errorf("Path is outside directory: %s", path)
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001617 }
1618 }
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001619 // TODO: filepath.Join isn't necessarily correct with embedded ninja
1620 // variables. '..' may remove the entire ninja variable, even if it
1621 // will be expanded to multiple nested directories.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001622 return filepath.Join(pathComponents...), nil
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001623}
1624
Dan Willemsen80a7c2a2015-12-21 14:57:11 -08001625// validatePath validates that a path does not include ninja variables, and that
1626// each path component does not attempt to leave its component. Returns a joined
1627// version of each path component.
Colin Cross1ccfcc32018-02-22 13:54:26 -08001628func validatePath(pathComponents ...string) (string, error) {
Jeff Gaston734e3802017-04-10 15:47:24 -07001629 for _, path := range pathComponents {
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001630 if strings.Contains(path, "$") {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001631 return "", fmt.Errorf("Path contains invalid character($): %s", path)
Dan Willemsen34cc69e2015-09-23 15:26:20 -07001632 }
1633 }
Colin Cross1ccfcc32018-02-22 13:54:26 -08001634 return validateSafePath(pathComponents...)
Colin Cross6e18ca42015-07-14 18:55:36 -07001635}
Colin Cross5b529592017-05-09 13:34:34 -07001636
Colin Cross0875c522017-11-28 17:34:01 -08001637func PathForPhony(ctx PathContext, phony string) WritablePath {
1638 if strings.ContainsAny(phony, "$/") {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001639 ReportPathErrorf(ctx, "Phony target contains invalid character ($ or /): %s", phony)
Colin Cross0875c522017-11-28 17:34:01 -08001640 }
Colin Cross74e3fe42017-12-11 15:51:44 -08001641 return PhonyPath{basePath{phony, ctx.Config(), ""}}
Colin Cross0875c522017-11-28 17:34:01 -08001642}
1643
Colin Cross74e3fe42017-12-11 15:51:44 -08001644type PhonyPath struct {
1645 basePath
1646}
1647
1648func (p PhonyPath) writablePath() {}
1649
Paul Duffin9b478b02019-12-10 13:41:51 +00001650func (p PhonyPath) buildDir() string {
1651 return p.config.buildDir
1652}
1653
Hans MÃ¥nssond3f2bd72020-11-27 12:37:28 +01001654func (p PhonyPath) ReplaceExtension(ctx PathContext, ext string) OutputPath {
1655 panic("Not implemented")
1656}
1657
Colin Cross74e3fe42017-12-11 15:51:44 -08001658var _ Path = PhonyPath{}
1659var _ WritablePath = PhonyPath{}
1660
Colin Cross5b529592017-05-09 13:34:34 -07001661type testPath struct {
1662 basePath
1663}
1664
1665func (p testPath) String() string {
1666 return p.path
1667}
1668
Colin Cross40e33732019-02-15 11:08:35 -08001669// PathForTesting returns a Path constructed from joining the elements of paths with '/'. It should only be used from
1670// within tests.
Colin Cross5b529592017-05-09 13:34:34 -07001671func PathForTesting(paths ...string) Path {
Colin Cross1ccfcc32018-02-22 13:54:26 -08001672 p, err := validateSafePath(paths...)
1673 if err != nil {
1674 panic(err)
1675 }
Colin Cross5b529592017-05-09 13:34:34 -07001676 return testPath{basePath{path: p, rel: p}}
1677}
1678
Colin Cross40e33732019-02-15 11:08:35 -08001679// PathsForTesting returns a Path constructed from each element in strs. It should only be used from within tests.
1680func PathsForTesting(strs ...string) Paths {
Colin Cross5b529592017-05-09 13:34:34 -07001681 p := make(Paths, len(strs))
1682 for i, s := range strs {
1683 p[i] = PathForTesting(s)
1684 }
1685
1686 return p
1687}
Colin Cross43f08db2018-11-12 10:13:39 -08001688
Colin Cross40e33732019-02-15 11:08:35 -08001689type testPathContext struct {
1690 config Config
Colin Cross40e33732019-02-15 11:08:35 -08001691}
1692
Colin Cross40e33732019-02-15 11:08:35 -08001693func (x *testPathContext) Config() Config { return x.config }
1694func (x *testPathContext) AddNinjaFileDeps(...string) {}
1695
1696// PathContextForTesting returns a PathContext that can be used in tests, for example to create an OutputPath with
1697// PathForOutput.
Colin Cross98be1bb2019-12-13 20:41:13 -08001698func PathContextForTesting(config Config) PathContext {
Colin Cross40e33732019-02-15 11:08:35 -08001699 return &testPathContext{
1700 config: config,
Colin Cross40e33732019-02-15 11:08:35 -08001701 }
1702}
1703
Ulya Trafimovichccc8c852020-10-14 11:29:07 +01001704type testModuleInstallPathContext struct {
1705 baseModuleContext
1706
1707 inData bool
1708 inTestcases bool
1709 inSanitizerDir bool
1710 inRamdisk bool
1711 inVendorRamdisk bool
1712 inRecovery bool
1713 inRoot bool
1714 forceOS *OsType
1715 forceArch *ArchType
1716}
1717
1718func (m testModuleInstallPathContext) Config() Config {
1719 return m.baseModuleContext.config
1720}
1721
1722func (testModuleInstallPathContext) AddNinjaFileDeps(deps ...string) {}
1723
1724func (m testModuleInstallPathContext) InstallInData() bool {
1725 return m.inData
1726}
1727
1728func (m testModuleInstallPathContext) InstallInTestcases() bool {
1729 return m.inTestcases
1730}
1731
1732func (m testModuleInstallPathContext) InstallInSanitizerDir() bool {
1733 return m.inSanitizerDir
1734}
1735
1736func (m testModuleInstallPathContext) InstallInRamdisk() bool {
1737 return m.inRamdisk
1738}
1739
1740func (m testModuleInstallPathContext) InstallInVendorRamdisk() bool {
1741 return m.inVendorRamdisk
1742}
1743
1744func (m testModuleInstallPathContext) InstallInRecovery() bool {
1745 return m.inRecovery
1746}
1747
1748func (m testModuleInstallPathContext) InstallInRoot() bool {
1749 return m.inRoot
1750}
1751
1752func (m testModuleInstallPathContext) InstallBypassMake() bool {
1753 return false
1754}
1755
1756func (m testModuleInstallPathContext) InstallForceOS() (*OsType, *ArchType) {
1757 return m.forceOS, m.forceArch
1758}
1759
1760// Construct a minimal ModuleInstallPathContext for testing. Note that baseModuleContext is
1761// default-initialized, which leaves blueprint.baseModuleContext set to nil, so methods that are
1762// delegated to it will panic.
1763func ModuleInstallPathContextForTesting(config Config) ModuleInstallPathContext {
1764 ctx := &testModuleInstallPathContext{}
1765 ctx.config = config
1766 ctx.os = Android
1767 return ctx
1768}
1769
Colin Cross43f08db2018-11-12 10:13:39 -08001770// Rel performs the same function as filepath.Rel, but reports errors to a PathContext, and reports an error if
1771// targetPath is not inside basePath.
1772func Rel(ctx PathContext, basePath string, targetPath string) string {
1773 rel, isRel := MaybeRel(ctx, basePath, targetPath)
1774 if !isRel {
Ulya Trafimovich5ab276a2020-08-25 12:45:15 +01001775 ReportPathErrorf(ctx, "path %q is not under path %q", targetPath, basePath)
Colin Cross43f08db2018-11-12 10:13:39 -08001776 return ""
1777 }
1778 return rel
1779}
1780
1781// MaybeRel performs the same function as filepath.Rel, but reports errors to a PathContext, and returns false if
1782// targetPath is not inside basePath.
1783func MaybeRel(ctx PathContext, basePath string, targetPath string) (string, bool) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001784 rel, isRel, err := maybeRelErr(basePath, targetPath)
1785 if err != nil {
1786 reportPathError(ctx, err)
1787 }
1788 return rel, isRel
1789}
1790
1791func maybeRelErr(basePath string, targetPath string) (string, bool, error) {
Colin Cross43f08db2018-11-12 10:13:39 -08001792 // filepath.Rel returns an error if one path is absolute and the other is not, handle that case first.
1793 if filepath.IsAbs(basePath) != filepath.IsAbs(targetPath) {
Dan Willemsen633c5022019-04-12 11:11:38 -07001794 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001795 }
1796 rel, err := filepath.Rel(basePath, targetPath)
1797 if err != nil {
Dan Willemsen633c5022019-04-12 11:11:38 -07001798 return "", false, err
Colin Cross43f08db2018-11-12 10:13:39 -08001799 } else if rel == ".." || strings.HasPrefix(rel, "../") || strings.HasPrefix(rel, "/") {
Dan Willemsen633c5022019-04-12 11:11:38 -07001800 return "", false, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001801 }
Dan Willemsen633c5022019-04-12 11:11:38 -07001802 return rel, true, nil
Colin Cross43f08db2018-11-12 10:13:39 -08001803}
Colin Cross988414c2020-01-11 01:11:46 +00001804
1805// Writes a file to the output directory. Attempting to write directly to the output directory
1806// will fail due to the sandbox of the soong_build process.
1807func WriteFileToOutputDir(path WritablePath, data []byte, perm os.FileMode) error {
1808 return ioutil.WriteFile(absolutePath(path.String()), data, perm)
1809}
1810
Liz Kammer2dd9ca42020-11-25 16:06:39 -08001811func RemoveAllOutputDir(path WritablePath) error {
1812 return os.RemoveAll(absolutePath(path.String()))
1813}
1814
1815func CreateOutputDirIfNonexistent(path WritablePath, perm os.FileMode) error {
1816 dir := absolutePath(path.String())
1817 if _, err := os.Stat(dir); os.IsNotExist(err) {
1818 return os.MkdirAll(dir, os.ModePerm)
1819 } else {
1820 return err
1821 }
1822}
1823
Colin Cross988414c2020-01-11 01:11:46 +00001824func absolutePath(path string) string {
1825 if filepath.IsAbs(path) {
1826 return path
1827 }
1828 return filepath.Join(absSrcDir, path)
1829}
Chris Parsons216e10a2020-07-09 17:12:52 -04001830
1831// A DataPath represents the path of a file to be used as data, for example
1832// a test library to be installed alongside a test.
1833// The data file should be installed (copied from `<SrcPath>`) to
1834// `<install_root>/<RelativeInstallPath>/<filename>`, or
1835// `<install_root>/<filename>` if RelativeInstallPath is empty.
1836type DataPath struct {
1837 // The path of the data file that should be copied into the data directory
1838 SrcPath Path
1839 // The install path of the data file, relative to the install root.
1840 RelativeInstallPath string
1841}