下面的程序列表uses
和definitions
给定的查询type
和给定的 go 包。
使用程序加载器包以编程方式加载 go 程序简单明了
package main
import (
"flag"
"fmt"
"strings"
"golang.org/x/tools/go/loader"
)
func main() {
var query string
var uses bool
var defs bool
flag.StringVar(&query, "query", "", "the fully qualified type path")
flag.BoolVar(&uses, "uses", true, "capture uses")
flag.BoolVar(&defs, "definitions", true, "capture definitions")
flag.Parse()
if query == "" {
panic("query must not be empty")
}
var queryPkg string
queryType := query
if i := strings.LastIndex(query, "."); i > -1 {
queryPkg = query[:i]
queryType = query[i+1:]
}
var conf loader.Config
_, err := conf.FromArgs(flag.Args(), false)
if err != nil {
panic(err)
}
prog, err := conf.Load()
if err != nil {
panic(err)
}
for pkgType, pkgInfo := range prog.AllPackages {
if queryPkg != "" {
if !strings.HasPrefix(pkgType.Path(), queryPkg) {
continue
}
}
if defs {
for typeInfo, ident := range pkgInfo.Defs {
if !strings.HasPrefix(typeInfo.Name, queryType) {
continue
}
f := prog.Fset.File(ident.Pos())
fpos := f.Position(ident.Pos())
fmt.Printf("def: %v %v.%v\n", fpos, pkgType.Path(), typeInfo.Name)
}
}
if uses {
for ident, oInfo := range pkgInfo.Uses {
if !strings.Contains(oInfo.Type().String(), queryType) {
continue
}
f := prog.Fset.File(ident.Pos())
fpos := f.Position(ident.Pos())
fmt.Printf("use: %v %v\n", fpos, oInfo.Type().String())
}
}
// -
}
}
然后你像这样运行它
$ go run main.go -query="io.Reader" io
def: /home/mh-cbon/.gvm/gos/go1.12.7/src/io/io.go:170:6 io.ReaderFrom
def: /home/mh-cbon/.gvm/gos/go1.12.7/src/io/io.go:77:6 io.Reader
def: /home/mh-cbon/.gvm/gos/go1.12.7/src/io/io.go:211:6 io.ReaderAt
use: /home/mh-cbon/.gvm/gos/go1.12.7/src/io/multi.go:20:13 []io.Reader
use: /home/mh-cbon/.gvm/gos/go1.12.7/src/io/multi.go:21:16 *io.multiReader
# a ton of output...
[mh-cbon@Host-001 ploader] $ go run main.go -query="Config" io
[mh-cbon@Host-001 ploader] $ go run main.go -query="io.Reader" -uses=false io
def: /home/mh-cbon/.gvm/gos/go1.12.7/src/io/io.go:170:6 io.ReaderFrom
def: /home/mh-cbon/.gvm/gos/go1.12.7/src/io/io.go:211:6 io.ReaderAt
def: /home/mh-cbon/.gvm/gos/go1.12.7/src/io/io.go:77:6 io.Reader
您可能需要改进匹配器引擎以使其更适合。