Skip to content

Commit d608688

Browse files
committed
refactor: replace hand-rolled parsers with regexes in magic strings test
isFormatString: 30-line character-by-character parser replaced with a single regex: %[-+#0 ]*\d*\.?\d*[sdvqwfegxXobctpT] isRegexRef: 4-way strings.Contains replaced with \$\d|\$\{ Signed-off-by: Jose Alekhinne <jose@ctx.ist>
1 parent e15c30c commit d608688

File tree

1 file changed

+13
-41
lines changed

1 file changed

+13
-41
lines changed

internal/audit/magic_strings_test.go

Lines changed: 13 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ package audit
99
import (
1010
"go/ast"
1111
"go/token"
12+
"regexp"
1213
"strconv"
1314
"strings"
1415
"testing"
@@ -164,51 +165,22 @@ func isExemptStringPackage(pkgPath string) bool {
164165
return false
165166
}
166167

167-
// isFormatString reports whether s looks like a printf
168-
// format string (contains % followed by a verb char).
168+
// fmtVerb matches a printf format directive.
169+
var fmtVerb = regexp.MustCompile(
170+
`%[-+#0 ]*\d*\.?\d*[sdvqwfegxXobctpT]`,
171+
)
172+
173+
// isFormatString reports whether s contains a printf
174+
// format directive.
169175
func isFormatString(s string) bool {
170-
if !strings.Contains(s, "%") {
171-
return false
172-
}
173-
// Any string containing a % verb is likely a format
174-
// string. Accept any string with at least one
175-
// standard format directive.
176-
for i := 0; i < len(s)-1; i++ {
177-
if s[i] != '%' {
178-
continue
179-
}
180-
next := s[i+1]
181-
if next == '%' {
182-
i++ // skip %%
183-
continue
184-
}
185-
// Skip flags/width/precision chars.
186-
j := i + 1
187-
for j < len(s) &&
188-
(s[j] == '+' || s[j] == '-' ||
189-
s[j] == '#' || s[j] == '0' ||
190-
s[j] == ' ' ||
191-
(s[j] >= '1' && s[j] <= '9') ||
192-
s[j] == '.') {
193-
j++
194-
}
195-
if j < len(s) {
196-
verb := s[j]
197-
if strings.ContainsRune(
198-
"sdvqwfegxXobctpT", rune(verb),
199-
) {
200-
return true
201-
}
202-
}
203-
}
204-
return false
176+
return fmtVerb.MatchString(s)
205177
}
206178

179+
// regexRef matches regex capture group references.
180+
var regexRef = regexp.MustCompile(`\$\d|\$\{`)
181+
207182
// isRegexRef reports whether s contains regex capture
208183
// group references ($1, $2, etc.).
209184
func isRegexRef(s string) bool {
210-
return strings.Contains(s, "$1") ||
211-
strings.Contains(s, "$2") ||
212-
strings.Contains(s, "$3") ||
213-
strings.Contains(s, "${")
185+
return regexRef.MatchString(s)
214186
}

0 commit comments

Comments
 (0)