Skip to content

Commit 382fd11

Browse files
committed
feat: StringsOption.Parse(string) now returns a slice containing the original string. Added DelimitedStringsOption which allows passing delimited options on the CLI, such as --option=opt1,opt2 when the delimiter is a comma, instead of requiring the longer form --option=op1 --option=opt2
1 parent edc78ef commit 382fd11

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

cli/parse.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ func setOpts(kv kv, kvType reflect.Kind, opts cmds.OptMap) error {
100100

101101
if kvType == cmds.Strings {
102102
res, _ := opts[kv.Key].([]string)
103-
opts[kv.Key] = append(res, kv.Value.(string))
103+
opts[kv.Key] = append(res, kv.Value.([]string)...)
104104
} else if _, exists := opts[kv.Key]; !exists {
105105
opts[kv.Key] = kv.Value
106106
} else {

option.go

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,44 @@ func FloatOption(names ...string) Option {
184184
func StringOption(names ...string) Option {
185185
return NewOption(String, names...)
186186
}
187+
188+
// StringsOption is a command option that can handle a slice of strings
187189
func StringsOption(names ...string) Option {
188-
return NewOption(Strings, names...)
190+
return DelimitedStringsOption("", names...)
191+
}
192+
193+
// DelimitedStringsOption like StringsOption is a command option that can handle a slice of strings.
194+
// However, DelimitedStringsOption will automatically break up the associated CLI inputs based on the delimiter.
195+
// For example, instead of passing `command --option=val1 --option=val2` you can pass `command --option=val1,val2` or
196+
// even `command --option=val1,val2 --option=val3,val4`.
197+
//
198+
// A delimiter of "" means that no delimiter is used
199+
func DelimitedStringsOption(delimiter string, names ...string) Option {
200+
return &stringsOption{
201+
Option: NewOption(Strings, names...),
202+
delimiter: delimiter,
203+
}
204+
}
205+
206+
type stringsOption struct {
207+
Option
208+
delimiter string
209+
}
210+
211+
func (s *stringsOption) WithDefault(v interface{}) Option {
212+
if v == nil {
213+
return s.Option.WithDefault(v)
214+
}
215+
216+
defVal := v.([]string)
217+
s.Option = s.Option.WithDefault(defVal)
218+
return s
219+
}
220+
221+
func (s *stringsOption) Parse(v string) (interface{}, error) {
222+
if s.delimiter == "" {
223+
return []string{v}, nil
224+
}
225+
226+
return strings.Split(v, s.delimiter), nil
189227
}

0 commit comments

Comments
 (0)