misc/cgo/testshared: make -v output less verbose

Previously, 'go test -v' in this directory would result in a massive
dump of go command output, because the test plumbed -v to 'build -x'.
This change separates them into distinct flags, so that '-v' only
implies the display of default 'go' command output.

Updates #30316

Change-Id: Ifb125f35ec6a0bebe7e8286e7c546d132fb213df
Reviewed-on: https://go-review.googlesource.com/c/go/+/208232
Run-TryBot: Bryan C. Mills <bcmills@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
diff --git a/misc/cgo/testshared/shared_test.go b/misc/cgo/testshared/shared_test.go
index 9d16338..35e7710 100644
--- a/misc/cgo/testshared/shared_test.go
+++ b/misc/cgo/testshared/shared_test.go
@@ -34,6 +34,8 @@
 var minpkgs = []string{"runtime", "sync/atomic"}
 var soname = "libruntime,sync-atomic.so"
 
+var testX = flag.Bool("testx", false, "if true, pass -x to 'go' subcommands invoked by the test")
+
 // run runs a command and calls t.Errorf if it fails.
 func run(t *testing.T, msg string, args ...string) {
 	c := exec.Command(args[0], args[1:]...)
@@ -46,23 +48,19 @@
 // t.Fatalf if the command fails.
 func goCmd(t *testing.T, args ...string) string {
 	newargs := []string{args[0], "-installsuffix=" + suffix}
-	if testing.Verbose() {
+	if *testX {
 		newargs = append(newargs, "-x")
 	}
 	newargs = append(newargs, args[1:]...)
 	c := exec.Command("go", newargs...)
-
 	stderr := new(strings.Builder)
-	var output []byte
-	var err error
-	if testing.Verbose() {
-		fmt.Printf("+ go %s\n", strings.Join(args, " "))
+	c.Stderr = stderr
+
+	if testing.Verbose() && t == nil {
+		fmt.Fprintf(os.Stderr, "+ go %s\n", strings.Join(args, " "))
 		c.Stderr = os.Stderr
-		stderr.WriteString("(output above)")
-	} else {
-		c.Stderr = stderr
 	}
-	output, err = c.Output()
+	output, err := c.Output()
 
 	if err != nil {
 		if t != nil {
@@ -72,6 +70,12 @@
 			log.Fatalf("executing %s failed %v:\n%s", strings.Join(c.Args, " "), err, stderr)
 		}
 	}
+	if testing.Verbose() && t != nil {
+		t.Logf("go %s", strings.Join(args, " "))
+		if stderr.Len() > 0 {
+			t.Logf("%s", stderr)
+		}
+	}
 	return string(bytes.TrimSpace(output))
 }