Skip to content

Commit

Permalink
ruleguard: unquote the pattern string properly (#73)
Browse files Browse the repository at this point in the history
Instead of just dropping the both quotes, do the
actual unquoting that may involve some string interpretation
in case of the "-literals.

strconv.Unquote() is the right way to do it.

Refs #72

Signed-off-by: Iskander Sharipov <quasilyte@gmail.com>
  • Loading branch information
quasilyte authored Aug 22, 2020
1 parent 1f9d835 commit f731d79
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 5 deletions.
10 changes: 10 additions & 0 deletions analyzer/testdata/src/regression/issue72.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package regression

import "fmt"

func testIssue72() {
_ = fmt.Sprintf("%s<%s>", "name", "email@domain.example") // want `\Quse net/mail Address.String() instead of fmt.Sprintf()`
_ = fmt.Sprintf("\"%s\" <%s>", "name", "email@domain.example") // want `\Quse net/mail Address.String() instead of fmt.Sprintf()`
_ = fmt.Sprintf(`"%s" <%s>`, "name", "email@domain.example") // want `\Quse net/mail Address.String() instead of fmt.Sprintf()`
_ = fmt.Sprintf(`"%s"<%s>`, "name", "email@domain.example") // want `\Quse net/mail Address.String() instead of fmt.Sprintf()`
}
9 changes: 9 additions & 0 deletions analyzer/testdata/src/regression/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,12 @@ func issue68(m fluent.Matcher) {
m.Match(`func $_($_ *testing.T) { $p; $*_ }`).Where(m["p"].Text != "t.Parallel()").Report(`Not a parallel test`)
m.Match(`func $_($_ *testing.T) { $p; $*_ }`).Where(m["p"].Text == "t.Parallel()").Report(`Parallel test`)
}

func issue72(m fluent.Matcher) {
m.Match("fmt.Sprintf(`\"%s\" <%s>`, $name, $email)",
"fmt.Sprintf(`\"%s\"<%s>`, $name, $email)",
`fmt.Sprintf("\"%s\" <%s>", $name, $email)`,
`fmt.Sprintf("\"%s\"<%s>", $name, $email)`,
`fmt.Sprintf("%s<%s>", $name, $email)`).
Report("use net/mail Address.String() instead of fmt.Sprintf()")
}
6 changes: 5 additions & 1 deletion ruleguard/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,11 @@ func (p *rulesParser) toStringValue(x ast.Node) (string, bool) {
if x.Kind != token.STRING {
return "", false
}
return unquoteNode(x), true
s, err := strconv.Unquote(x.Value)
if err != nil {
return "", false
}
return s, true
case ast.Expr:
typ, ok := p.types.Types[x]
if !ok || typ.Type.String() != "string" {
Expand Down
4 changes: 0 additions & 4 deletions ruleguard/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,6 @@ import (
"strings"
)

func unquoteNode(lit *ast.BasicLit) string {
return lit.Value[1 : len(lit.Value)-1]
}

func sprintNode(fset *token.FileSet, n ast.Node) string {
if fset == nil {
fset = token.NewFileSet()
Expand Down

0 comments on commit f731d79

Please sign in to comment.