blob: 70f58f597763b33d7f7cdfa1e6972efd65c453eb [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"
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +010020 "io/ioutil"
Colin Cross3f40fa42015-01-30 17:27:36 -080021 "os"
22 "path/filepath"
Jingwen Cheneb76c432021-01-28 08:22:12 -050023 "strings"
Lukacs T. Berkic99c9472021-03-24 10:50:06 +010024 "time"
Colin Cross3f40fa42015-01-30 17:27:36 -080025
Dan Willemsen66213a62021-09-21 17:50:30 -070026 "android/soong/android"
Spandan Das5af0bd32022-09-28 20:43:08 +000027 "android/soong/bazel"
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020028 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010029 "android/soong/shared"
Chris Parsons715b08f2022-03-22 19:23:40 -040030 "android/soong/ui/metrics/bp2build_metrics_proto"
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020031
Colin Cross70b40592015-03-23 12:57:34 -070032 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020033 "github.com/google/blueprint/deptools"
Chris Parsons715b08f2022-03-22 19:23:40 -040034 "github.com/google/blueprint/metrics"
Dan Willemsen66213a62021-09-21 17:50:30 -070035 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080036)
37
Colin Crosse87040b2017-12-11 15:52:26 -080038var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020039 topDir string
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020040 outDir string
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020041 soongOutDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020042 availableEnvFile string
43 usedEnvFile string
44
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020045 runGoTests bool
46
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020047 globFile string
48 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020049 delveListen string
50 delvePath string
51
Spandan Das5af0bd32022-09-28 20:43:08 +000052 moduleGraphFile string
53 moduleActionsFile string
54 docFile string
55 bazelQueryViewDir string
56 bazelApiBp2buildDir string
57 bp2buildMarker string
Lukacs T. Berkif9008072021-08-16 15:24:48 +020058
59 cmdlineArgs bootstrap.Args
Colin Crosse87040b2017-12-11 15:52:26 -080060)
61
62func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020063 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010064 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020065 flag.StringVar(&soongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020066 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
67 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020068 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
69 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020070 flag.StringVar(&outDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020071 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020072
73 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010074 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
75 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020076 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
77 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
78 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
79 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020080
81 // Flags representing various modes soong_build can run in
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020082 flag.StringVar(&moduleGraphFile, "module_graph_file", "", "JSON module graph file to output")
kgui67007242022-01-25 13:50:25 +080083 flag.StringVar(&moduleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
Colin Crosse87040b2017-12-11 15:52:26 -080084 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010085 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Spandan Das5af0bd32022-09-28 20:43:08 +000086 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 +020087 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020088 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020089 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
Chris Parsonsef615e52022-08-18 22:04:11 -040090 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
MarkDacekb78465d2022-10-18 20:10:16 +000091 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
Chris Parsonsef615e52022-08-18 22:04:11 -040092 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 +020093
94 // Flags that probably shouldn't be flags of soong_build but we haven't found
95 // the time to remove them yet
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020096 flag.BoolVar(&runGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070097
98 // Disable deterministic randomization in the protobuf package, so incremental
99 // builds with unrelated Soong changes don't trigger large rebuilds (since we
100 // write out text protos in command lines, and command line changes trigger
101 // rebuilds).
102 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -0800103}
104
Jeff Gaston088e29e2017-11-29 16:47:17 -0800105func newNameResolver(config android.Config) *android.NameResolver {
106 namespacePathsToExport := make(map[string]bool)
107
Dan Willemsen3fb1fae2018-03-12 15:30:26 -0700108 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800109 namespacePathsToExport[namespaceName] = true
110 }
111
112 namespacePathsToExport["."] = true // always export the root namespace
113
114 exportFilter := func(namespace *android.Namespace) bool {
115 return namespacePathsToExport[namespace.Path]
116 }
117
118 return android.NewNameResolver(exportFilter)
119}
120
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200121func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700122 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500123 ctx.Register()
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400124 ctx.SetNameInterface(newNameResolver(configuration))
125 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
126 return ctx
127}
128
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200129func newConfig(availableEnv map[string]string) android.Config {
Chris Parsonsad876012022-08-20 14:48:32 -0400130 var buildMode android.SoongBuildMode
131
132 if bp2buildMarker != "" {
133 buildMode = android.Bp2build
134 } else if bazelQueryViewDir != "" {
135 buildMode = android.GenerateQueryView
Spandan Das5af0bd32022-09-28 20:43:08 +0000136 } else if bazelApiBp2buildDir != "" {
137 buildMode = android.ApiBp2build
Chris Parsonsad876012022-08-20 14:48:32 -0400138 } else if moduleGraphFile != "" {
139 buildMode = android.GenerateModuleGraph
140 } else if docFile != "" {
141 buildMode = android.GenerateDocFile
Chris Parsonsef615e52022-08-18 22:04:11 -0400142 } else if cmdlineArgs.BazelModeDev {
143 buildMode = android.BazelDevMode
144 } else if cmdlineArgs.BazelMode {
145 buildMode = android.BazelProdMode
MarkDacekb78465d2022-10-18 20:10:16 +0000146 } else if cmdlineArgs.BazelModeStaging {
147 buildMode = android.BazelStagingMode
Chris Parsonsad876012022-08-20 14:48:32 -0400148 } else {
149 buildMode = android.AnalysisNoBazel
150 }
151
152 configuration, err := android.NewConfig(cmdlineArgs.ModuleListFile, buildMode, runGoTests, outDir, soongOutDir, availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400153 if err != nil {
154 fmt.Fprintf(os.Stderr, "%s", err)
155 os.Exit(1)
156 }
157 return configuration
158}
159
Chris Parsonsf874e462022-05-10 13:50:12 -0400160// Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
161// BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
162// for modules that should be handled by Bazel.
163func runMixedModeBuild(configuration android.Config, ctx *android.Context, extraNinjaDeps []string) {
164 ctx.EventHandler.Begin("mixed_build")
165 defer ctx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200166
Chris Parsonsf874e462022-05-10 13:50:12 -0400167 bazelHook := func() error {
168 ctx.EventHandler.Begin("bazel")
169 defer ctx.EventHandler.End("bazel")
Yu Liu8d82ac52022-05-17 15:13:28 -0700170 return configuration.BazelContext.InvokeBazel(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200171 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400172 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Chris Parsonsf874e462022-05-10 13:50:12 -0400173 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, bootstrap.DoEverything, ctx.Context, configuration)
Chris Parsons027881c2022-05-24 15:38:38 -0400174 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200175
MarkDacek0d5bca52022-10-10 20:07:48 +0000176 bazelPaths, err := readBazelPaths(configuration)
177 if err != nil {
178 panic("Bazel deps file not found: " + err.Error())
179 }
180 ninjaDeps = append(ninjaDeps, bazelPaths...)
181
Chris Parsonsf874e462022-05-10 13:50:12 -0400182 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200183 ninjaDeps = append(ninjaDeps, globListFiles...)
184
Chris Parsonsf874e462022-05-10 13:50:12 -0400185 writeDepFile(cmdlineArgs.OutFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200186}
187
188// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200189func runQueryView(queryviewDir, queryviewMarker string, configuration android.Config, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400190 ctx.EventHandler.Begin("queryview")
191 defer ctx.EventHandler.End("queryview")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200192 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200193 absoluteQueryViewDir := shared.JoinPath(topDir, queryviewDir)
Spandan Das5af0bd32022-09-28 20:43:08 +0000194 if err := createBazelWorkspace(codegenContext, absoluteQueryViewDir); err != nil {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200195 fmt.Fprintf(os.Stderr, "%s", err)
196 os.Exit(1)
197 }
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200198
199 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200200}
201
Spandan Das5af0bd32022-09-28 20:43:08 +0000202// Run the code-generation phase to convert API contributions to BUILD files.
203// Return marker file for the new synthetic workspace
204func runApiBp2build(configuration android.Config, extraNinjaDeps []string) string {
205 // Create a new context and register mutators that are only meaningful to API export
206 ctx := android.NewContext(configuration)
207 ctx.EventHandler.Begin("api_bp2build")
208 defer ctx.EventHandler.End("api_bp2build")
209 ctx.SetNameInterface(newNameResolver(configuration))
210 ctx.RegisterForApiBazelConversion()
211
212 // Register the Android.bp files in the tree
213 // Add them to the workspace's .d file
214 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
215 if paths, err := ctx.ListModulePaths("."); err == nil {
216 extraNinjaDeps = append(extraNinjaDeps, paths...)
217 } else {
218 panic(err)
219 }
220
221 // Run the loading and analysis phase
222 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs,
223 bootstrap.StopBeforePrepareBuildActions,
224 ctx.Context,
225 configuration)
226 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
227
228 // Add the globbed dependencies
229 globs := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
230 ninjaDeps = append(ninjaDeps, globs...)
231
232 // Run codegen to generate BUILD files
233 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.ApiBp2build)
234 absoluteApiBp2buildDir := shared.JoinPath(topDir, bazelApiBp2buildDir)
235 if err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir); err != nil {
236 fmt.Fprintf(os.Stderr, "%s", err)
237 os.Exit(1)
238 }
239 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
240
241 // Create soong_injection repository
242 soongInjectionFiles := bp2build.CreateSoongInjectionFiles(configuration, bp2build.CodegenMetrics{})
243 absoluteSoongInjectionDir := shared.JoinPath(topDir, configuration.SoongOutDir(), bazel.SoongInjectionDirName)
244 for _, file := range soongInjectionFiles {
245 writeReadOnlyFile(absoluteSoongInjectionDir, file)
246 }
247
248 workspace := shared.JoinPath(configuration.SoongOutDir(), "api_bp2build")
249
250 excludes := bazelArtifacts()
251 // Exclude all src BUILD files
252 excludes = append(excludes, apiBuildFileExcludes()...)
253
254 // Create the symlink forest
255 symlinkDeps := bp2build.PlantSymlinkForest(
256 configuration,
257 topDir,
258 workspace,
259 bazelApiBp2buildDir,
260 ".",
261 excludes)
262 ninjaDeps = append(ninjaDeps, symlinkDeps...)
263
264 workspaceMarkerFile := workspace + ".marker"
265 writeDepFile(workspaceMarkerFile, *ctx.EventHandler, ninjaDeps)
266 touch(shared.JoinPath(topDir, workspaceMarkerFile))
267 return workspaceMarkerFile
268}
269
270// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
271// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
272func apiBuildFileExcludes() []string {
273 ret := make([]string, 0)
274
275 srcs, err := getExistingBazelRelatedFiles(topDir)
276 if err != nil {
277 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
278 os.Exit(1)
279 }
280 for _, src := range srcs {
281 if src != "WORKSPACE" &&
282 src != "BUILD" &&
283 src != "BUILD.bazel" &&
284 !strings.HasPrefix(src, "build/bazel") &&
285 !strings.HasPrefix(src, "prebuilts/clang") {
286 ret = append(ret, src)
287 }
288 }
289 return ret
290}
291
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700292func writeMetrics(configuration android.Config, eventHandler metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400293 if len(metricsDir) < 1 {
294 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
295 os.Exit(1)
296 }
297 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
298 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200299 if err != nil {
300 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
301 os.Exit(1)
302 }
303}
304
kgui67007242022-01-25 13:50:25 +0800305func writeJsonModuleGraphAndActions(ctx *android.Context, graphPath string, actionsPath string) {
306 graphFile, graphErr := os.Create(shared.JoinPath(topDir, graphPath))
307 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, actionsPath))
308 if graphErr != nil || actionsErr != nil {
309 fmt.Fprintf(os.Stderr, "Graph err: %s, actions err: %s", graphErr, actionsErr)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200310 os.Exit(1)
311 }
312
kgui67007242022-01-25 13:50:25 +0800313 defer graphFile.Close()
314 defer actionsFile.Close()
315 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200316}
317
Chris Parsons715b08f2022-03-22 19:23:40 -0400318func writeBuildGlobsNinjaFile(ctx *android.Context, buildDir string, config interface{}) []string {
319 ctx.EventHandler.Begin("globs_ninja_file")
320 defer ctx.EventHandler.End("globs_ninja_file")
321
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200322 globDir := bootstrap.GlobDirectory(buildDir, globListDir)
323 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400324 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200325 GlobFile: globFile,
326 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400327 SrcDir: ctx.SrcDir(),
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200328 }, config)
329 return bootstrap.GlobFileListFiles(globDir)
330}
331
Chris Parsons715b08f2022-03-22 19:23:40 -0400332func writeDepFile(outputFile string, eventHandler metrics.EventHandler, ninjaDeps []string) {
333 eventHandler.Begin("ninja_deps")
334 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200335 depFile := shared.JoinPath(topDir, outputFile+".d")
336 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
337 if err != nil {
338 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", depFile, err)
339 os.Exit(1)
340 }
341}
342
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000343// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
344// or the actual Soong build for the build.ninja file. Returns the top level
345// output file of the specific activity.
ustacd245f72022-08-24 11:45:19 -0400346func doChosenActivity(ctx *android.Context, configuration android.Config, extraNinjaDeps []string) string {
Chris Parsonsad876012022-08-20 14:48:32 -0400347 if configuration.BuildMode == android.Bp2build {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200348 // Run the alternate pipeline of bp2build mutators and singleton to convert
349 // Blueprint to BUILD files before everything else.
350 runBp2Build(configuration, extraNinjaDeps)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000351 return bp2buildMarker
Chris Parsonsad876012022-08-20 14:48:32 -0400352 } else if configuration.IsMixedBuildsEnabled() {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200353 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000354 } else if configuration.BuildMode == android.ApiBp2build {
355 return runApiBp2build(configuration, extraNinjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200356 } else {
Chris Parsons715b08f2022-03-22 19:23:40 -0400357 var stopBefore bootstrap.StopBefore
Chris Parsonsad876012022-08-20 14:48:32 -0400358 if configuration.BuildMode == android.GenerateModuleGraph {
Chris Parsons715b08f2022-03-22 19:23:40 -0400359 stopBefore = bootstrap.StopBeforeWriteNinja
Chris Parsonsad876012022-08-20 14:48:32 -0400360 } else if configuration.BuildMode == android.GenerateQueryView || configuration.BuildMode == android.GenerateDocFile {
Chris Parsons715b08f2022-03-22 19:23:40 -0400361 stopBefore = bootstrap.StopBeforePrepareBuildActions
362 } else {
363 stopBefore = bootstrap.DoEverything
364 }
365
Chris Parsonsad876012022-08-20 14:48:32 -0400366 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, stopBefore, ctx.Context, configuration)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200367 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200368
Chris Parsons715b08f2022-03-22 19:23:40 -0400369 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200370 ninjaDeps = append(ninjaDeps, globListFiles...)
371
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200372 // Convert the Soong module graph into Bazel BUILD files.
Chris Parsonsad876012022-08-20 14:48:32 -0400373 if configuration.BuildMode == android.GenerateQueryView {
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200374 queryviewMarkerFile := bazelQueryViewDir + ".marker"
375 runQueryView(bazelQueryViewDir, queryviewMarkerFile, configuration, ctx)
Chris Parsons715b08f2022-03-22 19:23:40 -0400376 writeDepFile(queryviewMarkerFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200377 return queryviewMarkerFile
Chris Parsonsad876012022-08-20 14:48:32 -0400378 } else if configuration.BuildMode == android.GenerateModuleGraph {
kgui67007242022-01-25 13:50:25 +0800379 writeJsonModuleGraphAndActions(ctx, moduleGraphFile, moduleActionsFile)
Chris Parsons715b08f2022-03-22 19:23:40 -0400380 writeDepFile(moduleGraphFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200381 return moduleGraphFile
Chris Parsonsad876012022-08-20 14:48:32 -0400382 } else if configuration.BuildMode == android.GenerateDocFile {
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200383 // TODO: we could make writeDocs() return the list of documentation files
384 // written and add them to the .d file. Then soong_docs would be re-run
385 // whenever one is deleted.
386 if err := writeDocs(ctx, shared.JoinPath(topDir, docFile)); err != nil {
387 fmt.Fprintf(os.Stderr, "error building Soong documentation: %s\n", err)
388 os.Exit(1)
389 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400390 writeDepFile(docFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200391 return docFile
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200392 } else {
393 // The actual output (build.ninja) was written in the RunBlueprint() call
394 // above
Chris Parsons715b08f2022-03-22 19:23:40 -0400395 writeDepFile(cmdlineArgs.OutFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200396 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200397 }
398
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200399 return cmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200400}
401
402// soong_ui dumps the available environment variables to
403// soong.environment.available . Then soong_build itself is run with an empty
404// environment so that the only way environment variables can be accessed is
405// using Config, which tracks access to them.
406
407// At the end of the build, a file called soong.environment.used is written
408// containing the current value of all used environment variables. The next
409// time soong_ui is run, it checks whether any environment variables that was
410// used had changed and if so, it deletes soong.environment.used to cause a
411// rebuild.
412//
413// The dependency of build.ninja on soong.environment.used is declared in
414// build.ninja.d
415func parseAvailableEnv() map[string]string {
416 if availableEnvFile == "" {
417 fmt.Fprintf(os.Stderr, "--available_env not set\n")
418 os.Exit(1)
419 }
420
421 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
422 if err != nil {
423 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
424 os.Exit(1)
425 }
426
427 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200428}
429
Colin Cross3f40fa42015-01-30 17:27:36 -0800430func main() {
431 flag.Parse()
432
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100433 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100434 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100435
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200436 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200437
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200438 configuration := newConfig(availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100439 extraNinjaDeps := []string{
440 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200441 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100442 }
Colin Crossaa812d12019-06-19 13:33:24 -0700443
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100444 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
445 configuration.SetAllowMissingDependencies()
446 }
447
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100448 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700449 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
450 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200451 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700452 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500453
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700454 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
455 // change between every CI build, so tracking it would require re-running Soong for every build.
456 logDir := availableEnv["LOG_DIR"]
457
Joe Onorato2e5e4012022-06-07 17:16:08 -0700458 ctx := newContext(configuration)
459 ctx.EventHandler.Begin("soong_build")
460
ustacd245f72022-08-24 11:45:19 -0400461 finalOutputFile := doChosenActivity(ctx, configuration, extraNinjaDeps)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700462
463 ctx.EventHandler.End("soong_build")
464 writeMetrics(configuration, *ctx.EventHandler, logDir)
Chris Parsons715b08f2022-03-22 19:23:40 -0400465
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200466 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100467}
468
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200469func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
470 if usedEnvFile == "" {
471 return
472 }
473
474 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100475 data, err := shared.EnvFileContents(configuration.EnvDeps())
476 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200477 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100478 os.Exit(1)
479 }
480
481 err = ioutil.WriteFile(path, data, 0666)
482 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200483 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100484 os.Exit(1)
485 }
486
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200487 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100488 // wrote. We can't write the environment file earlier because one an access
489 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200490 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800491}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000492
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200493func touch(path string) {
494 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
495 if err != nil {
496 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
497 os.Exit(1)
498 }
499
500 err = f.Close()
501 if err != nil {
502 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
503 os.Exit(1)
504 }
505
506 currentTime := time.Now().Local()
507 err = os.Chtimes(path, currentTime, currentTime)
508 if err != nil {
509 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
510 os.Exit(1)
511 }
512}
513
Cole Faust324a92e2022-08-23 15:29:05 -0700514// Find BUILD files in the srcDir which are not in the allowlist
515// (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
516// and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
517func getPathsToIgnoredBuildFiles(config android.Bp2BuildConversionAllowlist, topDir string, srcDirBazelFiles []string, verbose bool) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400518 paths := make([]string, 0)
519
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400520 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
521 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
522 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400523 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400524 // Warn about error, but continue trying to check files
525 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
526 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400527 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400528 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400529 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400530 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400531 }
Cole Faust324a92e2022-08-23 15:29:05 -0700532 if fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel" {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400533 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400534 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400535 }
Cole Faust324a92e2022-08-23 15:29:05 -0700536 if config.ShouldKeepExistingBuildFileForDir(filepath.Dir(srcDirBazelFileRelativePath)) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400537 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400538 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400539 }
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400540 if verbose {
541 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
542 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400543 paths = append(paths, srcDirBazelFileRelativePath)
544 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400545
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400546 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400547}
548
549// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
550func getTemporaryExcludes() []string {
551 excludes := make([]string, 0)
552
553 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
554 excludes = append(excludes, "external/autotest/venv/autotest_lib")
Jingwen Chenc0c50212022-06-07 10:07:22 +0000555 excludes = append(excludes, "external/autotest/autotest_lib")
556 excludes = append(excludes, "external/autotest/client/autotest_lib/client")
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400557
558 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
559 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
560 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
561
562 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
563 excludes = append(excludes, "frameworks/compile/slang")
564
565 return excludes
566}
567
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400568// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
569// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
570func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200571 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400572 if !filepath.IsAbs(bazelFinderFile) {
573 // Assume this was a relative path under topDir
574 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
575 }
576 data, err := ioutil.ReadFile(bazelFinderFile)
577 if err != nil {
578 return nil, err
579 }
580 files := strings.Split(strings.TrimSpace(string(data)), "\n")
581 return files, nil
582}
583
Spandan Das5af0bd32022-09-28 20:43:08 +0000584func bazelArtifacts() []string {
585 return []string{
586 "bazel-bin",
587 "bazel-genfiles",
588 "bazel-out",
589 "bazel-testlogs",
590 "bazel-" + filepath.Base(topDir),
591 }
592}
593
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500594// Run Soong in the bp2build mode. This creates a standalone context that registers
595// an alternate pipeline of mutators and singletons specifically for generating
596// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200597func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Usta Shresthaa117c582022-10-04 12:13:25 -0400598 var codegenMetrics bp2build.CodegenMetrics
Chris Parsons715b08f2022-03-22 19:23:40 -0400599 eventHandler := metrics.EventHandler{}
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400600 eventHandler.Do("bp2build", func() {
Chris Parsons715b08f2022-03-22 19:23:40 -0400601
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400602 // Register an alternate set of singletons and mutators for bazel
603 // conversion for Bazel conversion.
604 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500605
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400606 // Propagate "allow misssing dependencies" bit. This is normally set in
607 // newContext(), but we create bp2buildCtx without calling that method.
608 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
609 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
610 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500611
Usta Shresthaa117c582022-10-04 12:13:25 -0400612 var ninjaDeps []string
613 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
614
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400615 // The bp2build process is a purely functional process that only depends on
616 // Android.bp files. It must not depend on the values of per-build product
617 // configurations or variables, since those will generate different BUILD
618 // files based on how the user has configured their tree.
619 bp2buildCtx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Usta Shresthaa117c582022-10-04 12:13:25 -0400620 if modulePaths, err := bp2buildCtx.ListModulePaths("."); err != nil {
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400621 panic(err)
Usta Shresthaa117c582022-10-04 12:13:25 -0400622 } else {
623 ninjaDeps = append(ninjaDeps, modulePaths...)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400624 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500625
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400626 // Run the loading and analysis pipeline to prepare the graph of regular
627 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
628 // from the regular Modules.
Usta Shresthaa117c582022-10-04 12:13:25 -0400629 eventHandler.Do("bootstrap", func() {
630 blueprintArgs := cmdlineArgs
631 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.StopBeforePrepareBuildActions, bp2buildCtx.Context, configuration)
632 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
633 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200634
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400635 globListFiles := writeBuildGlobsNinjaFile(bp2buildCtx, configuration.SoongOutDir(), configuration)
636 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200637
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400638 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400639 // and print conversion codegenMetrics to the user.
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400640 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
Usta Shresthaa117c582022-10-04 12:13:25 -0400641 eventHandler.Do("codegen", func() {
642 codegenMetrics = bp2build.Codegen(codegenContext)
643 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200644
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400645 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
646 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200647
Spandan Das5af0bd32022-09-28 20:43:08 +0000648 excludes := bazelArtifacts()
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200649
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400650 if outDir[0] != '/' {
651 excludes = append(excludes, outDir)
652 }
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200653
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400654 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
655 if err != nil {
656 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
657 os.Exit(1)
658 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400659
Cole Faust324a92e2022-08-23 15:29:05 -0700660 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(configuration.Bp2buildPackageConfig, topDir, existingBazelRelatedFiles, configuration.IsEnvTrue("BP2BUILD_VERBOSE"))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400661 excludes = append(excludes, pathsToIgnoredBuildFiles...)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400662
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400663 excludes = append(excludes, getTemporaryExcludes()...)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400664
Usta Shresthaa117c582022-10-04 12:13:25 -0400665 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
666 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
667 // or file created/deleted under it would trigger an update of the symlink
668 // forest.
669 eventHandler.Do("symlink_forest", func() {
670 symlinkForestDeps := bp2build.PlantSymlinkForest(
671 configuration, topDir, workspaceRoot, generatedRoot, ".", excludes)
672 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
673 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200674
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400675 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400676
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400677 writeDepFile(bp2buildMarker, eventHandler, ninjaDeps)
Chris Parsons715b08f2022-03-22 19:23:40 -0400678
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400679 // Create an empty bp2build marker file.
680 touch(shared.JoinPath(topDir, bp2buildMarker))
681 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400682
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200683 // Only report metrics when in bp2build mode. The metrics aren't relevant
684 // for queryview, since that's a total repo-wide conversion and there's a
685 // 1:1 mapping for each module.
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700686 if configuration.IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400687 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700688 }
Usta Shresthaa117c582022-10-04 12:13:25 -0400689 writeBp2BuildMetrics(&codegenMetrics, configuration, eventHandler)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500690}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500691
692// Write Bp2Build metrics into $LOG_DIR
Chris Parsons715b08f2022-03-22 19:23:40 -0400693func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics,
694 configuration android.Config, eventHandler metrics.EventHandler) {
695 for _, event := range eventHandler.CompletedEvents() {
696 codegenMetrics.Events = append(codegenMetrics.Events,
697 &bp2build_metrics_proto.Event{
698 Name: event.Id,
699 StartTime: uint64(event.Start.UnixNano()),
700 RealTime: event.RuntimeNanoseconds(),
701 })
702 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500703 metricsDir := configuration.Getenv("LOG_DIR")
704 if len(metricsDir) < 1 {
705 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
706 os.Exit(1)
707 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400708 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500709}
MarkDacek0d5bca52022-10-10 20:07:48 +0000710
711func readBazelPaths(configuration android.Config) ([]string, error) {
712 depsPath := configuration.Getenv("BAZEL_DEPS_FILE")
713
714 data, err := os.ReadFile(depsPath)
715 if err != nil {
716 return nil, err
717 }
718 paths := strings.Split(strings.TrimSpace(string(data)), "\n")
719 return paths, nil
720}