From a0c2140b91d8451b85837830d546d04d319218fc Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Fri, 7 Feb 2014 17:03:34 -0800 Subject: [PATCH] imports: fix a case where we weren't gofmt-compatible Because goimports also sorts stdlib-vs-external differently (whereas gofmt just sorts string-wise), we need to put a blank line between imports of different classes. This happened in some cases, but not all. Fixes golang/go#7132 LGTM=kamil.kisiel R=golang-codereviews, kamil.kisiel CC=golang-codereviews https://golang.org/cl/60870047 --- imports/fix_test.go | 38 +++++++++++++++++++++++++++++++++++++- imports/imports.go | 9 ++++++--- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/imports/fix_test.go b/imports/fix_test.go index d9822ee9f4..9b7ddde74e 100644 --- a/imports/fix_test.go +++ b/imports/fix_test.go @@ -469,6 +469,42 @@ import "fmt" func main() { fmt.Println("Hello, world") } +`, + }, + + // golang.org/issue/7132 + { + name: "issue 7132", + in: `package main + +import ( +"fmt" + +"gu" +"github.com/foo/bar" +) + +var ( +a = bar.a +b = gu.a +c = fmt.Printf +) +`, + out: `package main + +import ( + "fmt" + + "gu" + + "github.com/foo/bar" +) + +var ( + a = bar.a + b = gu.a + c = fmt.Printf +) `, }, } @@ -492,7 +528,7 @@ func TestFixImports(t *testing.T) { if *only != "" && tt.name != *only { continue } - buf, err := Process("foo.go", []byte(tt.in), nil) + buf, err := Process(tt.name+".go", []byte(tt.in), nil) if err != nil { t.Errorf("error on %q: %v", tt.name, err) continue diff --git a/imports/imports.go b/imports/imports.go index a40d075a61..67869eff7b 100644 --- a/imports/imports.go +++ b/imports/imports.go @@ -54,10 +54,13 @@ func Process(filename string, src []byte, opt *Options) ([]byte, error) { imps := astutil.Imports(fileSet, file) var spacesBefore []string // import paths we need spaces before - if len(imps) == 1 { - // We have just one block of imports. See if any are in different groups numbers. + for _, impSection := range imps { + // Within each block of contiguous imports, see if any + // import lines are in different group numbers. If so, + // we'll need to put a space between them so it's + // compatible with gofmt. lastGroup := -1 - for _, importSpec := range imps[0] { + for _, importSpec := range impSection { importPath, _ := strconv.Unquote(importSpec.Path.Value) groupNum := importGroup(importPath) if groupNum != lastGroup && lastGroup != -1 {