pkg/parsers: use strings.Cut(), and cleanup error-messages

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2022-11-01 13:09:43 +01:00
parent 3f935d0e2c
commit 6a91e09218
No known key found for this signature in database
GPG key ID: 76698F39D527CE8C
2 changed files with 12 additions and 11 deletions

View file

@ -9,13 +9,14 @@ import (
"strings"
)
// ParseKeyValueOpt parses and validates the specified string as a key/value pair (key=value)
func ParseKeyValueOpt(opt string) (string, string, error) {
parts := strings.SplitN(opt, "=", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("Unable to parse key/value option: %s", opt)
// ParseKeyValueOpt parses and validates the specified string as a key/value
// pair (key=value).
func ParseKeyValueOpt(opt string) (key string, value string, err error) {
k, v, ok := strings.Cut(opt, "=")
if !ok {
return "", "", fmt.Errorf("unable to parse key/value option: %s", opt)
}
return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), nil
return strings.TrimSpace(k), strings.TrimSpace(v), nil
}
// ParseUintListMaximum parses and validates the specified string as the value
@ -75,12 +76,12 @@ func parseUintList(val string, maximum int) (map[int]bool, error) {
}
availableInts[v] = true
} else {
split := strings.SplitN(r, "-", 2)
min, err := strconv.Atoi(split[0])
minS, maxS, _ := strings.Cut(r, "-")
min, err := strconv.Atoi(minS)
if err != nil {
return nil, errInvalidFormat
}
max, err := strconv.Atoi(split[1])
max, err := strconv.Atoi(maxS)
if err != nil {
return nil, errInvalidFormat
}

View file

@ -7,8 +7,8 @@ import (
func TestParseKeyValueOpt(t *testing.T) {
invalids := map[string]string{
"": "Unable to parse key/value option: ",
"key": "Unable to parse key/value option: key",
"": "unable to parse key/value option: ",
"key": "unable to parse key/value option: key",
}
for invalid, expectedError := range invalids {
if _, _, err := ParseKeyValueOpt(invalid); err == nil || err.Error() != expectedError {