blob: f5276c335ba84bc2c4169e0ac485897c15bc9a79 [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
Colin Crosse0df1a32019-06-09 19:40:08 -0700112 output := terminal.NewStatusOutput(c.stdio().Stdout(), os.Getenv("NINJA_STATUS"),
113 build.OsEnvironment().IsEnvTrue("ANDROID_QUIET_BUILD"))
114
115 log := logger.New(output)
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()
Colin Crosse0df1a32019-06-09 19:40:08 -0700128 stat.AddOutput(output)
Dan Willemsenb82471a2018-05-17 16:37:09 -0700129 stat.AddOutput(trace.StatusTracer())
130
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700131 build.SetupSignals(log, cancel, func() {
132 trace.Close()
133 log.Cleanup()
Dan Willemsenb82471a2018-05-17 16:37:09 -0700134 stat.Finish()
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700135 })
136
Dan Willemsen59339a22018-07-22 21:18:45 -0700137 buildCtx := build.Context{ContextImpl: &build.ContextImpl{
Dan Willemsenb82471a2018-05-17 16:37:09 -0700138 Context: ctx,
139 Logger: log,
Nan Zhang17f27672018-12-12 16:01:49 -0800140 Metrics: met,
Dan Willemsenb82471a2018-05-17 16:37:09 -0700141 Tracer: trace,
Colin Crosse0df1a32019-06-09 19:40:08 -0700142 Writer: output,
Dan Willemsenb82471a2018-05-17 16:37:09 -0700143 Status: stat,
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700144 }}
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700145
146 config := c.config(buildCtx, args...)
Dan Willemsen1e704462016-08-21 15:17:17 -0700147
Dan Willemsend9f6fa22016-08-21 15:17:17 -0700148 build.SetupOutDir(buildCtx, config)
Dan Willemsen8a073a82017-02-04 17:30:44 -0800149
Dan Willemsenb82471a2018-05-17 16:37:09 -0700150 logsDir := config.OutDir()
Dan Willemsen8a073a82017-02-04 17:30:44 -0800151 if config.Dist() {
Dan Willemsenb82471a2018-05-17 16:37:09 -0700152 logsDir = filepath.Join(config.DistDir(), "logs")
Dan Willemsen8a073a82017-02-04 17:30:44 -0800153 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700154
Dan Willemsenb82471a2018-05-17 16:37:09 -0700155 os.MkdirAll(logsDir, 0777)
156 log.SetOutput(filepath.Join(logsDir, "soong.log"))
157 trace.SetOutput(filepath.Join(logsDir, "build.trace"))
158 stat.AddOutput(status.NewVerboseLog(log, filepath.Join(logsDir, "verbose.log")))
159 stat.AddOutput(status.NewErrorLog(log, filepath.Join(logsDir, "error.log")))
160
Nan Zhangd50f53b2019-01-07 20:26:51 -0800161 defer met.Dump(filepath.Join(logsDir, "build_metrics"))
162
Dan Willemsen1e704462016-08-21 15:17:17 -0700163 if start, ok := os.LookupEnv("TRACE_BEGIN_SOONG"); ok {
164 if !strings.HasSuffix(start, "N") {
165 if start_time, err := strconv.ParseUint(start, 10, 64); err == nil {
166 log.Verbosef("Took %dms to start up.",
167 time.Since(time.Unix(0, int64(start_time))).Nanoseconds()/time.Millisecond.Nanoseconds())
Nan Zhang17f27672018-12-12 16:01:49 -0800168 buildCtx.CompleteTrace(metrics.RunSetupTool, "startup", start_time, uint64(time.Now().UnixNano()))
Dan Willemsen1e704462016-08-21 15:17:17 -0700169 }
170 }
Dan Willemsencae59bc2017-07-13 14:27:31 -0700171
172 if executable, err := os.Executable(); err == nil {
173 trace.ImportMicrofactoryLog(filepath.Join(filepath.Dir(executable), "."+filepath.Base(executable)+".trace"))
174 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700175 }
176
Jeff Gastonb64fc1c2017-08-04 12:30:12 -0700177 f := build.NewSourceFinder(buildCtx, config)
178 defer f.Shutdown()
179 build.FindSources(buildCtx, config, f)
180
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700181 c.run(buildCtx, config, args, logsDir)
Dan Willemsen051133b2017-07-14 11:29:29 -0700182}
183
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700184func dumpVar(ctx build.Context, config build.Config, args []string, _ string) {
Dan Willemsen051133b2017-07-14 11:29:29 -0700185 flags := flag.NewFlagSet("dumpvar", flag.ExitOnError)
186 flags.Usage = func() {
187 fmt.Fprintf(os.Stderr, "usage: %s --dumpvar-mode [--abs] <VAR>\n\n", os.Args[0])
188 fmt.Fprintln(os.Stderr, "In dumpvar mode, print the value of the legacy make variable VAR to stdout")
189 fmt.Fprintln(os.Stderr, "")
190
191 fmt.Fprintln(os.Stderr, "'report_config' is a special case that prints the human-readable config banner")
192 fmt.Fprintln(os.Stderr, "from the beginning of the build.")
193 fmt.Fprintln(os.Stderr, "")
194 flags.PrintDefaults()
195 }
196 abs := flags.Bool("abs", false, "Print the absolute path of the value")
197 flags.Parse(args)
198
199 if flags.NArg() != 1 {
200 flags.Usage()
201 os.Exit(1)
202 }
203
204 varName := flags.Arg(0)
205 if varName == "report_config" {
206 varData, err := build.DumpMakeVars(ctx, config, nil, build.BannerVars)
207 if err != nil {
208 ctx.Fatal(err)
209 }
210
211 fmt.Println(build.Banner(varData))
212 } else {
213 varData, err := build.DumpMakeVars(ctx, config, nil, []string{varName})
214 if err != nil {
215 ctx.Fatal(err)
216 }
217
218 if *abs {
219 var res []string
220 for _, path := range strings.Fields(varData[varName]) {
221 if abs, err := filepath.Abs(path); err == nil {
222 res = append(res, abs)
223 } else {
224 ctx.Fatalln("Failed to get absolute path of", path, err)
225 }
226 }
227 fmt.Println(strings.Join(res, " "))
228 } else {
229 fmt.Println(varData[varName])
230 }
231 }
232}
233
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700234func dumpVars(ctx build.Context, config build.Config, args []string, _ string) {
Dan Willemsen051133b2017-07-14 11:29:29 -0700235 flags := flag.NewFlagSet("dumpvars", flag.ExitOnError)
236 flags.Usage = func() {
237 fmt.Fprintf(os.Stderr, "usage: %s --dumpvars-mode [--vars=\"VAR VAR ...\"]\n\n", os.Args[0])
238 fmt.Fprintln(os.Stderr, "In dumpvars mode, dump the values of one or more legacy make variables, in")
239 fmt.Fprintln(os.Stderr, "shell syntax. The resulting output may be sourced directly into a shell to")
240 fmt.Fprintln(os.Stderr, "set corresponding shell variables.")
241 fmt.Fprintln(os.Stderr, "")
242
243 fmt.Fprintln(os.Stderr, "'report_config' is a special case that dumps a variable containing the")
244 fmt.Fprintln(os.Stderr, "human-readable config banner from the beginning of the build.")
245 fmt.Fprintln(os.Stderr, "")
246 flags.PrintDefaults()
247 }
248
249 varsStr := flags.String("vars", "", "Space-separated list of variables to dump")
250 absVarsStr := flags.String("abs-vars", "", "Space-separated list of variables to dump (using absolute paths)")
251
252 varPrefix := flags.String("var-prefix", "", "String to prepend to all variable names when dumping")
253 absVarPrefix := flags.String("abs-var-prefix", "", "String to prepent to all absolute path variable names when dumping")
254
255 flags.Parse(args)
256
257 if flags.NArg() != 0 {
258 flags.Usage()
259 os.Exit(1)
260 }
261
262 vars := strings.Fields(*varsStr)
263 absVars := strings.Fields(*absVarsStr)
264
265 allVars := append([]string{}, vars...)
266 allVars = append(allVars, absVars...)
267
268 if i := indexList("report_config", allVars); i != -1 {
269 allVars = append(allVars[:i], allVars[i+1:]...)
270 allVars = append(allVars, build.BannerVars...)
271 }
272
273 if len(allVars) == 0 {
274 return
275 }
276
277 varData, err := build.DumpMakeVars(ctx, config, nil, allVars)
278 if err != nil {
279 ctx.Fatal(err)
280 }
281
282 for _, name := range vars {
283 if name == "report_config" {
284 fmt.Printf("%sreport_config='%s'\n", *varPrefix, build.Banner(varData))
285 } else {
286 fmt.Printf("%s%s='%s'\n", *varPrefix, name, varData[name])
287 }
288 }
289 for _, name := range absVars {
290 var res []string
291 for _, path := range strings.Fields(varData[name]) {
292 abs, err := filepath.Abs(path)
293 if err != nil {
294 ctx.Fatalln("Failed to get absolute path of", path, err)
295 }
296 res = append(res, abs)
297 }
298 fmt.Printf("%s%s='%s'\n", *absVarPrefix, name, strings.Join(res, " "))
299 }
Dan Willemsen1e704462016-08-21 15:17:17 -0700300}
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700301
302func customStdio() terminal.StdioInterface {
303 return terminal.NewCustomStdio(os.Stdin, os.Stderr, os.Stderr)
304}
305
306// dumpVarConfig does not require any arguments to be parsed by the NewConfig.
307func dumpVarConfig(ctx build.Context, args ...string) build.Config {
308 return build.NewConfig(ctx)
309}
310
311func make(ctx build.Context, config build.Config, _ []string, logsDir string) {
312 if config.IsVerbose() {
313 writer := ctx.Writer
Colin Cross097ed2a2019-06-08 21:48:58 -0700314 fmt.Fprintln(writer, "! The argument `showcommands` is no longer supported.")
315 fmt.Fprintln(writer, "! Instead, the verbose log is always written to a compressed file in the output dir:")
316 fmt.Fprintln(writer, "!")
317 fmt.Fprintf(writer, "! gzip -cd %s/verbose.log.gz | less -R\n", logsDir)
318 fmt.Fprintln(writer, "!")
319 fmt.Fprintln(writer, "! Older versions are saved in verbose.log.#.gz files")
320 fmt.Fprintln(writer, "")
Patrice Arrudaa5c25422019-04-09 18:49:49 -0700321 time.Sleep(5 * time.Second)
322 }
323
324 toBuild := build.BuildAll
325 if config.Checkbuild() {
326 toBuild |= build.RunBuildTests
327 }
328 build.Build(ctx, config, toBuild)
329}
330
331// getCommand finds the appropriate command based on args[1] flag. args[0]
332// is the soong_ui filename.
333func getCommand(args []string) (*command, []string) {
334 if len(args) < 2 {
335 return nil, args
336 }
337
338 for _, c := range commands {
339 if c.flag == args[1] {
340 return &c, args[2:]
341 }
342
343 // special case for --make-mode: if soong_ui was called from
344 // build/make/core/main.mk, the makeparallel with --ninja
345 // option specified puts the -j<num> before --make-mode.
346 // TODO: Remove this hack once it has been fixed.
347 if c.flag == makeModeFlagName {
348 if inList(makeModeFlagName, args) {
349 return &c, args[1:]
350 }
351 }
352 }
353
354 // command not found
355 return nil, args
356}