blob: 5f9bd016e479193e17bf03f5fc47f6f941f18ea2 [file] [log] [blame]
Dan Willemsen1e704462016-08-21 15:17:17 -07001// Copyright 2017 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 "context"
Dan Willemsen051133b2017-07-14 11:29:29 -070019 "flag"
20 "fmt"
Dan Willemsen1e704462016-08-21 15:17:17 -070021 "os"
22 "path/filepath"
23 "strconv"
24 "strings"
25 "time"
26
27 "android/soong/ui/build"
28 "android/soong/ui/logger"
Nan Zhang17f27672018-12-12 16:01:49 -080029 "android/soong/ui/metrics"
Dan Willemsenb82471a2018-05-17 16:37:09 -070030 "android/soong/ui/status"
31 "android/soong/ui/terminal"
Dan Willemsend9f6fa22016-08-21 15:17:17 -070032 "android/soong/ui/tracer"
Dan Willemsen1e704462016-08-21 15:17:17 -070033)
34
Patrice Arrudaa5c25422019-04-09 18:49:49 -070035// A command represents an operation to be executed in the soong build
36// system.
37type command struct {
38 // the flag name (must have double dashes)
39 flag string
40
41 // description for the flag (to display when running help)
42 description string
43
44 // Creates the build configuration based on the args and build context.
45 config func(ctx build.Context, args ...string) build.Config
46
47 // Returns what type of IO redirection this Command requires.
48 stdio func() terminal.StdioInterface
49
50 // run the command
51 run func(ctx build.Context, config build.Config, args []string, logsDir string)
52}
53
54const makeModeFlagName = "--make-mode"
55
56// list of supported commands (flags) supported by soong ui
57var commands []command = []command{
58 {
59 flag: makeModeFlagName,
60 description: "build the modules by the target name (i.e. soong_docs)",
61 config: func(ctx build.Context, args ...string) build.Config {
62 return build.NewConfig(ctx, args...)
63 },
64 stdio: func() terminal.StdioInterface {
65 return terminal.StdioImpl{}
66 },
67 run: make,
68 }, {
69 flag: "--dumpvar-mode",
70 description: "print the value of the legacy make variable VAR to stdout",
71 config: dumpVarConfig,
72 stdio: customStdio,
73 run: dumpVar,
74 }, {
75 flag: "--dumpvars-mode",
76 description: "dump the values of one or more legacy make variables, in shell syntax",
77 config: dumpVarConfig,
78 stdio: customStdio,
79 run: dumpVars,
80 },
81}
82
83// indexList returns the index of first found s. -1 is return if s is not
84// found.
Dan Willemsen1e704462016-08-21 15:17:17 -070085func indexList(s string, list []string) int {
86 for i, l := range list {
87 if l == s {
88 return i
89 }
90 }
Dan Willemsen1e704462016-08-21 15:17:17 -070091 return -1
92}
93
Patrice Arrudaa5c25422019-04-09 18:49:49 -070094// inList returns true if one or more of s is in the list.
Dan Willemsen1e704462016-08-21 15:17:17 -070095func inList(s string, list []string) bool {
96 return indexList(s, list) != -1
97}
98
Patrice Arrudaa5c25422019-04-09 18:49:49 -070099// Main execution of soong_ui. The command format is as follows:
100//
101// soong_ui <command> [<arg 1> <arg 2> ... <arg n>]
102//
103// Command is the type of soong_ui execution. Only one type of
104// execution is specified. The args are specific to the command.
Dan Willemsen1e704462016-08-21 15:17:17 -0700105func main() {
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700106 c, args := getCommand(os.Args)
107 if c == nil {
108 fmt.Fprintf(os.Stderr, "The `soong` native UI is not yet available.\n")
109 os.Exit(1)
Dan Willemsenc35b3812018-07-16 19:59:10 -0700110 }
111
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700112 writer := terminal.NewWriter(c.stdio())
Dan Willemsenb82471a2018-05-17 16:37:09 -0700113 defer writer.Finish()
114
115 log := logger.New(writer)
Dan Willemsen1e704462016-08-21 15:17:17 -0700116 defer log.Cleanup()
117
Dan Willemsen1e704462016-08-21 15:17:17 -0700118 ctx, cancel := context.WithCancel(context.Background())
119 defer cancel()
120
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700121 trace := tracer.New(log)
122 defer trace.Close()
Dan Willemsen1e704462016-08-21 15:17:17 -0700123
Nan Zhang17f27672018-12-12 16:01:49 -0800124 met := metrics.New()
125
Dan Willemsenb82471a2018-05-17 16:37:09 -0700126 stat := &status.Status{}
127 defer stat.Finish()
Sasha Smundakc0c9ef92019-01-23 09:52:57 -0800128 stat.AddOutput(terminal.NewStatusOutput(writer, os.Getenv("NINJA_STATUS"),
129 build.OsEnvironment().IsEnvTrue("ANDROID_QUIET_BUILD")))
Dan Willemsenb82471a2018-05-17 16:37:09 -0700130 stat.AddOutput(trace.StatusTracer())
131
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700132 build.SetupSignals(log, cancel, func() {
133 trace.Close()
134 log.Cleanup()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700135 stat.Finish()
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700136 })
137
Dan Willemsen59339a22018-07-22 21:18:45 -0700138 buildCtx := build.Context{ContextImpl: &build.ContextImpl{
Dan Willemsenb82471a2018-05-17 16:37:09 -0700139 Context: ctx,
140 Logger: log,
Nan Zhang17f27672018-12-12 16:01:49 -0800141 Metrics: met,
Dan Willemsenb82471a2018-05-17 16:37:09 -0700142 Tracer: trace,
143 Writer: writer,
144 Status: stat,
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700145 }}
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700146
147 config := c.config(buildCtx, args...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700148
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700149 build.SetupOutDir(buildCtx, config)
Dan Willemsen8a073a82017-02-04 17:30:44 -0800150
Dan Willemsenb82471a2018-05-17 16:37:09 -0700151 logsDir := config.OutDir()
Dan Willemsen8a073a82017-02-04 17:30:44 -0800152 if config.Dist() {
Dan Willemsenb82471a2018-05-17 16:37:09 -0700153 logsDir = filepath.Join(config.DistDir(), "logs")
Dan Willemsen8a073a82017-02-04 17:30:44 -0800154 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700155
Dan Willemsenb82471a2018-05-17 16:37:09 -0700156 os.MkdirAll(logsDir, 0777)
157 log.SetOutput(filepath.Join(logsDir, "soong.log"))
158 trace.SetOutput(filepath.Join(logsDir, "build.trace"))
159 stat.AddOutput(status.NewVerboseLog(log, filepath.Join(logsDir, "verbose.log")))
160 stat.AddOutput(status.NewErrorLog(log, filepath.Join(logsDir, "error.log")))
161
Nan Zhangd50f53b2019-01-07 20:26:51 -0800162 defer met.Dump(filepath.Join(logsDir, "build_metrics"))
163
Dan Willemsen1e704462016-08-21 15:17:17 -0700164 if start, ok := os.LookupEnv("TRACE_BEGIN_SOONG"); ok {
165 if !strings.HasSuffix(start, "N") {
166 if start_time, err := strconv.ParseUint(start, 10, 64); err == nil {
167 log.Verbosef("Took %dms to start up.",
168 time.Since(time.Unix(0, int64(start_time))).Nanoseconds()/time.Millisecond.Nanoseconds())
Nan Zhang17f27672018-12-12 16:01:49 -0800169 buildCtx.CompleteTrace(metrics.RunSetupTool, "startup", start_time, uint64(time.Now().UnixNano()))
Dan Willemsen1e704462016-08-21 15:17:17 -0700170 }
171 }
Dan Willemsencae59bc2017-07-13 14:27:31 -0700172
173 if executable, err := os.Executable(); err == nil {
174 trace.ImportMicrofactoryLog(filepath.Join(filepath.Dir(executable), "."+filepath.Base(executable)+".trace"))
175 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700176 }
177
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700178 f := build.NewSourceFinder(buildCtx, config)
179 defer f.Shutdown()
180 build.FindSources(buildCtx, config, f)
181
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700182 c.run(buildCtx, config, args, logsDir)
Dan Willemsen051133b2017-07-14 11:29:29 -0700183}
184
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700185func dumpVar(ctx build.Context, config build.Config, args []string, _ string) {
Dan Willemsen051133b2017-07-14 11:29:29 -0700186 flags := flag.NewFlagSet("dumpvar", flag.ExitOnError)
187 flags.Usage = func() {
188 fmt.Fprintf(os.Stderr, "usage: %s --dumpvar-mode [--abs] <VAR>\n\n", os.Args[0])
189 fmt.Fprintln(os.Stderr, "In dumpvar mode, print the value of the legacy make variable VAR to stdout")
190 fmt.Fprintln(os.Stderr, "")
191
192 fmt.Fprintln(os.Stderr, "'report_config' is a special case that prints the human-readable config banner")
193 fmt.Fprintln(os.Stderr, "from the beginning of the build.")
194 fmt.Fprintln(os.Stderr, "")
195 flags.PrintDefaults()
196 }
197 abs := flags.Bool("abs", false, "Print the absolute path of the value")
198 flags.Parse(args)
199
200 if flags.NArg() != 1 {
201 flags.Usage()
202 os.Exit(1)
203 }
204
205 varName := flags.Arg(0)
206 if varName == "report_config" {
207 varData, err := build.DumpMakeVars(ctx, config, nil, build.BannerVars)
208 if err != nil {
209 ctx.Fatal(err)
210 }
211
212 fmt.Println(build.Banner(varData))
213 } else {
214 varData, err := build.DumpMakeVars(ctx, config, nil, []string{varName})
215 if err != nil {
216 ctx.Fatal(err)
217 }
218
219 if *abs {
220 var res []string
221 for _, path := range strings.Fields(varData[varName]) {
222 if abs, err := filepath.Abs(path); err == nil {
223 res = append(res, abs)
224 } else {
225 ctx.Fatalln("Failed to get absolute path of", path, err)
226 }
227 }
228 fmt.Println(strings.Join(res, " "))
229 } else {
230 fmt.Println(varData[varName])
231 }
232 }
233}
234
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700235func dumpVars(ctx build.Context, config build.Config, args []string, _ string) {
Dan Willemsen051133b2017-07-14 11:29:29 -0700236 flags := flag.NewFlagSet("dumpvars", flag.ExitOnError)
237 flags.Usage = func() {
238 fmt.Fprintf(os.Stderr, "usage: %s --dumpvars-mode [--vars=\"VAR VAR ...\"]\n\n", os.Args[0])
239 fmt.Fprintln(os.Stderr, "In dumpvars mode, dump the values of one or more legacy make variables, in")
240 fmt.Fprintln(os.Stderr, "shell syntax. The resulting output may be sourced directly into a shell to")
241 fmt.Fprintln(os.Stderr, "set corresponding shell variables.")
242 fmt.Fprintln(os.Stderr, "")
243
244 fmt.Fprintln(os.Stderr, "'report_config' is a special case that dumps a variable containing the")
245 fmt.Fprintln(os.Stderr, "human-readable config banner from the beginning of the build.")
246 fmt.Fprintln(os.Stderr, "")
247 flags.PrintDefaults()
248 }
249
250 varsStr := flags.String("vars", "", "Space-separated list of variables to dump")
251 absVarsStr := flags.String("abs-vars", "", "Space-separated list of variables to dump (using absolute paths)")
252
253 varPrefix := flags.String("var-prefix", "", "String to prepend to all variable names when dumping")
254 absVarPrefix := flags.String("abs-var-prefix", "", "String to prepent to all absolute path variable names when dumping")
255
256 flags.Parse(args)
257
258 if flags.NArg() != 0 {
259 flags.Usage()
260 os.Exit(1)
261 }
262
263 vars := strings.Fields(*varsStr)
264 absVars := strings.Fields(*absVarsStr)
265
266 allVars := append([]string{}, vars...)
267 allVars = append(allVars, absVars...)
268
269 if i := indexList("report_config", allVars); i != -1 {
270 allVars = append(allVars[:i], allVars[i+1:]...)
271 allVars = append(allVars, build.BannerVars...)
272 }
273
274 if len(allVars) == 0 {
275 return
276 }
277
278 varData, err := build.DumpMakeVars(ctx, config, nil, allVars)
279 if err != nil {
280 ctx.Fatal(err)
281 }
282
283 for _, name := range vars {
284 if name == "report_config" {
285 fmt.Printf("%sreport_config='%s'\n", *varPrefix, build.Banner(varData))
286 } else {
287 fmt.Printf("%s%s='%s'\n", *varPrefix, name, varData[name])
288 }
289 }
290 for _, name := range absVars {
291 var res []string
292 for _, path := range strings.Fields(varData[name]) {
293 abs, err := filepath.Abs(path)
294 if err != nil {
295 ctx.Fatalln("Failed to get absolute path of", path, err)
296 }
297 res = append(res, abs)
298 }
299 fmt.Printf("%s%s='%s'\n", *absVarPrefix, name, strings.Join(res, " "))
300 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700301}
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700302
303func customStdio() terminal.StdioInterface {
304 return terminal.NewCustomStdio(os.Stdin, os.Stderr, os.Stderr)
305}
306
307// dumpVarConfig does not require any arguments to be parsed by the NewConfig.
308func dumpVarConfig(ctx build.Context, args ...string) build.Config {
309 return build.NewConfig(ctx)
310}
311
312func make(ctx build.Context, config build.Config, _ []string, logsDir string) {
313 if config.IsVerbose() {
314 writer := ctx.Writer
315 writer.Print("! The argument `showcommands` is no longer supported.")
316 writer.Print("! Instead, the verbose log is always written to a compressed file in the output dir:")
317 writer.Print("!")
318 writer.Print(fmt.Sprintf("! gzip -cd %s/verbose.log.gz | less -R", logsDir))
319 writer.Print("!")
320 writer.Print("! Older versions are saved in verbose.log.#.gz files")
321 writer.Print("")
322 time.Sleep(5 * time.Second)
323 }
324
325 toBuild := build.BuildAll
326 if config.Checkbuild() {
327 toBuild |= build.RunBuildTests
328 }
329 build.Build(ctx, config, toBuild)
330}
331
332// getCommand finds the appropriate command based on args[1] flag. args[0]
333// is the soong_ui filename.
334func getCommand(args []string) (*command, []string) {
335 if len(args) < 2 {
336 return nil, args
337 }
338
339 for _, c := range commands {
340 if c.flag == args[1] {
341 return &c, args[2:]
342 }
343
344 // special case for --make-mode: if soong_ui was called from
345 // build/make/core/main.mk, the makeparallel with --ninja
346 // option specified puts the -j<num> before --make-mode.
347 // TODO: Remove this hack once it has been fixed.
348 if c.flag == makeModeFlagName {
349 if inList(makeModeFlagName, args) {
350 return &c, args[1:]
351 }
352 }
353 }
354
355 // command not found
356 return nil, args
357}