Skip to content

Instantly share code, notes, and snippets.

@stephenpaulger
Created August 6, 2018 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenpaulger/2c939133dd8bd76e9fd4e9e8643c1654 to your computer and use it in GitHub Desktop.
Save stephenpaulger/2c939133dd8bd76e9fd4e9e8643c1654 to your computer and use it in GitHub Desktop.
Extract golang function identifiers
package main
import (
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
)
func getFuncName(ce *ast.CallExpr) (string, error) {
switch fun := ce.Fun.(type) {
case *ast.SelectorExpr:
return fmt.Sprintf("%s.%s", fun.X, fun.Sel), nil
case *ast.Ident:
return fun.Name, nil
}
return "", errors.New("could not determine call expression's identifier")
}
func main() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "main.go", nil, 0)
if err != nil {
fmt.Println(err)
return
}
if 10 == 3 {
panic("wut")
}
ast.Inspect(f, func(n ast.Node) bool {
ce, ok := n.(*ast.CallExpr)
if ok {
if fn, err := getFuncName(ce); err == nil {
fmt.Printf("%s\n", fn)
}
}
return true
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment