Return empty args slice is the argument is an empty string

This commit is contained in:
Ryan Cavicchioni 2022-09-09 10:22:08 -05:00
parent 756aaf2379
commit 49000133d8
Signed by: ryanc
GPG Key ID: 877EEDAF9245103D
2 changed files with 12 additions and 3 deletions

View File

@ -118,6 +118,10 @@ func SplitCommandAndArg(s, prefix string) (cmd string, arg string) {
func SplitCommandAndArgs(s, prefix string, n int) (cmd string, args []string) {
cmd, arg := SplitCommandAndArg(s, prefix)
if arg == "" {
return cmd, []string{}
}
if n == 0 {
return cmd, strings.Split(arg, " ")
}
@ -126,6 +130,10 @@ func SplitCommandAndArgs(s, prefix string, n int) (cmd string, args []string) {
}
func SplitArgs(s string, n int) (args []string) {
if s == "" {
return []string{}
}
if n > 0 {
args = strings.SplitN(s, " ", n)
} else {

View File

@ -90,8 +90,8 @@ func TestSplitCommandAndArgs(t *testing.T) {
}{
{"!command x y", "!", 2, "command", []string{"x", "y"}},
{"!command x y z", "!", 2, "command", []string{"x", "y z"}},
{"!command", "!", 1, "command", []string{""}},
{"hey man", "!", 1, "", []string{""}},
{"!command", "!", 1, "command", []string{}},
{"hey man", "!", 1, "", []string{}},
}
for _, table := range tables {
gotCmd, gotArgs := SplitCommandAndArgs(table.s, table.prefix, table.n)
@ -99,7 +99,7 @@ func TestSplitCommandAndArgs(t *testing.T) {
t.Errorf("got: %s, want: %s", gotCmd, table.wantCmd)
}
if !reflect.DeepEqual(gotArgs, table.wantArgs) {
t.Errorf("got: %+v, want: %+v", gotArgs, table.wantArgs)
t.Errorf("got: %#v, want: %#v", gotArgs, table.wantArgs)
}
}
}
@ -115,6 +115,7 @@ func TestSplitArgs(t *testing.T) {
{"a b c", 2, []string{"a", "b c"}},
{"a b c", 3, []string{"a", "b", "c"}},
{"a b c", 4, []string{"a", "b", "c"}},
{"", 0, []string{}},
}
for _, table := range tables {
if got, want := SplitArgs(table.s, table.n), table.want; !reflect.DeepEqual(got, want) {