go.tools/astutil: add AddNamedImport
R=bradfitz CC=golang-dev https://golang.org/cl/23850044
This commit is contained in:
parent
515bcdc536
commit
545b16b6db
|
|
@ -11,6 +11,17 @@ import (
|
||||||
|
|
||||||
// AddImport adds the import path to the file f, if absent.
|
// AddImport adds the import path to the file f, if absent.
|
||||||
func AddImport(f *ast.File, ipath string) (added bool) {
|
func AddImport(f *ast.File, ipath string) (added bool) {
|
||||||
|
return AddNamedImport(f, "", ipath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddNamedImport adds the import path to the file f, if absent.
|
||||||
|
// If name is not empty, it is used to rename the import.
|
||||||
|
//
|
||||||
|
// For example, calling
|
||||||
|
// AddNamedImport(f, "pathpkg", "path")
|
||||||
|
// adds
|
||||||
|
// import pathpkg "path"
|
||||||
|
func AddNamedImport(f *ast.File, name, ipath string) (added bool) {
|
||||||
if imports(f, ipath) {
|
if imports(f, ipath) {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
@ -21,6 +32,9 @@ func AddImport(f *ast.File, ipath string) (added bool) {
|
||||||
Value: strconv.Quote(ipath),
|
Value: strconv.Quote(ipath),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
if name != "" {
|
||||||
|
newImport.Name = &ast.Ident{Name: name}
|
||||||
|
}
|
||||||
|
|
||||||
// Find an import decl to add to.
|
// Find an import decl to add to.
|
||||||
var (
|
var (
|
||||||
|
|
|
||||||
|
|
@ -31,6 +31,7 @@ func print(t *testing.T, name string, f *ast.File) string {
|
||||||
|
|
||||||
type test struct {
|
type test struct {
|
||||||
name string
|
name string
|
||||||
|
renamedPkg string
|
||||||
pkg string
|
pkg string
|
||||||
in string
|
in string
|
||||||
out string
|
out string
|
||||||
|
|
@ -150,6 +151,23 @@ import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"os"
|
"os"
|
||||||
)
|
)
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "",
|
||||||
|
renamedPkg: "fmtpkg",
|
||||||
|
pkg: "fmt",
|
||||||
|
in: `package main
|
||||||
|
|
||||||
|
import "os"
|
||||||
|
|
||||||
|
`,
|
||||||
|
out: `package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
fmtpkg "fmt"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
@ -157,7 +175,7 @@ import (
|
||||||
func TestAddImport(t *testing.T) {
|
func TestAddImport(t *testing.T) {
|
||||||
for _, test := range addTests {
|
for _, test := range addTests {
|
||||||
file := parse(t, test.name, test.in)
|
file := parse(t, test.name, test.in)
|
||||||
AddImport(file, test.pkg)
|
AddNamedImport(file, test.renamedPkg, test.pkg)
|
||||||
if got := print(t, test.name, file); got != test.out {
|
if got := print(t, test.name, file); got != test.out {
|
||||||
t.Errorf("%s:\ngot: %s\nwant: %s", test.name, got, test.out)
|
t.Errorf("%s:\ngot: %s\nwant: %s", test.name, got, test.out)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue