Add a unified status reporting UI

This adds a new status package that merges the running of "actions"
(ninja calls them edges) of multiple tools into one view of the current
state, and gives that to a number of different outputs.

For inputs:

Kati's output parser has been rewritten (and moved) to map onto the
StartAction/FinishAction API. A byproduct of this is that the build
servers should be able to extract errors from Kati better, since they
look like the errors that Ninja used to write.

Ninja is no longer directly connected to the terminal, but its output is
read via the protobuf frontend API, so it's just another tool whose
output becomes merged together.

multiproduct_kati loses its custom status routines, and uses the common
one instead.

For outputs:

The primary output is the ui/terminal.Status type, which along with
ui/terminal.Writer now controls everything about the terminal output.
Today, this doesn't really change any behaviors, but having all terminal
output going through here allows a more complicated (multi-line / full
window) status display in the future.

The tracer acts as an output of the status package, tracing all the
action start / finish events. This replaces reading the .ninja_log file,
so it now properly handles multiple output files from a single action.

A new rotated log file (out/error.log, or out/dist/logs/error.log) just
contains a description of all of the errors that happened during the
current build.

Another new compressed and rotated log file (out/verbose.log.gz, or
out/dist/logs/verbose.log.gz) contains the full verbose (showcommands)
log of every execution run by the build. Since this is now written on
every build, the showcommands argument is now ignored -- if you want to
get the commands run, look at the log file after the build.

Test: m
Test: <built-in tests>
Test: NINJA_ARGS="-t list" m
Test: check the build.trace.gz
Test: check the new log files
Change-Id: If1d8994890d43ef68f65aa10ddd8e6e06dc7013a
diff --git a/ui/build/Android.bp b/ui/build/Android.bp
index 1fe5b6f..a48a314 100644
--- a/ui/build/Android.bp
+++ b/ui/build/Android.bp
@@ -30,6 +30,8 @@
     deps: [
         "soong-ui-build-paths",
         "soong-ui-logger",
+        "soong-ui-status",
+        "soong-ui-terminal",
         "soong-ui-tracer",
         "soong-shared",
         "soong-finder",
@@ -62,13 +64,11 @@
     darwin: {
         srcs: [
             "sandbox_darwin.go",
-            "util_darwin.go"
         ],
     },
     linux: {
         srcs: [
             "sandbox_linux.go",
-            "util_linux.go"
         ],
     },
 }
diff --git a/ui/build/build.go b/ui/build/build.go
index acba275..96cfdbb 100644
--- a/ui/build/build.go
+++ b/ui/build/build.go
@@ -105,9 +105,7 @@
 func help(ctx Context, config Config, what int) {
 	cmd := Command(ctx, config, "help.sh", "build/make/help.sh")
 	cmd.Sandbox = dumpvarsSandbox
-	cmd.Stdout = ctx.Stdout()
-	cmd.Stderr = ctx.Stderr()
-	cmd.RunOrFatal()
+	cmd.RunAndPrintOrFatal()
 }
 
 // Build the tree. The 'what' argument can be used to chose which components of
diff --git a/ui/build/config_test.go b/ui/build/config_test.go
index e4eab94..242e3af 100644
--- a/ui/build/config_test.go
+++ b/ui/build/config_test.go
@@ -22,13 +22,14 @@
 	"testing"
 
 	"android/soong/ui/logger"
+	"android/soong/ui/terminal"
 )
 
 func testContext() Context {
 	return Context{&ContextImpl{
-		Context:        context.Background(),
-		Logger:         logger.New(&bytes.Buffer{}),
-		StdioInterface: NewCustomStdio(&bytes.Buffer{}, &bytes.Buffer{}, &bytes.Buffer{}),
+		Context: context.Background(),
+		Logger:  logger.New(&bytes.Buffer{}),
+		Writer:  terminal.NewWriter(terminal.NewCustomStdio(&bytes.Buffer{}, &bytes.Buffer{}, &bytes.Buffer{})),
 	}}
 }
 
diff --git a/ui/build/context.go b/ui/build/context.go
index 0636631..c8b00c3 100644
--- a/ui/build/context.go
+++ b/ui/build/context.go
@@ -16,45 +16,14 @@
 
 import (
 	"context"
-	"io"
-	"os"
-	"time"
 
 	"android/soong/ui/logger"
+	"android/soong/ui/status"
+	"android/soong/ui/terminal"
 	"android/soong/ui/tracer"
 )
 
-type StdioInterface interface {
-	Stdin() io.Reader
-	Stdout() io.Writer
-	Stderr() io.Writer
-}
-
-type StdioImpl struct{}
-
-func (StdioImpl) Stdin() io.Reader  { return os.Stdin }
-func (StdioImpl) Stdout() io.Writer { return os.Stdout }
-func (StdioImpl) Stderr() io.Writer { return os.Stderr }
-
-var _ StdioInterface = StdioImpl{}
-
-type customStdio struct {
-	stdin  io.Reader
-	stdout io.Writer
-	stderr io.Writer
-}
-
-func NewCustomStdio(stdin io.Reader, stdout, stderr io.Writer) StdioInterface {
-	return customStdio{stdin, stdout, stderr}
-}
-
-func (c customStdio) Stdin() io.Reader  { return c.stdin }
-func (c customStdio) Stdout() io.Writer { return c.stdout }
-func (c customStdio) Stderr() io.Writer { return c.stderr }
-
-var _ StdioInterface = customStdio{}
-
-// Context combines a context.Context, logger.Logger, and StdIO redirection.
+// Context combines a context.Context, logger.Logger, and terminal.Writer.
 // These all are agnostic of the current build, and may be used for multiple
 // builds, while the Config objects contain per-build information.
 type Context struct{ *ContextImpl }
@@ -62,7 +31,8 @@
 	context.Context
 	logger.Logger
 
-	StdioInterface
+	Writer terminal.Writer
+	Status *status.Status
 
 	Thread tracer.Thread
 	Tracer tracer.Tracer
@@ -88,28 +58,3 @@
 		c.Tracer.Complete(name, c.Thread, begin, end)
 	}
 }
-
-// ImportNinjaLog imports a .ninja_log file into the tracer.
-func (c ContextImpl) ImportNinjaLog(filename string, startOffset time.Time) {
-	if c.Tracer != nil {
-		c.Tracer.ImportNinjaLog(c.Thread, filename, startOffset)
-	}
-}
-
-func (c ContextImpl) IsTerminal() bool {
-	if term, ok := os.LookupEnv("TERM"); ok {
-		return term != "dumb" && isTerminal(c.Stdout()) && isTerminal(c.Stderr())
-	}
-	return false
-}
-
-func (c ContextImpl) IsErrTerminal() bool {
-	if term, ok := os.LookupEnv("TERM"); ok {
-		return term != "dumb" && isTerminal(c.Stderr())
-	}
-	return false
-}
-
-func (c ContextImpl) TermWidth() (int, bool) {
-	return termWidth(c.Stdout())
-}
diff --git a/ui/build/dumpvars.go b/ui/build/dumpvars.go
index 8429a8a..06bd74f 100644
--- a/ui/build/dumpvars.go
+++ b/ui/build/dumpvars.go
@@ -18,6 +18,8 @@
 	"bytes"
 	"fmt"
 	"strings"
+
+	"android/soong/ui/status"
 )
 
 // DumpMakeVars can be used to extract the values of Make variables after the
@@ -60,7 +62,7 @@
 	}
 	cmd.StartOrFatal()
 	// TODO: error out when Stderr contains any content
-	katiRewriteOutput(ctx, pipe)
+	status.KatiReader(ctx.Status.StartTool(), pipe)
 	cmd.WaitOrFatal()
 
 	ret := make(map[string]string, len(vars))
@@ -175,7 +177,7 @@
 	}
 
 	// Print the banner like make does
-	fmt.Fprintln(ctx.Stdout(), Banner(make_vars))
+	ctx.Writer.Print(Banner(make_vars))
 
 	// Populate the environment
 	env := config.Environment()
diff --git a/ui/build/exec.go b/ui/build/exec.go
index 90fb19d..5c312bc 100644
--- a/ui/build/exec.go
+++ b/ui/build/exec.go
@@ -122,3 +122,20 @@
 	c.reportError(err)
 	return ret
 }
+
+// RunAndPrintOrFatal will run the command, then after finishing
+// print any output, then handling any errors with a call to
+// ctx.Fatal
+func (c *Cmd) RunAndPrintOrFatal() {
+	ret, err := c.CombinedOutput()
+	st := c.ctx.Status.StartTool()
+	if len(ret) > 0 {
+		if err != nil {
+			st.Error(string(ret))
+		} else {
+			st.Print(string(ret))
+		}
+	}
+	st.Finish()
+	c.reportError(err)
+}
diff --git a/ui/build/kati.go b/ui/build/kati.go
index 7635c10..7cfa1cf 100644
--- a/ui/build/kati.go
+++ b/ui/build/kati.go
@@ -15,15 +15,14 @@
 package build
 
 import (
-	"bufio"
 	"crypto/md5"
 	"fmt"
-	"io"
 	"io/ioutil"
 	"path/filepath"
-	"regexp"
 	"strconv"
 	"strings"
+
+	"android/soong/ui/status"
 )
 
 var spaceSlashReplacer = strings.NewReplacer("/", "_", " ", "_")
@@ -117,77 +116,10 @@
 	cmd.Stderr = cmd.Stdout
 
 	cmd.StartOrFatal()
-	katiRewriteOutput(ctx, pipe)
+	status.KatiReader(ctx.Status.StartTool(), pipe)
 	cmd.WaitOrFatal()
 }
 
-var katiIncludeRe = regexp.MustCompile(`^(\[\d+/\d+] )?including [^ ]+ ...$`)
-var katiLogRe = regexp.MustCompile(`^\*kati\*: `)
-
-func katiRewriteOutput(ctx Context, pipe io.ReadCloser) {
-	haveBlankLine := true
-	smartTerminal := ctx.IsTerminal()
-	errSmartTerminal := ctx.IsErrTerminal()
-
-	scanner := bufio.NewScanner(pipe)
-	for scanner.Scan() {
-		line := scanner.Text()
-		verbose := katiIncludeRe.MatchString(line)
-
-		// Only put kati debug/stat lines in our verbose log
-		if katiLogRe.MatchString(line) {
-			ctx.Verbose(line)
-			continue
-		}
-
-		// For verbose lines, write them on the current line without a newline,
-		// then overwrite them if the next thing we're printing is another
-		// verbose line.
-		if smartTerminal && verbose {
-			// Limit line width to the terminal width, otherwise we'll wrap onto
-			// another line and we won't delete the previous line.
-			//
-			// Run this on every line in case the window has been resized while
-			// we're printing. This could be optimized to only re-run when we
-			// get SIGWINCH if it ever becomes too time consuming.
-			if max, ok := termWidth(ctx.Stdout()); ok {
-				if len(line) > max {
-					// Just do a max. Ninja elides the middle, but that's
-					// more complicated and these lines aren't that important.
-					line = line[:max]
-				}
-			}
-
-			// Move to the beginning on the line, print the output, then clear
-			// the rest of the line.
-			fmt.Fprint(ctx.Stdout(), "\r", line, "\x1b[K")
-			haveBlankLine = false
-			continue
-		} else if smartTerminal && !haveBlankLine {
-			// If we've previously written a verbose message, send a newline to save
-			// that message instead of overwriting it.
-			fmt.Fprintln(ctx.Stdout())
-			haveBlankLine = true
-		} else if !errSmartTerminal {
-			// Most editors display these as garbage, so strip them out.
-			line = string(stripAnsiEscapes([]byte(line)))
-		}
-
-		// Assume that non-verbose lines are important enough for stderr
-		fmt.Fprintln(ctx.Stderr(), line)
-	}
-
-	// Save our last verbose line.
-	if !haveBlankLine {
-		fmt.Fprintln(ctx.Stdout())
-	}
-
-	if err := scanner.Err(); err != nil {
-		ctx.Println("Error from kati parser:", err)
-		io.Copy(ctx.Stderr(), pipe)
-	}
-}
-
 func runKatiCleanSpec(ctx Context, config Config) {
 	ctx.BeginTrace("kati cleanspec")
 	defer ctx.EndTrace()
@@ -220,6 +152,6 @@
 	cmd.Stderr = cmd.Stdout
 
 	cmd.StartOrFatal()
-	katiRewriteOutput(ctx, pipe)
+	status.KatiReader(ctx.Status.StartTool(), pipe)
 	cmd.WaitOrFatal()
 }
diff --git a/ui/build/ninja.go b/ui/build/ninja.go
index 96b5e9d..c48fe0f 100644
--- a/ui/build/ninja.go
+++ b/ui/build/ninja.go
@@ -21,15 +21,21 @@
 	"strconv"
 	"strings"
 	"time"
+
+	"android/soong/ui/status"
 )
 
 func runNinja(ctx Context, config Config) {
 	ctx.BeginTrace("ninja")
 	defer ctx.EndTrace()
 
+	fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
+	status.NinjaReader(ctx, ctx.Status.StartTool(), fifo)
+
 	executable := config.PrebuiltBuildTool("ninja")
 	args := []string{
 		"-d", "keepdepfile",
+		fmt.Sprintf("--frontend=cat <&3 >%s", fifo),
 	}
 
 	args = append(args, config.NinjaArgs()...)
@@ -47,9 +53,6 @@
 
 	args = append(args, "-f", config.CombinedNinjaFile())
 
-	if config.IsVerbose() {
-		args = append(args, "-v")
-	}
 	args = append(args, "-w", "dupbuild=err")
 
 	cmd := Command(ctx, config, "ninja", executable, args...)
@@ -66,13 +69,6 @@
 		cmd.Args = append(cmd.Args, strings.Fields(extra)...)
 	}
 
-	if _, ok := cmd.Environment.Get("NINJA_STATUS"); !ok {
-		cmd.Environment.Set("NINJA_STATUS", "[%p %f/%t] ")
-	}
-
-	cmd.Stdin = ctx.Stdin()
-	cmd.Stdout = ctx.Stdout()
-	cmd.Stderr = ctx.Stderr()
 	logPath := filepath.Join(config.OutDir(), ".ninja_log")
 	ninjaHeartbeatDuration := time.Minute * 5
 	if overrideText, ok := cmd.Environment.Get("NINJA_HEARTBEAT_INTERVAL"); ok {
@@ -99,10 +95,7 @@
 		}
 	}()
 
-	startTime := time.Now()
-	defer ctx.ImportNinjaLog(logPath, startTime)
-
-	cmd.RunOrFatal()
+	cmd.RunAndPrintOrFatal()
 }
 
 type statusChecker struct {
diff --git a/ui/build/soong.go b/ui/build/soong.go
index a73082a..6c94079 100644
--- a/ui/build/soong.go
+++ b/ui/build/soong.go
@@ -15,12 +15,15 @@
 package build
 
 import (
+	"fmt"
 	"os"
 	"path/filepath"
 	"strconv"
-	"time"
+	"strings"
 
 	"github.com/google/blueprint/microfactory"
+
+	"android/soong/ui/status"
 )
 
 func runSoong(ctx Context, config Config) {
@@ -41,9 +44,8 @@
 		cmd.Environment.Set("SRCDIR", ".")
 		cmd.Environment.Set("TOPNAME", "Android.bp")
 		cmd.Sandbox = soongSandbox
-		cmd.Stdout = ctx.Stdout()
-		cmd.Stderr = ctx.Stderr()
-		cmd.RunOrFatal()
+
+		cmd.RunAndPrintOrFatal()
 	}()
 
 	func() {
@@ -56,12 +58,18 @@
 			if _, err := os.Stat(envTool); err == nil {
 				cmd := Command(ctx, config, "soong_env", envTool, envFile)
 				cmd.Sandbox = soongSandbox
-				cmd.Stdout = ctx.Stdout()
-				cmd.Stderr = ctx.Stderr()
+
+				var buf strings.Builder
+				cmd.Stdout = &buf
+				cmd.Stderr = &buf
 				if err := cmd.Run(); err != nil {
 					ctx.Verboseln("soong_env failed, forcing manifest regeneration")
 					os.Remove(envFile)
 				}
+
+				if buf.Len() > 0 {
+					ctx.Verboseln(buf.String())
+				}
 			} else {
 				ctx.Verboseln("Missing soong_env tool, forcing manifest regeneration")
 				os.Remove(envFile)
@@ -100,22 +108,18 @@
 		ctx.BeginTrace(name)
 		defer ctx.EndTrace()
 
+		fifo := filepath.Join(config.OutDir(), ".ninja_fifo")
+		status.NinjaReader(ctx, ctx.Status.StartTool(), fifo)
+
 		cmd := Command(ctx, config, "soong "+name,
 			config.PrebuiltBuildTool("ninja"),
 			"-d", "keepdepfile",
 			"-w", "dupbuild=err",
 			"-j", strconv.Itoa(config.Parallel()),
+			fmt.Sprintf("--frontend=cat <&3 >%s", fifo),
 			"-f", filepath.Join(config.SoongOutDir(), file))
-		if config.IsVerbose() {
-			cmd.Args = append(cmd.Args, "-v")
-		}
 		cmd.Sandbox = soongSandbox
-		cmd.Stdin = ctx.Stdin()
-		cmd.Stdout = ctx.Stdout()
-		cmd.Stderr = ctx.Stderr()
-
-		defer ctx.ImportNinjaLog(filepath.Join(config.OutDir(), ".ninja_log"), time.Now())
-		cmd.RunOrFatal()
+		cmd.RunAndPrintOrFatal()
 	}
 
 	ninja("minibootstrap", ".minibootstrap/build.ninja")
diff --git a/ui/build/util.go b/ui/build/util.go
index 96088fe..0676a86 100644
--- a/ui/build/util.go
+++ b/ui/build/util.go
@@ -15,13 +15,9 @@
 package build
 
 import (
-	"bytes"
-	"io"
 	"os"
 	"path/filepath"
 	"strings"
-	"syscall"
-	"unsafe"
 )
 
 func absPath(ctx Context, p string) string {
@@ -117,81 +113,3 @@
 	}
 	return str[:idx], str[idx+1:], true
 }
-
-func isTerminal(w io.Writer) bool {
-	if f, ok := w.(*os.File); ok {
-		var termios syscall.Termios
-		_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, f.Fd(),
-			ioctlGetTermios, uintptr(unsafe.Pointer(&termios)),
-			0, 0, 0)
-		return err == 0
-	}
-	return false
-}
-
-func termWidth(w io.Writer) (int, bool) {
-	if f, ok := w.(*os.File); ok {
-		var winsize struct {
-			ws_row, ws_column    uint16
-			ws_xpixel, ws_ypixel uint16
-		}
-		_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, f.Fd(),
-			syscall.TIOCGWINSZ, uintptr(unsafe.Pointer(&winsize)),
-			0, 0, 0)
-		return int(winsize.ws_column), err == 0
-	}
-	return 0, false
-}
-
-// stripAnsiEscapes strips ANSI control codes from a byte array in place.
-func stripAnsiEscapes(input []byte) []byte {
-	// read represents the remaining part of input that needs to be processed.
-	read := input
-	// write represents where we should be writing in input.
-	// It will share the same backing store as input so that we make our modifications
-	// in place.
-	write := input
-
-	// advance will copy count bytes from read to write and advance those slices
-	advance := func(write, read []byte, count int) ([]byte, []byte) {
-		copy(write, read[:count])
-		return write[count:], read[count:]
-	}
-
-	for {
-		// Find the next escape sequence
-		i := bytes.IndexByte(read, 0x1b)
-		// If it isn't found, or if there isn't room for <ESC>[, finish
-		if i == -1 || i+1 >= len(read) {
-			copy(write, read)
-			break
-		}
-
-		// Not a CSI code, continue searching
-		if read[i+1] != '[' {
-			write, read = advance(write, read, i+1)
-			continue
-		}
-
-		// Found a CSI code, advance up to the <ESC>
-		write, read = advance(write, read, i)
-
-		// Find the end of the CSI code
-		i = bytes.IndexFunc(read, func(r rune) bool {
-			return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
-		})
-		if i == -1 {
-			// We didn't find the end of the code, just remove the rest
-			i = len(read) - 1
-		}
-
-		// Strip off the end marker too
-		i = i + 1
-
-		// Skip the reader forward and reduce final length by that amount
-		read = read[i:]
-		input = input[:len(input)-i]
-	}
-
-	return input
-}
diff --git a/ui/build/util_darwin.go b/ui/build/util_darwin.go
deleted file mode 100644
index 254a9b8..0000000
--- a/ui/build/util_darwin.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package build
-
-import (
-	"syscall"
-)
-
-const ioctlGetTermios = syscall.TIOCGETA
diff --git a/ui/build/util_linux.go b/ui/build/util_linux.go
deleted file mode 100644
index 0a4e1d2..0000000
--- a/ui/build/util_linux.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright 2017 Google Inc. All rights reserved.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package build
-
-import (
-	"syscall"
-)
-
-const ioctlGetTermios = syscall.TCGETS
diff --git a/ui/build/util_test.go b/ui/build/util_test.go
index 0e0dbdf..89bfc77 100644
--- a/ui/build/util_test.go
+++ b/ui/build/util_test.go
@@ -49,48 +49,3 @@
 
 	ensureEmptyDirectoriesExist(ctx, filepath.Join(tmpDir, "a"))
 }
-
-func TestStripAnsiEscapes(t *testing.T) {
-	testcases := []struct {
-		input  string
-		output string
-	}{
-		{
-			"",
-			"",
-		},
-		{
-			"This is a test",
-			"This is a test",
-		},
-		{
-			"interrupted: \x1b[12",
-			"interrupted: ",
-		},
-		{
-			"other \x1bescape \x1b",
-			"other \x1bescape \x1b",
-		},
-		{ // from pretty-error macro
-			"\x1b[1mart/Android.mk: \x1b[31merror:\x1b[0m\x1b[1m art: test error \x1b[0m",
-			"art/Android.mk: error: art: test error ",
-		},
-		{ // from envsetup.sh make wrapper
-			"\x1b[0;31m#### make failed to build some targets (2 seconds) ####\x1b[00m",
-			"#### make failed to build some targets (2 seconds) ####",
-		},
-		{ // from clang (via ninja testcase)
-			"\x1b[1maffixmgr.cxx:286:15: \x1b[0m\x1b[0;1;35mwarning: \x1b[0m\x1b[1musing the result... [-Wparentheses]\x1b[0m",
-			"affixmgr.cxx:286:15: warning: using the result... [-Wparentheses]",
-		},
-	}
-	for _, tc := range testcases {
-		got := string(stripAnsiEscapes([]byte(tc.input)))
-		if got != tc.output {
-			t.Errorf("output strings didn't match\n"+
-				"input: %#v\n"+
-				" want: %#v\n"+
-				"  got: %#v", tc.input, tc.output, got)
-		}
-	}
-}