pkger/parser/parser.go

72 lines
1.1 KiB
Go
Raw Normal View History

2019-08-01 19:03:12 +03:00
package parser
import (
2019-08-30 00:05:44 +03:00
"fmt"
2019-09-23 16:53:30 +03:00
"go/parser"
"go/token"
2019-08-01 19:03:12 +03:00
"os"
2019-10-30 18:31:39 +03:00
"path/filepath"
2019-08-01 19:03:12 +03:00
2019-08-30 05:30:00 +03:00
"github.com/markbates/pkger/here"
2019-08-01 19:03:12 +03:00
)
2019-10-18 19:01:48 +03:00
// var DefaultIgnoredFolders = []string{".", "_", "vendor", "node_modules", "_fixtures", "testdata"}
2019-08-01 19:03:12 +03:00
2019-10-21 17:27:04 +03:00
func Parse(her here.Info) (Decls, error) {
2019-10-09 20:21:54 +03:00
src, err := fromSource(her)
if err != nil {
return nil, err
}
2019-08-01 19:03:12 +03:00
2019-10-09 20:21:54 +03:00
return src, nil
2019-08-01 19:03:12 +03:00
}
2019-10-21 17:27:04 +03:00
func fromSource(her here.Info) (Decls, error) {
2019-09-23 16:53:30 +03:00
root := her.Dir
fi, err := os.Stat(root)
2019-08-01 21:37:01 +03:00
if err != nil {
2019-09-23 16:53:30 +03:00
return nil, err
2019-08-01 21:37:01 +03:00
}
if !fi.IsDir() {
2019-09-23 16:53:30 +03:00
return nil, fmt.Errorf("%q is not a directory", root)
2019-08-01 21:37:01 +03:00
}
2019-08-02 00:56:37 +03:00
2019-10-30 18:31:39 +03:00
var decls Decls
2019-08-01 19:03:12 +03:00
2019-10-30 18:31:39 +03:00
err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
2019-10-21 17:27:04 +03:00
2019-10-30 18:31:39 +03:00
fset := token.NewFileSet()
2019-10-21 17:27:04 +03:00
2019-10-30 18:31:39 +03:00
if !info.IsDir() {
return nil
}
pkgs, err := parser.ParseDir(fset, path, nil, 0)
if err != nil {
return err
}
2019-08-01 19:03:12 +03:00
2019-10-30 18:31:39 +03:00
for _, pkg := range pkgs {
for name, pf := range pkg.Files {
f := &file{
fset: fset,
astFile: pf,
filename: name,
current: her,
}
x, err := f.find()
if err != nil {
return err
}
decls = append(decls, x...)
2019-09-23 16:53:30 +03:00
}
2019-08-01 19:03:12 +03:00
}
2019-10-30 18:31:39 +03:00
return nil
})
2019-10-15 23:40:45 +03:00
2019-10-30 18:31:39 +03:00
return decls, err
2019-08-01 19:03:12 +03:00
}