|
| 1 | +package linters |
| 2 | + |
| 3 | +import ( |
| 4 | + "go/ast" |
| 5 | + "go/token" |
| 6 | + "slices" |
| 7 | + "strconv" |
| 8 | + "strings" |
| 9 | + |
| 10 | + "github.com/golangci/plugin-module-register/register" |
| 11 | + "golang.org/x/tools/go/analysis" |
| 12 | +) |
| 13 | + |
| 14 | +func init() { |
| 15 | + register.Plugin("ocmlogger", New) |
| 16 | +} |
| 17 | + |
| 18 | +// OcmLoggerLinter checks that calls to the OCM logger (e.g. `logger.Info`, `logger.Warn`, etc.) use format strings correctly. |
| 19 | +// |
| 20 | +// Specifically, it verifies that the number of format specifiers (e.g. `%v`, `%s`, `%d`, ...) |
| 21 | +// in the log message matches the number of arguments passed after the format string. |
| 22 | +// |
| 23 | +// Example of a valid call: |
| 24 | +// |
| 25 | +// logger.Warn(ctx, "failed to create resource %s: %v", name, err) |
| 26 | +// |
| 27 | +// Example of an invalid call (missing one argument): |
| 28 | +// |
| 29 | +// logger.Warn(ctx, "failed to create resource %s: %v", name) |
| 30 | +// |
| 31 | +// The analyzer only runs on calls whose receiver is of type |
| 32 | +// `github.com/openshift-online/ocm-sdk-go/logging.Logger` (or a pointer to it). |
| 33 | +// |
| 34 | +// To disable the check for a specific line, add one of the following comments: |
| 35 | +// |
| 36 | +// //nolint:ocmlogger |
| 37 | +// // ocm-linter:ignore |
| 38 | +// |
| 39 | +// Example: |
| 40 | +// |
| 41 | +// logger.Info(ctx, "%s %d", name) //nolint:ocmlogger |
| 42 | +// |
| 43 | +// Comments can be placed on the same line (or the line immediately above) the call. |
| 44 | +// |
| 45 | +// var OcmLoggerLinter = &analysis.Analyzer{ |
| 46 | +// Name: "ocmlogger", |
| 47 | +// Doc: "checks that log calls have matching format strings and arguments", |
| 48 | +// Run: run, |
| 49 | +// } |
| 50 | +type OcmLoggerLinter struct{} |
| 51 | + |
| 52 | +func (f *OcmLoggerLinter) GetLoadMode() string { |
| 53 | + return register.LoadModeSyntax |
| 54 | +} |
| 55 | + |
| 56 | +func New(settings any) (register.LinterPlugin, error) { |
| 57 | + return &OcmLoggerLinter{}, nil |
| 58 | +} |
| 59 | + |
| 60 | +func (f *OcmLoggerLinter) BuildAnalyzers() ([]*analysis.Analyzer, error) { |
| 61 | + return []*analysis.Analyzer{ |
| 62 | + { |
| 63 | + Name: "ocmlogger", |
| 64 | + Doc: "find ocm logging usage errors", |
| 65 | + Run: f.run, |
| 66 | + }, |
| 67 | + }, nil |
| 68 | +} |
| 69 | + |
| 70 | +func (f *OcmLoggerLinter) isDisabled(pass *analysis.Pass, node ast.Node) bool { |
| 71 | + pos := pass.Fset.Position(node.Pos()) |
| 72 | + for _, f := range pass.Files { |
| 73 | + for _, cg := range f.Comments { |
| 74 | + for _, c := range cg.List { |
| 75 | + cpos := pass.Fset.Position(c.Pos()) |
| 76 | + if cpos.Filename != pos.Filename { |
| 77 | + continue |
| 78 | + } |
| 79 | + // same line or line above |
| 80 | + if cpos.Line == pos.Line || cpos.Line == pos.Line-1 { |
| 81 | + txt := c.Text // ex: "//nolint:ocmlogger" or "/* ... */" |
| 82 | + if strings.Contains(txt, "nolint:ocmlogger") || strings.Contains(txt, "ocm-linter:ignore") { |
| 83 | + return true |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + return false |
| 90 | +} |
| 91 | + |
| 92 | +func (f *OcmLoggerLinter) extractString(expr ast.Expr) (string, bool) { |
| 93 | + switch e := expr.(type) { |
| 94 | + case *ast.BasicLit: |
| 95 | + if e.Kind == token.STRING { |
| 96 | + s, err := strconv.Unquote(e.Value) |
| 97 | + if err != nil { |
| 98 | + return "", false |
| 99 | + } |
| 100 | + return s, true |
| 101 | + } |
| 102 | + case *ast.BinaryExpr: |
| 103 | + if e.Op == token.ADD { |
| 104 | + left, ok1 := f.extractString(e.X) |
| 105 | + right, ok2 := f.extractString(e.Y) |
| 106 | + if ok1 && ok2 { |
| 107 | + return left + right, true |
| 108 | + } |
| 109 | + } |
| 110 | + } |
| 111 | + return "", false |
| 112 | +} |
| 113 | + |
| 114 | +func (f *OcmLoggerLinter) countPlaceholders(fmtString string) int { |
| 115 | + count := 0 |
| 116 | + fmtStringLength := len(fmtString) |
| 117 | + for i := 0; i < fmtStringLength; i++ { |
| 118 | + if fmtString[i] != '%' { |
| 119 | + continue |
| 120 | + } |
| 121 | + // skip "%%" |
| 122 | + if i+1 < fmtStringLength && fmtString[i+1] == '%' { |
| 123 | + i++ // skip both |
| 124 | + continue |
| 125 | + } |
| 126 | + // placeholder found |
| 127 | + count++ |
| 128 | + } |
| 129 | + return count |
| 130 | +} |
| 131 | + |
| 132 | +func (f *OcmLoggerLinter) run(pass *analysis.Pass) (interface{}, error) { |
| 133 | + |
| 134 | + loggerMethods := []string{"Debug", "Info", "Warn", "Error", "Fatal"} |
| 135 | + |
| 136 | + for _, file := range pass.Files { |
| 137 | + ast.Inspect(file, func(n ast.Node) bool { |
| 138 | + call, ok := n.(*ast.CallExpr) |
| 139 | + if !ok { |
| 140 | + return true |
| 141 | + } |
| 142 | + |
| 143 | + sel, ok := call.Fun.(*ast.SelectorExpr) |
| 144 | + if !ok { |
| 145 | + return true |
| 146 | + } |
| 147 | + |
| 148 | + if !slices.Contains(loggerMethods, sel.Sel.Name) { |
| 149 | + return true |
| 150 | + } |
| 151 | + |
| 152 | + // Get the static type of the receiver |
| 153 | + recvType := pass.TypesInfo.TypeOf(sel.X) |
| 154 | + if recvType == nil { |
| 155 | + return true |
| 156 | + } |
| 157 | + |
| 158 | + // Check that the type is exactly github.com/openshift-online/ocm-sdk-go/logging.Logger or a pointer to that type |
| 159 | + typeString := recvType.String() |
| 160 | + if typeString != "github.com/openshift-online/ocm-sdk-go/logging.Logger" && |
| 161 | + typeString != "*github.com/openshift-online/ocm-sdk-go/logging.Logger" { |
| 162 | + return true |
| 163 | + } |
| 164 | + |
| 165 | + if len(call.Args) < 2 { |
| 166 | + // If the number of parameters is less than 2, it is a compilation error |
| 167 | + return true |
| 168 | + } |
| 169 | + |
| 170 | + // The second argument must be a string literal. If it is not, we cannot validate the number of |
| 171 | + // format arguments, so we ignore the line |
| 172 | + formatArg := call.Args[1] |
| 173 | + fmtString, ok := f.extractString(formatArg) |
| 174 | + if !ok { |
| 175 | + return true |
| 176 | + } |
| 177 | + |
| 178 | + // Count the placeholders |
| 179 | + countPlaceholders := f.countPlaceholders(fmtString) |
| 180 | + |
| 181 | + // Number of variadic arguments (after ctx and format) |
| 182 | + variadicCount := len(call.Args) - 2 |
| 183 | + |
| 184 | + if countPlaceholders != variadicCount && !f.isDisabled(pass, call) { |
| 185 | + pass.Reportf(call.Pos(), |
| 186 | + "number of format placeholders (%d) does not match number of arguments (%d)", |
| 187 | + countPlaceholders, variadicCount) |
| 188 | + } |
| 189 | + |
| 190 | + return true |
| 191 | + }) |
| 192 | + } |
| 193 | + return nil, nil |
| 194 | +} |
0 commit comments