Skip to content

Instantly share code, notes, and snippets.

@colinnewell
Last active Feb 23, 2021
Embed
What would you like to do?
Dumping a list of types in a project
package main
import (
"fmt"
"log"
"os"
"strings"
"golang.org/x/tools/go/packages"
)
func main() {
pList, err := packages.Load(&packages.Config{
Mode: packages.NeedFiles |
packages.LoadImports |
packages.NeedTypes,
}, "./...")
if err != nil {
log.Fatal(err)
}
path, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
for _, p := range pList {
packageName := p.String()
fmt.Printf("## %s\n\n", packageName)
fmt.Printf("Go files: \n")
for _, f := range p.GoFiles {
// strip current working directory from filenames.
f := strings.Replace(f, path+"/", "", -1)
fmt.Printf("* %s\n", f)
}
scope := p.Types.Scope()
fmt.Println()
fmt.Println("Types:")
for _, name := range scope.Names() {
scopeInfo := scope.Lookup(name).String()
// don't appear to have much control over this data. best I appear
// to be able to do is grab it as a string right now so just
// filtering out funcs, vars etc. with a simple string comparson.
if strings.HasPrefix(scopeInfo, "type") {
scopeInfo = strings.Replace(scopeInfo, packageName+".", "", -1)
space := strings.Index(scopeInfo, " ")
space = space + 1 + strings.Index(scopeInfo[space+1:], " ")
fmt.Printf("* %s\n", scopeInfo[:space])
}
}
fmt.Println("")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment