blob: 028ca44d095d1c90ed6280a0dee7350a37a99b12 [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 (
Usta Shrestha2ba28a32022-10-24 11:33:09 -040018 "bytes"
Colin Cross3f40fa42015-01-30 17:27:36 -080019 "flag"
20 "fmt"
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
Dan Willemsen66213a62021-09-21 17:50:30 -070027 "android/soong/android"
Spandan Das5af0bd32022-09-28 20:43:08 +000028 "android/soong/bazel"
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020029 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010030 "android/soong/shared"
Chris Parsons715b08f2022-03-22 19:23:40 -040031 "android/soong/ui/metrics/bp2build_metrics_proto"
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020032
Colin Cross70b40592015-03-23 12:57:34 -070033 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020034 "github.com/google/blueprint/deptools"
Chris Parsons715b08f2022-03-22 19:23:40 -040035 "github.com/google/blueprint/metrics"
Dan Willemsen66213a62021-09-21 17:50:30 -070036 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080037)
38
Colin Crosse87040b2017-12-11 15:52:26 -080039var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020040 topDir string
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020041 outDir string
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020042 soongOutDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020043 availableEnvFile string
44 usedEnvFile string
45
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020046 runGoTests bool
47
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020048 globFile string
49 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020050 delveListen string
51 delvePath string
52
Spandan Das5af0bd32022-09-28 20:43:08 +000053 moduleGraphFile string
54 moduleActionsFile string
55 docFile string
56 bazelQueryViewDir string
57 bazelApiBp2buildDir string
58 bp2buildMarker string
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000059 symlinkForestMarker string
Lukacs T. Berkif9008072021-08-16 15:24:48 +020060
61 cmdlineArgs bootstrap.Args
Colin Crosse87040b2017-12-11 15:52:26 -080062)
63
64func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020065 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010066 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020067 flag.StringVar(&soongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020068 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
69 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020070 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
71 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020072 flag.StringVar(&outDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020073 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020074
75 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010076 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
77 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020078 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
79 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
80 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
81 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020082
83 // Flags representing various modes soong_build can run in
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020084 flag.StringVar(&moduleGraphFile, "module_graph_file", "", "JSON module graph file to output")
kgui67007242022-01-25 13:50:25 +080085 flag.StringVar(&moduleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
Colin Crosse87040b2017-12-11 15:52:26 -080086 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010087 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Spandan Das5af0bd32022-09-28 20:43:08 +000088 flag.StringVar(&bazelApiBp2buildDir, "bazel_api_bp2build_dir", "", "path to the bazel api_bp2build directory relative to --top")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020089 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Lukacs T. Berkic541cd22022-10-26 07:26:50 +000090 flag.StringVar(&symlinkForestMarker, "symlink_forest_marker", "", "If set, create the bp2build symlink forest, touch the specified marker file, then exit")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020091 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020092 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
Chris Parsonsef615e52022-08-18 22:04:11 -040093 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
Jingwen Chene647db82022-11-01 11:28:29 +000094 flag.BoolVar(&cmdlineArgs.BazelModeStaging, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
Chris Parsonsef615e52022-08-18 22:04:11 -040095 flag.BoolVar(&cmdlineArgs.BazelModeDev, "bazel-mode-dev", false, "use bazel for analysis of a large number of modules (less stable)")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020096
97 // Flags that probably shouldn't be flags of soong_build but we haven't found
98 // the time to remove them yet
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020099 flag.BoolVar(&runGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -0700100
101 // Disable deterministic randomization in the protobuf package, so incremental
102 // builds with unrelated Soong changes don't trigger large rebuilds (since we
103 // write out text protos in command lines, and command line changes trigger
104 // rebuilds).
105 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -0800106}
107
Jeff Gaston088e29e2017-11-29 16:47:17 -0800108func newNameResolver(config android.Config) *android.NameResolver {
Paul Duffin3f7bf9f2022-11-08 12:21:15 +0000109 return android.NewNameResolver(config)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800110}
111
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200112func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700113 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500114 ctx.Register()
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400115 ctx.SetNameInterface(newNameResolver(configuration))
116 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
117 return ctx
118}
119
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200120func newConfig(availableEnv map[string]string) android.Config {
Chris Parsonsad876012022-08-20 14:48:32 -0400121 var buildMode android.SoongBuildMode
122
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000123 if symlinkForestMarker != "" {
124 buildMode = android.SymlinkForest
125 } else if bp2buildMarker != "" {
Chris Parsonsad876012022-08-20 14:48:32 -0400126 buildMode = android.Bp2build
127 } else if bazelQueryViewDir != "" {
128 buildMode = android.GenerateQueryView
Spandan Das5af0bd32022-09-28 20:43:08 +0000129 } else if bazelApiBp2buildDir != "" {
130 buildMode = android.ApiBp2build
Chris Parsonsad876012022-08-20 14:48:32 -0400131 } else if moduleGraphFile != "" {
132 buildMode = android.GenerateModuleGraph
133 } else if docFile != "" {
134 buildMode = android.GenerateDocFile
Chris Parsonsef615e52022-08-18 22:04:11 -0400135 } else if cmdlineArgs.BazelModeDev {
136 buildMode = android.BazelDevMode
137 } else if cmdlineArgs.BazelMode {
138 buildMode = android.BazelProdMode
MarkDacekb78465d2022-10-18 20:10:16 +0000139 } else if cmdlineArgs.BazelModeStaging {
140 buildMode = android.BazelStagingMode
Chris Parsonsad876012022-08-20 14:48:32 -0400141 } else {
142 buildMode = android.AnalysisNoBazel
143 }
144
145 configuration, err := android.NewConfig(cmdlineArgs.ModuleListFile, buildMode, runGoTests, outDir, soongOutDir, availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400146 if err != nil {
147 fmt.Fprintf(os.Stderr, "%s", err)
148 os.Exit(1)
149 }
150 return configuration
151}
152
Chris Parsonsf874e462022-05-10 13:50:12 -0400153// Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
154// BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
155// for modules that should be handled by Bazel.
156func runMixedModeBuild(configuration android.Config, ctx *android.Context, extraNinjaDeps []string) {
157 ctx.EventHandler.Begin("mixed_build")
158 defer ctx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200159
Chris Parsonsf874e462022-05-10 13:50:12 -0400160 bazelHook := func() error {
161 ctx.EventHandler.Begin("bazel")
162 defer ctx.EventHandler.End("bazel")
Yu Liu8d82ac52022-05-17 15:13:28 -0700163 return configuration.BazelContext.InvokeBazel(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200164 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400165 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Chris Parsonsf874e462022-05-10 13:50:12 -0400166 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, bootstrap.DoEverything, ctx.Context, configuration)
Chris Parsons027881c2022-05-24 15:38:38 -0400167 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200168
MarkDacek0d5bca52022-10-10 20:07:48 +0000169 bazelPaths, err := readBazelPaths(configuration)
170 if err != nil {
171 panic("Bazel deps file not found: " + err.Error())
172 }
173 ninjaDeps = append(ninjaDeps, bazelPaths...)
174
Chris Parsonsf874e462022-05-10 13:50:12 -0400175 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200176 ninjaDeps = append(ninjaDeps, globListFiles...)
177
Paul Duffin780a1852022-11-05 10:17:12 +0000178 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200179}
180
181// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200182func runQueryView(queryviewDir, queryviewMarker string, configuration android.Config, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400183 ctx.EventHandler.Begin("queryview")
184 defer ctx.EventHandler.End("queryview")
Paul Duffinc6390592022-11-04 13:35:21 +0000185 codegenContext := bp2build.NewCodegenContext(configuration, ctx, bp2build.QueryView)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200186 absoluteQueryViewDir := shared.JoinPath(topDir, queryviewDir)
Spandan Das5af0bd32022-09-28 20:43:08 +0000187 if err := createBazelWorkspace(codegenContext, absoluteQueryViewDir); err != nil {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200188 fmt.Fprintf(os.Stderr, "%s", err)
189 os.Exit(1)
190 }
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200191
192 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200193}
194
Spandan Das5af0bd32022-09-28 20:43:08 +0000195// Run the code-generation phase to convert API contributions to BUILD files.
196// Return marker file for the new synthetic workspace
197func runApiBp2build(configuration android.Config, extraNinjaDeps []string) string {
198 // Create a new context and register mutators that are only meaningful to API export
199 ctx := android.NewContext(configuration)
200 ctx.EventHandler.Begin("api_bp2build")
201 defer ctx.EventHandler.End("api_bp2build")
202 ctx.SetNameInterface(newNameResolver(configuration))
203 ctx.RegisterForApiBazelConversion()
204
205 // Register the Android.bp files in the tree
206 // Add them to the workspace's .d file
207 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
208 if paths, err := ctx.ListModulePaths("."); err == nil {
209 extraNinjaDeps = append(extraNinjaDeps, paths...)
210 } else {
211 panic(err)
212 }
213
214 // Run the loading and analysis phase
215 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs,
216 bootstrap.StopBeforePrepareBuildActions,
217 ctx.Context,
218 configuration)
219 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
220
221 // Add the globbed dependencies
222 globs := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
223 ninjaDeps = append(ninjaDeps, globs...)
224
225 // Run codegen to generate BUILD files
Paul Duffinc6390592022-11-04 13:35:21 +0000226 codegenContext := bp2build.NewCodegenContext(configuration, ctx, bp2build.ApiBp2build)
Spandan Das5af0bd32022-09-28 20:43:08 +0000227 absoluteApiBp2buildDir := shared.JoinPath(topDir, bazelApiBp2buildDir)
228 if err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir); err != nil {
229 fmt.Fprintf(os.Stderr, "%s", err)
230 os.Exit(1)
231 }
232 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
233
234 // Create soong_injection repository
Spandan Das7b6d5332022-11-01 17:37:07 +0000235 soongInjectionFiles := bp2build.CreateSoongInjectionFiles(configuration, bp2build.CreateCodegenMetrics())
Spandan Das5af0bd32022-09-28 20:43:08 +0000236 absoluteSoongInjectionDir := shared.JoinPath(topDir, configuration.SoongOutDir(), bazel.SoongInjectionDirName)
237 for _, file := range soongInjectionFiles {
238 writeReadOnlyFile(absoluteSoongInjectionDir, file)
239 }
240
241 workspace := shared.JoinPath(configuration.SoongOutDir(), "api_bp2build")
242
243 excludes := bazelArtifacts()
244 // Exclude all src BUILD files
245 excludes = append(excludes, apiBuildFileExcludes()...)
246
247 // Create the symlink forest
248 symlinkDeps := bp2build.PlantSymlinkForest(
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000249 configuration.IsEnvTrue("BP2BUILD_VERBOSE"),
Spandan Das5af0bd32022-09-28 20:43:08 +0000250 topDir,
251 workspace,
252 bazelApiBp2buildDir,
Spandan Das5af0bd32022-09-28 20:43:08 +0000253 excludes)
254 ninjaDeps = append(ninjaDeps, symlinkDeps...)
255
256 workspaceMarkerFile := workspace + ".marker"
Paul Duffin780a1852022-11-05 10:17:12 +0000257 writeDepFile(workspaceMarkerFile, ctx.EventHandler, ninjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000258 touch(shared.JoinPath(topDir, workspaceMarkerFile))
259 return workspaceMarkerFile
260}
261
262// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
263// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
264func apiBuildFileExcludes() []string {
265 ret := make([]string, 0)
266
267 srcs, err := getExistingBazelRelatedFiles(topDir)
268 if err != nil {
269 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
270 os.Exit(1)
271 }
272 for _, src := range srcs {
273 if src != "WORKSPACE" &&
274 src != "BUILD" &&
275 src != "BUILD.bazel" &&
276 !strings.HasPrefix(src, "build/bazel") &&
277 !strings.HasPrefix(src, "prebuilts/clang") {
278 ret = append(ret, src)
279 }
280 }
281 return ret
282}
283
Paul Duffin780a1852022-11-05 10:17:12 +0000284func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400285 if len(metricsDir) < 1 {
286 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
287 os.Exit(1)
288 }
289 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
290 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200291 if err != nil {
292 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
293 os.Exit(1)
294 }
295}
296
kgui67007242022-01-25 13:50:25 +0800297func writeJsonModuleGraphAndActions(ctx *android.Context, graphPath string, actionsPath string) {
298 graphFile, graphErr := os.Create(shared.JoinPath(topDir, graphPath))
299 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, actionsPath))
300 if graphErr != nil || actionsErr != nil {
301 fmt.Fprintf(os.Stderr, "Graph err: %s, actions err: %s", graphErr, actionsErr)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200302 os.Exit(1)
303 }
304
kgui67007242022-01-25 13:50:25 +0800305 defer graphFile.Close()
306 defer actionsFile.Close()
307 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200308}
309
Chris Parsons715b08f2022-03-22 19:23:40 -0400310func writeBuildGlobsNinjaFile(ctx *android.Context, buildDir string, config interface{}) []string {
311 ctx.EventHandler.Begin("globs_ninja_file")
312 defer ctx.EventHandler.End("globs_ninja_file")
313
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200314 globDir := bootstrap.GlobDirectory(buildDir, globListDir)
315 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400316 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200317 GlobFile: globFile,
318 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400319 SrcDir: ctx.SrcDir(),
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200320 }, config)
321 return bootstrap.GlobFileListFiles(globDir)
322}
323
Paul Duffin780a1852022-11-05 10:17:12 +0000324func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400325 eventHandler.Begin("ninja_deps")
326 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200327 depFile := shared.JoinPath(topDir, outputFile+".d")
328 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
329 if err != nil {
330 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", depFile, err)
331 os.Exit(1)
332 }
333}
334
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000335// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
336// or the actual Soong build for the build.ninja file. Returns the top level
337// output file of the specific activity.
Paul Duffinf4906562022-11-05 14:21:16 +0000338func doChosenActivity(ctx *android.Context, configuration android.Config, extraNinjaDeps []string, metricsDir string) string {
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000339 if configuration.BuildMode == android.SymlinkForest {
Paul Duffinf4906562022-11-05 14:21:16 +0000340 runSymlinkForestCreation(configuration, extraNinjaDeps, metricsDir)
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000341 return symlinkForestMarker
342 } else if configuration.BuildMode == android.Bp2build {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200343 // Run the alternate pipeline of bp2build mutators and singleton to convert
344 // Blueprint to BUILD files before everything else.
Paul Duffinf4906562022-11-05 14:21:16 +0000345 runBp2Build(configuration, extraNinjaDeps, metricsDir)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000346 return bp2buildMarker
Chris Parsonsad876012022-08-20 14:48:32 -0400347 } else if configuration.IsMixedBuildsEnabled() {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200348 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000349 } else if configuration.BuildMode == android.ApiBp2build {
350 return runApiBp2build(configuration, extraNinjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200351 } else {
Chris Parsons715b08f2022-03-22 19:23:40 -0400352 var stopBefore bootstrap.StopBefore
Chris Parsonsad876012022-08-20 14:48:32 -0400353 if configuration.BuildMode == android.GenerateModuleGraph {
Chris Parsons715b08f2022-03-22 19:23:40 -0400354 stopBefore = bootstrap.StopBeforeWriteNinja
Chris Parsonsad876012022-08-20 14:48:32 -0400355 } else if configuration.BuildMode == android.GenerateQueryView || configuration.BuildMode == android.GenerateDocFile {
Chris Parsons715b08f2022-03-22 19:23:40 -0400356 stopBefore = bootstrap.StopBeforePrepareBuildActions
357 } else {
358 stopBefore = bootstrap.DoEverything
359 }
360
Chris Parsonsad876012022-08-20 14:48:32 -0400361 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, stopBefore, ctx.Context, configuration)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200362 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200363
Chris Parsons715b08f2022-03-22 19:23:40 -0400364 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200365 ninjaDeps = append(ninjaDeps, globListFiles...)
366
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200367 // Convert the Soong module graph into Bazel BUILD files.
Chris Parsonsad876012022-08-20 14:48:32 -0400368 if configuration.BuildMode == android.GenerateQueryView {
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200369 queryviewMarkerFile := bazelQueryViewDir + ".marker"
370 runQueryView(bazelQueryViewDir, queryviewMarkerFile, configuration, ctx)
Paul Duffin780a1852022-11-05 10:17:12 +0000371 writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200372 return queryviewMarkerFile
Chris Parsonsad876012022-08-20 14:48:32 -0400373 } else if configuration.BuildMode == android.GenerateModuleGraph {
kgui67007242022-01-25 13:50:25 +0800374 writeJsonModuleGraphAndActions(ctx, moduleGraphFile, moduleActionsFile)
Paul Duffin780a1852022-11-05 10:17:12 +0000375 writeDepFile(moduleGraphFile, ctx.EventHandler, ninjaDeps)
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200376 return moduleGraphFile
Chris Parsonsad876012022-08-20 14:48:32 -0400377 } else if configuration.BuildMode == android.GenerateDocFile {
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200378 // TODO: we could make writeDocs() return the list of documentation files
379 // written and add them to the .d file. Then soong_docs would be re-run
380 // whenever one is deleted.
381 if err := writeDocs(ctx, shared.JoinPath(topDir, docFile)); err != nil {
382 fmt.Fprintf(os.Stderr, "error building Soong documentation: %s\n", err)
383 os.Exit(1)
384 }
Paul Duffin780a1852022-11-05 10:17:12 +0000385 writeDepFile(docFile, ctx.EventHandler, ninjaDeps)
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200386 return docFile
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200387 } else {
388 // The actual output (build.ninja) was written in the RunBlueprint() call
389 // above
Paul Duffin780a1852022-11-05 10:17:12 +0000390 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200391 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200392 }
393
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200394 return cmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200395}
396
397// soong_ui dumps the available environment variables to
398// soong.environment.available . Then soong_build itself is run with an empty
399// environment so that the only way environment variables can be accessed is
400// using Config, which tracks access to them.
401
402// At the end of the build, a file called soong.environment.used is written
403// containing the current value of all used environment variables. The next
404// time soong_ui is run, it checks whether any environment variables that was
405// used had changed and if so, it deletes soong.environment.used to cause a
406// rebuild.
407//
408// The dependency of build.ninja on soong.environment.used is declared in
409// build.ninja.d
410func parseAvailableEnv() map[string]string {
411 if availableEnvFile == "" {
412 fmt.Fprintf(os.Stderr, "--available_env not set\n")
413 os.Exit(1)
414 }
415
416 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
417 if err != nil {
418 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
419 os.Exit(1)
420 }
421
422 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200423}
424
Colin Cross3f40fa42015-01-30 17:27:36 -0800425func main() {
426 flag.Parse()
427
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100428 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100429 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100430
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200431 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200432
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200433 configuration := newConfig(availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100434 extraNinjaDeps := []string{
435 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200436 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100437 }
Colin Crossaa812d12019-06-19 13:33:24 -0700438
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100439 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
440 configuration.SetAllowMissingDependencies()
441 }
442
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100443 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700444 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
445 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200446 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700447 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500448
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700449 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
450 // change between every CI build, so tracking it would require re-running Soong for every build.
451 logDir := availableEnv["LOG_DIR"]
452
Joe Onorato2e5e4012022-06-07 17:16:08 -0700453 ctx := newContext(configuration)
454 ctx.EventHandler.Begin("soong_build")
455
Paul Duffinf4906562022-11-05 14:21:16 +0000456 finalOutputFile := doChosenActivity(ctx, configuration, extraNinjaDeps, logDir)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700457
458 ctx.EventHandler.End("soong_build")
Paul Duffin780a1852022-11-05 10:17:12 +0000459 writeMetrics(configuration, ctx.EventHandler, logDir)
Chris Parsons715b08f2022-03-22 19:23:40 -0400460
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200461 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100462}
463
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200464func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
465 if usedEnvFile == "" {
466 return
467 }
468
469 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100470 data, err := shared.EnvFileContents(configuration.EnvDeps())
471 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200472 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100473 os.Exit(1)
474 }
475
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400476 if preexistingData, err := os.ReadFile(path); err != nil {
477 if !os.IsNotExist(err) {
478 fmt.Fprintf(os.Stderr, "error reading used environment file '%s': %s\n", usedEnvFile, err)
479 os.Exit(1)
480 }
481 } else if bytes.Equal(preexistingData, data) {
482 // used environment file is unchanged
483 return
484 }
485 if err = os.WriteFile(path, data, 0666); err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200486 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100487 os.Exit(1)
488 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200489 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100490 // wrote. We can't write the environment file earlier because one an access
491 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200492 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800493}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000494
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200495func touch(path string) {
496 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
497 if err != nil {
498 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
499 os.Exit(1)
500 }
501
502 err = f.Close()
503 if err != nil {
504 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
505 os.Exit(1)
506 }
507
508 currentTime := time.Now().Local()
509 err = os.Chtimes(path, currentTime, currentTime)
510 if err != nil {
511 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
512 os.Exit(1)
513 }
514}
515
Cole Faust324a92e2022-08-23 15:29:05 -0700516// Find BUILD files in the srcDir which are not in the allowlist
517// (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
518// and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
519func getPathsToIgnoredBuildFiles(config android.Bp2BuildConversionAllowlist, topDir string, srcDirBazelFiles []string, verbose bool) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400520 paths := make([]string, 0)
521
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400522 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
523 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
524 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400525 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400526 // Warn about error, but continue trying to check files
527 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
528 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400529 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400530 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400531 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400532 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400533 }
Cole Faust324a92e2022-08-23 15:29:05 -0700534 if fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel" {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400535 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400536 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400537 }
Cole Faust324a92e2022-08-23 15:29:05 -0700538 if config.ShouldKeepExistingBuildFileForDir(filepath.Dir(srcDirBazelFileRelativePath)) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400539 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400540 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400541 }
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400542 if verbose {
543 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
544 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400545 paths = append(paths, srcDirBazelFileRelativePath)
546 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400547
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400548 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400549}
550
551// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
552func getTemporaryExcludes() []string {
553 excludes := make([]string, 0)
554
555 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
556 excludes = append(excludes, "external/autotest/venv/autotest_lib")
Jingwen Chenc0c50212022-06-07 10:07:22 +0000557 excludes = append(excludes, "external/autotest/autotest_lib")
558 excludes = append(excludes, "external/autotest/client/autotest_lib/client")
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400559
560 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
561 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
562 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
563
564 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
565 excludes = append(excludes, "frameworks/compile/slang")
566
567 return excludes
568}
569
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400570// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
571// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
572func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200573 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400574 if !filepath.IsAbs(bazelFinderFile) {
575 // Assume this was a relative path under topDir
576 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
577 }
578 data, err := ioutil.ReadFile(bazelFinderFile)
579 if err != nil {
580 return nil, err
581 }
582 files := strings.Split(strings.TrimSpace(string(data)), "\n")
583 return files, nil
584}
585
Spandan Das5af0bd32022-09-28 20:43:08 +0000586func bazelArtifacts() []string {
587 return []string{
588 "bazel-bin",
589 "bazel-genfiles",
590 "bazel-out",
591 "bazel-testlogs",
592 "bazel-" + filepath.Base(topDir),
593 }
594}
595
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000596// This could in theory easily be separated into a binary that generically
597// merges two directories into a symlink tree. The main obstacle is that this
598// function currently depends on both Bazel-specific knowledge (the existence
599// of bazel-* symlinks) and configuration (the set of BUILD.bazel files that
600// should and should not be kept)
601//
602// Ideally, bp2build would write a file that contains instructions to the
603// symlink tree creation binary. Then the latter would not need to depend on
604// the very heavy-weight machinery of soong_build .
Paul Duffinf4906562022-11-05 14:21:16 +0000605func runSymlinkForestCreation(configuration android.Config, extraNinjaDeps []string, metricsDir string) {
Paul Duffin780a1852022-11-05 10:17:12 +0000606 eventHandler := &metrics.EventHandler{}
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000607
608 var ninjaDeps []string
609 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
610
611 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
612 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
613
614 excludes := bazelArtifacts()
615
616 if outDir[0] != '/' {
617 excludes = append(excludes, outDir)
618 }
619
620 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
621 if err != nil {
622 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
623 os.Exit(1)
624 }
625
626 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(configuration.Bp2buildPackageConfig, topDir, existingBazelRelatedFiles, configuration.IsEnvTrue("BP2BUILD_VERBOSE"))
627 excludes = append(excludes, pathsToIgnoredBuildFiles...)
628 excludes = append(excludes, getTemporaryExcludes()...)
629
630 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
631 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
632 // or file created/deleted under it would trigger an update of the symlink
633 // forest.
634 eventHandler.Do("symlink_forest", func() {
635 symlinkForestDeps := bp2build.PlantSymlinkForest(
636 configuration.IsEnvTrue("BP2BUILD_VERBOSE"), topDir, workspaceRoot, generatedRoot, excludes)
637 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
638 })
639
640 writeDepFile(symlinkForestMarker, eventHandler, ninjaDeps)
641 touch(shared.JoinPath(topDir, symlinkForestMarker))
usta4f5d2c12022-10-28 23:32:01 -0400642 codegenMetrics := bp2build.ReadCodegenMetrics(metricsDir)
643 if codegenMetrics == nil {
644 m := bp2build.CreateCodegenMetrics()
645 codegenMetrics = &m
646 } else {
647 //TODO (usta) we cannot determine if we loaded a stale file, i.e. from an unrelated prior
648 //invocation of codegen. We should simply use a separate .pb file
649 }
Paul Duffinf4906562022-11-05 14:21:16 +0000650 writeBp2BuildMetrics(codegenMetrics, eventHandler, metricsDir)
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000651}
652
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500653// Run Soong in the bp2build mode. This creates a standalone context that registers
654// an alternate pipeline of mutators and singletons specifically for generating
655// Bazel BUILD files instead of Ninja files.
Paul Duffinf4906562022-11-05 14:21:16 +0000656func runBp2Build(configuration android.Config, extraNinjaDeps []string, metricsDir string) {
usta4f5d2c12022-10-28 23:32:01 -0400657 var codegenMetrics *bp2build.CodegenMetrics
Paul Duffin780a1852022-11-05 10:17:12 +0000658 eventHandler := &metrics.EventHandler{}
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400659 eventHandler.Do("bp2build", func() {
Chris Parsons715b08f2022-03-22 19:23:40 -0400660
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400661 // Register an alternate set of singletons and mutators for bazel
662 // conversion for Bazel conversion.
663 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500664
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400665 // Propagate "allow misssing dependencies" bit. This is normally set in
666 // newContext(), but we create bp2buildCtx without calling that method.
667 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
668 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
669 bp2buildCtx.RegisterForBazelConversion()
Lukacs T. Berkia3b96882022-10-17 08:04:11 +0000670 bp2buildCtx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500671
Usta Shresthaa117c582022-10-04 12:13:25 -0400672 var ninjaDeps []string
673 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
674
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400675 // Run the loading and analysis pipeline to prepare the graph of regular
676 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
677 // from the regular Modules.
Usta Shresthaa117c582022-10-04 12:13:25 -0400678 eventHandler.Do("bootstrap", func() {
679 blueprintArgs := cmdlineArgs
680 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.StopBeforePrepareBuildActions, bp2buildCtx.Context, configuration)
681 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
682 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200683
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400684 globListFiles := writeBuildGlobsNinjaFile(bp2buildCtx, configuration.SoongOutDir(), configuration)
685 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200686
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400687 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400688 // and print conversion codegenMetrics to the user.
Paul Duffinc6390592022-11-04 13:35:21 +0000689 codegenContext := bp2build.NewCodegenContext(configuration, bp2buildCtx, bp2build.Bp2Build)
Usta Shresthaa117c582022-10-04 12:13:25 -0400690 eventHandler.Do("codegen", func() {
691 codegenMetrics = bp2build.Codegen(codegenContext)
692 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200693
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400694 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400695
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400696 writeDepFile(bp2buildMarker, eventHandler, ninjaDeps)
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000697 touch(shared.JoinPath(topDir, bp2buildMarker))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400698 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400699
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200700 // Only report metrics when in bp2build mode. The metrics aren't relevant
701 // for queryview, since that's a total repo-wide conversion and there's a
702 // 1:1 mapping for each module.
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700703 if configuration.IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400704 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700705 }
Paul Duffinf4906562022-11-05 14:21:16 +0000706 writeBp2BuildMetrics(codegenMetrics, eventHandler, metricsDir)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500707}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500708
709// Write Bp2Build metrics into $LOG_DIR
Paul Duffinf4906562022-11-05 14:21:16 +0000710func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400711 for _, event := range eventHandler.CompletedEvents() {
usta4f5d2c12022-10-28 23:32:01 -0400712 codegenMetrics.AddEvent(&bp2build_metrics_proto.Event{
713 Name: event.Id,
714 StartTime: uint64(event.Start.UnixNano()),
715 RealTime: event.RuntimeNanoseconds(),
716 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400717 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500718 if len(metricsDir) < 1 {
719 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
720 os.Exit(1)
721 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400722 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500723}
MarkDacek0d5bca52022-10-10 20:07:48 +0000724
725func readBazelPaths(configuration android.Config) ([]string, error) {
726 depsPath := configuration.Getenv("BAZEL_DEPS_FILE")
727
728 data, err := os.ReadFile(depsPath)
729 if err != nil {
730 return nil, err
731 }
732 paths := strings.Split(strings.TrimSpace(string(data)), "\n")
733 return paths, nil
734}