Last active
February 23, 2021 16:17
-
-
Save colinnewell/17e1dc326e8006de6ba130a7d7f5b758 to your computer and use it in GitHub Desktop.
Dumping a list of types in a project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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