go/ast/astutil: do not remove imports in AddNamedImport

When adding imports to an existing import declaration, ensure that
the target declaration will be printed with parentheses. This allows
all of the imported packages to be printed, not just the first one.

Fixes golang/go#17212

Change-Id: Ie5de5ec9bca6169650336ee2ea98334817e64e48
Reviewed-on: https://go-review.googlesource.com/29688
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
Rhys Hiltner 2016-09-23 17:37:05 -07:00 committed by Brad Fitzpatrick
parent 69f6f5b782
commit af95c112ad
2 changed files with 39 additions and 0 deletions

View File

@ -160,6 +160,9 @@ func AddNamedImport(fset *token.FileSet, f *ast.File, name, ipath string) (added
first = gen
continue // Don't touch the first one.
}
// We now know there is more than one package in this import
// declaration. Ensure that it ends up parenthesized.
first.Lparen = first.Pos()
// Move the imports of the other import declaration to the first one.
for _, spec := range gen.Specs {
spec.(*ast.ImportSpec).Path.ValuePos = first.Pos()

View File

@ -509,6 +509,42 @@ import "C"
// Comment
import "C"
import "bufio"
`,
},
{
name: `issue 17212 several single-import lines with shared prefix ending in a slash`,
pkg: "net/http",
in: `package main
import "bufio"
import "net/url"
`,
out: `package main
import (
"bufio"
"net/http"
"net/url"
)
`,
},
{
name: `issue 17212 block imports lines with shared prefix ending in a slash`,
pkg: "net/http",
in: `package main
import (
"bufio"
"net/url"
)
`,
out: `package main
import (
"bufio"
"net/http"
"net/url"
)
`,
},
{