1
0
mirror of https://github.com/golang/go synced 2024-11-18 10:14:45 -07:00

go.tools/astutil: make sure import blocks are marked as such (Lparen=1)

R=bradfitz
CC=golang-dev
https://golang.org/cl/22320044
This commit is contained in:
David Crawshaw 2013-11-06 15:31:54 -05:00
parent 56a1b4d0b7
commit 6df4bd0406
2 changed files with 78 additions and 9 deletions

View File

@ -15,13 +15,6 @@ func AddImport(f *ast.File, ipath string) (added bool) {
return false
}
// Determine name of import.
// Assume added imports follow convention of using last element.
_, name := path.Split(ipath)
// Rename any conflicting top-level references from name to name_.
renameTop(f, name, name+"_")
newImport := &ast.ImportSpec{
Path: &ast.BasicLit{
Kind: token.STRING,
@ -88,6 +81,11 @@ func AddImport(f *ast.File, ipath string) (added bool) {
newImport.Path.ValuePos = prev.Pos()
newImport.EndPos = prev.Pos()
}
if len(impDecl.Specs) > 1 && impDecl.Lparen == 0 {
// set Lparen to something not zero, so the printer prints
// the full block rather just the first ImportSpec.
impDecl.Lparen = 1
}
f.Imports = append(f.Imports, newImport)
return true
@ -240,9 +238,9 @@ func declImports(gen *ast.GenDecl, path string) bool {
return false
}
// renameTop renames all references to the top-level name old.
// RenameTop renames all references to the top-level name old.
// It returns true if it makes any changes.
func renameTop(f *ast.File, old, new string) bool {
func RenameTop(f *ast.File, old, new string) bool {
var fixed bool
// Rename any conflicting imports

View File

@ -133,6 +133,22 @@ import (
"d/f"
)
`,
},
{
name: "import into singular block",
pkg: "bytes",
in: `package main
import "os"
`,
out: `package main
import (
"bytes"
"os"
)
`,
},
}
@ -147,6 +163,22 @@ func TestAddImport(t *testing.T) {
}
}
func TestDoubleAddImport(t *testing.T) {
file := parse(t, "doubleimport", "package main\n")
AddImport(file, "os")
AddImport(file, "bytes")
want := `package main
import (
"bytes"
"os"
)
`
if got := print(t, "doubleimport", file); got != want {
t.Errorf("got: %s\nwant: %s", got, want)
}
}
var deleteTests = []test{
{
name: "import.4",
@ -315,6 +347,13 @@ import (
"io"
"os"
)
`,
},
{
name: "handle.raw.quote.imports",
pkg: "os",
in: "package main\n\nimport `os`",
out: `package main
`,
},
}
@ -457,3 +496,35 @@ func TestRewriteImport(t *testing.T) {
}
}
}
var renameTests = []rewriteTest{
{
name: "rename pkg use",
srcPkg: "bytes",
dstPkg: "bytes_",
in: `package main
func f() []byte {
buf := new(bytes.Buffer)
return buf.Bytes()
}
`,
out: `package main
func f() []byte {
buf := new(bytes_.Buffer)
return buf.Bytes()
}
`,
},
}
func TestRenameTop(t *testing.T) {
for _, test := range renameTests {
file := parse(t, test.name, test.in)
RenameTop(file, test.srcPkg, test.dstPkg)
if got := print(t, test.name, file); got != test.out {
t.Errorf("%s:\ngot: %s\nwant: %s", test.name, got, test.out)
}
}
}