Fix couldn't load package bug, if multiple GOPATH exists and target code is not in first GOPATH

This commit is contained in:
damnever 2017-05-06 10:16:11 +08:00
parent 917c72fddb
commit 78f796a291
3 changed files with 58 additions and 8 deletions

View file

@ -23,7 +23,6 @@ import (
"go/token"
"go/types"
"log"
"path/filepath"
"strings"
"golang.org/x/tools/go/loader"
@ -39,20 +38,20 @@ type Package struct {
// ParsePackage parses the package in the given directory and returns it.
func ParsePackage(directory string) (*Package, error) {
relDir, err := filepath.Rel(filepath.Join(build.Default.GOPATH, "src"), directory)
p, err := build.ImportDir(directory, build.FindOnly)
if err != nil {
return nil, fmt.Errorf("provided directory not under GOPATH (%s): %v",
build.Default.GOPATH, err)
return nil, fmt.Errorf("provided directory (%s) may not under GOPATH (%s): %v",
directory, build.Default.GOPATH, err)
}
conf := loader.Config{TypeChecker: types.Config{FakeImportC: true}}
conf.Import(relDir)
conf.Import(p.ImportPath)
program, err := conf.Load()
if err != nil {
return nil, fmt.Errorf("couldn't load package: %v", err)
}
pkgInfo := program.Package(relDir)
pkgInfo := program.Package(p.ImportPath)
return &Package{
Name: pkgInfo.Pkg.Name(),
files: pkgInfo.Files,