Skip to content

Instantly share code, notes, and snippets.

@wata727
Created October 8, 2018 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wata727/345e0be0b8e345f1307bcf38362795a9 to your computer and use it in GitHub Desktop.
Save wata727/345e0be0b8e345f1307bcf38362795a9 to your computer and use it in GitHub Desktop.
go/types: type check is failed with custom importer (golang.org/x/tools/go/packages)
package main
import (
"go/ast"
"go/parser"
"go/token"
"go/types"
"io/ioutil"
"golang.org/x/tools/go/packages"
)
func main() {
src, err := ioutil.ReadFile("project/main.go")
if err != nil {
panic(err)
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "main.go", string(src), parser.Mode(0))
if err != nil {
panic(err)
}
conf := types.Config{Importer: &Importer{}}
if _, err = conf.Check("main", fset, []*ast.File{f}, nil); err != nil {
panic(err)
}
}
type Importer struct{}
func (p *Importer) Import(path string) (*types.Package, error) {
return p.ImportFrom(path, "", 0)
}
func (i *Importer) ImportFrom(path, dir string, mode types.ImportMode) (*types.Package, error) {
cfg := &packages.Config{
Mode: packages.LoadTypes,
Dir: dir,
}
pkgs, err := packages.Load(cfg, path)
if err != nil {
return nil, err
}
if len(pkgs) > 0 {
return pkgs[0].Types, nil
}
return nil, err
}
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
filepath.Walk(".", walker)
}
func walker(path string, info os.FileInfo, err error) error {
fmt.Print(path)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment