Skip to content

Commit

Permalink
feat: StringsOption with delimiter
Browse files Browse the repository at this point in the history
  • Loading branch information
aschmahmann committed Jan 15, 2021
1 parent edc78ef commit 9aabff1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
2 changes: 1 addition & 1 deletion cli/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func setOpts(kv kv, kvType reflect.Kind, opts cmds.OptMap) error {

if kvType == cmds.Strings {
res, _ := opts[kv.Key].([]string)
opts[kv.Key] = append(res, kv.Value.(string))
opts[kv.Key] = append(res, kv.Value.([]string)...)
} else if _, exists := opts[kv.Key]; !exists {
opts[kv.Key] = kv.Value
} else {
Expand Down
34 changes: 33 additions & 1 deletion option.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,38 @@ func FloatOption(names ...string) Option {
func StringOption(names ...string) Option {
return NewOption(String, names...)
}

// StringsOption is a command option that takes which returns a slice of strings. When parsing
func StringsOption(names ...string) Option {
return NewOption(Strings, names...)
return DelimitedStringsOption("", names...)
}

func DelimitedStringsOption(delimiter string, names ...string) Option {
return &stringsOption{
Option: NewOption(Strings, names...),
delimiter: delimiter,
}
}

type stringsOption struct {
Option
delimiter string
}

func (s *stringsOption) WithDefault(v interface{}) Option {
if v == nil {
return s.WithDefault(v)
}

defVal := v.([]string)
s.Option = s.Option.WithDefault(defVal)
return s
}

func (s *stringsOption) Parse(v string) (interface{}, error) {
if s.delimiter == "" {
return []string{v}, nil
}

return strings.Split(v, s.delimiter), nil
}

0 comments on commit 9aabff1

Please sign in to comment.