Golang go/build.Context.SrcDirs() function examples

package go/build

SrcDirs returns a list of package source root directories. It draws from the current Go root and Go path but omits directories that do not exist.

Golang go/build.Context.SrcDirs() function usage examples

Example 1:

 // Gets all local Go packages (from GOROOT and all GOPATH workspaces).
 func GetGoPackages(out chan<- *GoPackage) {
  for _, root := range build.Default.SrcDirs() {
  _ = filepath.Walk(root, func(path string, fi os.FileInfo, _ error) error {
 switch {
 case !fi.IsDir():
 return nil
 case path == root:
 return nil
 case strings.HasPrefix(fi.Name(), "."):
 return filepath.SkipDir
 default:
 importPath, err := filepath.Rel(root, path)
 if err != nil {
 return nil
 }
 if goPackage := GoPackageFromImportPath(importPath); goPackage != nil {
 out <- goPackage
 }
 return nil
 }
 })
  }
  close(out)
 }

Example 2:

 func init() {
 trimPaths = build.Default.SrcDirs()
 }

References :

https://github.com/shurcooL/go/blob/master/gists/gist8018045/main.go

http://golang.org/pkg/go/build/#Context.SrcDirs

Advertisement