blob: 3a4d71aaf03609eb14c0e6313a9c04a4d0ceb298 [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"
21 "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. Berkif8e24282021-04-14 10:31:00 +020040 availableEnvFile string
41 usedEnvFile string
42
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +020043 globFile string
44 globListDir string
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020045 delveListen string
46 delvePath string
47
Sasha Smundakaf5ca922022-12-12 21:23:34 -080048 cmdlineArgs android.CmdArgs
Colin Crosse87040b2017-12-11 15:52:26 -080049)
50
51func init() {
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020052 // Flags that make sense in every mode
Lukacs T. Berki7690c092021-02-26 14:27:36 +010053 flag.StringVar(&topDir, "top", "", "Top directory of the Android source tree")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080054 flag.StringVar(&cmdlineArgs.SoongOutDir, "soong_out", "", "Soong output directory (usually $TOP/out/soong)")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020055 flag.StringVar(&availableEnvFile, "available_env", "", "File containing available environment variables")
56 flag.StringVar(&usedEnvFile, "used_env", "", "File containing used environment variables")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020057 flag.StringVar(&globFile, "globFile", "build-globs.ninja", "the Ninja file of globs to output")
58 flag.StringVar(&globListDir, "globListDir", "", "the directory containing the glob list files")
Sasha Smundakaf5ca922022-12-12 21:23:34 -080059 flag.StringVar(&cmdlineArgs.OutDir, "out", "", "the ninja builddir directory")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020060 flag.StringVar(&cmdlineArgs.ModuleListFile, "l", "", "file that lists filepaths to parse")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020061
62 // Debug flags
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +010063 flag.StringVar(&delveListen, "delve_listen", "", "Delve port to listen on for debugging")
64 flag.StringVar(&delvePath, "delve_path", "", "Path to Delve. Only used if --delve_listen is set")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020065 flag.StringVar(&cmdlineArgs.Cpuprofile, "cpuprofile", "", "write cpu profile to file")
66 flag.StringVar(&cmdlineArgs.TraceFile, "trace", "", "write trace to file")
67 flag.StringVar(&cmdlineArgs.Memprofile, "memprofile", "", "write memory profile to file")
68 flag.BoolVar(&cmdlineArgs.NoGC, "nogc", false, "turn off GC for debugging")
Lukacs T. Berkif8e24282021-04-14 10:31:00 +020069
70 // Flags representing various modes soong_build can run in
Sasha Smundakaf5ca922022-12-12 21:23:34 -080071 flag.StringVar(&cmdlineArgs.ModuleGraphFile, "module_graph_file", "", "JSON module graph file to output")
72 flag.StringVar(&cmdlineArgs.ModuleActionsFile, "module_actions_file", "", "JSON file to output inputs/outputs of actions of modules")
73 flag.StringVar(&cmdlineArgs.DocFile, "soong_docs", "", "build documentation file to output")
74 flag.StringVar(&cmdlineArgs.BazelQueryViewDir, "bazel_queryview_dir", "", "path to the bazel queryview directory relative to --top")
75 flag.StringVar(&cmdlineArgs.BazelApiBp2buildDir, "bazel_api_bp2build_dir", "", "path to the bazel api_bp2build directory relative to --top")
76 flag.StringVar(&cmdlineArgs.Bp2buildMarker, "bp2build_marker", "", "If set, run bp2build, touch the specified marker file then exit")
77 flag.StringVar(&cmdlineArgs.SymlinkForestMarker, "symlink_forest_marker", "", "If set, create the bp2build symlink forest, touch the specified marker file, then exit")
Lukacs T. Berkif9008072021-08-16 15:24:48 +020078 flag.StringVar(&cmdlineArgs.OutFile, "o", "build.ninja", "the Ninja file to output")
MarkDacekd06db5d2022-11-29 00:47:59 +000079 flag.StringVar(&cmdlineArgs.BazelForceEnabledModules, "bazel-force-enabled-modules", "", "additional modules to build with Bazel. Comma-delimited")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020080 flag.BoolVar(&cmdlineArgs.EmptyNinjaFile, "empty-ninja-file", false, "write out a 0-byte ninja file")
LaMont Jones52a72432023-03-09 18:19:35 +000081 flag.BoolVar(&cmdlineArgs.MultitreeBuild, "multitree-build", false, "this is a multitree build")
Chris Parsonsef615e52022-08-18 22:04:11 -040082 flag.BoolVar(&cmdlineArgs.BazelMode, "bazel-mode", false, "use bazel for analysis of certain modules")
Jingwen Chene647db82022-11-01 11:28:29 +000083 flag.BoolVar(&cmdlineArgs.BazelModeStaging, "bazel-mode-staging", false, "use bazel for analysis of certain near-ready modules")
Chris Parsonsef615e52022-08-18 22:04:11 -040084 flag.BoolVar(&cmdlineArgs.BazelModeDev, "bazel-mode-dev", false, "use bazel for analysis of a large number of modules (less stable)")
Chris Parsons9402ca82023-02-23 17:28:06 -050085 flag.BoolVar(&cmdlineArgs.UseBazelProxy, "use-bazel-proxy", false, "communicate with bazel using unix socket proxy instead of spawning subprocesses")
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020086
Sasha Smundakaf5ca922022-12-12 21:23:34 -080087 // Flags that probably shouldn't be flags of soong_build, but we haven't found
Lukacs T. Berkib078ade2021-08-31 10:42:08 +020088 // the time to remove them yet
Sasha Smundakaf5ca922022-12-12 21:23:34 -080089 flag.BoolVar(&cmdlineArgs.RunGoTests, "t", false, "build and run go tests during bootstrap")
Dan Willemsen66213a62021-09-21 17:50:30 -070090
91 // Disable deterministic randomization in the protobuf package, so incremental
92 // builds with unrelated Soong changes don't trigger large rebuilds (since we
93 // write out text protos in command lines, and command line changes trigger
94 // rebuilds).
95 androidProtobuf.DisableRand()
Colin Crosse87040b2017-12-11 15:52:26 -080096}
97
Jeff Gaston088e29e2017-11-29 16:47:17 -080098func newNameResolver(config android.Config) *android.NameResolver {
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000099 return android.NewNameResolver(config)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800100}
101
Lukacs T. Berkiffc9e8d2021-09-07 17:54:38 +0200102func newContext(configuration android.Config) *android.Context {
Colin Crossae8600b2020-10-29 17:09:13 -0700103 ctx := android.NewContext(configuration)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400104 ctx.SetNameInterface(newNameResolver(configuration))
105 ctx.SetAllowMissingDependencies(configuration.AllowMissingDependencies())
Spandan Dasc5763832022-11-08 18:42:16 +0000106 ctx.AddIncludeTags(configuration.IncludeTags()...)
Chris Parsonsf3c96ef2020-09-29 02:23:17 -0400107 return ctx
108}
109
Chris Parsonsf874e462022-05-10 13:50:12 -0400110// Bazel-enabled mode. Attaches a mutator to queue Bazel requests, adds a
111// BeforePrepareBuildActionsHook to invoke Bazel, and then uses Bazel metadata
112// for modules that should be handled by Bazel.
Sasha Smundak1845f422022-12-13 14:18:58 -0800113func runMixedModeBuild(ctx *android.Context, extraNinjaDeps []string) string {
Chris Parsonsf874e462022-05-10 13:50:12 -0400114 ctx.EventHandler.Begin("mixed_build")
115 defer ctx.EventHandler.End("mixed_build")
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200116
Chris Parsonsf874e462022-05-10 13:50:12 -0400117 bazelHook := func() error {
Sasha Smundak1845f422022-12-13 14:18:58 -0800118 return ctx.Config().BazelContext.InvokeBazel(ctx.Config(), ctx)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200119 }
Chris Parsonsf874e462022-05-10 13:50:12 -0400120 ctx.SetBeforePrepareBuildActionsHook(bazelHook)
Sasha Smundak1845f422022-12-13 14:18:58 -0800121 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, bootstrap.DoEverything, ctx.Context, ctx.Config())
Chris Parsons027881c2022-05-24 15:38:38 -0400122 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200123
Sasha Smundak1845f422022-12-13 14:18:58 -0800124 bazelPaths, err := readFileLines(ctx.Config().Getenv("BAZEL_DEPS_FILE"))
MarkDacek0d5bca52022-10-10 20:07:48 +0000125 if err != nil {
126 panic("Bazel deps file not found: " + err.Error())
127 }
128 ninjaDeps = append(ninjaDeps, bazelPaths...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800129 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200130
Paul Duffin780a1852022-11-05 10:17:12 +0000131 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Paul Duffin0c09a432022-11-05 15:28:04 +0000132 return cmdlineArgs.OutFile
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200133}
134
135// Run the code-generation phase to convert BazelTargetModules to BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800136func runQueryView(queryviewDir, queryviewMarker string, ctx *android.Context) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400137 ctx.EventHandler.Begin("queryview")
138 defer ctx.EventHandler.End("queryview")
Cole Faustb85d1a12022-11-08 18:14:01 -0800139 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.QueryView, topDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000140 err := createBazelWorkspace(codegenContext, shared.JoinPath(topDir, queryviewDir), false)
Sasha Smundak1845f422022-12-13 14:18:58 -0800141 maybeQuit(err, "")
Lukacs T. Berki3a821692021-09-06 17:08:02 +0200142 touch(shared.JoinPath(topDir, queryviewMarker))
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200143}
144
Spandan Das5af0bd32022-09-28 20:43:08 +0000145// Run the code-generation phase to convert API contributions to BUILD files.
146// Return marker file for the new synthetic workspace
Sasha Smundak1845f422022-12-13 14:18:58 -0800147func runApiBp2build(ctx *android.Context, extraNinjaDeps []string) string {
Spandan Das5af0bd32022-09-28 20:43:08 +0000148 ctx.EventHandler.Begin("api_bp2build")
149 defer ctx.EventHandler.End("api_bp2build")
Spandan Das255648c2023-01-11 03:05:24 +0000150 // api_bp2build does not run the typical pipeline of soong mutators.
151 // Hoevever, it still runs the defaults mutator which can create dependencies.
152 // These dependencies might not always exist (e.g. in tests)
153 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
Spandan Das5af0bd32022-09-28 20:43:08 +0000154 ctx.RegisterForApiBazelConversion()
155
156 // Register the Android.bp files in the tree
157 // Add them to the workspace's .d file
158 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
159 if paths, err := ctx.ListModulePaths("."); err == nil {
160 extraNinjaDeps = append(extraNinjaDeps, paths...)
161 } else {
162 panic(err)
163 }
164
165 // Run the loading and analysis phase
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800166 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args,
Spandan Das5af0bd32022-09-28 20:43:08 +0000167 bootstrap.StopBeforePrepareBuildActions,
168 ctx.Context,
Sasha Smundak1845f422022-12-13 14:18:58 -0800169 ctx.Config())
Spandan Das5af0bd32022-09-28 20:43:08 +0000170 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
171
172 // Add the globbed dependencies
Sasha Smundak1845f422022-12-13 14:18:58 -0800173 ninjaDeps = append(ninjaDeps, writeBuildGlobsNinjaFile(ctx)...)
Spandan Das5af0bd32022-09-28 20:43:08 +0000174
175 // Run codegen to generate BUILD files
Cole Faustb85d1a12022-11-08 18:14:01 -0800176 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.ApiBp2build, topDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800177 absoluteApiBp2buildDir := shared.JoinPath(topDir, cmdlineArgs.BazelApiBp2buildDir)
Spandan Das98cb8562023-03-09 23:05:47 +0000178 // Always generate bp2build_all_srcs filegroups in api_bp2build.
179 // This is necessary to force each Android.bp file to create an equivalent BUILD file
180 // and prevent package boundray issues.
181 // e.g.
182 // Source
183 // f/b/Android.bp
184 // java_library{
185 // name: "foo",
186 // api: "api/current.txt",
187 // }
188 //
189 // f/b/api/Android.bp <- will cause package boundary issues
190 //
191 // Gen
192 // f/b/BUILD
193 // java_contribution{
194 // name: "foo.contribution",
195 // api: "//f/b/api:current.txt",
196 // }
197 //
198 // If we don't generate f/b/api/BUILD, foo.contribution will be unbuildable.
199 err := createBazelWorkspace(codegenContext, absoluteApiBp2buildDir, true)
Sasha Smundak1845f422022-12-13 14:18:58 -0800200 maybeQuit(err, "")
Spandan Das5af0bd32022-09-28 20:43:08 +0000201 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
202
203 // Create soong_injection repository
Cole Faust9e384e22023-02-08 17:43:09 -0800204 soongInjectionFiles, err := bp2build.CreateSoongInjectionDirFiles(codegenContext, bp2build.CreateCodegenMetrics())
205 maybeQuit(err, "")
Sasha Smundak1845f422022-12-13 14:18:58 -0800206 absoluteSoongInjectionDir := shared.JoinPath(topDir, ctx.Config().SoongOutDir(), bazel.SoongInjectionDirName)
Spandan Das5af0bd32022-09-28 20:43:08 +0000207 for _, file := range soongInjectionFiles {
Spandan Das067210f2022-12-07 01:14:52 +0000208 // The API targets in api_bp2build workspace do not have any dependency on api_bp2build.
209 // But we need to create these files to prevent errors during Bazel analysis.
210 // These need to be created in Read-Write mode.
211 // This is because the subsequent step (bp2build in api domain analysis) creates them in Read-Write mode
212 // to allow users to edit/experiment in the synthetic workspace.
213 writeReadWriteFile(absoluteSoongInjectionDir, file)
Spandan Das5af0bd32022-09-28 20:43:08 +0000214 }
215
Sasha Smundak1845f422022-12-13 14:18:58 -0800216 workspace := shared.JoinPath(ctx.Config().SoongOutDir(), "api_bp2build")
Spandan Das5af0bd32022-09-28 20:43:08 +0000217 // Create the symlink forest
Usta Shresthada15c612022-11-08 14:12:36 -0500218 symlinkDeps, _, _ := bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800219 ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE"),
Spandan Das5af0bd32022-09-28 20:43:08 +0000220 topDir,
221 workspace,
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800222 cmdlineArgs.BazelApiBp2buildDir,
Sasha Smundak1845f422022-12-13 14:18:58 -0800223 apiBuildFileExcludes(ctx))
Spandan Das5af0bd32022-09-28 20:43:08 +0000224 ninjaDeps = append(ninjaDeps, symlinkDeps...)
225
226 workspaceMarkerFile := workspace + ".marker"
Paul Duffin780a1852022-11-05 10:17:12 +0000227 writeDepFile(workspaceMarkerFile, ctx.EventHandler, ninjaDeps)
Spandan Das5af0bd32022-09-28 20:43:08 +0000228 touch(shared.JoinPath(topDir, workspaceMarkerFile))
229 return workspaceMarkerFile
230}
231
232// With some exceptions, api_bp2build does not have any dependencies on the checked-in BUILD files
233// Exclude them from the generated workspace to prevent unrelated errors during the loading phase
Sasha Smundak1845f422022-12-13 14:18:58 -0800234func apiBuildFileExcludes(ctx *android.Context) []string {
235 ret := bazelArtifacts()
Spandan Das5af0bd32022-09-28 20:43:08 +0000236 srcs, err := getExistingBazelRelatedFiles(topDir)
Sasha Smundak1845f422022-12-13 14:18:58 -0800237 maybeQuit(err, "Error determining existing Bazel-related files")
Spandan Das5af0bd32022-09-28 20:43:08 +0000238 for _, src := range srcs {
Sasha Smundak1845f422022-12-13 14:18:58 -0800239 // Exclude all src BUILD files
Spandan Das5af0bd32022-09-28 20:43:08 +0000240 if src != "WORKSPACE" &&
241 src != "BUILD" &&
242 src != "BUILD.bazel" &&
243 !strings.HasPrefix(src, "build/bazel") &&
Spandan Das6b91a382022-11-30 02:17:06 +0000244 !strings.HasPrefix(src, "external/bazel-skylib") &&
Spandan Das5af0bd32022-09-28 20:43:08 +0000245 !strings.HasPrefix(src, "prebuilts/clang") {
246 ret = append(ret, src)
247 }
248 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800249 // Android.bp files for api surfaces are mounted to out/, but out/ should not be a
250 // dep for api_bp2build. Otherwise, api_bp2build will be run every single time
251 ret = append(ret, ctx.Config().OutDir())
Spandan Das5af0bd32022-09-28 20:43:08 +0000252 return ret
253}
254
Paul Duffin780a1852022-11-05 10:17:12 +0000255func writeMetrics(configuration android.Config, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400256 if len(metricsDir) < 1 {
257 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating soong metrics: LOG_DIR\n")
258 os.Exit(1)
259 }
260 metricsFile := filepath.Join(metricsDir, "soong_build_metrics.pb")
261 err := android.WriteMetrics(configuration, eventHandler, metricsFile)
Sasha Smundak1845f422022-12-13 14:18:58 -0800262 maybeQuit(err, "error writing soong_build metrics %s", metricsFile)
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200263}
264
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800265func writeJsonModuleGraphAndActions(ctx *android.Context, cmdArgs android.CmdArgs) {
266 graphFile, graphErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleGraphFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800267 maybeQuit(graphErr, "graph err")
kgui67007242022-01-25 13:50:25 +0800268 defer graphFile.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800269 actionsFile, actionsErr := os.Create(shared.JoinPath(topDir, cmdArgs.ModuleActionsFile))
270 maybeQuit(actionsErr, "actions err")
kgui67007242022-01-25 13:50:25 +0800271 defer actionsFile.Close()
272 ctx.Context.PrintJSONGraphAndActions(graphFile, actionsFile)
Lukacs T. Berki97bb9f12021-04-01 18:28:45 +0200273}
274
Sasha Smundak1845f422022-12-13 14:18:58 -0800275func writeBuildGlobsNinjaFile(ctx *android.Context) []string {
Chris Parsons715b08f2022-03-22 19:23:40 -0400276 ctx.EventHandler.Begin("globs_ninja_file")
277 defer ctx.EventHandler.End("globs_ninja_file")
278
Sasha Smundak1845f422022-12-13 14:18:58 -0800279 globDir := bootstrap.GlobDirectory(ctx.Config().SoongOutDir(), globListDir)
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200280 bootstrap.WriteBuildGlobsNinjaFile(&bootstrap.GlobSingleton{
Chris Parsons715b08f2022-03-22 19:23:40 -0400281 GlobLister: ctx.Globs,
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200282 GlobFile: globFile,
283 GlobDir: globDir,
Chris Parsons715b08f2022-03-22 19:23:40 -0400284 SrcDir: ctx.SrcDir(),
Sasha Smundak1845f422022-12-13 14:18:58 -0800285 }, ctx.Config())
Lukacs T. Berki809d2ed2021-08-18 10:55:32 +0200286 return bootstrap.GlobFileListFiles(globDir)
287}
288
Paul Duffin780a1852022-11-05 10:17:12 +0000289func writeDepFile(outputFile string, eventHandler *metrics.EventHandler, ninjaDeps []string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400290 eventHandler.Begin("ninja_deps")
291 defer eventHandler.End("ninja_deps")
Lukacs T. Berkie571dc32021-08-25 14:14:13 +0200292 depFile := shared.JoinPath(topDir, outputFile+".d")
293 err := deptools.WriteDepFile(depFile, outputFile, ninjaDeps)
Sasha Smundak1845f422022-12-13 14:18:58 -0800294 maybeQuit(err, "error writing depfile '%s'", depFile)
Paul Duffin0c09a432022-11-05 15:28:04 +0000295}
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200296
Paul Duffin0c09a432022-11-05 15:28:04 +0000297// runSoongOnlyBuild runs the standard Soong build in a number of different modes.
Sasha Smundak1845f422022-12-13 14:18:58 -0800298func runSoongOnlyBuild(ctx *android.Context, extraNinjaDeps []string) string {
Paul Duffin39eae8f2022-11-05 14:59:52 +0000299 ctx.EventHandler.Begin("soong_build")
300 defer ctx.EventHandler.End("soong_build")
301
Paul Duffin0c09a432022-11-05 15:28:04 +0000302 var stopBefore bootstrap.StopBefore
Sasha Smundak1845f422022-12-13 14:18:58 -0800303 switch ctx.Config().BuildMode {
304 case android.GenerateModuleGraph:
Paul Duffin0c09a432022-11-05 15:28:04 +0000305 stopBefore = bootstrap.StopBeforeWriteNinja
Usta Shrestha7fae6952022-12-21 11:46:28 -0500306 case android.GenerateQueryView, android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000307 stopBefore = bootstrap.StopBeforePrepareBuildActions
Sasha Smundak1845f422022-12-13 14:18:58 -0800308 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000309 stopBefore = bootstrap.DoEverything
310 }
311
Sasha Smundak1845f422022-12-13 14:18:58 -0800312 ninjaDeps := bootstrap.RunBlueprint(cmdlineArgs.Args, stopBefore, ctx.Context, ctx.Config())
Paul Duffin0c09a432022-11-05 15:28:04 +0000313 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
314
Sasha Smundak1845f422022-12-13 14:18:58 -0800315 globListFiles := writeBuildGlobsNinjaFile(ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000316 ninjaDeps = append(ninjaDeps, globListFiles...)
317
318 // Convert the Soong module graph into Bazel BUILD files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800319 switch ctx.Config().BuildMode {
320 case android.GenerateQueryView:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800321 queryviewMarkerFile := cmdlineArgs.BazelQueryViewDir + ".marker"
Sasha Smundak1845f422022-12-13 14:18:58 -0800322 runQueryView(cmdlineArgs.BazelQueryViewDir, queryviewMarkerFile, ctx)
Paul Duffin0c09a432022-11-05 15:28:04 +0000323 writeDepFile(queryviewMarkerFile, ctx.EventHandler, ninjaDeps)
324 return queryviewMarkerFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800325 case android.GenerateModuleGraph:
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800326 writeJsonModuleGraphAndActions(ctx, cmdlineArgs)
327 writeDepFile(cmdlineArgs.ModuleGraphFile, ctx.EventHandler, ninjaDeps)
328 return cmdlineArgs.ModuleGraphFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800329 case android.GenerateDocFile:
Paul Duffin0c09a432022-11-05 15:28:04 +0000330 // TODO: we could make writeDocs() return the list of documentation files
331 // written and add them to the .d file. Then soong_docs would be re-run
332 // whenever one is deleted.
Sasha Smundak1845f422022-12-13 14:18:58 -0800333 err := writeDocs(ctx, shared.JoinPath(topDir, cmdlineArgs.DocFile))
334 maybeQuit(err, "error building Soong documentation")
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800335 writeDepFile(cmdlineArgs.DocFile, ctx.EventHandler, ninjaDeps)
336 return cmdlineArgs.DocFile
Sasha Smundak1845f422022-12-13 14:18:58 -0800337 default:
Paul Duffin0c09a432022-11-05 15:28:04 +0000338 // The actual output (build.ninja) was written in the RunBlueprint() call
339 // above
340 writeDepFile(cmdlineArgs.OutFile, ctx.EventHandler, ninjaDeps)
Paul Duffinb713ddf2022-11-05 16:14:30 +0000341 return cmdlineArgs.OutFile
Paul Duffin0c09a432022-11-05 15:28:04 +0000342 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200343}
344
345// soong_ui dumps the available environment variables to
346// soong.environment.available . Then soong_build itself is run with an empty
347// environment so that the only way environment variables can be accessed is
348// using Config, which tracks access to them.
349
350// At the end of the build, a file called soong.environment.used is written
351// containing the current value of all used environment variables. The next
352// time soong_ui is run, it checks whether any environment variables that was
353// used had changed and if so, it deletes soong.environment.used to cause a
354// rebuild.
355//
356// The dependency of build.ninja on soong.environment.used is declared in
357// build.ninja.d
358func parseAvailableEnv() map[string]string {
359 if availableEnvFile == "" {
360 fmt.Fprintf(os.Stderr, "--available_env not set\n")
361 os.Exit(1)
362 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200363 result, err := shared.EnvFromFile(shared.JoinPath(topDir, availableEnvFile))
Sasha Smundak1845f422022-12-13 14:18:58 -0800364 maybeQuit(err, "error reading available environment file '%s'", availableEnvFile)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200365 return result
Lukacs T. Berki6790ebc2021-04-01 17:55:58 +0200366}
367
Colin Cross3f40fa42015-01-30 17:27:36 -0800368func main() {
369 flag.Parse()
370
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100371 shared.ReexecWithDelveMaybe(delveListen, delvePath)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100372 android.InitSandbox(topDir)
Lukacs T. Berki7690c092021-02-26 14:27:36 +0100373
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200374 availableEnv := parseAvailableEnv()
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800375 configuration, err := android.NewConfig(cmdlineArgs, availableEnv)
Sasha Smundak1845f422022-12-13 14:18:58 -0800376 maybeQuit(err, "")
Lukacs T. Berkid1e3f1f2021-03-16 08:55:23 +0100377 if configuration.Getenv("ALLOW_MISSING_DEPENDENCIES") == "true" {
378 configuration.SetAllowMissingDependencies()
379 }
380
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800381 extraNinjaDeps := []string{configuration.ProductVariablesFileName, usedEnvFile}
Lukacs T. Berki7d613bf2021-03-02 10:09:41 +0100382 if shared.IsDebugging() {
Colin Crossaa812d12019-06-19 13:33:24 -0700383 // Add a non-existent file to the dependencies so that soong_build will rerun when the debugger is
384 // enabled even if it completed successfully.
Lukacs T. Berki9f6c24a2021-08-26 15:07:24 +0200385 extraNinjaDeps = append(extraNinjaDeps, filepath.Join(configuration.SoongOutDir(), "always_rerun_for_delve"))
Colin Crossaa812d12019-06-19 13:33:24 -0700386 }
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500387
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700388 // Bypass configuration.Getenv, as LOG_DIR does not need to be dependency tracked. By definition, it will
389 // change between every CI build, so tracking it would require re-running Soong for every build.
Sasha Smundak1845f422022-12-13 14:18:58 -0800390 metricsDir := availableEnv["LOG_DIR"]
Dan Willemsenccf36aa2022-04-20 23:11:43 -0700391
Joe Onorato2e5e4012022-06-07 17:16:08 -0700392 ctx := newContext(configuration)
Joe Onorato2e5e4012022-06-07 17:16:08 -0700393
Sasha Smundak1845f422022-12-13 14:18:58 -0800394 var finalOutputFile string
Joe Onorato2e5e4012022-06-07 17:16:08 -0700395
Sasha Smundak1845f422022-12-13 14:18:58 -0800396 // Run Soong for a specific activity, like bp2build, queryview
397 // or the actual Soong build for the build.ninja file.
398 switch configuration.BuildMode {
399 case android.SymlinkForest:
400 finalOutputFile = runSymlinkForestCreation(ctx, extraNinjaDeps, metricsDir)
401 case android.Bp2build:
402 // Run the alternate pipeline of bp2build mutators and singleton to convert
403 // Blueprint to BUILD files before everything else.
404 finalOutputFile = runBp2Build(ctx, extraNinjaDeps, metricsDir)
405 case android.ApiBp2build:
406 finalOutputFile = runApiBp2build(ctx, extraNinjaDeps)
407 writeMetrics(configuration, ctx.EventHandler, metricsDir)
408 default:
409 ctx.Register()
410 if configuration.IsMixedBuildsEnabled() {
411 finalOutputFile = runMixedModeBuild(ctx, extraNinjaDeps)
412 } else {
413 finalOutputFile = runSoongOnlyBuild(ctx, extraNinjaDeps)
414 }
415 writeMetrics(configuration, ctx.EventHandler, metricsDir)
416 }
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200417 writeUsedEnvironmentFile(configuration, finalOutputFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100418}
419
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200420func writeUsedEnvironmentFile(configuration android.Config, finalOutputFile string) {
421 if usedEnvFile == "" {
422 return
423 }
424
425 path := shared.JoinPath(topDir, usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100426 data, err := shared.EnvFileContents(configuration.EnvDeps())
Sasha Smundak1845f422022-12-13 14:18:58 -0800427 maybeQuit(err, "error writing used environment file '%s'\n", usedEnvFile)
Lukacs T. Berkif0b3b942021-03-23 11:46:47 +0100428
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400429 if preexistingData, err := os.ReadFile(path); err != nil {
430 if !os.IsNotExist(err) {
Sasha Smundak1845f422022-12-13 14:18:58 -0800431 maybeQuit(err, "error reading used environment file '%s'", usedEnvFile)
Usta Shrestha2ba28a32022-10-24 11:33:09 -0400432 }
433 } else if bytes.Equal(preexistingData, data) {
434 // used environment file is unchanged
435 return
436 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800437 err = os.WriteFile(path, data, 0666)
438 maybeQuit(err, "error writing used environment file '%s'", usedEnvFile)
439
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200440 // Touch the output file so that it's not older than the file we just
Lukacs T. Berkic99c9472021-03-24 10:50:06 +0100441 // wrote. We can't write the environment file earlier because one an access
442 // new environment variables while writing it.
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200443 touch(shared.JoinPath(topDir, finalOutputFile))
Colin Cross3f40fa42015-01-30 17:27:36 -0800444}
Jingwen Chen5ba7e472020-07-15 10:06:41 +0000445
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200446func touch(path string) {
447 f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
Sasha Smundak1845f422022-12-13 14:18:58 -0800448 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200449 err = f.Close()
Sasha Smundak1845f422022-12-13 14:18:58 -0800450 maybeQuit(err, "Error touching '%s'", path)
Lukacs T. Berkif8e24282021-04-14 10:31:00 +0200451
452 currentTime := time.Now().Local()
453 err = os.Chtimes(path, currentTime, currentTime)
Sasha Smundak1845f422022-12-13 14:18:58 -0800454 maybeQuit(err, "error touching '%s'", path)
Rupert Shuttleworth00960792021-05-12 21:20:13 -0400455}
456
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400457// Read the bazel.list file that the Soong Finder already dumped earlier (hopefully)
458// It contains the locations of BUILD files, BUILD.bazel files, etc. in the source dir
459func getExistingBazelRelatedFiles(topDir string) ([]string, error) {
Lukacs T. Berkif9008072021-08-16 15:24:48 +0200460 bazelFinderFile := filepath.Join(filepath.Dir(cmdlineArgs.ModuleListFile), "bazel.list")
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400461 if !filepath.IsAbs(bazelFinderFile) {
462 // Assume this was a relative path under topDir
463 bazelFinderFile = filepath.Join(topDir, bazelFinderFile)
464 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800465 return readFileLines(bazelFinderFile)
Rupert Shuttleworthe03bb612021-05-20 19:34:50 -0400466}
467
Spandan Das5af0bd32022-09-28 20:43:08 +0000468func bazelArtifacts() []string {
469 return []string{
470 "bazel-bin",
471 "bazel-genfiles",
472 "bazel-out",
473 "bazel-testlogs",
Usta (Tsering) Shresthac4c07b12022-11-08 18:31:14 -0500474 "bazel-workspace",
Spandan Das5af0bd32022-09-28 20:43:08 +0000475 "bazel-" + filepath.Base(topDir),
476 }
477}
478
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000479// This could in theory easily be separated into a binary that generically
480// merges two directories into a symlink tree. The main obstacle is that this
481// function currently depends on both Bazel-specific knowledge (the existence
482// of bazel-* symlinks) and configuration (the set of BUILD.bazel files that
483// should and should not be kept)
484//
485// Ideally, bp2build would write a file that contains instructions to the
486// symlink tree creation binary. Then the latter would not need to depend on
487// the very heavy-weight machinery of soong_build .
Sasha Smundak1845f422022-12-13 14:18:58 -0800488func runSymlinkForestCreation(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
Usta Shresthada15c612022-11-08 14:12:36 -0500489 var ninjaDeps []string
490 var mkdirCount, symlinkCount uint64
491
Paul Duffinb4e8d912022-11-04 13:35:50 +0000492 ctx.EventHandler.Do("symlink_forest", func() {
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000493 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
Sasha Smundak1845f422022-12-13 14:18:58 -0800494 verbose := ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE")
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000495
496 // PlantSymlinkForest() returns all the directories that were readdir()'ed.
497 // Such a directory SHOULD be added to `ninjaDeps` so that a child directory
498 // or file created/deleted under it would trigger an update of the symlink forest.
Sasha Smundak1845f422022-12-13 14:18:58 -0800499 generatedRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "bp2build")
500 workspaceRoot := shared.JoinPath(ctx.Config().SoongOutDir(), "workspace")
Usta Shresthada15c612022-11-08 14:12:36 -0500501 var symlinkForestDeps []string
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000502 ctx.EventHandler.Do("plant", func() {
Usta Shresthada15c612022-11-08 14:12:36 -0500503 symlinkForestDeps, mkdirCount, symlinkCount = bp2build.PlantSymlinkForest(
Sasha Smundak1845f422022-12-13 14:18:58 -0800504 verbose, topDir, workspaceRoot, generatedRoot, excludedFromSymlinkForest(ctx, verbose))
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000505 })
Usta Shresthada15c612022-11-08 14:12:36 -0500506 ninjaDeps = append(ninjaDeps, symlinkForestDeps...)
Usta (Tsering) Shrestha93b2a9b2022-12-01 05:55:35 +0000507 })
Usta Shresthada15c612022-11-08 14:12:36 -0500508
509 writeDepFile(cmdlineArgs.SymlinkForestMarker, ctx.EventHandler, ninjaDeps)
510 touch(shared.JoinPath(topDir, cmdlineArgs.SymlinkForestMarker))
usta4f5d2c12022-10-28 23:32:01 -0400511 codegenMetrics := bp2build.ReadCodegenMetrics(metricsDir)
512 if codegenMetrics == nil {
513 m := bp2build.CreateCodegenMetrics()
514 codegenMetrics = &m
515 } else {
516 //TODO (usta) we cannot determine if we loaded a stale file, i.e. from an unrelated prior
517 //invocation of codegen. We should simply use a separate .pb file
518 }
Usta Shresthada15c612022-11-08 14:12:36 -0500519 codegenMetrics.SetSymlinkCount(symlinkCount)
520 codegenMetrics.SetMkDirCount(mkdirCount)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000521 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800522 return cmdlineArgs.SymlinkForestMarker
Lukacs T. Berkic541cd22022-10-26 07:26:50 +0000523}
524
Sasha Smundak1845f422022-12-13 14:18:58 -0800525func excludedFromSymlinkForest(ctx *android.Context, verbose bool) []string {
526 excluded := bazelArtifacts()
527 if cmdlineArgs.OutDir[0] != '/' {
528 excluded = append(excluded, cmdlineArgs.OutDir)
529 }
530
531 // Find BUILD files in the srcDir which are not in the allowlist
532 // (android.Bp2BuildConversionAllowlist#ShouldKeepExistingBuildFileForDir)
533 // and return their paths so they can be left out of the Bazel workspace dir (i.e. ignored)
534 existingBazelFiles, err := getExistingBazelRelatedFiles(topDir)
535 maybeQuit(err, "Error determining existing Bazel-related files")
536
537 for _, path := range existingBazelFiles {
538 fullPath := shared.JoinPath(topDir, path)
539 fileInfo, err2 := os.Stat(fullPath)
540 if err2 != nil {
541 // Warn about error, but continue trying to check files
542 fmt.Fprintf(os.Stderr, "WARNING: Error accessing path '%s', err: %s\n", fullPath, err2)
543 continue
544 }
545 // Exclude only files named 'BUILD' or 'BUILD.bazel' and unless forcibly kept
546 if fileInfo.IsDir() ||
547 (fileInfo.Name() != "BUILD" && fileInfo.Name() != "BUILD.bazel") ||
548 ctx.Config().Bp2buildPackageConfig.ShouldKeepExistingBuildFileForDir(filepath.Dir(path)) {
549 // Don't ignore this existing build file
550 continue
551 }
552 if verbose {
553 fmt.Fprintf(os.Stderr, "Ignoring existing BUILD file: %s\n", path)
554 }
555 excluded = append(excluded, path)
556 }
557
558 // Temporarily exclude stuff to make `bazel build //external/...` (and `bazel build //frameworks/...`) work
559 excluded = append(excluded,
560 // FIXME: 'autotest_lib' is a symlink back to external/autotest, and this causes an infinite
561 // symlink expansion error for Bazel
562 "external/autotest/venv/autotest_lib",
563 "external/autotest/autotest_lib",
564 "external/autotest/client/autotest_lib/client",
565
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
568 // BUILD files we want to ignore
569 "external/google-fruit/extras/bazel_root/third_party/fruit",
570
571 // FIXME: 'frameworks/compile/slang' has a filegroup error due to an escaping issue
572 "frameworks/compile/slang",
573
574 // FIXME(b/260809113): 'prebuilts/clang/host/linux-x86/clang-dev' is a tool-generated symlink
575 // directory that contains a BUILD file. The bazel files finder code doesn't traverse into symlink dirs,
576 // and hence is not aware of this BUILD file and exclude it accordingly during symlink forest generation
577 // when checking against keepExistingBuildFiles allowlist.
578 //
579 // This is necessary because globs in //prebuilts/clang/host/linux-x86/BUILD
580 // currently assume no subpackages (keepExistingBuildFile is not recursive for that directory).
581 //
582 // This is a bandaid until we the symlink forest logic can intelligently exclude BUILD files found in
583 // source symlink dirs according to the keepExistingBuildFile allowlist.
584 "prebuilts/clang/host/linux-x86/clang-dev",
585 )
586 return excluded
587}
588
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500589// Run Soong in the bp2build mode. This creates a standalone context that registers
590// an alternate pipeline of mutators and singletons specifically for generating
591// Bazel BUILD files instead of Ninja files.
Sasha Smundak1845f422022-12-13 14:18:58 -0800592func runBp2Build(ctx *android.Context, extraNinjaDeps []string, metricsDir string) string {
usta4f5d2c12022-10-28 23:32:01 -0400593 var codegenMetrics *bp2build.CodegenMetrics
Paul Duffinb4e8d912022-11-04 13:35:50 +0000594 ctx.EventHandler.Do("bp2build", func() {
Jingwen Cheneb76c432021-01-28 08:22:12 -0500595
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400596 // Propagate "allow misssing dependencies" bit. This is normally set in
Paul Duffinb4e8d912022-11-04 13:35:50 +0000597 // newContext(), but we create ctx without calling that method.
Sasha Smundak1845f422022-12-13 14:18:58 -0800598 ctx.SetAllowMissingDependencies(ctx.Config().AllowMissingDependencies())
599 ctx.SetNameInterface(newNameResolver(ctx.Config()))
Paul Duffinb4e8d912022-11-04 13:35:50 +0000600 ctx.RegisterForBazelConversion()
601 ctx.SetModuleListFile(cmdlineArgs.ModuleListFile)
Jingwen Cheneb76c432021-01-28 08:22:12 -0500602
Usta Shresthaa117c582022-10-04 12:13:25 -0400603 var ninjaDeps []string
604 ninjaDeps = append(ninjaDeps, extraNinjaDeps...)
605
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400606 // Run the loading and analysis pipeline to prepare the graph of regular
607 // Modules parsed from Android.bp files, and the BazelTargetModules mapped
608 // from the regular Modules.
Paul Duffinb4e8d912022-11-04 13:35:50 +0000609 ctx.EventHandler.Do("bootstrap", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400610 blueprintArgs := cmdlineArgs
Sasha Smundak1845f422022-12-13 14:18:58 -0800611 bootstrapDeps := bootstrap.RunBlueprint(blueprintArgs.Args,
612 bootstrap.StopBeforePrepareBuildActions, ctx.Context, ctx.Config())
Usta Shresthaa117c582022-10-04 12:13:25 -0400613 ninjaDeps = append(ninjaDeps, bootstrapDeps...)
614 })
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200615
Sasha Smundak1845f422022-12-13 14:18:58 -0800616 globListFiles := writeBuildGlobsNinjaFile(ctx)
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400617 ninjaDeps = append(ninjaDeps, globListFiles...)
Lukacs T. Berkid518e1a2021-04-14 13:49:50 +0200618
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400619 // Run the code-generation phase to convert BazelTargetModules to BUILD files
Usta Shresthaa117c582022-10-04 12:13:25 -0400620 // and print conversion codegenMetrics to the user.
Cole Faustb85d1a12022-11-08 18:14:01 -0800621 codegenContext := bp2build.NewCodegenContext(ctx.Config(), ctx, bp2build.Bp2Build, topDir)
Paul Duffinb4e8d912022-11-04 13:35:50 +0000622 ctx.EventHandler.Do("codegen", func() {
Usta Shresthaa117c582022-10-04 12:13:25 -0400623 codegenMetrics = bp2build.Codegen(codegenContext)
624 })
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200625
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400626 ninjaDeps = append(ninjaDeps, codegenContext.AdditionalNinjaDeps()...)
Chris Parsons715b08f2022-03-22 19:23:40 -0400627
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800628 writeDepFile(cmdlineArgs.Bp2buildMarker, ctx.EventHandler, ninjaDeps)
629 touch(shared.JoinPath(topDir, cmdlineArgs.Bp2buildMarker))
Usta Shrestha5c6b9482022-05-26 12:22:17 -0400630 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400631
Lukacs T. Berkib353cca2021-04-16 13:47:36 +0200632 // Only report metrics when in bp2build mode. The metrics aren't relevant
633 // for queryview, since that's a total repo-wide conversion and there's a
634 // 1:1 mapping for each module.
Sasha Smundak1845f422022-12-13 14:18:58 -0800635 if ctx.Config().IsEnvTrue("BP2BUILD_VERBOSE") {
Usta Shresthaa117c582022-10-04 12:13:25 -0400636 codegenMetrics.Print()
Sasha Smundak0fd93e02022-05-19 19:34:31 -0700637 }
Paul Duffinb4e8d912022-11-04 13:35:50 +0000638 writeBp2BuildMetrics(codegenMetrics, ctx.EventHandler, metricsDir)
Sasha Smundakaf5ca922022-12-12 21:23:34 -0800639 return cmdlineArgs.Bp2buildMarker
Jingwen Chendaa54bc2020-12-14 02:58:54 -0500640}
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500641
642// Write Bp2Build metrics into $LOG_DIR
Paul Duffinf4906562022-11-05 14:21:16 +0000643func writeBp2BuildMetrics(codegenMetrics *bp2build.CodegenMetrics, eventHandler *metrics.EventHandler, metricsDir string) {
Chris Parsons715b08f2022-03-22 19:23:40 -0400644 for _, event := range eventHandler.CompletedEvents() {
usta4f5d2c12022-10-28 23:32:01 -0400645 codegenMetrics.AddEvent(&bp2build_metrics_proto.Event{
646 Name: event.Id,
647 StartTime: uint64(event.Start.UnixNano()),
648 RealTime: event.RuntimeNanoseconds(),
649 })
Chris Parsons715b08f2022-03-22 19:23:40 -0400650 }
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500651 if len(metricsDir) < 1 {
652 fmt.Fprintf(os.Stderr, "\nMissing required env var for generating bp2build metrics: LOG_DIR\n")
653 os.Exit(1)
654 }
Chris Parsons715b08f2022-03-22 19:23:40 -0400655 codegenMetrics.Write(metricsDir)
Alex Márquez Pérez Muñíz Díaz Púras Thaureaux947fdbf2021-11-10 09:55:20 -0500656}
MarkDacek0d5bca52022-10-10 20:07:48 +0000657
Sasha Smundak1845f422022-12-13 14:18:58 -0800658func readFileLines(path string) ([]string, error) {
659 data, err := os.ReadFile(path)
660 if err == nil {
661 return strings.Split(strings.TrimSpace(string(data)), "\n"), nil
MarkDacek0d5bca52022-10-10 20:07:48 +0000662 }
Sasha Smundak1845f422022-12-13 14:18:58 -0800663 return nil, err
664
665}
666func maybeQuit(err error, format string, args ...interface{}) {
667 if err == nil {
668 return
669 }
670 if format != "" {
671 fmt.Fprintln(os.Stderr, fmt.Sprintf(format, args...)+": "+err.Error())
672 } else {
673 fmt.Fprintln(os.Stderr, err)
674 }
675 os.Exit(1)
MarkDacek0d5bca52022-10-10 20:07:48 +0000676}