go/ast/astutil: keep comment position for existing imports.

Fixes golang/go#10337.

Change-Id: Ia21547bb57790c077ca01a2ad656086da3f2ba8a
Reviewed-on: https://go-review.googlesource.com/19822
Reviewed-by: Robert Griesemer <gri@golang.org>
This commit is contained in:
David R. Jenni 2016-02-23 09:31:56 +01:00 committed by Robert Griesemer
parent f7268ab39b
commit 108746816d
2 changed files with 67 additions and 3 deletions

View File

@ -117,10 +117,16 @@ func AddNamedImport(fset *token.FileSet, f *ast.File, name, ipath string) (added
impDecl.Specs[insertAt] = newImport impDecl.Specs[insertAt] = newImport
pos := impDecl.Pos() pos := impDecl.Pos()
if insertAt > 0 { if insertAt > 0 {
// If there is a comment after an existing import, preserve the comment
// position by adding the new import after the comment.
if spec, ok := impDecl.Specs[insertAt-1].(*ast.ImportSpec); ok && spec.Comment != nil {
pos = spec.Comment.End()
} else {
// Assign same position as the previous import, // Assign same position as the previous import,
// so that the sorter sees it as being in the same block. // so that the sorter sees it as being in the same block.
pos = impDecl.Specs[insertAt-1].Pos() pos = impDecl.Specs[insertAt-1].Pos()
} }
}
if newImport.Name != nil { if newImport.Name != nil {
newImport.Name.NamePos = pos newImport.Name.NamePos = pos
} }

View File

@ -338,6 +338,64 @@ import (
"rsc.io/p" "rsc.io/p"
) )
`,
},
// Issue 10337: Preserve comment position
{
name: "issue 10337",
pkg: "fmt",
in: `package main
import (
"bytes" // a
"log" // c
)
`,
out: `package main
import (
"bytes" // a
"fmt"
"log" // c
)
`,
},
{
name: "issue 10337 new import at the start",
pkg: "bytes",
in: `package main
import (
"fmt" // b
"log" // c
)
`,
out: `package main
import (
"bytes"
"fmt" // b
"log" // c
)
`,
},
{
name: "issue 10337 new import at the end",
pkg: "log",
in: `package main
import (
"bytes" // a
"fmt" // b
)
`,
out: `package main
import (
"bytes" // a
"fmt" // b
"log"
)
`, `,
}, },
} }