英文:
Can't get parser.ParseDir to parse Import statements
问题
我正在翻译你提供的内容,请稍等片刻。
英文:
I'm having trouble getting parser.ParseDir to return any information in the returned struct.Imports field. parser.ParseFile does seem to work however. I would much rather use ParseDir than have to go through and call ParseFile on each file. Here's what I've tried:
package crawlers
import (
"fmt"
"go/parser"
"go/token"
"os"
"path/filepath"
)
type GoImports struct {
//imports []*string
}
//returns fullpaths
func (g *GoImports) Crawl(entry string) ([]*string, error) {
fp, err := filepath.Abs(entry)
if err != nil {
return nil, err
}
info, err := os.Stat(fp)
if err != nil {
return nil, err
}
if !info.IsDir() {
return nil, fmt.Errorf("Entry point should be a path to a directory of a go package.")
}
fset := token.NewFileSet()
//foo, err := parser.ParseDir(fset, fp, nil, parser.ImportsOnly)
//foo, err := parser.ParseDir(fset, "/Users/dowen00/local/go/src/got/crawlers/testdata/barpackage", nil, parser.ImportsOnly)
foo, err := parser.ParseDir(fset, "/Users/dowen00/local/go/src/opscli", func(os.FileInfo) bool { return true }, parser.ImportsOnly)
//_, err = parser.ParseDir(fset, "/Users/dowen00/local/go/src/got/crawlers/testdata", nil, parser.ImportsOnly)
//foo, err := parser.ParseFile(fset, "/Users/dowen00/local/go/src/got/crawlers/testdata/barpackage/bar.go", nil, parser.ImportsOnly)
if err != nil {
return nil, err
}
//fmt.Printf("%c\n", foo)
//fmt.Printf("%c\n", fset)
for k, v := range foo {
//for kv, vv := range v.Imports {
//fmt.Printf("%s: %c\n", kv, vv)
//}
fmt.Printf("%s: %c\n", k, v.Imports)
}
return nil, nil
}
What am I doing wrong?
答案1
得分: 0
我已经解决了这个问题。如果事实上还没有实施,那么在https://golang.org/pkg/go/parser/#ParseDir的Go文档中可能需要进行修订,以避免浪费人们的时间。
以下是解决方法:
for _, v := range foo {
//for kv, vv := range v.Imports {
//fmt.Printf("%s: %c\n", kv, vv)
//}
for kk, vv := range v.Files {
for _, i := range vv.Imports {
fmt.Printf("%s: %s\n", kk, i.Path.Value)
}
}
//fmt.Printf("%s: %c\n", k, v.Files)
}
请注意,这是代码部分,不需要翻译。
英文:
I was able to work around the problem. If this, in fact, hasn't been implemented the go docs at https://golang.org/pkg/go/parser/#ParseDir should probably be revised to avoid wasting people's time.
Here's the work around:
for _, v := range foo {
//for kv, vv := range v.Imports {
//fmt.Printf("%s: %c\n", kv, vv)
//}
for kk, vv := range v.Files {
for _, i := range vv.Imports {
fmt.Printf("%s: %s\n", kk, i.Path.Value)
}
}
//fmt.Printf("%s: %c\n", k, v.Files)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论