blob: 5174570f82c35c465847dce22dfd05d853cae073 [file] [log] [blame]
Colin Cross3f40fa42015-01-30 17:27:36 -08001// Copyright 2015 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package main
16
17import (
Usta Shrestha2ba28a32022-10-24 11:33:09 -040018 "bytes"
Colin Cross3f40fa42015-01-30 17:27:36 -080019 "flag"
20 "fmt"
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +010021 "io/ioutil"
Colin Cross3f40fa42015-01-30 17:27:36 -080022 "os"
23 "path/filepath"
Jingwen Cheneb76c432021-01-28 08:22:12 -050024 "strings"
Lukacs T. Berkic99c9472021-03-24 10:50:06 +010025 "time"
Colin Cross3f40fa42015-01-30 17:27:36 -080026
Dan Willemsen66213a62021-09-21 17:50:30 -070027 "android/soong/android"
Spandan Das5af0bd32022-09-28 20:43:08 +000028 "android/soong/bazel"
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020029 "android/soong/bp2build"
Lukacs T. Berki7690c092021-02-26 14:27:36 +010030 "android/soong/shared"
Chris Parsons715b08f2022-03-22 19:23:40 -040031 "android/soong/ui/metrics/bp2build_metrics_proto"
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020032
Colin Cross70b40592015-03-23 12:57:34 -070033 "github.com/google/blueprint/bootstrap"
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +020034 "github.com/google/blueprint/deptools"
Chris Parsons715b08f2022-03-22 19:23:40 -040035 "github.com/google/blueprint/metrics"
Dan Willemsen66213a62021-09-21 17:50:30 -070036 androidProtobuf "google.golang.org/protobuf/android"
Colin Cross3f40fa42015-01-30 17:27:36 -080037)
38
Colin Crosse87040b2017-12-11 15:52:26 -080039var (
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020040 topDir string
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020041 outDir string
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020042 soongOutDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020043 availableEnvFile string
44 usedEnvFile string
45
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020046 runGoTests bool
47
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020048 globFile string
49 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020050 delveListen string
51 delvePath string
52
Spandan Das5af0bd32022-09-28 20:43:08 +000053 moduleGraphFile string
54 moduleActionsFile string
55 docFile string
56 bazelQueryViewDir string
57 bazelApiBp2buildDir string
58 bp2buildMarker string
Lukacs T. Berkif9008072021-08-16 15:24:48 +020059
60 cmdlineArgs bootstrap.Args
Colin Crosse87040b2017-12-11 15:52:26 -080061)
62
63func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020064 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010065 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Lukacs T. Berkid6cee7e2021-09-01 16:25:51 +020066 flag.StringVar(&soongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020067 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
68 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020069 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
70 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020071 flag.StringVar(&outDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020072 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020073
74 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010075 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
76 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020077 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
78 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
79 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
80 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020081
82 // Flags representing various modes soong_build can run in
Lukacs T. Berkie571dc32021-08-25 14:14:13 +020083 flag.StringVar(&moduleGraphFile, "module_graph_file", "", "JSON module graph file to output")
kgui67007242022-01-25 13:50:25 +080084 flag.StringVar(&moduleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
Colin Crosse87040b2017-12-11 15:52:26 -080085 flag.StringVar(&docFile, "soong_docs", "", "build documentation file to output")
Lukacs T. Berki47a9d0c2021-03-08 16:34:09 +010086 flag.StringVar(&bazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
Spandan Das5af0bd32022-09-28 20:43:08 +000087 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 +020088 flag.StringVar(&bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020089 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020090 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
Chris Parsonsef615e52022-08-18 22:04:11 -040091 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
MarkDacekb78465d2022-10-18 20:10:16 +000092 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
Chris Parsonsef615e52022-08-18 22:04:11 -040093 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 +020094
95 // Flags that probably shouldn't be flags of soong_build but we haven't found
96 // the time to remove them yet
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +020097 flag.BoolVar(&runGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070098
99 // Disable deterministic randomization in the protobuf package, so incremental
100 // builds with unrelated Soong changes don't trigger large rebuilds (since we
101 // write out text protos in command lines, and command line changes trigger
102 // rebuilds).
103 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -0800104}
105
Jeff Gaston088e29e2017-11-29 16:47:17 -0800106func newNameResolver(config android.Config) *android.NameResolver {
107 namespacePathsToExport := make(map[string]bool)
108
Dan Willemsen3fb1fae2018-03-12 15:30:26 -0700109 for _, namespaceName := range config.ExportedNamespaces() {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800110 namespacePathsToExport[namespaceName] = true
111 }
112
113 namespacePathsToExport["."] = true // always export the root namespace
114
115 exportFilter := func(namespace *android.Namespace) bool {
116 return namespacePathsToExport[namespace.Path]
117 }
118
119 return android.NewNameResolver(exportFilter)
120}
121
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200122func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700123 ctx := android.NewContext(configuration)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500124 ctx.Register()
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400125 ctx.SetNameInterface(newNameResolver(configuration))
126 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
127 return ctx
128}
129
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200130func newConfig(availableEnv map[string]string) android.Config {
Chris Parsonsad876012022-08-20 14:48:32 -0400131 var buildMode android.SoongBuildMode
132
133 if bp2buildMarker != "" {
134 buildMode = android.Bp2build
135 } else if bazelQueryViewDir != "" {
136 buildMode = android.GenerateQueryView
Spandan Das5af0bd32022-09-28 20:43:08 +0000137 } else if bazelApiBp2buildDir != "" {
138 buildMode = android.ApiBp2build
Chris Parsonsad876012022-08-20 14:48:32 -0400139 } else if moduleGraphFile != "" {
140 buildMode = android.GenerateModuleGraph
141 } else if docFile != "" {
142 buildMode = android.GenerateDocFile
Chris Parsonsef615e52022-08-18 22:04:11 -0400143 } else if cmdlineArgs.BazelModeDev {
144 buildMode = android.BazelDevMode
145 } else if cmdlineArgs.BazelMode {
146 buildMode = android.BazelProdMode
MarkDacekb78465d2022-10-18 20:10:16 +0000147 } else if cmdlineArgs.BazelModeStaging {
148 buildMode = android.BazelStagingMode
Chris Parsonsad876012022-08-20 14:48:32 -0400149 } else {
150 buildMode = android.AnalysisNoBazel
151 }
152
153 configuration, err := android.NewConfig(cmdlineArgs.ModuleListFile, buildMode, runGoTests, outDir, soongOutDir, availableEnv)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400154 if err != nil {
155 fmt.Fprintf(os.Stderr, "%s", err)
156 os.Exit(1)
157 }
158 return configuration
159}
160
Chris Parsonsf874e462022-05-10 13:50:12 -0400161// Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
162// BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
163// for modules that should be handled by Bazel.
164func runMixedModeBuild(configuration android.Config, ctx *android.Context, extraNinjaDeps []string) {
165 ctx.EventHandler.Begin("mixed_build")
166 defer ctx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200167
Chris Parsonsf874e462022-05-10 13:50:12 -0400168 bazelHook := func() error {
169 ctx.EventHandler.Begin("bazel")
170 defer ctx.EventHandler.End("bazel")
Yu Liu8d82ac52022-05-17 15:13:28 -0700171 return configuration.BazelContext.InvokeBazel(configuration)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200172 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400173 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Chris Parsonsf874e462022-05-10 13:50:12 -0400174 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, bootstrap.DoEverything, ctx.Context, configuration)
Chris Parsons027881c2022-05-24 15:38:38 -0400175 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200176
MarkDacek0d5bca52022-10-10 20:07:48 +0000177 bazelPaths, err := readBazelPaths(configuration)
178 if err != nil {
179 panic("Bazel deps file not found: " + err.Error())
180 }
181 ninjaDeps = append(ninjaDeps, bazelPaths...)
182
Chris Parsonsf874e462022-05-10 13:50:12 -0400183 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200184 ninjaDeps = append(ninjaDeps, globListFiles...)
185
Chris Parsonsf874e462022-05-10 13:50:12 -0400186 writeDepFile(cmdlineArgs.OutFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200187}
188
189// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200190func runQueryView(queryviewDir, queryviewMarker string, configuration android.Config, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400191 ctx.EventHandler.Begin("queryview")
192 defer ctx.EventHandler.End("queryview")
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200193 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.QueryView)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200194 absoluteQueryViewDir := shared.JoinPath(topDir, queryviewDir)
Spandan Das5af0bd32022-09-28 20:43:08 +0000195 if err := createBazelWorkspace(codegenContext, absoluteQueryViewDir); err != nil {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200196 fmt.Fprintf(os.Stderr, "%s", err)
197 os.Exit(1)
198 }
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200199
200 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200201}
202
Spandan Das5af0bd32022-09-28 20:43:08 +0000203// Run the code-generation phase to convert API contributions to BUILD files.
204// Return marker file for the new synthetic workspace
205func runApiBp2build(configuration android.Config, extraNinjaDeps []string) string {
206 // Create a new context and register mutators that are only meaningful to API export
207 ctx := android.NewContext(configuration)
208 ctx.EventHandler.Begin("api_bp2build")
209 defer ctx.EventHandler.End("api_bp2build")
210 ctx.SetNameInterface(newNameResolver(configuration))
211 ctx.RegisterForApiBazelConversion()
212
213 // Register the Android.bp files in the tree
214 // Add them to the workspace's .d file
215 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
216 if paths, err := ctx.ListModulePaths("."); err == nil {
217 extraNinjaDeps = append(extraNinjaDeps, paths...)
218 } else {
219 panic(err)
220 }
221
222 // Run the loading and analysis phase
223 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs,
224 bootstrap.StopBeforePrepareBuildActions,
225 ctx.Context,
226 configuration)
227 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
228
229 // Add the globbed dependencies
230 globs := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
231 ninjaDeps = append(ninjaDeps, globs...)
232
233 // Run codegen to generate BUILD files
234 codegenContext := bp2build.NewCodegenContext(configuration, *ctx, bp2build.ApiBp2build)
235 absoluteApiBp2buildDir := shared.JoinPath(topDir, bazelApiBp2buildDir)
236 if err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir); err != nil {
237 fmt.Fprintf(os.Stderr, "%s", err)
238 os.Exit(1)
239 }
240 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
241
242 // Create soong_injection repository
243 soongInjectionFiles := bp2build.CreateSoongInjectionFiles(configuration, bp2build.CodegenMetrics{})
244 absoluteSoongInjectionDir := shared.JoinPath(topDir, configuration.SoongOutDir(), bazel.SoongInjectionDirName)
245 for _, file := range soongInjectionFiles {
246 writeReadOnlyFile(absoluteSoongInjectionDir, file)
247 }
248
249 workspace := shared.JoinPath(configuration.SoongOutDir(), "api_bp2build")
250
251 excludes := bazelArtifacts()
252 // Exclude all src BUILD files
253 excludes = append(excludes, apiBuildFileExcludes()...)
254
255 // Create the symlink forest
256 symlinkDeps := bp2build.PlantSymlinkForest(
257 configuration,
258 topDir,
259 workspace,
260 bazelApiBp2buildDir,
261 ".",
262 excludes)
263 ninjaDeps = append(ninjaDeps, symlinkDeps...)
264
265 workspaceMarkerFile := workspace + ".marker"
266 writeDepFile(workspaceMarkerFile, *ctx.EventHandler, ninjaDeps)
267 touch(shared.JoinPath(topDir, workspaceMarkerFile))
268 return workspaceMarkerFile
269}
270
271// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
272// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
273func apiBuildFileExcludes() []string {
274 ret := make([]string, 0)
275
276 srcs, err := getExistingBazelRelatedFiles(topDir)
277 if err != nil {
278 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
279 os.Exit(1)
280 }
281 for _, src := range srcs {
282 if src != "WORKSPACE" &&
283 src != "BUILD" &&
284 src != "BUILD.bazel" &&
285 !strings.HasPrefix(src, "build/bazel") &&
286 !strings.HasPrefix(src, "prebuilts/clang") {
287 ret = append(ret, src)
288 }
289 }
290 return ret
291}
292
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700293func writeMetrics(configuration android.Config, eventHandler metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400294 if len(metricsDir) < 1 {
295 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
296 os.Exit(1)
297 }
298 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
299 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200300 if err != nil {
301 fmt.Fprintf(os.Stderr, "error writing soong_build metrics %s: %s", metricsFile, err)
302 os.Exit(1)
303 }
304}
305
kgui67007242022-01-25 13:50:25 +0800306func writeJsonModuleGraphAndActions(ctx *android.Context, graphPath string, actionsPath string) {
307 graphFile, graphErr := os.Create(shared.JoinPath(topDir, graphPath))
308 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, actionsPath))
309 if graphErr != nil || actionsErr != nil {
310 fmt.Fprintf(os.Stderr, "Graph err: %s, actions err: %s", graphErr, actionsErr)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200311 os.Exit(1)
312 }
313
kgui67007242022-01-25 13:50:25 +0800314 defer graphFile.Close()
315 defer actionsFile.Close()
316 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200317}
318
Chris Parsons715b08f2022-03-22 19:23:40 -0400319func writeBuildGlobsNinjaFile(ctx *android.Context, buildDir string, config interface{}) []string {
320 ctx.EventHandler.Begin("globs_ninja_file")
321 defer ctx.EventHandler.End("globs_ninja_file")
322
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200323 globDir := bootstrap.GlobDirectory(buildDir, globListDir)
324 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400325 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200326 GlobFile: globFile,
327 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400328 SrcDir: ctx.SrcDir(),
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200329 }, config)
330 return bootstrap.GlobFileListFiles(globDir)
331}
332
Chris Parsons715b08f2022-03-22 19:23:40 -0400333func writeDepFile(outputFile string, eventHandler metrics.EventHandler, ninjaDeps []string) {
334 eventHandler.Begin("ninja_deps")
335 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200336 depFile := shared.JoinPath(topDir, outputFile+".d")
337 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
338 if err != nil {
339 fmt.Fprintf(os.Stderr, "Error writing depfile '%s': %s\n", depFile, err)
340 os.Exit(1)
341 }
342}
343
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000344// doChosenActivity runs Soong for a specific activity, like bp2build, queryview
345// or the actual Soong build for the build.ninja file. Returns the top level
346// output file of the specific activity.
ustacd245f72022-08-24 11:45:19 -0400347func doChosenActivity(ctx *android.Context, configuration android.Config, extraNinjaDeps []string) string {
Chris Parsonsad876012022-08-20 14:48:32 -0400348 if configuration.BuildMode == android.Bp2build {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200349 // Run the alternate pipeline of bp2build mutators and singleton to convert
350 // Blueprint to BUILD files before everything else.
351 runBp2Build(configuration, extraNinjaDeps)
Jingwen Chen4fabaf52021-05-25 02:40:29 +0000352 return bp2buildMarker
Chris Parsonsad876012022-08-20 14:48:32 -0400353 } else if configuration.IsMixedBuildsEnabled() {
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200354 runMixedModeBuild(configuration, ctx, extraNinjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000355 } else if configuration.BuildMode == android.ApiBp2build {
356 return runApiBp2build(configuration, extraNinjaDeps)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200357 } else {
Chris Parsons715b08f2022-03-22 19:23:40 -0400358 var stopBefore bootstrap.StopBefore
Chris Parsonsad876012022-08-20 14:48:32 -0400359 if configuration.BuildMode == android.GenerateModuleGraph {
Chris Parsons715b08f2022-03-22 19:23:40 -0400360 stopBefore = bootstrap.StopBeforeWriteNinja
Chris Parsonsad876012022-08-20 14:48:32 -0400361 } else if configuration.BuildMode == android.GenerateQueryView || configuration.BuildMode == android.GenerateDocFile {
Chris Parsons715b08f2022-03-22 19:23:40 -0400362 stopBefore = bootstrap.StopBeforePrepareBuildActions
363 } else {
364 stopBefore = bootstrap.DoEverything
365 }
366
Chris Parsonsad876012022-08-20 14:48:32 -0400367 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs, stopBefore, ctx.Context, configuration)
Lukacs T. Berki6124c9b2021-04-15 15:06:40 +0200368 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200369
Chris Parsons715b08f2022-03-22 19:23:40 -0400370 globListFiles := writeBuildGlobsNinjaFile(ctx, configuration.SoongOutDir(), configuration)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200371 ninjaDeps = append(ninjaDeps, globListFiles...)
372
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200373 // Convert the Soong module graph into Bazel BUILD files.
Chris Parsonsad876012022-08-20 14:48:32 -0400374 if configuration.BuildMode == android.GenerateQueryView {
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200375 queryviewMarkerFile := bazelQueryViewDir + ".marker"
376 runQueryView(bazelQueryViewDir, queryviewMarkerFile, configuration, ctx)
Chris Parsons715b08f2022-03-22 19:23:40 -0400377 writeDepFile(queryviewMarkerFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200378 return queryviewMarkerFile
Chris Parsonsad876012022-08-20 14:48:32 -0400379 } else if configuration.BuildMode == android.GenerateModuleGraph {
kgui67007242022-01-25 13:50:25 +0800380 writeJsonModuleGraphAndActions(ctx, moduleGraphFile, moduleActionsFile)
Chris Parsons715b08f2022-03-22 19:23:40 -0400381 writeDepFile(moduleGraphFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200382 return moduleGraphFile
Chris Parsonsad876012022-08-20 14:48:32 -0400383 } else if configuration.BuildMode == android.GenerateDocFile {
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200384 // TODO: we could make writeDocs() return the list of documentation files
385 // written and add them to the .d file. Then soong_docs would be re-run
386 // whenever one is deleted.
387 if err := writeDocs(ctx, shared.JoinPath(topDir, docFile)); err != nil {
388 fmt.Fprintf(os.Stderr, "error building Soong documentation: %s\n", err)
389 os.Exit(1)
390 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400391 writeDepFile(docFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkic6012f32021-09-06 18:31:46 +0200392 return docFile
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200393 } else {
394 // The actual output (build.ninja) was written in the RunBlueprint() call
395 // above
Chris Parsons715b08f2022-03-22 19:23:40 -0400396 writeDepFile(cmdlineArgs.OutFile, *ctx.EventHandler, ninjaDeps)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200397 }
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200398 }
399
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200400 return cmdlineArgs.OutFile
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200401}
402
403// soong_ui dumps the available environment variables to
404// soong.environment.available . Then soong_build itself is run with an empty
405// environment so that the only way environment variables can be accessed is
406// using Config, which tracks access to them.
407
408// At the end of the build, a file called soong.environment.used is written
409// containing the current value of all used environment variables. The next
410// time soong_ui is run, it checks whether any environment variables that was
411// used had changed and if so, it deletes soong.environment.used to cause a
412// rebuild.
413//
414// The dependency of build.ninja on soong.environment.used is declared in
415// build.ninja.d
416func parseAvailableEnv() map[string]string {
417 if availableEnvFile == "" {
418 fmt.Fprintf(os.Stderr, "--available_env not set\n")
419 os.Exit(1)
420 }
421
422 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
423 if err != nil {
424 fmt.Fprintf(os.Stderr, "error reading available environment file '%s': %s\n", availableEnvFile, err)
425 os.Exit(1)
426 }
427
428 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200429}
430
Colin Cross3f40fa42015-01-30 17:27:36 -0800431func main() {
432 flag.Parse()
433
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100434 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100435 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100436
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200437 availableEnv := parseAvailableEnv()
Lukacs T. Berki53b2f362021-04-12 14:04:24 +0200438
Lukacs T. Berki89fcdcb2021-09-07 09:10:33 +0200439 configuration := newConfig(availableEnv)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100440 extraNinjaDeps := []string{
441 configuration.ProductVariablesFileName,
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200442 usedEnvFile,
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100443 }
Colin Crossaa812d12019-06-19 13:33:24 -0700444
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100445 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
446 configuration.SetAllowMissingDependencies()
447 }
448
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100449 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700450 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
451 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200452 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700453 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500454
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700455 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
456 // change between every CI build, so tracking it would require re-running Soong for every build.
457 logDir := availableEnv["LOG_DIR"]
458
Joe Onorato2e5e4012022-06-07 17:16:08 -0700459 ctx := newContext(configuration)
460 ctx.EventHandler.Begin("soong_build")
461
ustacd245f72022-08-24 11:45:19 -0400462 finalOutputFile := doChosenActivity(ctx, configuration, extraNinjaDeps)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700463
464 ctx.EventHandler.End("soong_build")
465 writeMetrics(configuration, *ctx.EventHandler, logDir)
Chris Parsons715b08f2022-03-22 19:23:40 -0400466
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200467 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100468}
469
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200470func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
471 if usedEnvFile == "" {
472 return
473 }
474
475 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100476 data, err := shared.EnvFileContents(configuration.EnvDeps())
477 if err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200478 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100479 os.Exit(1)
480 }
481
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400482 if preexistingData, err := os.ReadFile(path); err != nil {
483 if !os.IsNotExist(err) {
484 fmt.Fprintf(os.Stderr, "error reading used environment file '%s': %s\n", usedEnvFile, err)
485 os.Exit(1)
486 }
487 } else if bytes.Equal(preexistingData, data) {
488 // used environment file is unchanged
489 return
490 }
491 if err = os.WriteFile(path, data, 0666); err != nil {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200492 fmt.Fprintf(os.Stderr, "error writing used environment file '%s': %s\n", usedEnvFile, err)
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100493 os.Exit(1)
494 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200495 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100496 // wrote. We can't write the environment file earlier because one an access
497 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200498 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800499}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000500
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200501func touch(path string) {
502 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
503 if err != nil {
504 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
505 os.Exit(1)
506 }
507
508 err = f.Close()
509 if err != nil {
510 fmt.Fprintf(os.Stderr, "Error touching '%s': %s\n", path, err)
511 os.Exit(1)
512 }
513
514 currentTime := time.Now().Local()
515 err = os.Chtimes(path, currentTime, currentTime)
516 if err != nil {
517 fmt.Fprintf(os.Stderr, "error touching '%s': %s\n", path, err)
518 os.Exit(1)
519 }
520}
521
Cole Faust324a92e2022-08-23 15:29:05 -0700522// Find BUILD files in the srcDir which are not in the allowlist
523// (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
524// and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
525func getPathsToIgnoredBuildFiles(config android.Bp2BuildConversionAllowlist, topDir string, srcDirBazelFiles []string, verbose bool) []string {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400526 paths := make([]string, 0)
527
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400528 for _, srcDirBazelFileRelativePath := range srcDirBazelFiles {
529 srcDirBazelFileFullPath := shared.JoinPath(topDir, srcDirBazelFileRelativePath)
530 fileInfo, err := os.Stat(srcDirBazelFileFullPath)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400531 if err != nil {
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400532 // Warn about error, but continue trying to check files
533 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", srcDirBazelFileFullPath, err)
534 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400535 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400536 if fileInfo.IsDir() {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400537 // Don't ignore entire directories
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400538 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400539 }
Cole Faust324a92e2022-08-23 15:29:05 -0700540 if fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel" {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400541 // Don't ignore this file - it is not a build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400542 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400543 }
Cole Faust324a92e2022-08-23 15:29:05 -0700544 if config.ShouldKeepExistingBuildFileForDir(filepath.Dir(srcDirBazelFileRelativePath)) {
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400545 // Don't ignore this existing build file
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400546 continue
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400547 }
Liz Kammer1aefc9d2021-10-18 16:59:00 -0400548 if verbose {
549 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", srcDirBazelFileRelativePath)
550 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400551 paths = append(paths, srcDirBazelFileRelativePath)
552 }
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400553
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400554 return paths
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400555}
556
557// Returns temporary symlink forest excludes necessary for bazel build //external/... (and bazel build //frameworks/...) to work
558func getTemporaryExcludes() []string {
559 excludes := make([]string, 0)
560
561 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite symlink expansion error for Bazel
562 excludes = append(excludes, "external/autotest/venv/autotest_lib")
Jingwen Chenc0c50212022-06-07 10:07:22 +0000563 excludes = append(excludes, "external/autotest/autotest_lib")
564 excludes = append(excludes, "external/autotest/client/autotest_lib/client")
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400565
566 // FIXME: The external/google-fruit/extras/bazel_root/third_party/fruit dir is poison
567 // It contains several symlinks back to real source dirs, and those source dirs contain BUILD files we want to ignore
568 excludes = append(excludes, "external/google-fruit/extras/bazel_root/third_party/fruit")
569
570 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
571 excludes = append(excludes, "frameworks/compile/slang")
572
573 return excludes
574}
575
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400576// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
577// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
578func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200579 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400580 if !filepath.IsAbs(bazelFinderFile) {
581 // Assume this was a relative path under topDir
582 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
583 }
584 data, err := ioutil.ReadFile(bazelFinderFile)
585 if err != nil {
586 return nil, err
587 }
588 files := strings.Split(strings.TrimSpace(string(data)), "\n")
589 return files, nil
590}
591
Spandan Das5af0bd32022-09-28 20:43:08 +0000592func bazelArtifacts() []string {
593 return []string{
594 "bazel-bin",
595 "bazel-genfiles",
596 "bazel-out",
597 "bazel-testlogs",
598 "bazel-" + filepath.Base(topDir),
599 }
600}
601
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500602// Run Soong in the bp2build mode. This creates a standalone context that registers
603// an alternate pipeline of mutators and singletons specifically for generating
604// Bazel BUILD files instead of Ninja files.
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200605func runBp2Build(configuration android.Config, extraNinjaDeps []string) {
Usta Shresthaa117c582022-10-04 12:13:25 -0400606 var codegenMetrics bp2build.CodegenMetrics
Chris Parsons715b08f2022-03-22 19:23:40 -0400607 eventHandler := metrics.EventHandler{}
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400608 eventHandler.Do("bp2build", func() {
Chris Parsons715b08f2022-03-22 19:23:40 -0400609
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400610 // Register an alternate set of singletons and mutators for bazel
611 // conversion for Bazel conversion.
612 bp2buildCtx := android.NewContext(configuration)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500613
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400614 // Propagate "allow misssing dependencies" bit. This is normally set in
615 // newContext(), but we create bp2buildCtx without calling that method.
616 bp2buildCtx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
617 bp2buildCtx.SetNameInterface(newNameResolver(configuration))
618 bp2buildCtx.RegisterForBazelConversion()
Lukacs T. Berkia3b96882022-10-17 08:04:11 +0000619 bp2buildCtx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500620
Usta Shresthaa117c582022-10-04 12:13:25 -0400621 var ninjaDeps []string
622 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
623
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400624 // Run the loading and analysis pipeline to prepare the graph of regular
625 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
626 // from the regular Modules.
Usta Shresthaa117c582022-10-04 12:13:25 -0400627 eventHandler.Do("bootstrap", func() {
628 blueprintArgs := cmdlineArgs
629 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs, bootstrap.StopBeforePrepareBuildActions, bp2buildCtx.Context, configuration)
630 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
631 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200632
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400633 globListFiles := writeBuildGlobsNinjaFile(bp2buildCtx, configuration.SoongOutDir(), configuration)
634 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200635
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400636 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400637 // and print conversion codegenMetrics to the user.
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400638 codegenContext := bp2build.NewCodegenContext(configuration, *bp2buildCtx, bp2build.Bp2Build)
Usta Shresthaa117c582022-10-04 12:13:25 -0400639 eventHandler.Do("codegen", func() {
640 codegenMetrics = bp2build.Codegen(codegenContext)
641 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200642
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400643 generatedRoot := shared.JoinPath(configuration.SoongOutDir(), "bp2build")
644 workspaceRoot := shared.JoinPath(configuration.SoongOutDir(), "workspace")
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200645
Spandan Das5af0bd32022-09-28 20:43:08 +0000646 excludes := bazelArtifacts()
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200647
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400648 if outDir[0] != '/' {
649 excludes = append(excludes, outDir)
650 }
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200651
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400652 existingBazelRelatedFiles, err := getExistingBazelRelatedFiles(topDir)
653 if err != nil {
654 fmt.Fprintf(os.Stderr, "Error determining existing Bazel-related files: %s\n", err)
655 os.Exit(1)
656 }
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400657
Cole Faust324a92e2022-08-23 15:29:05 -0700658 pathsToIgnoredBuildFiles := getPathsToIgnoredBuildFiles(configuration.Bp2buildPackageConfig, topDir, existingBazelRelatedFiles, configuration.IsEnvTrue("BP2BUILD_VERBOSE"))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400659 excludes = append(excludes, pathsToIgnoredBuildFiles...)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400660
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400661 excludes = append(excludes, getTemporaryExcludes()...)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400662
Usta Shresthaa117c582022-10-04 12:13:25 -0400663 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
664 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
665 // or file created/deleted under it would trigger an update of the symlink
666 // forest.
667 eventHandler.Do("symlink_forest", func() {
668 symlinkForestDeps := bp2build.PlantSymlinkForest(
669 configuration, topDir, workspaceRoot, generatedRoot, ".", excludes)
670 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
671 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200672
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400673 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400674
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400675 writeDepFile(bp2buildMarker, eventHandler, ninjaDeps)
Chris Parsons715b08f2022-03-22 19:23:40 -0400676
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400677 // Create an empty bp2build marker file.
678 touch(shared.JoinPath(topDir, bp2buildMarker))
679 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400680
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200681 // Only report metrics when in bp2build mode. The metrics aren't relevant
682 // for queryview, since that's a total repo-wide conversion and there's a
683 // 1:1 mapping for each module.
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700684 if configuration.IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400685 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700686 }
Usta Shresthaa117c582022-10-04 12:13:25 -0400687 writeBp2BuildMetrics(&codegenMetrics, configuration, eventHandler)
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500688}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500689
690// Write Bp2Build metrics into $LOG_DIR
Chris Parsons715b08f2022-03-22 19:23:40 -0400691func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics,
692 configuration android.Config, eventHandler metrics.EventHandler) {
693 for _, event := range eventHandler.CompletedEvents() {
694 codegenMetrics.Events = append(codegenMetrics.Events,
695 &bp2build_metrics_proto.Event{
696 Name: event.Id,
697 StartTime: uint64(event.Start.UnixNano()),
698 RealTime: event.RuntimeNanoseconds(),
699 })
700 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500701 metricsDir := configuration.Getenv("LOG_DIR")
702 if len(metricsDir) < 1 {
703 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
704 os.Exit(1)
705 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400706 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500707}
MarkDacek0d5bca52022-10-10 20:07:48 +0000708
709func readBazelPaths(configuration android.Config) ([]string, error) {
710 depsPath := configuration.Getenv("BAZEL_DEPS_FILE")
711
712 data, err := os.ReadFile(depsPath)
713 if err != nil {
714 return nil, err
715 }
716 paths := strings.Split(strings.TrimSpace(string(data)), "\n")
717 return paths, nil
718}