diff --git a/ruleguard.rules.go b/ruleguard.rules.go index 0887ca1..178d06c 100644 --- a/ruleguard.rules.go +++ b/ruleguard.rules.go @@ -322,6 +322,19 @@ func joinpath(m dsl.Matcher) { Report(`did you mean path.Join() or filepath.Join() ?`) } +func rewriteSplitN(m dsl.Matcher) { + m.Match( + `$x := strings.SplitN($y, $delim, 2)[0]`, + `$x := strings.SplitN($y, $delim, -1)[0]`, + `$x := strings.Split($y, $delim)[0]`, + ). + Suggest(`$x, _, _ := strings.Cut($y, $delim)`). + Report(`Use strings.Cut instead of strings.SplitN for cleaner string splitting`) + m.Match(`$x := strings.SplitN($y, $delim, 2)[1]`). + Suggest(`_, $x, _ := strings.Cut($y, $delim)`). + Report(`Use strings.Cut instead of strings.SplitN for cleaner string splitting`) +} + func readfull(m dsl.Matcher) { m.Match(`$n, $err := io.ReadFull($_, $slice) if $err != nil || $n != len($slice) { diff --git a/splitn.yml b/splitn.yml new file mode 100644 index 0000000..4eec599 --- /dev/null +++ b/splitn.yml @@ -0,0 +1,21 @@ +rules: + - id: rewrite-splitn-to-cut-first + patterns: + - pattern-either: + - pattern: $X := strings.SplitN($Y, $DELIM, 2)[0] + - pattern: $X := strings.SplitN($Y, $DELIM, -1)[0] + - pattern: $X := strings.Split($Y, $DELIM)[0] + message: Replace strings.SplitN with strings.Cut for cleaner string splitting + languages: [go] + severity: ERROR + fix: | + $X, _, _ := strings.Cut($Y, $DELIM) + + - id: rewrite-splitn-to-cut-second + pattern: | + $X := strings.SplitN($Y, $DELIM, 2)[1] + message: Replace strings.SplitN with strings.Cut for cleaner string splitting + languages: [go] + severity: ERROR + fix: | + _, $X, _ := strings.Cut($Y, $DELIM)