Skip to content

Commit

Permalink
imports: fixup comments on import lines correctly
Browse files Browse the repository at this point in the history
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 <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
  • Loading branch information
cuonglm authored and bradfitz committed Jul 2, 2018
1 parent 1c99e12 commit b23eb62
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
31 changes: 29 additions & 2 deletions imports/fix_test.go
Expand Up @@ -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)
}
`,
},
}
Expand Down Expand Up @@ -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) {
Expand Down
7 changes: 7 additions & 0 deletions imports/sortimports.go
Expand Up @@ -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))
Expand Down

0 comments on commit b23eb62

Please sign in to comment.