blob: 70c88563f0872a233e6ea6c5fc6384a9af02f1fe [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
15package main
16
17import (
18 "flag"
19 "fmt"
Rupert Shuttleworth00960792021-05-12 21:20:13 -040020 "io/fs"
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +010021 "io/ioutil"
Colin Cross3f40fa42015-01-30 17:27:36 -080022 "os"
23 "path/filepath"
Jingwen Cheneb76c432021-01-28 08:22:12 -050024 "strings"
Lukacs T. Berkic99c9472021-03-24 10:50:06 +010025 "time"
Colin Cross3f40fa42015-01-30 17:27:36 -080026
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020027 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010028 "android/soong/shared"
Colin Crosscb33a002021-04-12 22:25:17 -070029
Colin Cross70b40592015-03-23 12:57:34 -070030 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020031 "github.com/google/blueprint/deptools"
Colin Cross3f40fa42015-01-30 17:27:36 -080032
Colin Cross635c3b02016-05-18 15:37:25 -070033 "android/soong/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080034)
35
Colin Crosse87040b2017-12-11 15:52:26 -080036var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020037 topDir string
38 outDir string
39 availableEnvFile string
40 usedEnvFile string
41
42 delveListen string
43 delvePath string
44
Jingwen Chen50f93d22020-11-05 07:42:11 -050045 docFile string
46 bazelQueryViewDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020047 bp2buildMarker string
Colin Crosse87040b2017-12-11 15:52:26 -080048)
49
50func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020051 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010052 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
53 flag.StringVar(&outDir, "out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020054 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
55 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
56
57 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010058 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
59 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020060
61 // Flags representing various modes soong_build can run in
Colin Crosse87040b2017-12-11 15:52:26 -080062 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010063 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020064 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Colin Crosse87040b2017-12-11 15:52:26 -080065}
66
Jeff Gaston088e29e2017-11-29 16:47:17 -080067func newNameResolver(config android.Config) *android.NameResolver {
68 namespacePathsToExport := make(map[string]bool)
69
Dan Willemsen3fb1fae2018-03-12 15:30:26 -070070 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -080071 namespacePathsToExport[namespaceName] = true
72 }
73
74 namespacePathsToExport["."] = true // always export the root namespace
75
76 exportFilter := func(namespace *android.Namespace) bool {
77 return namespacePathsToExport[namespace.Path]
78 }
79
80 return android.NewNameResolver(exportFilter)
81}
82
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +020083func newContext(configuration android.Config, prepareBuildActions bool) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -070084 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -050085 ctx.Register()
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +020086 if !prepareBuildActions {
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040087 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
88 }
89 ctx.SetNameInterface(newNameResolver(configuration))
90 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
91 return ctx
92}
93
Lukacs T. Berki53b2f362021-04-12 14:04:24 +020094func newConfig(srcDir, outDir string, availableEnv map[string]string) android.Config {
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020095 configuration, err := android.NewConfig(srcDir, outDir, bootstrap.CmdlineArgs.ModuleListFile, availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -040096 if err != nil {
97 fmt.Fprintf(os.Stderr, "%s", err)
98 os.Exit(1)
99 }
100 return configuration
101}
102
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200103// Bazel-enabled mode. Soong runs in two passes.
104// First pass: Analyze the build tree, but only store all bazel commands
105// needed to correctly evaluate the tree in the second pass.
106// TODO(cparsons): Don't output any ninja file, as the second pass will overwrite
107// the incorrect results from the first pass, and file I/O is expensive.
108func runMixedModeBuild(configuration android.Config, firstCtx *android.Context, extraNinjaDeps []string) {
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200109 var firstArgs, secondArgs bootstrap.Args
110
111 firstArgs = bootstrap.CmdlineArgs
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200112 configuration.SetStopBefore(bootstrap.StopBeforeWriteNinja)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200113 bootstrap.RunBlueprint(firstArgs, firstCtx.Context, configuration)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200114
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200115 // Invoke bazel commands and save results for second pass.
116 if err := configuration.BazelContext.InvokeBazel(); err != nil {
117 fmt.Fprintf(os.Stderr, "%s", err)
118 os.Exit(1)
119 }
120 // Second pass: Full analysis, using the bazel command results. Output ninja file.
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200121 secondConfig, err := android.ConfigForAdditionalRun(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200122 if err != nil {
123 fmt.Fprintf(os.Stderr, "%s", err)
124 os.Exit(1)
125 }
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200126 secondCtx := newContext(secondConfig, true)
127 secondArgs = bootstrap.CmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200128 ninjaDeps := bootstrap.RunBlueprint(secondArgs, secondCtx.Context, secondConfig)
129 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200130 err = deptools.WriteDepFile(shared.JoinPath(topDir, secondArgs.DepFile), secondArgs.OutFile, ninjaDeps)
131 if err != nil {
132 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", secondArgs.DepFile, err)
133 os.Exit(1)
134 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200135}
136
137// Run the code-generation phase to convert BazelTargetModules to BUILD files.
138func runQueryView(configuration android.Config, ctx *android.Context) {
139 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
140 absoluteQueryViewDir := shared.JoinPath(topDir, bazelQueryViewDir)
141 if err := createBazelQueryView(codegenContext, absoluteQueryViewDir); err != nil {
142 fmt.Fprintf(os.Stderr, "%s", err)
143 os.Exit(1)
144 }
145}
146
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200147func runSoongDocs(configuration android.Config) {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200148 ctx := newContext(configuration, false)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200149 soongDocsArgs := bootstrap.CmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200150 bootstrap.RunBlueprint(soongDocsArgs, ctx.Context, configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200151 if err := writeDocs(ctx, configuration, docFile); err != nil {
152 fmt.Fprintf(os.Stderr, "%s", err)
153 os.Exit(1)
154 }
155}
156
157func writeMetrics(configuration android.Config) {
Lukacs T. Berki745380c2021-04-12 12:07:44 +0200158 metricsFile := filepath.Join(configuration.BuildDir(), "soong_build_metrics.pb")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200159 err := android.WriteMetrics(configuration, metricsFile)
160 if err != nil {
161 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
162 os.Exit(1)
163 }
164}
165
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200166func writeJsonModuleGraph(configuration android.Config, ctx *android.Context, path string, extraNinjaDeps []string) {
167 f, err := os.Create(path)
168 if err != nil {
169 fmt.Fprintf(os.Stderr, "%s", err)
170 os.Exit(1)
171 }
172
173 defer f.Close()
174 ctx.Context.PrintJSONGraph(f)
175 writeFakeNinjaFile(extraNinjaDeps, configuration.BuildDir())
176}
177
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200178func doChosenActivity(configuration android.Config, extraNinjaDeps []string) string {
Chris Parsonsec1a3dc2021-04-20 15:32:07 -0400179 bazelConversionRequested := bp2buildMarker != ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200180 mixedModeBuild := configuration.BazelContext.BazelEnabled()
181 generateQueryView := bazelQueryViewDir != ""
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200182 jsonModuleFile := configuration.Getenv("SOONG_DUMP_JSON_MODULE_GRAPH")
183
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200184 blueprintArgs := bootstrap.CmdlineArgs
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200185 prepareBuildActions := !generateQueryView && jsonModuleFile == ""
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200186 if bazelConversionRequested {
187 // Run the alternate pipeline of bp2build mutators and singleton to convert
188 // Blueprint to BUILD files before everything else.
189 runBp2Build(configuration, extraNinjaDeps)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200190 if bp2buildMarker != "" {
191 return bp2buildMarker
192 } else {
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200193 return bootstrap.CmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200194 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200195 }
196
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200197 ctx := newContext(configuration, prepareBuildActions)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200198 if mixedModeBuild {
199 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
200 } else {
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200201 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, ctx.Context, configuration)
202 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200203 err := deptools.WriteDepFile(shared.JoinPath(topDir, blueprintArgs.DepFile), blueprintArgs.OutFile, ninjaDeps)
204 if err != nil {
205 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", blueprintArgs.DepFile, err)
206 os.Exit(1)
207 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200208 }
209
210 // Convert the Soong module graph into Bazel BUILD files.
211 if generateQueryView {
212 runQueryView(configuration, ctx)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200213 return bootstrap.CmdlineArgs.OutFile // TODO: This is a lie
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200214 }
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200215
216 if jsonModuleFile != "" {
217 writeJsonModuleGraph(configuration, ctx, jsonModuleFile, extraNinjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200218 return bootstrap.CmdlineArgs.OutFile // TODO: This is a lie
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200219 }
220
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200221 writeMetrics(configuration)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200222 return bootstrap.CmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200223}
224
225// soong_ui dumps the available environment variables to
226// soong.environment.available . Then soong_build itself is run with an empty
227// environment so that the only way environment variables can be accessed is
228// using Config, which tracks access to them.
229
230// At the end of the build, a file called soong.environment.used is written
231// containing the current value of all used environment variables. The next
232// time soong_ui is run, it checks whether any environment variables that was
233// used had changed and if so, it deletes soong.environment.used to cause a
234// rebuild.
235//
236// The dependency of build.ninja on soong.environment.used is declared in
237// build.ninja.d
238func parseAvailableEnv() map[string]string {
239 if availableEnvFile == "" {
240 fmt.Fprintf(os.Stderr, "--available_env not set\n")
241 os.Exit(1)
242 }
243
244 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
245 if err != nil {
246 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
247 os.Exit(1)
248 }
249
250 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200251}
252
Colin Cross3f40fa42015-01-30 17:27:36 -0800253func main() {
254 flag.Parse()
255
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100256 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100257 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100258
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200259 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200260
Colin Cross3f40fa42015-01-30 17:27:36 -0800261 // The top-level Blueprints file is passed as the first argument.
262 srcDir := filepath.Dir(flag.Arg(0))
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200263 configuration := newConfig(srcDir, outDir, availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100264 extraNinjaDeps := []string{
265 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200266 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100267 }
Colin Crossaa812d12019-06-19 13:33:24 -0700268
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100269 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
270 configuration.SetAllowMissingDependencies()
271 }
272
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100273 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700274 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
275 // enabled even if it completed successfully.
276 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.BuildDir(), "always_rerun_for_delve"))
277 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500278
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200279 if docFile != "" {
280 // We don't write an used variables file when generating documentation
281 // because that is done from within the actual builds as a Ninja action and
282 // thus it would overwrite the actual used variables file so this is
283 // special-cased.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200284 // TODO: Fix this by not passing --used_env to the soong_docs invocation
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200285 runSoongDocs(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200286 return
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400287 }
Jingwen Chen4133ce62020-12-02 04:34:15 -0500288
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200289 finalOutputFile := doChosenActivity(configuration, extraNinjaDeps)
290 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100291}
292
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200293func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
294 if usedEnvFile == "" {
295 return
296 }
297
298 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100299 data, err := shared.EnvFileContents(configuration.EnvDeps())
300 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200301 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100302 os.Exit(1)
303 }
304
305 err = ioutil.WriteFile(path, data, 0666)
306 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200307 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100308 os.Exit(1)
309 }
310
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200311 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100312 // wrote. We can't write the environment file earlier because one an access
313 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200314 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800315}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000316
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200317// Workarounds to support running bp2build in a clean AOSP checkout with no
318// prior builds, and exiting early as soon as the BUILD files get generated,
319// therefore not creating build.ninja files that soong_ui and callers of
320// soong_build expects.
321//
322// These files are: build.ninja and build.ninja.d. Since Kati hasn't been
323// ran as well, and `nothing` is defined in a .mk file, there isn't a ninja
324// target called `nothing`, so we manually create it here.
325func writeFakeNinjaFile(extraNinjaDeps []string, buildDir string) {
326 extraNinjaDepsString := strings.Join(extraNinjaDeps, " \\\n ")
327
328 ninjaFileName := "build.ninja"
329 ninjaFile := shared.JoinPath(topDir, buildDir, ninjaFileName)
330 ninjaFileD := shared.JoinPath(topDir, buildDir, ninjaFileName)
331 // A workaround to create the 'nothing' ninja target so `m nothing` works,
332 // since bp2build runs without Kati, and the 'nothing' target is declared in
333 // a Makefile.
334 ioutil.WriteFile(ninjaFile, []byte("build nothing: phony\n phony_output = true\n"), 0666)
335 ioutil.WriteFile(ninjaFileD,
336 []byte(fmt.Sprintf("%s: \\\n %s\n", ninjaFileName, extraNinjaDepsString)),
337 0666)
338}
339
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200340func touch(path string) {
341 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
342 if err != nil {
343 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
344 os.Exit(1)
345 }
346
347 err = f.Close()
348 if err != nil {
349 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
350 os.Exit(1)
351 }
352
353 currentTime := time.Now().Local()
354 err = os.Chtimes(path, currentTime, currentTime)
355 if err != nil {
356 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
357 os.Exit(1)
358 }
359}
360
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400361// Find BUILD files in the srcDir which...
362//
363// - are not on the allow list (android/bazel.go#ShouldKeepExistingBuildFileForDir())
364//
365// - won't be overwritten by corresponding bp2build generated files
366//
367// And return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
368func getPathsToIgnoredBuildFiles(topDir string, outDir string, generatedRoot string) ([]string, error) {
369 paths := make([]string, 0)
370
371 err := filepath.WalkDir(topDir, func(fFullPath string, fDirEntry fs.DirEntry, err error) error {
372 if err != nil {
373 // Warn about error, but continue trying to walk the directory tree
374 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", fFullPath, err)
375 return nil
376 }
377 if fDirEntry.IsDir() {
378 // Don't ignore entire directories
379 return nil
380 }
381 if !(fDirEntry.Name() == "BUILD" || fDirEntry.Name() == "BUILD.bazel") {
382 // Don't ignore this file - it is not a build file
383 return nil
384 }
385 f := strings.TrimPrefix(fFullPath, topDir+"/")
386 if strings.HasPrefix(f, ".repo/") {
387 // Don't check for files to ignore in the .repo dir (recursively)
388 return fs.SkipDir
389 }
390 if strings.HasPrefix(f, outDir+"/") {
391 // Don't check for files to ignore in the out dir (recursively)
392 return fs.SkipDir
393 }
394 if strings.HasPrefix(f, generatedRoot) {
395 // Don't check for files to ignore in the bp2build dir (recursively)
396 // NOTE: This is usually under outDir
397 return fs.SkipDir
398 }
399 fDir := filepath.Dir(f)
400 if android.ShouldKeepExistingBuildFileForDir(fDir) {
401 // Don't ignore this existing build file
402 return nil
403 }
404 f_bp2build := shared.JoinPath(topDir, generatedRoot, f)
405 if _, err := os.Stat(f_bp2build); err == nil {
406 // If bp2build generated an alternate BUILD file, don't exclude this workspace path
407 // BUILD file clash resolution happens later in the symlink forest creation
408 return nil
409 }
410 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", f)
411 paths = append(paths, f)
412 return nil
413 })
414
415 return paths, err
416}
417
418// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
419func getTemporaryExcludes() []string {
420 excludes := make([]string, 0)
421
422 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
423 excludes = append(excludes, "external/autotest/venv/autotest_lib")
424
425 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
426 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
427 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
428
429 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
430 excludes = append(excludes, "frameworks/compile/slang")
431
432 return excludes
433}
434
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500435// Run Soong in the bp2build mode. This creates a standalone context that registers
436// an alternate pipeline of mutators and singletons specifically for generating
437// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200438func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500439 // Register an alternate set of singletons and mutators for bazel
440 // conversion for Bazel conversion.
441 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500442
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200443 // Propagate "allow misssing dependencies" bit. This is normally set in
444 // newContext(), but we create bp2buildCtx without calling that method.
445 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500446 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200447 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500448
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500449 // The bp2build process is a purely functional process that only depends on
450 // Android.bp files. It must not depend on the values of per-build product
451 // configurations or variables, since those will generate different BUILD
452 // files based on how the user has configured their tree.
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200453 bp2buildCtx.SetModuleListFile(bootstrap.CmdlineArgs.ModuleListFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200454 modulePaths, err := bp2buildCtx.ListModulePaths(configuration.SrcDir())
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500455 if err != nil {
456 panic(err)
457 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500458
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100459 extraNinjaDeps = append(extraNinjaDeps, modulePaths...)
460
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200461 // No need to generate Ninja build rules/statements from Modules and Singletons.
462 configuration.SetStopBefore(bootstrap.StopBeforePrepareBuildActions)
463
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500464 // Run the loading and analysis pipeline to prepare the graph of regular
465 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
466 // from the regular Modules.
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200467 blueprintArgs := bootstrap.CmdlineArgs
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200468 ninjaDeps := bootstrap.RunBlueprint(blueprintArgs, bp2buildCtx.Context, configuration)
469 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200470
Colin Crosscb33a002021-04-12 22:25:17 -0700471 ninjaDeps = append(ninjaDeps, bootstrap.GlobFileListFiles(configuration)...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200472
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200473 // Run the code-generation phase to convert BazelTargetModules to BUILD files
474 // and print conversion metrics to the user.
475 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
476 metrics := bp2build.Codegen(codegenContext)
477
478 generatedRoot := shared.JoinPath(configuration.BuildDir(), "bp2build")
479 workspaceRoot := shared.JoinPath(configuration.BuildDir(), "workspace")
480
481 excludes := []string{
482 "bazel-bin",
483 "bazel-genfiles",
484 "bazel-out",
485 "bazel-testlogs",
486 "bazel-" + filepath.Base(topDir),
487 }
488
489 if bootstrap.CmdlineArgs.NinjaBuildDir[0] != '/' {
490 excludes = append(excludes, bootstrap.CmdlineArgs.NinjaBuildDir)
491 }
492
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400493 // FIXME: Don't hardcode this here
494 topLevelOutDir := "out"
495
496 pathsToIgnoredBuildFiles, err := getPathsToIgnoredBuildFiles(topDir, topLevelOutDir, generatedRoot)
497 if err != nil {
498 fmt.Fprintf(os.Stderr, "Error walking SrcDir: '%s': %s\n", configuration.SrcDir(), err)
499 os.Exit(1)
500 }
501 excludes = append(excludes, pathsToIgnoredBuildFiles...)
502
503 excludes = append(excludes, getTemporaryExcludes()...)
504
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200505 symlinkForestDeps := bp2build.PlantSymlinkForest(
506 topDir, workspaceRoot, generatedRoot, configuration.SrcDir(), excludes)
507
508 // Only report metrics when in bp2build mode. The metrics aren't relevant
509 // for queryview, since that's a total repo-wide conversion and there's a
510 // 1:1 mapping for each module.
511 metrics.Print()
512
513 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
514 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
515
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200516 depFile := bp2buildMarker + ".d"
517 err = deptools.WriteDepFile(shared.JoinPath(topDir, depFile), bp2buildMarker, ninjaDeps)
518 if err != nil {
519 fmt.Fprintf(os.Stderr, "Cannot write depfile '%s': %s\n", depFile, err)
520 os.Exit(1)
521 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500522
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200523 if bp2buildMarker != "" {
524 touch(shared.JoinPath(topDir, bp2buildMarker))
525 } else {
526 writeFakeNinjaFile(extraNinjaDeps, codegenContext.Config().BuildDir())
527 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500528}