diff --git a/pkg/utils/args.go b/pkg/utils/args.go new file mode 100644 index 000000000..6d9cceb85 --- /dev/null +++ b/pkg/utils/args.go @@ -0,0 +1,17 @@ +package utils + +import ( + "github.com/mattn/go-shellwords" +) + +// SplitArgs splits a string into arguments, respecting quoted strings. +// This is a wrapper around shellwords.Parse for convenience. +func SplitArgs(s string) []string { + args, err := shellwords.Parse(s) + if err != nil { + // If parsing fails, return empty slice + // The caller can check for empty result + return []string{} + } + return args +} diff --git a/pkg/utils/args_test.go b/pkg/utils/args_test.go new file mode 100644 index 000000000..18192a884 --- /dev/null +++ b/pkg/utils/args_test.go @@ -0,0 +1,59 @@ +package utils + +import ( + "reflect" + "testing" +) + +func TestSplitArgs(t *testing.T) { + tests := []struct { + name string + input string + expected []string + }{ + { + name: "simple arguments", + input: "arg1 arg2 arg3", + expected: []string{"arg1", "arg2", "arg3"}, + }, + { + name: "quoted arguments", + input: `arg1 "arg with spaces" arg3`, + expected: []string{"arg1", "arg with spaces", "arg3"}, + }, + { + name: "single quoted arguments", + input: `arg1 'arg with spaces' arg3`, + expected: []string{"arg1", "arg with spaces", "arg3"}, + }, + { + name: "mixed quotes", + input: `arg1 "double quoted" 'single quoted' arg4`, + expected: []string{"arg1", "double quoted", "single quoted", "arg4"}, + }, + { + name: "empty string", + input: "", + expected: []string{}, + }, + { + name: "flags with values", + input: "--flag1 value1 --flag2 value2", + expected: []string{"--flag1", "value1", "--flag2", "value2"}, + }, + { + name: "flags with quoted values", + input: `--flag1 "value with spaces" --flag2 value2`, + expected: []string{"--flag1", "value with spaces", "--flag2", "value2"}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := SplitArgs(tt.input) + if !reflect.DeepEqual(result, tt.expected) { + t.Errorf("SplitArgs(%q) = %v, expected %v", tt.input, result, tt.expected) + } + }) + } +}