|
| 1 | +package analyzer |
| 2 | + |
| 3 | +import ( |
| 4 | + "go/ast" |
| 5 | + "strings" |
| 6 | + |
| 7 | + "golang.org/x/tools/go/analysis/passes/inspect" |
| 8 | + "golang.org/x/tools/go/ast/inspector" |
| 9 | + |
| 10 | + "golang.org/x/tools/go/analysis" |
| 11 | +) |
| 12 | + |
| 13 | +var Analyzer = &analysis.Analyzer{ |
| 14 | + Name: "go_printf_func_name", |
| 15 | + Doc: "Checks that printf-like functions are named with `f` at the end.", |
| 16 | + Run: run, |
| 17 | + Requires: []*analysis.Analyzer{inspect.Analyzer}, |
| 18 | +} |
| 19 | + |
| 20 | +func run(pass *analysis.Pass) (interface{}, error) { |
| 21 | + inspector := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector) |
| 22 | + nodeFilter := []ast.Node{ |
| 23 | + (*ast.FuncDecl)(nil), |
| 24 | + } |
| 25 | + |
| 26 | + inspector.Preorder(nodeFilter, func(node ast.Node) { |
| 27 | + funcDecl := node.(*ast.FuncDecl) |
| 28 | + |
| 29 | + params := funcDecl.Type.Params.List |
| 30 | + if len(params) < 2 { // [0] must be format (string), [1] must be args (...interface{}) |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + formatParamType, ok := params[len(params)-2].Type.(*ast.Ident) |
| 35 | + if !ok { // first param type isn't identificator so it can't be of type "string" |
| 36 | + return |
| 37 | + } |
| 38 | + |
| 39 | + if formatParamType.Name != "string" { // first param (format) type is not string |
| 40 | + return |
| 41 | + } |
| 42 | + |
| 43 | + argsParamType, ok := params[len(params)-1].Type.(*ast.Ellipsis) |
| 44 | + if !ok { // args are not ellipsis (...args) |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + elementType, ok := argsParamType.Elt.(*ast.InterfaceType) |
| 49 | + if !ok { // args are not of interface type, but we need interface{} |
| 50 | + return |
| 51 | + } |
| 52 | + |
| 53 | + if elementType.Methods != nil && len(elementType.Methods.List) != 0 { |
| 54 | + return // has >= 1 method in interface, but we need an empty interface "interface{}" |
| 55 | + } |
| 56 | + |
| 57 | + if strings.HasSuffix(funcDecl.Name.Name, "f") { |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + pass.Reportf(node.Pos(), "printf-like formatting function '%s' should be named '%sf'\n", |
| 62 | + funcDecl.Name.Name, funcDecl.Name.Name) |
| 63 | + }) |
| 64 | + |
| 65 | + return nil, nil |
| 66 | +} |
0 commit comments