finder.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // Copyright 2017 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. package build
  15. import (
  16. "bytes"
  17. "io/ioutil"
  18. "os"
  19. "path/filepath"
  20. "strings"
  21. "android/soong/finder"
  22. "android/soong/finder/fs"
  23. "android/soong/ui/logger"
  24. "android/soong/ui/metrics"
  25. )
  26. // This file provides an interface to the Finder type for soong_ui. Finder is
  27. // used to recursively traverse the source tree to gather paths of files, such
  28. // as Android.bp or Android.mk, and store the lists/database of paths in files
  29. // under `$OUT_DIR/.module_paths`. This directory can also be dist'd.
  30. // NewSourceFinder returns a new Finder configured to search for source files.
  31. // Callers of NewSourceFinder should call <f.Shutdown()> when done
  32. func NewSourceFinder(ctx Context, config Config) (f *finder.Finder) {
  33. ctx.BeginTrace(metrics.RunSetupTool, "find modules")
  34. defer ctx.EndTrace()
  35. // Set up the working directory for the Finder.
  36. dir, err := os.Getwd()
  37. if err != nil {
  38. ctx.Fatalf("No working directory for module-finder: %v", err.Error())
  39. }
  40. filesystem := fs.OsFs
  41. // .out-dir and .find-ignore are markers for Finder to ignore siblings and
  42. // subdirectories of the directory Finder finds them in, hence stopping the
  43. // search recursively down those branches. It's possible that these files
  44. // are in the root directory, and if they are, then the subsequent error
  45. // messages are very confusing, so check for that here.
  46. pruneFiles := []string{".out-dir", ".find-ignore"}
  47. for _, name := range pruneFiles {
  48. prunePath := filepath.Join(dir, name)
  49. _, statErr := filesystem.Lstat(prunePath)
  50. if statErr == nil {
  51. ctx.Fatalf("%v must not exist", prunePath)
  52. }
  53. }
  54. // Set up configuration parameters for the Finder cache.
  55. cacheParams := finder.CacheParams{
  56. WorkingDirectory: dir,
  57. RootDirs: []string{"."},
  58. FollowSymlinks: config.environ.IsEnvTrue("ALLOW_BP_UNDER_SYMLINKS"),
  59. ExcludeDirs: []string{".git", ".repo"},
  60. PruneFiles: pruneFiles,
  61. IncludeFiles: []string{
  62. // Kati build definitions.
  63. "Android.mk",
  64. // Product configuration files.
  65. "AndroidProducts.mk",
  66. // General Soong build definitions, using the Blueprint syntax.
  67. "Android.bp",
  68. // Bazel build definitions.
  69. "BUILD.bazel",
  70. // Bazel build definitions.
  71. "BUILD",
  72. // Kati clean definitions.
  73. "CleanSpec.mk",
  74. // Ownership definition.
  75. "OWNERS",
  76. // Test configuration for modules in directories that contain this
  77. // file.
  78. "TEST_MAPPING",
  79. // Bazel top-level file to mark a directory as a Bazel workspace.
  80. "WORKSPACE",
  81. },
  82. // Bazel Starlark configuration files and all .mk files for product/board configuration.
  83. IncludeSuffixes: []string{".bzl", ".mk"},
  84. }
  85. dumpDir := config.FileListDir()
  86. f, err = finder.New(cacheParams, filesystem, logger.New(ioutil.Discard),
  87. filepath.Join(dumpDir, "files.db"))
  88. if err != nil {
  89. ctx.Fatalf("Could not create module-finder: %v", err)
  90. }
  91. return f
  92. }
  93. // Finds the list of Bazel-related files (BUILD, WORKSPACE and Starlark) in the tree.
  94. func findBazelFiles(entries finder.DirEntries) (dirNames []string, fileNames []string) {
  95. matches := []string{}
  96. for _, foundName := range entries.FileNames {
  97. if foundName == "BUILD.bazel" || foundName == "BUILD" || foundName == "WORKSPACE" || strings.HasSuffix(foundName, ".bzl") {
  98. matches = append(matches, foundName)
  99. }
  100. }
  101. return entries.DirNames, matches
  102. }
  103. func findProductAndBoardConfigFiles(entries finder.DirEntries) (dirNames []string, fileNames []string) {
  104. matches := []string{}
  105. for _, foundName := range entries.FileNames {
  106. if foundName != "Android.mk" &&
  107. foundName != "AndroidProducts.mk" &&
  108. foundName != "CleanSpec.mk" &&
  109. strings.HasSuffix(foundName, ".mk") {
  110. matches = append(matches, foundName)
  111. }
  112. }
  113. return entries.DirNames, matches
  114. }
  115. // FindSources searches for source files known to <f> and writes them to the filesystem for
  116. // use later.
  117. func FindSources(ctx Context, config Config, f *finder.Finder) {
  118. // note that dumpDir in FindSources may be different than dumpDir in NewSourceFinder
  119. // if a caller such as multiproduct_kati wants to share one Finder among several builds
  120. dumpDir := config.FileListDir()
  121. os.MkdirAll(dumpDir, 0777)
  122. // Stop searching a subdirectory recursively after finding an Android.mk.
  123. androidMks := f.FindFirstNamedAt(".", "Android.mk")
  124. err := dumpListToFile(ctx, config, androidMks, filepath.Join(dumpDir, "Android.mk.list"))
  125. if err != nil {
  126. ctx.Fatalf("Could not export module list: %v", err)
  127. }
  128. // Gate collecting/reporting mk metrics on builds that specifically request
  129. // it, as identifying the total number of mk files adds 4-5ms onto null
  130. // builds.
  131. if config.reportMkMetrics {
  132. androidMksTotal := f.FindNamedAt(".", "Android.mk")
  133. ctx.Metrics.SetToplevelMakefiles(len(androidMks))
  134. ctx.Metrics.SetTotalMakefiles(len(androidMksTotal))
  135. ctx.Metrics.DumpMkMetrics(config.MkMetrics())
  136. }
  137. // Stop searching a subdirectory recursively after finding a CleanSpec.mk.
  138. cleanSpecs := f.FindFirstNamedAt(".", "CleanSpec.mk")
  139. err = dumpListToFile(ctx, config, cleanSpecs, filepath.Join(dumpDir, "CleanSpec.mk.list"))
  140. if err != nil {
  141. ctx.Fatalf("Could not export module list: %v", err)
  142. }
  143. // Only consider AndroidProducts.mk in device/, vendor/ and product/, recursively in these directories.
  144. androidProductsMks := f.FindNamedAt("device", "AndroidProducts.mk")
  145. androidProductsMks = append(androidProductsMks, f.FindNamedAt("vendor", "AndroidProducts.mk")...)
  146. androidProductsMks = append(androidProductsMks, f.FindNamedAt("product", "AndroidProducts.mk")...)
  147. err = dumpListToFile(ctx, config, androidProductsMks, filepath.Join(dumpDir, "AndroidProducts.mk.list"))
  148. if err != nil {
  149. ctx.Fatalf("Could not export product list: %v", err)
  150. }
  151. // Recursively look for all Bazel related files.
  152. bazelFiles := f.FindMatching(".", findBazelFiles)
  153. err = dumpListToFile(ctx, config, bazelFiles, filepath.Join(dumpDir, "bazel.list"))
  154. if err != nil {
  155. ctx.Fatalf("Could not export bazel BUILD list: %v", err)
  156. }
  157. // Recursively look for all OWNERS files.
  158. owners := f.FindNamedAt(".", "OWNERS")
  159. err = dumpListToFile(ctx, config, owners, filepath.Join(dumpDir, "OWNERS.list"))
  160. if err != nil {
  161. ctx.Fatalf("Could not find OWNERS: %v", err)
  162. }
  163. // Recursively look for all TEST_MAPPING files.
  164. testMappings := f.FindNamedAt(".", "TEST_MAPPING")
  165. err = dumpListToFile(ctx, config, testMappings, filepath.Join(dumpDir, "TEST_MAPPING.list"))
  166. if err != nil {
  167. ctx.Fatalf("Could not find TEST_MAPPING: %v", err)
  168. }
  169. // Recursively look for all Android.bp files
  170. androidBps := f.FindNamedAt(".", "Android.bp")
  171. if len(androidBps) == 0 {
  172. ctx.Fatalf("No Android.bp found")
  173. }
  174. err = dumpListToFile(ctx, config, androidBps, filepath.Join(dumpDir, "Android.bp.list"))
  175. if err != nil {
  176. ctx.Fatalf("Could not find modules: %v", err)
  177. }
  178. // Recursively look for all product/board config files.
  179. configurationFiles := f.FindMatching(".", findProductAndBoardConfigFiles)
  180. err = dumpListToFile(ctx, config, configurationFiles, filepath.Join(dumpDir, "configuration.list"))
  181. if err != nil {
  182. ctx.Fatalf("Could not export product/board configuration list: %v", err)
  183. }
  184. if config.Dist() {
  185. f.WaitForDbDump()
  186. // Dist the files.db plain text database.
  187. distFile(ctx, config, f.DbPath, "module_paths")
  188. }
  189. }
  190. // Write the .list files to disk.
  191. func dumpListToFile(ctx Context, config Config, list []string, filePath string) (err error) {
  192. desiredText := strings.Join(list, "\n")
  193. desiredBytes := []byte(desiredText)
  194. actualBytes, readErr := ioutil.ReadFile(filePath)
  195. if readErr != nil || !bytes.Equal(desiredBytes, actualBytes) {
  196. err = ioutil.WriteFile(filePath, desiredBytes, 0777)
  197. if err != nil {
  198. return err
  199. }
  200. }
  201. distFile(ctx, config, filePath, "module_paths")
  202. return nil
  203. }