Skip to content

Instantly share code, notes, and snippets.

@Oppodelldog
Created September 20, 2020 22:01
Show Gist options
  • Save Oppodelldog/7c10839db3336f97fa406fe6318f0891 to your computer and use it in GitHub Desktop.
Save Oppodelldog/7c10839db3336f97fa406fe6318f0891 to your computer and use it in GitHub Desktop.
dump label usages in go src
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"io/ioutil"
"os"
"path"
"path/filepath"
)
const dumpCode = false
func main() {
panicOnError(filepath.Walk(path.Join(os.Getenv("GOROOT"), "src"),
func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if filepath.Ext(path) == ".go" {
dumpLabels(path)
}
return nil
},
))
}
func dumpLabels(file string) {
var (
data = mustReadFile(file)
fileSet = token.NewFileSet()
f = mustParse(fileSet, file, data)
)
ast.Inspect(f, func(n ast.Node) bool {
if n == nil {
return true
}
if label, ok := n.(*ast.LabeledStmt); ok {
fmt.Printf("%v+%v - %s\n",
file,
fileSet.Position(n.Pos()).Line,
label.Label.Name,
)
if dumpCode {
fmt.Println(string(data[n.Pos()-1 : n.End()-1]))
fmt.Println()
}
}
return true
})
}
func mustParse(fileSet *token.FileSet, file string, data []byte) *ast.File {
f, err := parser.ParseFile(fileSet, file, data, parser.ParseComments)
panicOnError(err)
return f
}
func mustReadFile(file string) []byte {
b, err := ioutil.ReadFile(file)
panicOnError(err)
return b
}
func panicOnError(err error) {
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment