diff --git a/imports/fix_test.go b/imports/fix_test.go index 68996ed2eae..f9bac4610b0 100644 --- a/imports/fix_test.go +++ b/imports/fix_test.go @@ -915,6 +915,110 @@ func main() { x := math.MaxInt64 fmt.Println(strings.Join(",", []string{"hi"}), x) } +`, + }, + + { + name: "issue #26246 1", + in: `package main + +import ( + _ "io" + _ "net/http" + _ "net/http/pprof" // install the pprof http handlers + _ "strings" +) + +func main() { +} +`, + out: `package main + +import ( + _ "io" + _ "net/http" + _ "net/http/pprof" // install the pprof http handlers + _ "strings" +) + +func main() { +} +`, + }, + + { + name: "issue #26246 2", + in: `package main + +import ( + _ "io" + _ "net/http/pprof" // install the pprof http handlers + _ "net/http" + _ "strings" +) + +func main() { +} +`, + out: `package main + +import ( + _ "io" + _ "net/http" + _ "net/http/pprof" // install the pprof http handlers + _ "strings" +) + +func main() { +} +`, + }, + + { + name: "issue #26246 3", + in: `package main + +import ( + "encoding/json" + "io" + "net/http" + _ "net/http/pprof" // install the pprof http handlers + "strings" + + "github.com/pkg/errors" +) + +func main() { + _ = strings.ToUpper("hello") + _ = io.EOF + var ( + _ json.Number + _ *http.Request + _ errors.Frame + ) +} +`, + out: `package main + +import ( + "encoding/json" + "io" + "net/http" + _ "net/http/pprof" // install the pprof http handlers + "strings" + + "github.com/pkg/errors" +) + +func main() { + _ = strings.ToUpper("hello") + _ = io.EOF + var ( + _ json.Number + _ *http.Request + _ errors.Frame + ) +} `, }, } diff --git a/imports/sortimports.go b/imports/sortimports.go index 93711565a9b..f3dd56c7a6f 100644 --- a/imports/sortimports.go +++ b/imports/sortimports.go @@ -183,6 +183,17 @@ func sortSpecs(fset *token.FileSet, f *ast.File, specs []ast.Spec) []ast.Spec { sort.Sort(byCommentPos(comments)) + // Fixup comments can insert blank lines, because import specs are on different lines. + // We remove those blank lines here by merging import spec to the first import spec line. + firstSpecLine := fset.Position(specs[0].Pos()).Line + for _, s := range specs[1:] { + p := s.Pos() + line := fset.File(p).Line(p) + for previousLine := line - 1; previousLine >= firstSpecLine; { + fset.File(p).MergeLine(previousLine) + previousLine-- + } + } return specs }