Created
August 6, 2018 08:49
-
-
Save stephenpaulger/2c939133dd8bd76e9fd4e9e8643c1654 to your computer and use it in GitHub Desktop.
Extract golang function identifiers
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 ( | |
"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