From 0133cac3176f225883c5d817146de8633ed07ebc Mon Sep 17 00:00:00 2001 From: Heschi Kreinick Date: Mon, 6 May 2019 16:34:48 -0400 Subject: [PATCH] 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 TryBot-Result: Gobot Gobot Reviewed-by: Brad Fitzpatrick --- cmd/goimports/goimports.go | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/cmd/goimports/goimports.go b/cmd/goimports/goimports.go index 0a9fe12a13..a476a7f3c3 100644 --- a/cmd/goimports/goimports.go +++ b/cmd/goimports/goimports.go @@ -10,6 +10,7 @@ import ( "errors" "flag" "fmt" + "go/build" "go/scanner" "io" "io/ioutil" @@ -21,7 +22,7 @@ import ( "runtime/pprof" "strings" - "golang.org/x/tools/imports" + "golang.org/x/tools/internal/imports" ) var ( @@ -42,13 +43,18 @@ var ( 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 @@ func gofmtMain() { 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)