2013-12-17 19:21:03 -07:00
|
|
|
// Copyright 2013 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package imports
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"go/ast"
|
|
|
|
"go/build"
|
|
|
|
"go/parser"
|
|
|
|
"go/token"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
"sync"
|
|
|
|
|
2015-01-08 19:32:51 -07:00
|
|
|
"golang.org/x/tools/go/ast/astutil"
|
2013-12-17 19:21:03 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
// importToGroup is a list of functions which map from an import path to
|
|
|
|
// a group number.
|
|
|
|
var importToGroup = []func(importPath string) (num int, ok bool){
|
|
|
|
func(importPath string) (num int, ok bool) {
|
|
|
|
if strings.HasPrefix(importPath, "appengine") {
|
|
|
|
return 2, true
|
|
|
|
}
|
|
|
|
return
|
|
|
|
},
|
|
|
|
func(importPath string) (num int, ok bool) {
|
|
|
|
if strings.Contains(importPath, ".") {
|
|
|
|
return 1, true
|
|
|
|
}
|
|
|
|
return
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
func importGroup(importPath string) int {
|
|
|
|
for _, fn := range importToGroup {
|
|
|
|
if n, ok := fn(importPath); ok {
|
|
|
|
return n
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
|
2015-12-10 23:32:07 -07:00
|
|
|
func fixImports(fset *token.FileSet, f *ast.File, filename string) (added []string, err error) {
|
2014-05-02 15:38:08 -06:00
|
|
|
// refs are a set of possible package references currently unsatisfied by imports.
|
2013-12-17 19:21:03 -07:00
|
|
|
// first key: either base package (e.g. "fmt") or renamed package
|
|
|
|
// second key: referenced package symbol (e.g. "Println")
|
|
|
|
refs := make(map[string]map[string]bool)
|
|
|
|
|
|
|
|
// decls are the current package imports. key is base package or renamed package.
|
|
|
|
decls := make(map[string]*ast.ImportSpec)
|
|
|
|
|
|
|
|
// collect potential uses of packages.
|
|
|
|
var visitor visitFn
|
|
|
|
visitor = visitFn(func(node ast.Node) ast.Visitor {
|
|
|
|
if node == nil {
|
|
|
|
return visitor
|
|
|
|
}
|
|
|
|
switch v := node.(type) {
|
|
|
|
case *ast.ImportSpec:
|
|
|
|
if v.Name != nil {
|
|
|
|
decls[v.Name.Name] = v
|
|
|
|
} else {
|
|
|
|
local := importPathToName(strings.Trim(v.Path.Value, `\"`))
|
|
|
|
decls[local] = v
|
|
|
|
}
|
|
|
|
case *ast.SelectorExpr:
|
|
|
|
xident, ok := v.X.(*ast.Ident)
|
|
|
|
if !ok {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
if xident.Obj != nil {
|
|
|
|
// if the parser can resolve it, it's not a package ref
|
|
|
|
break
|
|
|
|
}
|
|
|
|
pkgName := xident.Name
|
|
|
|
if refs[pkgName] == nil {
|
|
|
|
refs[pkgName] = make(map[string]bool)
|
|
|
|
}
|
|
|
|
if decls[pkgName] == nil {
|
|
|
|
refs[pkgName][v.Sel.Name] = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return visitor
|
|
|
|
})
|
|
|
|
ast.Walk(visitor, f)
|
|
|
|
|
2015-08-07 09:16:12 -06:00
|
|
|
// Nil out any unused ImportSpecs, to be removed in following passes
|
2016-02-25 12:09:00 -07:00
|
|
|
unusedImport := map[string]string{}
|
2015-08-07 09:16:12 -06:00
|
|
|
for pkg, is := range decls {
|
|
|
|
if refs[pkg] == nil && pkg != "_" && pkg != "." {
|
2016-02-25 12:09:00 -07:00
|
|
|
name := ""
|
|
|
|
if is.Name != nil {
|
|
|
|
name = is.Name.Name
|
|
|
|
}
|
|
|
|
unusedImport[strings.Trim(is.Path.Value, `"`)] = name
|
2015-08-07 09:16:12 -06:00
|
|
|
}
|
|
|
|
}
|
2016-02-25 12:09:00 -07:00
|
|
|
for ipath, name := range unusedImport {
|
2015-08-07 09:16:12 -06:00
|
|
|
if ipath == "C" {
|
|
|
|
// Don't remove cgo stuff.
|
|
|
|
continue
|
|
|
|
}
|
2016-02-25 12:09:00 -07:00
|
|
|
astutil.DeleteNamedImport(fset, f, name, ipath)
|
2015-08-07 09:16:12 -06:00
|
|
|
}
|
|
|
|
|
2013-12-17 19:21:03 -07:00
|
|
|
// Search for imports matching potential package references.
|
|
|
|
searches := 0
|
|
|
|
type result struct {
|
|
|
|
ipath string
|
2014-03-25 07:37:10 -06:00
|
|
|
name string
|
2013-12-17 19:21:03 -07:00
|
|
|
err error
|
|
|
|
}
|
|
|
|
results := make(chan result)
|
|
|
|
for pkgName, symbols := range refs {
|
|
|
|
if len(symbols) == 0 {
|
|
|
|
continue // skip over packages already imported
|
|
|
|
}
|
|
|
|
go func(pkgName string, symbols map[string]bool) {
|
2015-12-10 23:32:07 -07:00
|
|
|
ipath, rename, err := findImport(pkgName, symbols, filename)
|
2014-03-25 07:37:10 -06:00
|
|
|
r := result{ipath: ipath, err: err}
|
|
|
|
if rename {
|
|
|
|
r.name = pkgName
|
|
|
|
}
|
|
|
|
results <- r
|
2013-12-17 19:21:03 -07:00
|
|
|
}(pkgName, symbols)
|
|
|
|
searches++
|
|
|
|
}
|
|
|
|
for i := 0; i < searches; i++ {
|
|
|
|
result := <-results
|
|
|
|
if result.err != nil {
|
|
|
|
return nil, result.err
|
|
|
|
}
|
|
|
|
if result.ipath != "" {
|
2014-03-25 07:37:10 -06:00
|
|
|
if result.name != "" {
|
|
|
|
astutil.AddNamedImport(fset, f, result.name, result.ipath)
|
|
|
|
} else {
|
|
|
|
astutil.AddImport(fset, f, result.ipath)
|
|
|
|
}
|
2013-12-17 19:21:03 -07:00
|
|
|
added = append(added, result.ipath)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return added, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// importPathToName returns the package name for the given import path.
|
|
|
|
var importPathToName = importPathToNameGoPath
|
|
|
|
|
|
|
|
// importPathToNameBasic assumes the package name is the base of import path.
|
|
|
|
func importPathToNameBasic(importPath string) (packageName string) {
|
|
|
|
return path.Base(importPath)
|
|
|
|
}
|
|
|
|
|
|
|
|
// importPathToNameGoPath finds out the actual package name, as declared in its .go files.
|
|
|
|
// If there's a problem, it falls back to using importPathToNameBasic.
|
|
|
|
func importPathToNameGoPath(importPath string) (packageName string) {
|
|
|
|
if buildPkg, err := build.Import(importPath, "", 0); err == nil {
|
|
|
|
return buildPkg.Name
|
|
|
|
} else {
|
|
|
|
return importPathToNameBasic(importPath)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type pkg struct {
|
|
|
|
importpath string // full pkg import path, e.g. "net/http"
|
|
|
|
dir string // absolute file path to pkg directory e.g. "/usr/lib/go/src/fmt"
|
|
|
|
}
|
|
|
|
|
2016-03-19 02:01:33 -06:00
|
|
|
var pkgIndexOnce = &sync.Once{}
|
2013-12-17 19:21:03 -07:00
|
|
|
|
|
|
|
var pkgIndex struct {
|
|
|
|
sync.Mutex
|
|
|
|
m map[string][]pkg // shortname => []pkg, e.g "http" => "net/http"
|
|
|
|
}
|
|
|
|
|
2014-04-08 17:43:52 -06:00
|
|
|
// gate is a semaphore for limiting concurrency.
|
2014-04-09 18:40:05 -06:00
|
|
|
type gate chan struct{}
|
2014-04-08 17:43:52 -06:00
|
|
|
|
2014-04-09 18:40:05 -06:00
|
|
|
func (g gate) enter() { g <- struct{}{} }
|
2014-04-08 17:43:52 -06:00
|
|
|
func (g gate) leave() { <-g }
|
|
|
|
|
|
|
|
// fsgate protects the OS & filesystem from too much concurrency.
|
|
|
|
// Too much disk I/O -> too many threads -> swapping and bad scheduling.
|
|
|
|
var fsgate = make(gate, 8)
|
|
|
|
|
2013-12-17 19:21:03 -07:00
|
|
|
func loadPkgIndex() {
|
|
|
|
pkgIndex.Lock()
|
|
|
|
pkgIndex.m = make(map[string][]pkg)
|
|
|
|
pkgIndex.Unlock()
|
|
|
|
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
for _, path := range build.Default.SrcDirs() {
|
2014-04-08 17:43:52 -06:00
|
|
|
fsgate.enter()
|
2013-12-17 19:21:03 -07:00
|
|
|
f, err := os.Open(path)
|
|
|
|
if err != nil {
|
2014-04-08 17:43:52 -06:00
|
|
|
fsgate.leave()
|
2013-12-17 19:21:03 -07:00
|
|
|
fmt.Fprint(os.Stderr, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
children, err := f.Readdir(-1)
|
|
|
|
f.Close()
|
2014-04-08 17:43:52 -06:00
|
|
|
fsgate.leave()
|
2013-12-17 19:21:03 -07:00
|
|
|
if err != nil {
|
|
|
|
fmt.Fprint(os.Stderr, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
for _, child := range children {
|
|
|
|
if child.IsDir() {
|
|
|
|
wg.Add(1)
|
|
|
|
go func(path, name string) {
|
|
|
|
defer wg.Done()
|
|
|
|
loadPkg(&wg, path, name)
|
|
|
|
}(path, child.Name())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
wg.Wait()
|
|
|
|
}
|
|
|
|
|
|
|
|
func loadPkg(wg *sync.WaitGroup, root, pkgrelpath string) {
|
|
|
|
importpath := filepath.ToSlash(pkgrelpath)
|
|
|
|
dir := filepath.Join(root, importpath)
|
|
|
|
|
2014-04-08 17:43:52 -06:00
|
|
|
fsgate.enter()
|
|
|
|
defer fsgate.leave()
|
2013-12-17 19:21:03 -07:00
|
|
|
pkgDir, err := os.Open(dir)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
children, err := pkgDir.Readdir(-1)
|
|
|
|
pkgDir.Close()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2014-04-08 17:43:52 -06:00
|
|
|
// hasGo tracks whether a directory actually appears to be a
|
|
|
|
// Go source code directory. If $GOPATH == $HOME, and
|
|
|
|
// $HOME/src has lots of other large non-Go projects in it,
|
|
|
|
// then the calls to importPathToName below can be expensive.
|
|
|
|
hasGo := false
|
2013-12-17 19:21:03 -07:00
|
|
|
for _, child := range children {
|
2014-11-12 13:45:17 -07:00
|
|
|
// Avoid .foo, _foo, and testdata directory trees.
|
2013-12-17 19:21:03 -07:00
|
|
|
name := child.Name()
|
2014-11-12 13:45:17 -07:00
|
|
|
if name == "" || name[0] == '.' || name[0] == '_' || name == "testdata" {
|
2013-12-17 19:21:03 -07:00
|
|
|
continue
|
|
|
|
}
|
2014-04-08 17:43:52 -06:00
|
|
|
if strings.HasSuffix(name, ".go") {
|
|
|
|
hasGo = true
|
|
|
|
}
|
2013-12-17 19:21:03 -07:00
|
|
|
if child.IsDir() {
|
|
|
|
wg.Add(1)
|
|
|
|
go func(root, name string) {
|
|
|
|
defer wg.Done()
|
|
|
|
loadPkg(wg, root, name)
|
|
|
|
}(root, filepath.Join(importpath, name))
|
|
|
|
}
|
|
|
|
}
|
2014-04-08 17:43:52 -06:00
|
|
|
if hasGo {
|
|
|
|
shortName := importPathToName(importpath)
|
|
|
|
pkgIndex.Lock()
|
|
|
|
pkgIndex.m[shortName] = append(pkgIndex.m[shortName], pkg{
|
|
|
|
importpath: importpath,
|
|
|
|
dir: dir,
|
|
|
|
})
|
|
|
|
pkgIndex.Unlock()
|
|
|
|
}
|
|
|
|
|
2013-12-17 19:21:03 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// loadExports returns a list exports for a package.
|
|
|
|
var loadExports = loadExportsGoPath
|
|
|
|
|
|
|
|
func loadExportsGoPath(dir string) map[string]bool {
|
|
|
|
exports := make(map[string]bool)
|
|
|
|
buildPkg, err := build.ImportDir(dir, 0)
|
|
|
|
if err != nil {
|
|
|
|
if strings.Contains(err.Error(), "no buildable Go source files in") {
|
|
|
|
return nil
|
|
|
|
}
|
2014-09-05 12:13:44 -06:00
|
|
|
fmt.Fprintf(os.Stderr, "could not import %q: %v\n", dir, err)
|
2013-12-17 19:21:03 -07:00
|
|
|
return nil
|
|
|
|
}
|
2013-12-18 10:09:37 -07:00
|
|
|
fset := token.NewFileSet()
|
2014-09-29 13:46:11 -06:00
|
|
|
for _, files := range [...][]string{buildPkg.GoFiles, buildPkg.CgoFiles} {
|
|
|
|
for _, file := range files {
|
|
|
|
f, err := parser.ParseFile(fset, filepath.Join(dir, file), nil, 0)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Fprintf(os.Stderr, "could not parse %q: %v\n", file, err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
for name := range f.Scope.Objects {
|
|
|
|
if ast.IsExported(name) {
|
|
|
|
exports[name] = true
|
|
|
|
}
|
2013-12-17 19:21:03 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return exports
|
|
|
|
}
|
|
|
|
|
|
|
|
// findImport searches for a package with the given symbols.
|
|
|
|
// If no package is found, findImport returns "".
|
|
|
|
// Declared as a variable rather than a function so goimports can be easily
|
|
|
|
// extended by adding a file with an init function.
|
|
|
|
var findImport = findImportGoPath
|
|
|
|
|
2015-12-10 23:32:07 -07:00
|
|
|
func findImportGoPath(pkgName string, symbols map[string]bool, filename string) (string, bool, error) {
|
2014-01-26 10:47:31 -07:00
|
|
|
// Fast path for the standard library.
|
|
|
|
// In the common case we hopefully never have to scan the GOPATH, which can
|
|
|
|
// be slow with moving disks.
|
2014-03-25 07:37:10 -06:00
|
|
|
if pkg, rename, ok := findImportStdlib(pkgName, symbols); ok {
|
|
|
|
return pkg, rename, nil
|
2014-01-26 10:47:31 -07:00
|
|
|
}
|
2013-12-17 19:21:03 -07:00
|
|
|
|
2014-03-25 07:37:10 -06:00
|
|
|
// TODO(sameer): look at the import lines for other Go files in the
|
|
|
|
// local directory, since the user is likely to import the same packages
|
|
|
|
// in the current Go file. Return rename=true when the other Go files
|
|
|
|
// use a renamed package that's also used in the current file.
|
|
|
|
|
2013-12-17 19:21:03 -07:00
|
|
|
pkgIndexOnce.Do(loadPkgIndex)
|
|
|
|
|
|
|
|
// Collect exports for packages with matching names.
|
2015-12-10 23:32:07 -07:00
|
|
|
var (
|
|
|
|
wg sync.WaitGroup
|
|
|
|
mu sync.Mutex
|
|
|
|
shortest string
|
|
|
|
)
|
2013-12-17 19:21:03 -07:00
|
|
|
pkgIndex.Lock()
|
|
|
|
for _, pkg := range pkgIndex.m[pkgName] {
|
2015-12-10 23:32:07 -07:00
|
|
|
if !canUse(filename, pkg.dir) {
|
|
|
|
continue
|
|
|
|
}
|
2013-12-17 19:21:03 -07:00
|
|
|
wg.Add(1)
|
|
|
|
go func(importpath, dir string) {
|
|
|
|
defer wg.Done()
|
|
|
|
exports := loadExports(dir)
|
2015-12-10 23:32:07 -07:00
|
|
|
if exports == nil {
|
|
|
|
return
|
2013-12-17 19:21:03 -07:00
|
|
|
}
|
2015-12-10 23:32:07 -07:00
|
|
|
// If it doesn't have the right symbols, stop.
|
|
|
|
for symbol := range symbols {
|
|
|
|
if !exports[symbol] {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Devendorize for use in import statement.
|
|
|
|
if i := strings.LastIndex(importpath, "/vendor/"); i >= 0 {
|
|
|
|
importpath = importpath[i+len("/vendor/"):]
|
|
|
|
} else if strings.HasPrefix(importpath, "vendor/") {
|
|
|
|
importpath = importpath[len("vendor/"):]
|
|
|
|
}
|
|
|
|
|
|
|
|
// Save as the answer.
|
|
|
|
// If there are multiple candidates, the shortest wins,
|
|
|
|
// to prefer "bytes" over "github.com/foo/bytes".
|
|
|
|
mu.Lock()
|
|
|
|
if shortest == "" || len(importpath) < len(shortest) || len(importpath) == len(shortest) && importpath < shortest {
|
|
|
|
shortest = importpath
|
|
|
|
}
|
|
|
|
mu.Unlock()
|
2013-12-17 19:21:03 -07:00
|
|
|
}(pkg.importpath, pkg.dir)
|
|
|
|
}
|
|
|
|
pkgIndex.Unlock()
|
|
|
|
wg.Wait()
|
|
|
|
|
2015-12-10 23:32:07 -07:00
|
|
|
return shortest, false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func canUse(filename, dir string) bool {
|
|
|
|
dirSlash := filepath.ToSlash(dir)
|
|
|
|
if !strings.Contains(dirSlash, "/vendor/") && !strings.Contains(dirSlash, "/internal/") && !strings.HasSuffix(dirSlash, "/internal") {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
// Vendor or internal directory only visible from children of parent.
|
|
|
|
// That means the path from the current directory to the target directory
|
|
|
|
// can contain ../vendor or ../internal but not ../foo/vendor or ../foo/internal
|
|
|
|
// or bar/vendor or bar/internal.
|
|
|
|
// After stripping all the leading ../, the only okay place to see vendor or internal
|
|
|
|
// is at the very beginning of the path.
|
|
|
|
abs, err := filepath.Abs(filename)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
2013-12-17 19:21:03 -07:00
|
|
|
}
|
2015-12-10 23:32:07 -07:00
|
|
|
rel, err := filepath.Rel(abs, dir)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
2013-12-17 19:21:03 -07:00
|
|
|
}
|
2015-12-10 23:32:07 -07:00
|
|
|
relSlash := filepath.ToSlash(rel)
|
|
|
|
if i := strings.LastIndex(relSlash, "../"); i >= 0 {
|
|
|
|
relSlash = relSlash[i+len("../"):]
|
2013-12-17 19:21:03 -07:00
|
|
|
}
|
2015-12-10 23:32:07 -07:00
|
|
|
return !strings.Contains(relSlash, "/vendor/") && !strings.Contains(relSlash, "/internal/") && !strings.HasSuffix(relSlash, "/internal")
|
2013-12-17 19:21:03 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
type visitFn func(node ast.Node) ast.Visitor
|
|
|
|
|
|
|
|
func (fn visitFn) Visit(node ast.Node) ast.Visitor {
|
|
|
|
return fn(node)
|
|
|
|
}
|
2014-01-26 10:47:31 -07:00
|
|
|
|
2014-03-25 07:37:10 -06:00
|
|
|
func findImportStdlib(shortPkg string, symbols map[string]bool) (importPath string, rename, ok bool) {
|
2014-01-26 10:47:31 -07:00
|
|
|
for symbol := range symbols {
|
|
|
|
path := stdlib[shortPkg+"."+symbol]
|
|
|
|
if path == "" {
|
2014-03-25 07:37:10 -06:00
|
|
|
return "", false, false
|
2014-01-26 10:47:31 -07:00
|
|
|
}
|
|
|
|
if importPath != "" && importPath != path {
|
|
|
|
// Ambiguous. Symbols pointed to different things.
|
2014-03-25 07:37:10 -06:00
|
|
|
return "", false, false
|
2014-01-26 10:47:31 -07:00
|
|
|
}
|
|
|
|
importPath = path
|
|
|
|
}
|
2014-03-25 07:37:10 -06:00
|
|
|
return importPath, false, importPath != ""
|
2014-01-26 10:47:31 -07:00
|
|
|
}
|