Skip to content

Commit

Permalink
fix: support method call from structures for string-format (#840)
Browse files Browse the repository at this point in the history
* fix: support method call from structures for string-format

* fix: added test for MR
  • Loading branch information
rmarku authored Jul 29, 2023
1 parent 6a2c5b1 commit a155d92
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
10 changes: 7 additions & 3 deletions rule/string-format.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,10 +211,14 @@ func (lintStringFormatRule) getCallName(call *ast.CallExpr) (callName string, ok
if selector, ok := call.Fun.(*ast.SelectorExpr); ok {
// Scoped function call
scope, ok := selector.X.(*ast.Ident)
if !ok {
return "", false
if ok {
return scope.Name + "." + selector.Sel.Name, true
}
// Scoped function call inside structure
recv, ok := selector.X.(*ast.SelectorExpr)
if ok {
return recv.Sel.Name + "." + selector.Sel.Name, true
}
return scope.Name + "." + selector.Sel.Name, true
}

return "", false
Expand Down
6 changes: 5 additions & 1 deletion test/string-format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ func TestStringFormat(t *testing.T) {
[]interface{}{
"s.Method3[2]",
"!/^[Tt][Hh]/",
"must not start with 'th'"}}})
"must not start with 'th'"},
[]interface{}{
"s.Method4", // same as before, but called from a struct
"!/^[Ot][Tt]/",
"must not start with 'ot'"}}})
}

func TestStringFormatArgumentParsing(t *testing.T) {
Expand Down
15 changes: 15 additions & 0 deletions testdata/string-format.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@ func (s stringFormatMethods) Method3(a, b, c string) {

}

type stringFormatMethodsInjected struct{}

func (s stringFormatMethodsInjected) Method4(a, b, c string) {

}

type container struct {
s stringFormatMethodsInjected
}

func stringFormat() {
stringFormatMethod1("This string is fine", "")
stringFormatMethod1("this string is not capitalized", "") // MATCH /must start with a capital letter/
Expand All @@ -27,4 +37,9 @@ func stringFormat() {
d: "This string is capitalized, but ends with a period."}) // MATCH /string literal doesn't match user defined regex /[^\.]$//
s := stringFormatMethods{}
s.Method3("", "", "This string starts with th") // MATCH /must not start with 'th'/

c := container{
s: stringFormatMethods{},
}
c.s.Method4("Other string starts with ot") // MATCH /must not start with 'ot'/
}

0 comments on commit a155d92

Please sign in to comment.