Support go modules by using go/packages instead of go/loader

This commit is contained in:
Ivan Safonov 2019-01-23 00:52:12 +07:00
parent 39f6db0ed3
commit 1174b6968d

View File

@ -10,14 +10,13 @@ import (
"go/token" "go/token"
"go/types" "go/types"
"io" "io"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
"strings" "strings"
"text/template" "text/template"
"golang.org/x/tools/go/loader" "golang.org/x/tools/go/packages"
) )
// This list comes from the golint codebase. Golint will complain about any of // This list comes from the golint codebase. Golint will complain about any of
@ -137,7 +136,7 @@ func (m *Mocker) Mock(w io.Writer, name ...string) error {
mocksMethods := false mocksMethods := false
tpkg := pkgInfo.Pkg tpkg := pkgInfo.Types
for _, n := range name { for _, n := range name {
iface := tpkg.Scope().Lookup(n) iface := tpkg.Scope().Lookup(n)
if iface == nil { if iface == nil {
@ -228,41 +227,30 @@ func (m *Mocker) extractArgs(sig *types.Signature, list *types.Tuple, nameFormat
return params return params
} }
func pkgInfoFromPath(src string) (*loader.PackageInfo, error) { func pkgInfoFromPath(src string) (*packages.Package, error) {
abs, err := filepath.Abs(src) abs, err := filepath.Abs(src)
if err != nil { if err != nil {
return nil, err return nil, err
} }
pkgFull := stripGopath(abs) pkgFull := stripGopath(abs)
conf := loader.Config{ conf := packages.Config{
ParserMode: parser.SpuriousErrors, Mode: packages.LoadSyntax,
Cwd: src, Dir: src,
} }
if strings.HasPrefix(pkgFull, string(filepath.Separator)) {
files, err := ioutil.ReadDir(pkgFull) foundPackages, err := packages.Load(&conf, pkgFull)
if err != nil {
return nil, err
}
for _, file := range files {
if !file.IsDir() && strings.HasSuffix(file.Name(), ".go") && !strings.HasSuffix(file.Name(), "_test.go") {
conf.CreateFromFilenames(abs, file.Name())
}
}
} else {
conf.Import(pkgFull)
}
lprog, err := conf.Load()
if err != nil { if err != nil {
return nil, err return nil, err
} }
pkgInfo := lprog.Package(pkgFull) if len(foundPackages) == 0 {
if pkgInfo == nil { return nil, errors.New("No packages found")
return nil, errors.New("package was nil")
} }
if len(foundPackages) > 1 {
return pkgInfo, nil return nil, errors.New("More than one package was found")
}
return foundPackages[0], nil
} }
type doc struct { type doc struct {