Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add undefinedFormatting checker #1156

Merged
merged 3 commits into from Dec 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 15 additions & 0 deletions checkers/rules/rules.go
Expand Up @@ -717,3 +717,18 @@ func emptyDecl(m dsl.Matcher) {
m.Match(`const()`).Report(`empty const() block`)
m.Match(`type()`).Report(`empty type() block`)
}

//doc:summary Detects bad usage of fmt.Errorf
//doc:tags diagnostic experimental opinionated
//doc:before fmt.Errorf(xs)
//doc:after fmt.Errorf("%s", xs)
func undefinedFormatting(m dsl.Matcher) {
m.Match(`fmt.Errorf($f)`).
Where(!m["f"].Const).
Suggest("errors.New($f)").
Report(`use errors.New($f) or fmt.Errorf("%s", $f) instead`)

m.Match(`fmt.Errorf($f($*args))`).
Suggest("errors.New($f($*args))").
Report(`use errors.New($f($*args)) or fmt.Errorf("%s",$f($*args)) instead`)
}
43 changes: 43 additions & 0 deletions checkers/rulesdata/rulesdata.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions checkers/testdata/undefinedFormatting/negative_tests.go
@@ -0,0 +1,15 @@
package checker_test

import (
"fmt"
)

var foo = "bar"

func fmtFormatting() {
fmt.Errorf("%s", foo)
fmt.Errorf("123")
fmt.Errorf("%s", fooError())
}

func fooError() string { return "foo" }
19 changes: 19 additions & 0 deletions checkers/testdata/undefinedFormatting/positive_tests.go
@@ -0,0 +1,19 @@
package checker_test

import (
"fmt"
)

func fmtUndefinedFormatting() {
foo := "foo happend"
fooFunc := func(k string) (string, string) { return "", "123" }
var barFunc = func() string { return "123" }
/*! use errors.New(foo) or fmt.Errorf("%s", foo) instead */
fmt.Errorf(foo)

/*! use errors.New(fooFunc("123")) or fmt.Errorf("%s", fooFunc("123")) instead */
fmt.Errorf(fooFunc("123"))

/*! use errors.New(barFunc()) or fmt.Errorf("%s", barFunc()) instead */
fmt.Errorf(barFunc())
}
2 changes: 1 addition & 1 deletion framework/lintmain/internal/hotload/hotload.go
Expand Up @@ -7,7 +7,7 @@ import (
"github.com/go-critic/go-critic/framework/linter"
)

// CheckersFromDylib loads checkers provided by a dynamic lybrary found under path.
// CheckersFromDylib loads checkers provided by a dynamic library found under path.
//
// The returned info slice must be re-assigned to the original info slice,
// since there will be new entries there.
Expand Down