cmd/goimports: reuse cached state

The internal imports API allows the user to control the lifetime of
caches, via the ProcessEnv object. Change the goimports command to use
the same cache for its lifetime. This should speed up goimports -w *.go
dramatically in cases where imports need to be added.

Change-Id: I01e3531ad53b038896435474ac9a8be97d5f3c10
Reviewed-on: https://go-review.googlesource.com/c/tools/+/175448
Run-TryBot: Heschi Kreinick <heschi@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
diff --git a/cmd/goimports/goimports.go b/cmd/goimports/goimports.go
index 0a9fe12..a476a7f 100644
--- a/cmd/goimports/goimports.go
+++ b/cmd/goimports/goimports.go
@@ -10,6 +10,7 @@
 	"errors"
 	"flag"
 	"fmt"
+	"go/build"
 	"go/scanner"
 	"io"
 	"io/ioutil"
@@ -21,7 +22,7 @@
 	"runtime/pprof"
 	"strings"
 
-	"golang.org/x/tools/imports"
+	"golang.org/x/tools/internal/imports"
 )
 
 var (
@@ -42,13 +43,18 @@
 		TabIndent: true,
 		Comments:  true,
 		Fragment:  true,
+		// This environment, and its caches, will be reused for the whole run.
+		Env: &imports.ProcessEnv{
+			GOPATH: build.Default.GOPATH,
+			GOROOT: build.Default.GOROOT,
+		},
 	}
 	exitCode = 0
 )
 
 func init() {
 	flag.BoolVar(&options.AllErrors, "e", false, "report all errors (not just the first 10 on different lines)")
-	flag.StringVar(&imports.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
+	flag.StringVar(&options.Env.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
 	flag.BoolVar(&options.FormatOnly, "format-only", false, "if true, don't fix imports and only format. In this mode, goimports is effectively gofmt, with the addition that imports are grouped into sections.")
 }
 
@@ -252,7 +258,7 @@
 
 	if verbose {
 		log.SetFlags(log.LstdFlags | log.Lmicroseconds)
-		imports.Debug = true
+		options.Env.Debug = true
 	}
 	if options.TabWidth < 0 {
 		fmt.Fprintf(os.Stderr, "negative tabwidth %d\n", options.TabWidth)