Skip to content

Commit

Permalink
checkers: add dynamicFmtString checker (#1156)
Browse files Browse the repository at this point in the history
  • Loading branch information
peakle committed Dec 26, 2021
1 parent 785d1f6 commit a4c828a
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 1 deletion.
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

0 comments on commit a4c828a

Please sign in to comment.