diff --git a/cli/cli.go b/cli/cli.go index f4150d4..4d2f7eb 100644 --- a/cli/cli.go +++ b/cli/cli.go @@ -3,7 +3,6 @@ package cli import ( "encoding/json" "fmt" - "go/build" "os" "github.com/urfave/cli" @@ -45,22 +44,10 @@ func Run(version string) { return } - wd, err := os.Getwd() - if err != nil { - msg := fmt.Sprintf("failed to get working dir: %s", err) - err = cli.NewExitError(msg, 1) - return - } - importPkg, err := build.Import(opts.PkgPath, wd, build.ImportComment) - if err != nil { - msg := fmt.Sprintf("failed to import pkg %s: %s", opts.PkgPath, err) - err = cli.NewExitError(msg, 1) - return - } parser := tspec.NewParser() - pkg, err := parser.ParseDir(opts.PkgPath, importPkg.Name) + pkg, err := parser.Import(opts.PkgPath) if err != nil { - msg := fmt.Sprintf("failed to parse pkg %s: %s", opts.PkgPath, err) + msg := fmt.Sprintf("failed to import pkg %s: %s", pkg.Name, err) err = cli.NewExitError(msg, 1) return } diff --git a/tspec/tspec.go b/tspec/tspec.go index 37fd773..cf4572a 100644 --- a/tspec/tspec.go +++ b/tspec/tspec.go @@ -59,10 +59,8 @@ func (t *Parser) ParseDir(dirPath string, pkgName string) (pkg *ast.Package, err return } -// Import parses import spec and returns related package -func (t *Parser) Import(ispec *ast.ImportSpec) (pkg *ast.Package, err error) { - pkgPath := strings.Trim(ispec.Path.Value, "\"") - +// Import imports package dir and returns related package +func (t *Parser) Import(pkgPath string) (pkg *ast.Package, err error) { wd, err := os.Getwd() if err != nil { err = errors.WithStack(err) @@ -137,7 +135,8 @@ func (t *Parser) parseTypeStr(oPkg *ast.Package, typeStr string) (pkg *ast.Packa var p *ast.Package for _, file := range oPkg.Files { for _, ispec := range file.Imports { - p, err = t.Import(ispec) + pkgPath := strings.Trim(ispec.Path.Value, "\"") + p, err = t.Import(pkgPath) if err != nil { err = errors.WithStack(err) return diff --git a/tspec/tspec_test.go b/tspec/tspec_test.go index 58486bb..82d6a35 100644 --- a/tspec/tspec_test.go +++ b/tspec/tspec_test.go @@ -7,6 +7,7 @@ import ( "go/ast" "go/parser" "go/token" + "strings" "testing" "github.com/stretchr/testify/suite" @@ -73,7 +74,8 @@ import ( "github.com/wy-z/tspec/samples" ) `, parser.ImportsOnly) - pkg, err := tspec.NewParser().Import(f.Imports[0]) + pkgPath := strings.Trim(f.Imports[0].Path.Value, "\"") + pkg, err := tspec.NewParser().Import(pkgPath) if err != nil { msg := fmt.Sprintf("failed to import 'github.com/wy-z/tspec/samples': %s", err) panic(msg)