cmd/getgo: exec main from TestMain instead of running 'go build' in tests

This was noticed from
https://build.golang.org/log/da703ece9e1626eaeabf485e1a3a8180a6bde512,
but I suspect not relevant to the getgo test failure observed there.

Updates golang/go#28387

Change-Id: I1a156e780beabb13b4df6fd5313d4785aeb26e97
Reviewed-on: https://go-review.googlesource.com/c/tools/+/390075
Trust: Bryan Mills <bcmills@google.com>
Run-TryBot: Bryan Mills <bcmills@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
diff --git a/cmd/getgo/.gitignore b/cmd/getgo/.gitignore
index d4984ab..47fe984 100644
--- a/cmd/getgo/.gitignore
+++ b/cmd/getgo/.gitignore
@@ -1,3 +1,2 @@
 build
-testgetgo
 getgo
diff --git a/cmd/getgo/main_test.go b/cmd/getgo/main_test.go
index 0c0e8b9..fc28c5d 100644
--- a/cmd/getgo/main_test.go
+++ b/cmd/getgo/main_test.go
@@ -13,50 +13,27 @@
 	"io/ioutil"
 	"os"
 	"os/exec"
-	"runtime"
 	"testing"
 )
 
-const (
-	testbin = "testgetgo"
-)
-
-var (
-	exeSuffix string // ".exe" on Windows
-)
-
-func init() {
-	if runtime.GOOS == "windows" {
-		exeSuffix = ".exe"
-	}
-}
-
-// TestMain creates a getgo command for testing purposes and
-// deletes it after the tests have been run.
 func TestMain(m *testing.M) {
+	if os.Getenv("GO_GETGO_TEST_IS_GETGO") != "" {
+		main()
+		os.Exit(0)
+	}
+
 	if os.Getenv("GOGET_INTEGRATION") == "" {
 		fmt.Fprintln(os.Stderr, "main_test: Skipping integration tests with GOGET_INTEGRATION unset")
 		return
 	}
 
-	args := []string{"build", "-tags", testbin, "-o", testbin + exeSuffix}
-	out, err := exec.Command("go", args...).CombinedOutput()
-	if err != nil {
-		fmt.Fprintf(os.Stderr, "building %s failed: %v\n%s", testbin, err, out)
-		os.Exit(2)
-	}
-
 	// Don't let these environment variables confuse the test.
 	os.Unsetenv("GOBIN")
 	os.Unsetenv("GOPATH")
 	os.Unsetenv("GIT_ALLOW_PROTOCOL")
 	os.Unsetenv("PATH")
 
-	r := m.Run()
-
-	os.Remove(testbin + exeSuffix)
-
-	os.Exit(r)
+	os.Exit(m.Run())
 }
 
 func createTmpHome(t *testing.T) string {
@@ -72,12 +49,18 @@
 // doRun runs the test getgo command, recording stdout and stderr and
 // returning exit status.
 func doRun(t *testing.T, args ...string) error {
+	exe, err := os.Executable()
+	if err != nil {
+		t.Fatal(err)
+	}
+	t.Helper()
+
+	t.Logf("running getgo %v", args)
 	var stdout, stderr bytes.Buffer
-	t.Logf("running %s %v", testbin, args)
-	cmd := exec.Command("./"+testbin+exeSuffix, args...)
+	cmd := exec.Command(exe, args...)
 	cmd.Stdout = &stdout
 	cmd.Stderr = &stderr
-	cmd.Env = os.Environ()
+	cmd.Env = append(os.Environ(), "GO_GETGO_TEST_IS_GETGO=1")
 	status := cmd.Run()
 	if stdout.Len() > 0 {
 		t.Log("standard output:")