Skip to content

Commit 4b3fdfd

Browse files
adonovangopherbot
authored andcommitted
go/analysis/passes/printf: suppress diagnostic for Println("...%XX...")
A common form of literal string is a URL containing URL-escaped characters. This CL causes the printf checker not to report a "Println call has possible Printf formatting directive" diagnostic for it. + test Fixes golang/go#29854 Change-Id: Ib1dcc44dd8185da17f61296632ad030cb1e58420 Reviewed-on: https://go-review.googlesource.com/c/tools/+/650175 LUCI-TryBot-Result: Go LUCI <[email protected]> Auto-Submit: Alan Donovan <[email protected]> Commit-Queue: Alan Donovan <[email protected]> Reviewed-by: Jonathan Amsterdam <[email protected]>
1 parent fe883a8 commit 4b3fdfd

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

go/analysis/passes/printf/printf.go

+15-3
Original file line numberDiff line numberDiff line change
@@ -924,9 +924,14 @@ func checkPrint(pass *analysis.Pass, call *ast.CallExpr, name string) {
924924
// The % in "abc 0.0%" couldn't be a formatting directive.
925925
s = strings.TrimSuffix(s, "%")
926926
if strings.Contains(s, "%") {
927-
m := printFormatRE.FindStringSubmatch(s)
928-
if m != nil {
929-
pass.ReportRangef(call, "%s call has possible Printf formatting directive %s", name, m[0])
927+
for _, m := range printFormatRE.FindAllString(s, -1) {
928+
// Allow %XX where XX are hex digits,
929+
// as this is common in URLs.
930+
if len(m) >= 3 && isHex(m[1]) && isHex(m[2]) {
931+
continue
932+
}
933+
pass.ReportRangef(call, "%s call has possible Printf formatting directive %s", name, m)
934+
break // report only the first one
930935
}
931936
}
932937
}
@@ -992,3 +997,10 @@ func (ss stringSet) Set(flag string) error {
992997
//
993998
// Remove this after the 1.24 release.
994999
var suppressNonconstants bool
1000+
1001+
// isHex reports whether b is a hex digit.
1002+
func isHex(b byte) bool {
1003+
return '0' <= b && b <= '9' ||
1004+
'A' <= b && b <= 'F' ||
1005+
'a' <= b && b <= 'f'
1006+
}

go/analysis/passes/printf/testdata/src/a/a.go

+2
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,8 @@ func PrintfTests() {
154154
fmt.Println("%v", "hi") // want "fmt.Println call has possible Printf formatting directive %v"
155155
fmt.Println("%T", "hi") // want "fmt.Println call has possible Printf formatting directive %T"
156156
fmt.Println("%s"+" there", "hi") // want "fmt.Println call has possible Printf formatting directive %s"
157+
fmt.Println("http://foo.com?q%2Fabc") // no diagnostic: %XX is excepted
158+
fmt.Println("http://foo.com?q%2Fabc-%s") // want"fmt.Println call has possible Printf formatting directive %s"
157159
fmt.Println("0.0%") // correct (trailing % couldn't be a formatting directive)
158160
fmt.Printf("%s", "hi", 3) // want "fmt.Printf call needs 1 arg but has 2 args"
159161
_ = fmt.Sprintf("%"+("s"), "hi", 3) // want "fmt.Sprintf call needs 1 arg but has 2 args"

0 commit comments

Comments
 (0)