blob: 0ba25c8846801c37b4a854f2ad64863595037d9c [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 Parsonsf874e462022-05-10 13:50:12 -0400170 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, bootstrap.DoEverything, ctx.Context, configuration)
Chris Parsons027881c2022-05-24 15:38:38 -0400171 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200172
MarkDacek0d5bca52022-10-10 20:07:48 +0000173 bazelPaths, err := readBazelPaths(configuration)
174 if err != nil {
175 panic("Bazel deps file not found: " + err.Error())
176 }
177 ninjaDeps = append(ninjaDeps, bazelPaths...)
178
Chris Parsonsf874e462022-05-10 13:50:12 -0400179 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200180 ninjaDeps = append(ninjaDeps, globListFiles...)
181
Chris Parsonsf874e462022-05-10 13:50:12 -0400182 writeDepFile(cmdlineArgs.OutFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200183}
184
185// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200186func runQueryView(queryviewDir, queryviewMarker string, configuration android.Config, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400187 ctx.EventHandler.Begin("queryview")
188 defer ctx.EventHandler.End("queryview")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200189 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200190 absoluteQueryViewDir := shared.JoinPath(topDir, queryviewDir)
Spandan Das5af0bd32022-09-28 20:43:08 +0000191 if err := createBazelWorkspace(codegenContext, absoluteQueryViewDir); err != nil {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200192 fmt.Fprintf(os.Stderr, "%s", err)
193 os.Exit(1)
194 }
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200195
196 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200197}
198
Spandan Das5af0bd32022-09-28 20:43:08 +0000199// Run the code-generation phase to convert API contributions to BUILD files.
200// Return marker file for the new synthetic workspace
201func runApiBp2build(configuration android.Config, extraNinjaDeps []string) string {
202 // Create a new context and register mutators that are only meaningful to API export
203 ctx := android.NewContext(configuration)
204 ctx.EventHandler.Begin("api_bp2build")
205 defer ctx.EventHandler.End("api_bp2build")
206 ctx.SetNameInterface(newNameResolver(configuration))
207 ctx.RegisterForApiBazelConversion()
208
209 // Register the Android.bp files in the tree
210 // Add them to the workspace's .d file
211 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
212 if paths, err := ctx.ListModulePaths("."); err == nil {
213 extraNinjaDeps = append(extraNinjaDeps, paths...)
214 } else {
215 panic(err)
216 }
217
218 // Run the loading and analysis phase
219 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs,
220 bootstrap.StopBeforePrepareBuildActions,
221 ctx.Context,
222 configuration)
223 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
224
225 // Add the globbed dependencies
226 globs := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
227 ninjaDeps = append(ninjaDeps, globs...)
228
229 // Run codegen to generate BUILD files
230 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.ApiBp2build)
231 absoluteApiBp2buildDir := shared.JoinPath(topDir, bazelApiBp2buildDir)
232 if err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir); err != nil {
233 fmt.Fprintf(os.Stderr, "%s", err)
234 os.Exit(1)
235 }
236 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
237
238 // Create soong_injection repository
239 soongInjectionFiles := bp2build.CreateSoongInjectionFiles(configuration, bp2build.CodegenMetrics{})
240 absoluteSoongInjectionDir := shared.JoinPath(topDir, configuration.SoongOutDir(), bazel.SoongInjectionDirName)
241 for _, file := range soongInjectionFiles {
242 writeReadOnlyFile(absoluteSoongInjectionDir, file)
243 }
244
245 workspace := shared.JoinPath(configuration.SoongOutDir(), "api_bp2build")
246
247 excludes := bazelArtifacts()
248 // Exclude all src BUILD files
249 excludes = append(excludes, apiBuildFileExcludes()...)
250
251 // Create the symlink forest
252 symlinkDeps := bp2build.PlantSymlinkForest(
253 configuration,
254 topDir,
255 workspace,
256 bazelApiBp2buildDir,
257 ".",
258 excludes)
259 ninjaDeps = append(ninjaDeps, symlinkDeps...)
260
261 workspaceMarkerFile := workspace + ".marker"
262 writeDepFile(workspaceMarkerFile, *ctx.EventHandler, ninjaDeps)
263 touch(shared.JoinPath(topDir, workspaceMarkerFile))
264 return workspaceMarkerFile
265}
266
267// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
268// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
269func apiBuildFileExcludes() []string {
270 ret := make([]string, 0)
271
272 srcs, err := getExistingBazelRelatedFiles(topDir)
273 if err != nil {
274 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
275 os.Exit(1)
276 }
277 for _, src := range srcs {
278 if src != "WORKSPACE" &&
279 src != "BUILD" &&
280 src != "BUILD.bazel" &&
281 !strings.HasPrefix(src, "build/bazel") &&
282 !strings.HasPrefix(src, "prebuilts/clang") {
283 ret = append(ret, src)
284 }
285 }
286 return ret
287}
288
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700289func writeMetrics(configuration android.Config, eventHandler metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400290 if len(metricsDir) < 1 {
291 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
292 os.Exit(1)
293 }
294 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
295 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200296 if err != nil {
297 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
298 os.Exit(1)
299 }
300}
301
kgui67007242022-01-25 13:50:25 +0800302func writeJsonModuleGraphAndActions(ctx *android.Context, graphPath string, actionsPath string) {
303 graphFile, graphErr := os.Create(shared.JoinPath(topDir, graphPath))
304 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, actionsPath))
305 if graphErr != nil || actionsErr != nil {
306 fmt.Fprintf(os.Stderr, "Graph err: %s, actions err: %s", graphErr, actionsErr)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200307 os.Exit(1)
308 }
309
kgui67007242022-01-25 13:50:25 +0800310 defer graphFile.Close()
311 defer actionsFile.Close()
312 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200313}
314
Chris Parsons715b08f2022-03-22 19:23:40 -0400315func writeBuildGlobsNinjaFile(ctx *android.Context, buildDir string, config interface{}) []string {
316 ctx.EventHandler.Begin("globs_ninja_file")
317 defer ctx.EventHandler.End("globs_ninja_file")
318
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200319 globDir := bootstrap.GlobDirectory(buildDir, globListDir)
320 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400321 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200322 GlobFile: globFile,
323 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400324 SrcDir: ctx.SrcDir(),
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200325 }, config)
326 return bootstrap.GlobFileListFiles(globDir)
327}
328
Chris Parsons715b08f2022-03-22 19:23:40 -0400329func writeDepFile(outputFile string, eventHandler metrics.EventHandler, ninjaDeps []string) {
330 eventHandler.Begin("ninja_deps")
331 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200332 depFile := shared.JoinPath(topDir, outputFile+".d")
333 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
334 if err != nil {
335 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", depFile, err)
336 os.Exit(1)
337 }
338}
339
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000340// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
341// or the actual Soong build for the build.ninja file. Returns the top level
342// output file of the specific activity.
ustacd245f72022-08-24 11:45:19 -0400343func doChosenActivity(ctx *android.Context, configuration android.Config, extraNinjaDeps []string) string {
Chris Parsonsad876012022-08-20 14:48:32 -0400344 if configuration.BuildMode == android.Bp2build {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200345 // Run the alternate pipeline of bp2build mutators and singleton to convert
346 // Blueprint to BUILD files before everything else.
347 runBp2Build(configuration, extraNinjaDeps)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000348 return bp2buildMarker
Chris Parsonsad876012022-08-20 14:48:32 -0400349 } else if configuration.IsMixedBuildsEnabled() {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200350 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000351 } else if configuration.BuildMode == android.ApiBp2build {
352 return runApiBp2build(configuration, extraNinjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200353 } else {
Chris Parsons715b08f2022-03-22 19:23:40 -0400354 var stopBefore bootstrap.StopBefore
Chris Parsonsad876012022-08-20 14:48:32 -0400355 if configuration.BuildMode == android.GenerateModuleGraph {
Chris Parsons715b08f2022-03-22 19:23:40 -0400356 stopBefore = bootstrap.StopBeforeWriteNinja
Chris Parsonsad876012022-08-20 14:48:32 -0400357 } else if configuration.BuildMode == android.GenerateQueryView || configuration.BuildMode == android.GenerateDocFile {
Chris Parsons715b08f2022-03-22 19:23:40 -0400358 stopBefore = bootstrap.StopBeforePrepareBuildActions
359 } else {
360 stopBefore = bootstrap.DoEverything
361 }
362
Chris Parsonsad876012022-08-20 14:48:32 -0400363 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, stopBefore, ctx.Context, configuration)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200364 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200365
Chris Parsons715b08f2022-03-22 19:23:40 -0400366 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200367 ninjaDeps = append(ninjaDeps, globListFiles...)
368
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200369 // Convert the Soong module graph into Bazel BUILD files.
Chris Parsonsad876012022-08-20 14:48:32 -0400370 if configuration.BuildMode == android.GenerateQueryView {
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200371 queryviewMarkerFile := bazelQueryViewDir + ".marker"
372 runQueryView(bazelQueryViewDir, queryviewMarkerFile, configuration, ctx)
Chris Parsons715b08f2022-03-22 19:23:40 -0400373 writeDepFile(queryviewMarkerFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200374 return queryviewMarkerFile
Chris Parsonsad876012022-08-20 14:48:32 -0400375 } else if configuration.BuildMode == android.GenerateModuleGraph {
kgui67007242022-01-25 13:50:25 +0800376 writeJsonModuleGraphAndActions(ctx, moduleGraphFile, moduleActionsFile)
Chris Parsons715b08f2022-03-22 19:23:40 -0400377 writeDepFile(moduleGraphFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200378 return moduleGraphFile
Chris Parsonsad876012022-08-20 14:48:32 -0400379 } else if configuration.BuildMode == android.GenerateDocFile {
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200380 // TODO: we could make writeDocs() return the list of documentation files
381 // written and add them to the .d file. Then soong_docs would be re-run
382 // whenever one is deleted.
383 if err := writeDocs(ctx, shared.JoinPath(topDir, docFile)); err != nil {
384 fmt.Fprintf(os.Stderr, "error building Soong documentation: %s\n", err)
385 os.Exit(1)
386 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400387 writeDepFile(docFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200388 return docFile
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200389 } else {
390 // The actual output (build.ninja) was written in the RunBlueprint() call
391 // above
Chris Parsons715b08f2022-03-22 19:23:40 -0400392 writeDepFile(cmdlineArgs.OutFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200393 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200394 }
395
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200396 return cmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200397}
398
399// soong_ui dumps the available environment variables to
400// soong.environment.available . Then soong_build itself is run with an empty
401// environment so that the only way environment variables can be accessed is
402// using Config, which tracks access to them.
403
404// At the end of the build, a file called soong.environment.used is written
405// containing the current value of all used environment variables. The next
406// time soong_ui is run, it checks whether any environment variables that was
407// used had changed and if so, it deletes soong.environment.used to cause a
408// rebuild.
409//
410// The dependency of build.ninja on soong.environment.used is declared in
411// build.ninja.d
412func parseAvailableEnv() map[string]string {
413 if availableEnvFile == "" {
414 fmt.Fprintf(os.Stderr, "--available_env not set\n")
415 os.Exit(1)
416 }
417
418 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
419 if err != nil {
420 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
421 os.Exit(1)
422 }
423
424 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200425}
426
Colin Cross3f40fa42015-01-30 17:27:36 -0800427func main() {
428 flag.Parse()
429
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100430 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100431 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100432
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200433 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200434
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200435 configuration := newConfig(availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100436 extraNinjaDeps := []string{
437 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200438 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100439 }
Colin Crossaa812d12019-06-19 13:33:24 -0700440
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100441 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
442 configuration.SetAllowMissingDependencies()
443 }
444
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100445 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700446 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
447 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200448 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700449 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500450
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700451 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
452 // change between every CI build, so tracking it would require re-running Soong for every build.
453 logDir := availableEnv["LOG_DIR"]
454
Joe Onorato2e5e4012022-06-07 17:16:08 -0700455 ctx := newContext(configuration)
456 ctx.EventHandler.Begin("soong_build")
457
ustacd245f72022-08-24 11:45:19 -0400458 finalOutputFile := doChosenActivity(ctx, configuration, extraNinjaDeps)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700459
460 ctx.EventHandler.End("soong_build")
461 writeMetrics(configuration, *ctx.EventHandler, logDir)
Chris Parsons715b08f2022-03-22 19:23:40 -0400462
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200463 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100464}
465
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200466func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
467 if usedEnvFile == "" {
468 return
469 }
470
471 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100472 data, err := shared.EnvFileContents(configuration.EnvDeps())
473 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200474 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100475 os.Exit(1)
476 }
477
478 err = ioutil.WriteFile(path, data, 0666)
479 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200480 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100481 os.Exit(1)
482 }
483
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200484 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100485 // wrote. We can't write the environment file earlier because one an access
486 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200487 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800488}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000489
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200490func touch(path string) {
491 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
492 if err != nil {
493 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
494 os.Exit(1)
495 }
496
497 err = f.Close()
498 if err != nil {
499 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
500 os.Exit(1)
501 }
502
503 currentTime := time.Now().Local()
504 err = os.Chtimes(path, currentTime, currentTime)
505 if err != nil {
506 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
507 os.Exit(1)
508 }
509}
510
Cole Faust324a92e2022-08-23 15:29:05 -0700511// Find BUILD files in the srcDir which are not in the allowlist
512// (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
513// and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
514func getPathsToIgnoredBuildFiles(config android.Bp2BuildConversionAllowlist, topDir string, srcDirBazelFiles []string, verbose bool) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400515 paths := make([]string, 0)
516
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400517 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
518 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
519 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400520 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400521 // Warn about error, but continue trying to check files
522 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
523 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400524 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400525 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400526 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400527 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400528 }
Cole Faust324a92e2022-08-23 15:29:05 -0700529 if fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel" {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400530 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400531 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400532 }
Cole Faust324a92e2022-08-23 15:29:05 -0700533 if config.ShouldKeepExistingBuildFileForDir(filepath.Dir(srcDirBazelFileRelativePath)) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400534 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400535 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400536 }
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400537 if verbose {
538 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
539 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400540 paths = append(paths, srcDirBazelFileRelativePath)
541 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400542
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400543 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400544}
545
546// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
547func getTemporaryExcludes() []string {
548 excludes := make([]string, 0)
549
550 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
551 excludes = append(excludes, "external/autotest/venv/autotest_lib")
Jingwen Chenc0c50212022-06-07 10:07:22 +0000552 excludes = append(excludes, "external/autotest/autotest_lib")
553 excludes = append(excludes, "external/autotest/client/autotest_lib/client")
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400554
555 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
556 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
557 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
558
559 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
560 excludes = append(excludes, "frameworks/compile/slang")
561
562 return excludes
563}
564
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400565// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
566// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
567func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200568 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400569 if !filepath.IsAbs(bazelFinderFile) {
570 // Assume this was a relative path under topDir
571 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
572 }
573 data, err := ioutil.ReadFile(bazelFinderFile)
574 if err != nil {
575 return nil, err
576 }
577 files := strings.Split(strings.TrimSpace(string(data)), "\n")
578 return files, nil
579}
580
Spandan Das5af0bd32022-09-28 20:43:08 +0000581func bazelArtifacts() []string {
582 return []string{
583 "bazel-bin",
584 "bazel-genfiles",
585 "bazel-out",
586 "bazel-testlogs",
587 "bazel-" + filepath.Base(topDir),
588 }
589}
590
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500591// Run Soong in the bp2build mode. This creates a standalone context that registers
592// an alternate pipeline of mutators and singletons specifically for generating
593// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200594func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Usta Shresthaa117c582022-10-04 12:13:25 -0400595 var codegenMetrics bp2build.CodegenMetrics
Chris Parsons715b08f2022-03-22 19:23:40 -0400596 eventHandler := metrics.EventHandler{}
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400597 eventHandler.Do("bp2build", func() {
Chris Parsons715b08f2022-03-22 19:23:40 -0400598
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400599 // Register an alternate set of singletons and mutators for bazel
600 // conversion for Bazel conversion.
601 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500602
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400603 // Propagate "allow misssing dependencies" bit. This is normally set in
604 // newContext(), but we create bp2buildCtx without calling that method.
605 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
606 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
607 bp2buildCtx.RegisterForBazelConversion()
Jingwen Cheneb76c432021-01-28 08:22:12 -0500608
Usta Shresthaa117c582022-10-04 12:13:25 -0400609 var ninjaDeps []string
610 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
611
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400612 // The bp2build process is a purely functional process that only depends on
613 // Android.bp files. It must not depend on the values of per-build product
614 // configurations or variables, since those will generate different BUILD
615 // files based on how the user has configured their tree.
616 bp2buildCtx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Usta Shresthaa117c582022-10-04 12:13:25 -0400617 if modulePaths, err := bp2buildCtx.ListModulePaths("."); err != nil {
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400618 panic(err)
Usta Shresthaa117c582022-10-04 12:13:25 -0400619 } else {
620 ninjaDeps = append(ninjaDeps, modulePaths...)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400621 }
Jingwen Chen7dcc4fc2021-02-05 01:28:44 -0500622
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400623 // Run the loading and analysis pipeline to prepare the graph of regular
624 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
625 // from the regular Modules.
Usta Shresthaa117c582022-10-04 12:13:25 -0400626 eventHandler.Do("bootstrap", func() {
627 blueprintArgs := cmdlineArgs
628 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.StopBeforePrepareBuildActions, bp2buildCtx.Context, configuration)
629 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
630 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200631
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400632 globListFiles := writeBuildGlobsNinjaFile(bp2buildCtx, configuration.SoongOutDir(), configuration)
633 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200634
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400635 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400636 // and print conversion codegenMetrics to the user.
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400637 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
Usta Shresthaa117c582022-10-04 12:13:25 -0400638 eventHandler.Do("codegen", func() {
639 codegenMetrics = bp2build.Codegen(codegenContext)
640 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200641
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400642 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
643 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200644
Spandan Das5af0bd32022-09-28 20:43:08 +0000645 excludes := bazelArtifacts()
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200646
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400647 if outDir[0] != '/' {
648 excludes = append(excludes, outDir)
649 }
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200650
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400651 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
652 if err != nil {
653 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
654 os.Exit(1)
655 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400656
Cole Faust324a92e2022-08-23 15:29:05 -0700657 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(configuration.Bp2buildPackageConfig, topDir, existingBazelRelatedFiles, configuration.IsEnvTrue("BP2BUILD_VERBOSE"))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400658 excludes = append(excludes, pathsToIgnoredBuildFiles...)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400659
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400660 excludes = append(excludes, getTemporaryExcludes()...)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400661
Usta Shresthaa117c582022-10-04 12:13:25 -0400662 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
663 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
664 // or file created/deleted under it would trigger an update of the symlink
665 // forest.
666 eventHandler.Do("symlink_forest", func() {
667 symlinkForestDeps := bp2build.PlantSymlinkForest(
668 configuration, topDir, workspaceRoot, generatedRoot, ".", excludes)
669 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
670 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200671
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400672 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400673
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400674 writeDepFile(bp2buildMarker, eventHandler, ninjaDeps)
Chris Parsons715b08f2022-03-22 19:23:40 -0400675
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400676 // Create an empty bp2build marker file.
677 touch(shared.JoinPath(topDir, bp2buildMarker))
678 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400679
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200680 // Only report metrics when in bp2build mode. The metrics aren't relevant
681 // for queryview, since that's a total repo-wide conversion and there's a
682 // 1:1 mapping for each module.
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700683 if configuration.IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400684 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700685 }
Usta Shresthaa117c582022-10-04 12:13:25 -0400686 writeBp2BuildMetrics(&codegenMetrics, configuration, eventHandler)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500687}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500688
689// Write Bp2Build metrics into $LOG_DIR
Chris Parsons715b08f2022-03-22 19:23:40 -0400690func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics,
691 configuration android.Config, eventHandler metrics.EventHandler) {
692 for _, event := range eventHandler.CompletedEvents() {
693 codegenMetrics.Events = append(codegenMetrics.Events,
694 &bp2build_metrics_proto.Event{
695 Name: event.Id,
696 StartTime: uint64(event.Start.UnixNano()),
697 RealTime: event.RuntimeNanoseconds(),
698 })
699 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500700 metricsDir := configuration.Getenv("LOG_DIR")
701 if len(metricsDir) < 1 {
702 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
703 os.Exit(1)
704 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400705 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500706}
MarkDacek0d5bca52022-10-10 20:07:48 +0000707
708func readBazelPaths(configuration android.Config) ([]string, error) {
709 depsPath := configuration.Getenv("BAZEL_DEPS_FILE")
710
711 data, err := os.ReadFile(depsPath)
712 if err != nil {
713 return nil, err
714 }
715 paths := strings.Split(strings.TrimSpace(string(data)), "\n")
716 return paths, nil
717}