Skip to content

Commit

Permalink
Feat: Add flags list
Browse files Browse the repository at this point in the history
  • Loading branch information
HuYlllc committed Jul 26, 2024
1 parent 830a8bf commit 27a20ab
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
27 changes: 27 additions & 0 deletions flagmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ package grumble

import (
"fmt"
"strings"
"time"
)

Expand Down Expand Up @@ -161,3 +162,29 @@ func (f FlagMap) Duration(long string) time.Duration {
}
return v
}

// List returns the given flag value as a slice of strings.
// Panics if not present. Flags must be registered.
// List returns the given flag value as a slice of key-value pairs.
// Panics if not present. Flags must be registered.
func (f FlagMap) List(long string) map[string]string {
i := f[long]
if i == nil {
panic(fmt.Errorf("missing flag value: flag '%s' not registered", long))
}
val, ok := i.Value.([]string)
if !ok {
panic(fmt.Errorf("failed to assert flag '%s' to []string", long))
}

result := make(map[string]string)
for _, item := range val {
parts := strings.SplitN(item, "=", 2)
if len(parts) == 2 {
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
result[key] = value
}
}
return result
}
40 changes: 40 additions & 0 deletions flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -486,3 +486,43 @@ func trimQuotes(s string) string {
}
return s
}

func (f *Flags) ListL(long string, defaultValue []string, help string) {
f.List("", long, defaultValue, help)
}

func (f *Flags) List(short, long string, defaultValue []string, help string) {
f.register(short, long, help, "list", true, defaultValue,
func(res FlagMap) {
res[long] = &FlagMapItem{
Value: defaultValue,
IsDefault: true,
}
},
func(flag, equalVal string, args []string, res FlagMap) ([]string, bool, error) {
if !f.match(flag, short, long) {
return args, false, nil
}

if len(equalVal) > 0 {
values := strings.Split(equalVal, ",")
res[long] = &FlagMapItem{
Value: values,
IsDefault: false,
}
return args, true, nil
}

if len(args) == 0 {
return args, false, fmt.Errorf("missing list values for flag: %s", flag)
}

values := strings.Split(args[0], ",")
res[long] = &FlagMapItem{
Value: values,
IsDefault: false,
}
args = args[1:]
return args, true, nil
})
}

0 comments on commit 27a20ab

Please sign in to comment.