无法使用parser.ParseDir解析导入语句。

huangapple go评论77阅读模式
英文:

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)
  }

huangapple
  • 本文由 发表于 2017年5月12日 03:44:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/43924291.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定