go-critic: fix invalid type conversions. (#2186)

This commit is contained in:
Ludovic Fernandez 2021-08-20 09:30:05 +02:00 committed by GitHub
parent d3705d0e8b
commit ee30b44e4e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -5,6 +5,7 @@ import (
"go/ast" "go/ast"
"go/types" "go/types"
"path/filepath" "path/filepath"
"reflect"
"runtime" "runtime"
"sort" "sort"
"strings" "strings"
@ -87,7 +88,7 @@ func configureCheckerInfo(info *gocriticlinter.CheckerInfo, allParams map[string
for k, p := range params { for k, p := range params {
v, ok := infoParams[k] v, ok := infoParams[k]
if ok { if ok {
v.Value = p v.Value = normalizeCheckerParamsValue(p)
continue continue
} }
@ -110,6 +111,26 @@ func configureCheckerInfo(info *gocriticlinter.CheckerInfo, allParams map[string
return nil return nil
} }
// normalizeCheckerParamsValue normalizes value types.
// go-critic asserts that CheckerParam.Value has some specific types,
// but the file parsers (TOML, YAML, JSON) don't create the same representation for raw type.
// then we have to convert value types into the expected value types.
// Maybe in the future, this kind of conversion will be done in go-critic itself.
//nolint:exhaustive // only 3 types (int, bool, and string) are supported by CheckerParam.Value
func normalizeCheckerParamsValue(p interface{}) interface{} {
rv := reflect.ValueOf(p)
switch rv.Type().Kind() {
case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int:
return int(rv.Int())
case reflect.Bool:
return rv.Bool()
case reflect.String:
return rv.String()
default:
return p
}
}
func buildEnabledCheckers(lintCtx *linter.Context, linterCtx *gocriticlinter.Context) ([]*gocriticlinter.Checker, error) { func buildEnabledCheckers(lintCtx *linter.Context, linterCtx *gocriticlinter.Context) ([]*gocriticlinter.Checker, error) {
s := lintCtx.Settings().Gocritic s := lintCtx.Settings().Gocritic
allParams := s.GetLowercasedParams() allParams := s.GetLowercasedParams()