Created
October 1, 2020 20:19
-
-
Save seamusv/3140165a18520be6bc194477116ca4f2 to your computer and use it in GitHub Desktop.
AST Walker
This file contains hidden or 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" | |
"go/ast" | |
"go/parser" | |
"go/token" | |
) | |
func main() { | |
fset := token.NewFileSet() | |
//Parse the file and create an AST | |
file, err := parser.ParseFile(fset, "user/manager.go", nil, parser.ParseComments) | |
if err != nil { | |
panic(err) | |
} | |
ast.Inspect(file, func(fileNode ast.Node) bool { | |
if funcDecl, ok := fileNode.(*ast.FuncDecl); ok { | |
var found = false | |
var hasLocalLog = false | |
functionName := funcDecl.Name.Name | |
var functionValue = "" | |
ast.Inspect(funcDecl.Body, func(bodyNode ast.Node) bool { | |
if localLog, ok := bodyNode.(*ast.AssignStmt); ok && isLocalLog(localLog) { | |
hasLocalLog = true | |
ast.Inspect(localLog, func(logNode ast.Node) bool { | |
if selectorExpr, ok := logNode.(*ast.SelectorExpr); ok && selectorExpr.Sel.Name == "Str" { | |
if callExpr, ok := selectorExpr.X.(*ast.CallExpr); ok && len(callExpr.Args) == 2 { | |
if var1, ok := callExpr.Args[0].(*ast.BasicLit); ok && var1.Value == "\"function\"" { | |
functionValue = callExpr.Args[1].(*ast.BasicLit).Value | |
found = true | |
} | |
} | |
} | |
return true | |
}) | |
} | |
return true | |
}) | |
if hasLocalLog { | |
if found && functionValue != fmt.Sprintf("\"%s\"", functionName) { | |
fmt.Printf("Incorrect function label for '%s'\n", functionName) | |
} else if !found { | |
fmt.Printf("Missing function label for '%s'\n", functionName) | |
} | |
} | |
} | |
return true | |
}) | |
} | |
func isLocalLog(n *ast.AssignStmt) bool { | |
for _, expr := range n.Lhs { | |
if value, ok := expr.(*ast.Ident); ok && value.Name == "localLog" { | |
return true | |
} | |
} | |
return false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment