blob: 9f00fc3381c39613db9008529bbbc3058b9ecd71 [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")
91 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 +020092
93 // Flags that probably shouldn't be flags of soong_build but we haven't found
94 // the time to remove them yet
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020095 flag.BoolVar(&runGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070096
97 // Disable deterministic randomization in the protobuf package, so incremental
98 // builds with unrelated Soong changes don't trigger large rebuilds (since we
99 // write out text protos in command lines, and command line changes trigger
100 // rebuilds).
101 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -0800102}
103
Jeff Gaston088e29e2017-11-29 16:47:17 -0800104func newNameResolver(config android.Config) *android.NameResolver {
105 namespacePathsToExport := make(map[string]bool)
106
Dan Willemsen3fb1fae2018-03-12 15:30:26 -0700107 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800108 namespacePathsToExport[namespaceName] = true
109 }
110
111 namespacePathsToExport["."] = true // always export the root namespace
112
113 exportFilter := func(namespace *android.Namespace) bool {
114 return namespacePathsToExport[namespace.Path]
115 }
116
117 return android.NewNameResolver(exportFilter)
118}
119
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200120func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700121 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500122 ctx.Register()
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400123 ctx.SetNameInterface(newNameResolver(configuration))
124 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
125 return ctx
126}
127
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200128func newConfig(availableEnv map[string]string) android.Config {
Chris Parsonsad876012022-08-20 14:48:32 -0400129 var buildMode android.SoongBuildMode
130
131 if bp2buildMarker != "" {
132 buildMode = android.Bp2build
133 } else if bazelQueryViewDir != "" {
134 buildMode = android.GenerateQueryView
Spandan Das5af0bd32022-09-28 20:43:08 +0000135 } else if bazelApiBp2buildDir != "" {
136 buildMode = android.ApiBp2build
Chris Parsonsad876012022-08-20 14:48:32 -0400137 } else if moduleGraphFile != "" {
138 buildMode = android.GenerateModuleGraph
139 } else if docFile != "" {
140 buildMode = android.GenerateDocFile
Chris Parsonsef615e52022-08-18 22:04:11 -0400141 } else if cmdlineArgs.BazelModeDev {
142 buildMode = android.BazelDevMode
143 } else if cmdlineArgs.BazelMode {
144 buildMode = android.BazelProdMode
Chris Parsonsad876012022-08-20 14:48:32 -0400145 } else {
146 buildMode = android.AnalysisNoBazel
147 }
148
149 configuration, err := android.NewConfig(cmdlineArgs.ModuleListFile, buildMode, runGoTests, outDir, soongOutDir, availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400150 if err != nil {
151 fmt.Fprintf(os.Stderr, "%s", err)
152 os.Exit(1)
153 }
154 return configuration
155}
156
Chris Parsonsf874e462022-05-10 13:50:12 -0400157// Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
158// BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
159// for modules that should be handled by Bazel.
160func runMixedModeBuild(configuration android.Config, ctx *android.Context, extraNinjaDeps []string) {
161 ctx.EventHandler.Begin("mixed_build")
162 defer ctx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200163
Chris Parsonsf874e462022-05-10 13:50:12 -0400164 bazelHook := func() error {
165 ctx.EventHandler.Begin("bazel")
166 defer ctx.EventHandler.End("bazel")
Yu Liu8d82ac52022-05-17 15:13:28 -0700167 return configuration.BazelContext.InvokeBazel(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200168 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400169 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Chris Parsons715b08f2022-03-22 19:23:40 -0400170
Chris Parsonsf874e462022-05-10 13:50:12 -0400171 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, bootstrap.DoEverything, ctx.Context, configuration)
Chris Parsons027881c2022-05-24 15:38:38 -0400172 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200173
Chris Parsonsf874e462022-05-10 13:50:12 -0400174 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200175 ninjaDeps = append(ninjaDeps, globListFiles...)
176
Chris Parsonsf874e462022-05-10 13:50:12 -0400177 writeDepFile(cmdlineArgs.OutFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200178}
179
180// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200181func runQueryView(queryviewDir, queryviewMarker string, configuration android.Config, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400182 ctx.EventHandler.Begin("queryview")
183 defer ctx.EventHandler.End("queryview")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200184 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200185 absoluteQueryViewDir := shared.JoinPath(topDir, queryviewDir)
Spandan Das5af0bd32022-09-28 20:43:08 +0000186 if err := createBazelWorkspace(codegenContext, absoluteQueryViewDir); err != nil {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200187 fmt.Fprintf(os.Stderr, "%s", err)
188 os.Exit(1)
189 }
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200190
191 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200192}
193
Spandan Das5af0bd32022-09-28 20:43:08 +0000194// Run the code-generation phase to convert API contributions to BUILD files.
195// Return marker file for the new synthetic workspace
196func runApiBp2build(configuration android.Config, extraNinjaDeps []string) string {
197 // Create a new context and register mutators that are only meaningful to API export
198 ctx := android.NewContext(configuration)
199 ctx.EventHandler.Begin("api_bp2build")
200 defer ctx.EventHandler.End("api_bp2build")
201 ctx.SetNameInterface(newNameResolver(configuration))
202 ctx.RegisterForApiBazelConversion()
203
204 // Register the Android.bp files in the tree
205 // Add them to the workspace's .d file
206 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
207 if paths, err := ctx.ListModulePaths("."); err == nil {
208 extraNinjaDeps = append(extraNinjaDeps, paths...)
209 } else {
210 panic(err)
211 }
212
213 // Run the loading and analysis phase
214 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs,
215 bootstrap.StopBeforePrepareBuildActions,
216 ctx.Context,
217 configuration)
218 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
219
220 // Add the globbed dependencies
221 globs := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
222 ninjaDeps = append(ninjaDeps, globs...)
223
224 // Run codegen to generate BUILD files
225 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.ApiBp2build)
226 absoluteApiBp2buildDir := shared.JoinPath(topDir, bazelApiBp2buildDir)
227 if err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir); err != nil {
228 fmt.Fprintf(os.Stderr, "%s", err)
229 os.Exit(1)
230 }
231 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
232
233 // Create soong_injection repository
234 soongInjectionFiles := bp2build.CreateSoongInjectionFiles(configuration, bp2build.CodegenMetrics{})
235 absoluteSoongInjectionDir := shared.JoinPath(topDir, configuration.SoongOutDir(), bazel.SoongInjectionDirName)
236 for _, file := range soongInjectionFiles {
237 writeReadOnlyFile(absoluteSoongInjectionDir, file)
238 }
239
240 workspace := shared.JoinPath(configuration.SoongOutDir(), "api_bp2build")
241
242 excludes := bazelArtifacts()
243 // Exclude all src BUILD files
244 excludes = append(excludes, apiBuildFileExcludes()...)
245
246 // Create the symlink forest
247 symlinkDeps := bp2build.PlantSymlinkForest(
248 configuration,
249 topDir,
250 workspace,
251 bazelApiBp2buildDir,
252 ".",
253 excludes)
254 ninjaDeps = append(ninjaDeps, symlinkDeps...)
255
256 workspaceMarkerFile := workspace + ".marker"
257 writeDepFile(workspaceMarkerFile, *ctx.EventHandler, ninjaDeps)
258 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
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700284func 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
Chris Parsons715b08f2022-03-22 19:23:40 -0400324func writeDepFile(outputFile string, eventHandler metrics.EventHandler, ninjaDeps []string) {
325 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.
ustacd245f72022-08-24 11:45:19 -0400338func doChosenActivity(ctx *android.Context, configuration android.Config, extraNinjaDeps []string) string {
Chris Parsonsad876012022-08-20 14:48:32 -0400339 if configuration.BuildMode == android.Bp2build {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200340 // Run the alternate pipeline of bp2build mutators and singleton to convert
341 // Blueprint to BUILD files before everything else.
342 runBp2Build(configuration, extraNinjaDeps)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000343 return bp2buildMarker
Chris Parsonsad876012022-08-20 14:48:32 -0400344 } else if configuration.IsMixedBuildsEnabled() {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200345 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000346 } else if configuration.BuildMode == android.ApiBp2build {
347 return runApiBp2build(configuration, extraNinjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200348 } else {
Chris Parsons715b08f2022-03-22 19:23:40 -0400349 var stopBefore bootstrap.StopBefore
Chris Parsonsad876012022-08-20 14:48:32 -0400350 if configuration.BuildMode == android.GenerateModuleGraph {
Chris Parsons715b08f2022-03-22 19:23:40 -0400351 stopBefore = bootstrap.StopBeforeWriteNinja
Chris Parsonsad876012022-08-20 14:48:32 -0400352 } else if configuration.BuildMode == android.GenerateQueryView || configuration.BuildMode == android.GenerateDocFile {
Chris Parsons715b08f2022-03-22 19:23:40 -0400353 stopBefore = bootstrap.StopBeforePrepareBuildActions
354 } else {
355 stopBefore = bootstrap.DoEverything
356 }
357
Chris Parsonsad876012022-08-20 14:48:32 -0400358 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, stopBefore, ctx.Context, configuration)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200359 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200360
Chris Parsons715b08f2022-03-22 19:23:40 -0400361 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200362 ninjaDeps = append(ninjaDeps, globListFiles...)
363
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200364 // Convert the Soong module graph into Bazel BUILD files.
Chris Parsonsad876012022-08-20 14:48:32 -0400365 if configuration.BuildMode == android.GenerateQueryView {
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200366 queryviewMarkerFile := bazelQueryViewDir + ".marker"
367 runQueryView(bazelQueryViewDir, queryviewMarkerFile, configuration, ctx)
Chris Parsons715b08f2022-03-22 19:23:40 -0400368 writeDepFile(queryviewMarkerFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200369 return queryviewMarkerFile
Chris Parsonsad876012022-08-20 14:48:32 -0400370 } else if configuration.BuildMode == android.GenerateModuleGraph {
kgui67007242022-01-25 13:50:25 +0800371 writeJsonModuleGraphAndActions(ctx, moduleGraphFile, moduleActionsFile)
Chris Parsons715b08f2022-03-22 19:23:40 -0400372 writeDepFile(moduleGraphFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200373 return moduleGraphFile
Chris Parsonsad876012022-08-20 14:48:32 -0400374 } else if configuration.BuildMode == android.GenerateDocFile {
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200375 // TODO: we could make writeDocs() return the list of documentation files
376 // written and add them to the .d file. Then soong_docs would be re-run
377 // whenever one is deleted.
378 if err := writeDocs(ctx, shared.JoinPath(topDir, docFile)); err != nil {
379 fmt.Fprintf(os.Stderr, "error building Soong documentation: %s\n", err)
380 os.Exit(1)
381 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400382 writeDepFile(docFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200383 return docFile
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200384 } else {
385 // The actual output (build.ninja) was written in the RunBlueprint() call
386 // above
Chris Parsons715b08f2022-03-22 19:23:40 -0400387 writeDepFile(cmdlineArgs.OutFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200388 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200389 }
390
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200391 return cmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200392}
393
394// soong_ui dumps the available environment variables to
395// soong.environment.available . Then soong_build itself is run with an empty
396// environment so that the only way environment variables can be accessed is
397// using Config, which tracks access to them.
398
399// At the end of the build, a file called soong.environment.used is written
400// containing the current value of all used environment variables. The next
401// time soong_ui is run, it checks whether any environment variables that was
402// used had changed and if so, it deletes soong.environment.used to cause a
403// rebuild.
404//
405// The dependency of build.ninja on soong.environment.used is declared in
406// build.ninja.d
407func parseAvailableEnv() map[string]string {
408 if availableEnvFile == "" {
409 fmt.Fprintf(os.Stderr, "--available_env not set\n")
410 os.Exit(1)
411 }
412
413 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
414 if err != nil {
415 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
416 os.Exit(1)
417 }
418
419 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200420}
421
Colin Cross3f40fa42015-01-30 17:27:36 -0800422func main() {
423 flag.Parse()
424
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100425 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100426 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100427
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200428 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200429
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200430 configuration := newConfig(availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100431 extraNinjaDeps := []string{
432 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200433 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100434 }
Colin Crossaa812d12019-06-19 13:33:24 -0700435
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100436 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
437 configuration.SetAllowMissingDependencies()
438 }
439
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100440 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700441 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
442 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200443 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700444 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500445
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700446 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
447 // change between every CI build, so tracking it would require re-running Soong for every build.
448 logDir := availableEnv["LOG_DIR"]
449
Joe Onorato2e5e4012022-06-07 17:16:08 -0700450 ctx := newContext(configuration)
451 ctx.EventHandler.Begin("soong_build")
452
ustacd245f72022-08-24 11:45:19 -0400453 finalOutputFile := doChosenActivity(ctx, configuration, extraNinjaDeps)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700454
455 ctx.EventHandler.End("soong_build")
456 writeMetrics(configuration, *ctx.EventHandler, logDir)
Chris Parsons715b08f2022-03-22 19:23:40 -0400457
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200458 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100459}
460
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200461func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
462 if usedEnvFile == "" {
463 return
464 }
465
466 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100467 data, err := shared.EnvFileContents(configuration.EnvDeps())
468 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200469 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100470 os.Exit(1)
471 }
472
473 err = ioutil.WriteFile(path, data, 0666)
474 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200475 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100476 os.Exit(1)
477 }
478
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200479 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100480 // wrote. We can't write the environment file earlier because one an access
481 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200482 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800483}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000484
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200485func touch(path string) {
486 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
487 if err != nil {
488 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
489 os.Exit(1)
490 }
491
492 err = f.Close()
493 if err != nil {
494 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
495 os.Exit(1)
496 }
497
498 currentTime := time.Now().Local()
499 err = os.Chtimes(path, currentTime, currentTime)
500 if err != nil {
501 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
502 os.Exit(1)
503 }
504}
505
Cole Faust324a92e2022-08-23 15:29:05 -0700506// Find BUILD files in the srcDir which are not in the allowlist
507// (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
508// and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
509func getPathsToIgnoredBuildFiles(config android.Bp2BuildConversionAllowlist, topDir string, srcDirBazelFiles []string, verbose bool) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400510 paths := make([]string, 0)
511
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400512 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
513 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
514 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400515 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400516 // Warn about error, but continue trying to check files
517 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
518 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400519 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400520 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400521 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400522 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400523 }
Cole Faust324a92e2022-08-23 15:29:05 -0700524 if fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel" {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400525 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400526 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400527 }
Cole Faust324a92e2022-08-23 15:29:05 -0700528 if config.ShouldKeepExistingBuildFileForDir(filepath.Dir(srcDirBazelFileRelativePath)) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400529 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400530 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400531 }
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400532 if verbose {
533 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
534 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400535 paths = append(paths, srcDirBazelFileRelativePath)
536 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400537
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400538 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400539}
540
541// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
542func getTemporaryExcludes() []string {
543 excludes := make([]string, 0)
544
545 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
546 excludes = append(excludes, "external/autotest/venv/autotest_lib")
Jingwen Chenc0c50212022-06-07 10:07:22 +0000547 excludes = append(excludes, "external/autotest/autotest_lib")
548 excludes = append(excludes, "external/autotest/client/autotest_lib/client")
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400549
550 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
551 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
552 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
553
554 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
555 excludes = append(excludes, "frameworks/compile/slang")
556
557 return excludes
558}
559
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400560// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
561// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
562func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200563 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400564 if !filepath.IsAbs(bazelFinderFile) {
565 // Assume this was a relative path under topDir
566 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
567 }
568 data, err := ioutil.ReadFile(bazelFinderFile)
569 if err != nil {
570 return nil, err
571 }
572 files := strings.Split(strings.TrimSpace(string(data)), "\n")
573 return files, nil
574}
575
Spandan Das5af0bd32022-09-28 20:43:08 +0000576func bazelArtifacts() []string {
577 return []string{
578 "bazel-bin",
579 "bazel-genfiles",
580 "bazel-out",
581 "bazel-testlogs",
582 "bazel-" + filepath.Base(topDir),
583 }
584}
585
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500586// Run Soong in the bp2build mode. This creates a standalone context that registers
587// an alternate pipeline of mutators and singletons specifically for generating
588// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200589func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Usta Shresthaa117c582022-10-04 12:13:25 -0400590 var codegenMetrics bp2build.CodegenMetrics
Chris Parsons715b08f2022-03-22 19:23:40 -0400591 eventHandler := metrics.EventHandler{}
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400592 eventHandler.Do("bp2build", func() {
Chris Parsons715b08f2022-03-22 19:23:40 -0400593
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400594 // Register an alternate set of singletons and mutators for bazel
595 // conversion for Bazel conversion.
596 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500597
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400598 // Propagate "allow misssing dependencies" bit. This is normally set in
599 // newContext(), but we create bp2buildCtx without calling that method.
600 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
601 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
602 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500603
Usta Shresthaa117c582022-10-04 12:13:25 -0400604 var ninjaDeps []string
605 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
606
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400607 // The bp2build process is a purely functional process that only depends on
608 // Android.bp files. It must not depend on the values of per-build product
609 // configurations or variables, since those will generate different BUILD
610 // files based on how the user has configured their tree.
611 bp2buildCtx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Usta Shresthaa117c582022-10-04 12:13:25 -0400612 if modulePaths, err := bp2buildCtx.ListModulePaths("."); err != nil {
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400613 panic(err)
Usta Shresthaa117c582022-10-04 12:13:25 -0400614 } else {
615 ninjaDeps = append(ninjaDeps, modulePaths...)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400616 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500617
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400618 // Run the loading and analysis pipeline to prepare the graph of regular
619 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
620 // from the regular Modules.
Usta Shresthaa117c582022-10-04 12:13:25 -0400621 eventHandler.Do("bootstrap", func() {
622 blueprintArgs := cmdlineArgs
623 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.StopBeforePrepareBuildActions, bp2buildCtx.Context, configuration)
624 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
625 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200626
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400627 globListFiles := writeBuildGlobsNinjaFile(bp2buildCtx, configuration.SoongOutDir(), configuration)
628 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200629
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400630 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400631 // and print conversion codegenMetrics to the user.
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400632 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
Usta Shresthaa117c582022-10-04 12:13:25 -0400633 eventHandler.Do("codegen", func() {
634 codegenMetrics = bp2build.Codegen(codegenContext)
635 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200636
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400637 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
638 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200639
Spandan Das5af0bd32022-09-28 20:43:08 +0000640 excludes := bazelArtifacts()
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200641
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400642 if outDir[0] != '/' {
643 excludes = append(excludes, outDir)
644 }
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200645
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400646 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
647 if err != nil {
648 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
649 os.Exit(1)
650 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400651
Cole Faust324a92e2022-08-23 15:29:05 -0700652 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(configuration.Bp2buildPackageConfig, topDir, existingBazelRelatedFiles, configuration.IsEnvTrue("BP2BUILD_VERBOSE"))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400653 excludes = append(excludes, pathsToIgnoredBuildFiles...)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400654
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400655 excludes = append(excludes, getTemporaryExcludes()...)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400656
Usta Shresthaa117c582022-10-04 12:13:25 -0400657 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
658 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
659 // or file created/deleted under it would trigger an update of the symlink
660 // forest.
661 eventHandler.Do("symlink_forest", func() {
662 symlinkForestDeps := bp2build.PlantSymlinkForest(
663 configuration, topDir, workspaceRoot, generatedRoot, ".", excludes)
664 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
665 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200666
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400667 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400668
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400669 writeDepFile(bp2buildMarker, eventHandler, ninjaDeps)
Chris Parsons715b08f2022-03-22 19:23:40 -0400670
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400671 // Create an empty bp2build marker file.
672 touch(shared.JoinPath(topDir, bp2buildMarker))
673 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400674
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200675 // Only report metrics when in bp2build mode. The metrics aren't relevant
676 // for queryview, since that's a total repo-wide conversion and there's a
677 // 1:1 mapping for each module.
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700678 if configuration.IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400679 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700680 }
Usta Shresthaa117c582022-10-04 12:13:25 -0400681 writeBp2BuildMetrics(&codegenMetrics, configuration, eventHandler)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500682}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500683
684// Write Bp2Build metrics into $LOG_DIR
Chris Parsons715b08f2022-03-22 19:23:40 -0400685func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics,
686 configuration android.Config, eventHandler metrics.EventHandler) {
687 for _, event := range eventHandler.CompletedEvents() {
688 codegenMetrics.Events = append(codegenMetrics.Events,
689 &bp2build_metrics_proto.Event{
690 Name: event.Id,
691 StartTime: uint64(event.Start.UnixNano()),
692 RealTime: event.RuntimeNanoseconds(),
693 })
694 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500695 metricsDir := configuration.Getenv("LOG_DIR")
696 if len(metricsDir) < 1 {
697 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
698 os.Exit(1)
699 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400700 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500701}