From b23eb6252fad4550577208636764807058a5331a Mon Sep 17 00:00:00 2001 From: LE Manh Cuong Date: Sun, 1 Jul 2018 22:28:45 +0700 Subject: [PATCH] imports: fixup comments on import lines correctly The current implementation uses the added import specs EndPos to fixup the comments position after import specs is sorted. If two or more import specs have the same EndPos, a comment associated with one of them is always added to the last import spec. This commit uses the current import spec position to compute new position for next import spec. So there is never two or more specs have the same EndPos. Fixes golang/go#23709 Change-Id: I60ace9431d871e94a2b3d90892aa80d0671aeea0 Reviewed-on: https://go-review.googlesource.com/121878 Run-TryBot: Brad Fitzpatrick TryBot-Result: Gobot Gobot Reviewed-by: Brad Fitzpatrick --- imports/fix_test.go | 31 +++++++++++++++++++++++++++++-- imports/sortimports.go | 7 +++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/imports/fix_test.go b/imports/fix_test.go index e2873008..654d6559 100644 --- a/imports/fix_test.go +++ b/imports/fix_test.go @@ -888,6 +888,33 @@ import "fmt" func main() { _ = fmt.Println } +`, + }, + + { + name: "issue #23709", + in: `package main + +import ( + "math" // fun +) + +func main() { + x := math.MaxInt64 + fmt.Println(strings.Join(",", []string{"hi"}), x) +}`, + out: `package main + +import ( + "fmt" + "math" // fun + "strings" +) + +func main() { + x := math.MaxInt64 + fmt.Println(strings.Join(",", []string{"hi"}), x) +} `, }, } @@ -1643,8 +1670,8 @@ func TestImportPathToNameGoPathParse(t *testing.T) { func TestIgnoreConfiguration(t *testing.T) { testConfig{ gopathFiles: map[string]string{ - ".goimportsignore": "# comment line\n\n example.net", // tests comment, blank line, whitespace trimming - "example.net/pkg/pkg.go": "package pkg\nconst X = 1", + ".goimportsignore": "# comment line\n\n example.net", // tests comment, blank line, whitespace trimming + "example.net/pkg/pkg.go": "package pkg\nconst X = 1", "otherwise-longer-so-worse.example.net/foo/pkg/pkg.go": "package pkg\nconst X = 1", }, }.test(t, func(t *goimportTest) { diff --git a/imports/sortimports.go b/imports/sortimports.go index 653afc51..93711565 100644 --- a/imports/sortimports.go +++ b/imports/sortimports.go @@ -167,11 +167,18 @@ func sortSpecs(fset *token.FileSet, f *ast.File, specs []ast.Spec) []ast.Spec { } s.Path.ValuePos = pos[i].Start s.EndPos = pos[i].End + nextSpecPos := pos[i].End + for _, g := range importComment[s] { for _, c := range g.List { c.Slash = pos[i].End + nextSpecPos = c.End() } } + if i < len(specs)-1 { + pos[i+1].Start = nextSpecPos + pos[i+1].End = nextSpecPos + } } sort.Sort(byCommentPos(comments))