-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathparse.go
87 lines (79 loc) · 2.17 KB
/
parse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package astrav
import (
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"net/http"
"os"
"path"
"strings"
"github.com/pkg/errors"
)
// Parse calls ParseFile for all files with names ending in ".go" in the
// http.FileSystem specified by path and returns a map of package name -> package
// AST with all the packages found.
//
// If filter != nil, only the files with os.FileInfo entries passing through
// the filter (and ending in ".go") are considered. The mode bits are passed
// to ParseFile unchanged. Position information is recorded in fset, which
// must not be nil.
//
// If the directory couldn't be read, a nil map and the respective error are
// returned. If a parse error occurred, a non-nil but incomplete map and the
// first error encountered are returned.
//
func Parse(fset *token.FileSet, root http.FileSystem, dir string, filter func(os.FileInfo) bool,
mode parser.Mode) (pkgs map[string]*ast.Package, fileSources map[string][]byte, first error) {
fd, err := root.Open(dir)
if err != nil {
return nil, nil, errors.WithStack(err)
}
defer fd.Close()
list, err := fd.Readdir(-1)
if err != nil {
return nil, nil, errors.WithStack(err)
}
pkgs = make(map[string]*ast.Package)
fileSources = make(map[string][]byte)
for _, d := range list {
filename := d.Name()
if !strings.HasSuffix(filename, ".go") || filter != nil && !filter(d) {
continue
}
fileBytes, err := getSource(path.Join(dir, filename), root)
if err != nil {
if first == nil {
first = err
}
continue
}
fileSources[path.Join(dir, filename)] = fileBytes
src, err := parser.ParseFile(fset, path.Join(dir, filename), fileBytes, mode)
if err != nil {
if first == nil {
first = errors.WithStack(err)
}
continue
}
name := src.Name.Name
pkg, found := pkgs[name]
if !found {
pkg = &ast.Package{
Name: name,
Files: make(map[string]*ast.File),
}
pkgs[name] = pkg
}
pkg.Files[filename] = src
}
return pkgs, fileSources, first
}
func getSource(path string, dir http.FileSystem) ([]byte, error) {
f, err := dir.Open(path)
if err != nil {
return nil, errors.WithStack(err)
}
bytes, err := ioutil.ReadAll(f)
return bytes, errors.WithStack(err)
}