From 6a91e09218110bf2c1d42d797ef6772380bb45c7 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Tue, 1 Nov 2022 13:09:43 +0100 Subject: pkg/parsers: use strings.Cut(), and cleanup error-messages Signed-off-by: Sebastiaan van Stijn --- pkg/parsers/parsers.go | 19 ++++++++++--------- pkg/parsers/parsers_test.go | 4 ++-- 2 files changed, 12 insertions(+), 11 deletions(-) (limited to 'pkg') diff --git a/pkg/parsers/parsers.go b/pkg/parsers/parsers.go index e6d7b33ec0..e438b5a40a 100644 --- a/pkg/parsers/parsers.go +++ b/pkg/parsers/parsers.go @@ -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 } diff --git a/pkg/parsers/parsers_test.go b/pkg/parsers/parsers_test.go index 12e5969091..dca3a07b91 100644 --- a/pkg/parsers/parsers_test.go +++ b/pkg/parsers/parsers_test.go @@ -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 { -- cgit v1.2.1