1
0
mirror of https://github.com/mgechev/revive.git synced 2025-11-27 22:18:41 +02:00
Files
revive/rule/context_as_argument.go

97 lines
2.9 KiB
Go
Raw Normal View History

2018-01-25 11:34:38 -08:00
package rule
import (
"fmt"
2018-01-25 11:34:38 -08:00
"go/ast"
"strings"
2018-01-25 11:34:38 -08:00
"github.com/mgechev/revive/internal/astutils"
2018-01-25 11:34:38 -08:00
"github.com/mgechev/revive/lint"
)
2024-12-01 17:44:41 +02:00
// ContextAsArgumentRule suggests that `context.Context` should be the first argument of a function.
type ContextAsArgumentRule struct {
allowTypes map[string]struct{}
}
2018-01-25 11:34:38 -08:00
// Apply applies the rule to given file.
func (r *ContextAsArgumentRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure {
var failures []lint.Failure
for _, decl := range file.AST.Decls {
fn, ok := decl.(*ast.FuncDecl)
if !ok || len(fn.Type.Params.List) <= 1 {
continue // not a function or a function with less than 2 parameters
}
2018-01-25 11:34:38 -08:00
fnArgs := fn.Type.Params.List
// A context.Context should be the first parameter of a function.
// Flag any that show up after the first.
isCtxStillAllowed := true
for _, arg := range fnArgs {
argIsCtx := astutils.IsPkgDotName(arg.Type, "context", "Context")
if argIsCtx && !isCtxStillAllowed {
failures = append(failures, lint.Failure{
Node: arg,
Category: lint.FailureCategoryArgOrder,
Failure: "context.Context should be the first parameter of a function",
Confidence: 0.9,
})
break // only flag one
}
2018-01-25 11:34:38 -08:00
typeName := astutils.GoFmt(arg.Type)
// a parameter of type context.Context is still allowed if the current arg type is in the allow types LookUpTable
_, isCtxStillAllowed = r.allowTypes[typeName]
}
}
2018-01-25 11:34:38 -08:00
return failures
}
2018-01-25 11:34:38 -08:00
// Name returns the rule name.
2022-04-10 11:55:13 +02:00
func (*ContextAsArgumentRule) Name() string {
2018-05-26 21:28:31 -07:00
return "context-as-argument"
2018-01-25 11:34:38 -08:00
}
// Configure validates the rule configuration, and configures the rule accordingly.
//
// Configuration implements the [lint.ConfigurableRule] interface.
func (r *ContextAsArgumentRule) Configure(arguments lint.Arguments) error {
types, err := r.getAllowTypesFromArguments(arguments)
if err != nil {
return err
}
r.allowTypes = types
return nil
}
refactor: fix linting issues (#1188) * refactor: fix thelper issues test/utils_test.go:19:6 thelper test helper function should start from t.Helper() test/utils_test.go:42:6 thelper test helper function should start from t.Helper() test/utils_test.go:63:6 thelper test helper function should start from t.Helper() test/utils_test.go:146:6 thelper test helper function should start from t.Helper() * refactor: fix govet issues rule/error_strings.go:50:21 govet printf: non-constant format string in call to fmt.Errorf * refactor: fix gosimple issue rule/bare_return.go:52:9 gosimple S1016: should convert w (type lintBareReturnRule) to bareReturnFinder instead of using struct literal * refactor: fix errorlint issues lint/filefilter.go:70:86 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/filefilter.go:113:104 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/filefilter.go:125:89 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/linter.go:166:72 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors lint/linter.go:171:73 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors config/config.go:174:57 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors config/config.go:179:64 errorlint non-wrapping format verb for fmt.Errorf. Use `%w` to format errors * refactor: fix revive issue about comment spacing cli/main.go:31:2 revive comment-spacings: no space between comment delimiter and comment text * refactor: fix revive issue about unused-receiver revivelib/core_test.go:77:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ revivelib/core_test.go:81:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/context_as_argument.go:76:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/var_naming.go:73:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/modifies_value_receiver.go:59:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ rule/filename_format.go:43:7 revive unused-receiver: method receiver 'r' is not referenced in method's body, consider removing or renaming it as _ * refactor: fix revive issues about unused-parameter revivelib/core_test.go:81:24 revive unused-parameter: parameter 'file' seems to be unused, consider removing or renaming it as _ revivelib/core_test.go:81:41 revive unused-parameter: parameter 'arguments' seems to be unused, consider removing or renaming it as _ * refactor: fix gocritic issues about commentedOutCode test/utils_test.go:119:5 gocritic commentedOutCode: may want to remove commented-out code rule/unreachable_code.go:65:3 gocritic commentedOutCode: may want to remove commented-out code
2024-12-12 08:42:41 +01:00
func (*ContextAsArgumentRule) getAllowTypesFromArguments(args lint.Arguments) (map[string]struct{}, error) {
allowTypesBefore := []string{}
if len(args) >= 1 {
argKV, ok := args[0].(map[string]any)
if !ok {
return nil, fmt.Errorf("invalid argument to the context-as-argument rule. Expecting a k,v map, got %T", args[0])
}
for k, v := range argKV {
if !isRuleOption(k, "allowTypesBefore") {
return nil, fmt.Errorf("invalid argument to the context-as-argument rule. Unrecognized key %s", k)
}
typesBefore, ok := v.(string)
if !ok {
return nil, fmt.Errorf("invalid argument to the context-as-argument.allowTypesBefore rule. Expecting a string, got %T", v)
}
allowTypesBefore = append(allowTypesBefore, strings.Split(typesBefore, ",")...)
}
}
result := make(map[string]struct{}, len(allowTypesBefore))
for _, v := range allowTypesBefore {
result[v] = struct{}{}
}
result["context.Context"] = struct{}{} // context.Context is always allowed before another context.Context
return result, nil
2018-01-25 11:34:38 -08:00
}