Skip to content

Instantly share code, notes, and snippets.

@tleyden
Created November 14, 2017 00:40
Show Gist options
  • Save tleyden/cdf99f12c48b73bdc0246c66c4e1eb63 to your computer and use it in GitHub Desktop.
Save tleyden/cdf99f12c48b73bdc0246c66c4e1eb63 to your computer and use it in GitHub Desktop.
Find all functions that take an "error" as a parameter using Go's AST parser
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
"strings"
)
func main() {
pkgRoot := "/Users/tleyden/Development/sync_gateway/godeps/src/github.com/couchbase/sync_gateway"
processPackage(fmt.Sprintf("%s/auth", pkgRoot))
processPackage(fmt.Sprintf("%s/base", pkgRoot))
processPackage(fmt.Sprintf("%s/channels", pkgRoot))
processPackage(fmt.Sprintf("%s/db", pkgRoot))
processPackage(fmt.Sprintf("%s/rest", pkgRoot))
}
func processPackage(path string) {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, path, nil, 0)
if err != nil {
panic(fmt.Sprintf("error parsing dir: %v", err))
}
for _, pkg := range pkgs {
log.Printf("Processing package: %v", pkg.Name)
for _, file := range pkg.Files {
ast.Walk(new(FuncVisitor), file)
}
}
}
type FuncVisitor struct{}
func (v *FuncVisitor) Visit(node ast.Node) (w ast.Visitor) {
switch t := node.(type) {
case *ast.FuncDecl:
t.Name = ast.NewIdent(strings.Title(t.Name.Name))
for _, param := range t.Type.Params.List {
argIdentifier, ok := param.Type.(*ast.Ident)
if !ok {
continue
}
if argIdentifier.Name == "error" {
log.Printf("Function/method that takes an error type as a parameter: %v", t.Name)
}
}
}
return v
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment