Golang go/parser.ParseDir() function example

package go/parser

ParseDir calls ParseFile for all files with names ending in ".go" in the directory 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.

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.

Golang go/parser.ParseDir() function usage example

 var pkgRealpath, pkgpath string
 fileSet := token.NewFileSet()
 astPkgs, err := parser.ParseDir(fileSet, pkgRealpath, func(info os.FileInfo) bool {
 name := info.Name()
 return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
 }, parser.ParseComments)

References :

https://github.com/astaxie/beego/blob/master/parser.go

http://golang.org/pkg/go/parser/#ParseDir

Advertisement