forked from lukehoban/ident
-
Notifications
You must be signed in to change notification settings - Fork 0
/
findReferences.go
110 lines (94 loc) · 1.88 KB
/
findReferences.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package ident
import (
"os"
"path"
"strings"
"github.com/rogpeppe/godef/go/ast"
"github.com/rogpeppe/godef/go/parser"
)
func (def Definition) findReferences(searchpath string, recursive bool) (chan Reference, chan error) {
refs := make(chan Reference)
errs := make(chan error, 1000)
// returns true on error and reports it
failed := func(err error) bool {
if err != nil {
select {
case errs <- err:
default:
}
return true
}
return false
}
scanAST := func(f ast.Node) {
check := func(expr ast.Expr) {
pos := getDefPosition(expr)
if pos != nil && *pos == def.Position {
refs <- Reference{fileset.Position(expr.Pos())}
}
}
ast.Inspect(f, func(node ast.Node) bool {
switch e := node.(type) {
case *ast.SelectorExpr:
if e.Sel.Name == def.Name {
check(e)
}
case *ast.Ident:
if e.Name == def.Name {
check(e)
}
}
return true
})
}
scanFile := func(filepath string) {
f, err := parser.ParseFile(fileset, filepath, nil, 0, getScope(filepath))
if failed(err) {
return
}
scanAST(f)
}
var scanFolder func(dirpath string)
scanFolder = func(dirpath string) {
filter := func(fi os.FileInfo) bool {
return path.Ext(fi.Name()) == ".go"
}
result, err := parser.ParseDir(fileset, dirpath, filter, 0)
if failed(err) {
return
}
for _, pkg := range result {
scanAST(pkg)
}
if !recursive {
return
}
dir, err := os.Open(dirpath)
if failed(err) {
return
}
infos, err := dir.Readdir(0)
if failed(err) {
return
}
for _, fi := range infos {
if fi.IsDir() && !strings.HasPrefix(fi.Name(), ".") {
scanFolder(path.Join(dirpath, fi.Name()))
}
}
}
go func() {
defer close(refs)
defer close(errs)
fi, err := os.Lstat(searchpath)
if err != nil {
return
}
if fi.IsDir() {
scanFolder(searchpath)
} else {
scanFile(searchpath)
}
}()
return refs, errs
}