Skip to content

Commit

Permalink
add slice support to dynamic var
Browse files Browse the repository at this point in the history
  • Loading branch information
RamanaReddy0M committed Aug 11, 2023
1 parent a634ac4 commit 14d114e
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
14 changes: 12 additions & 2 deletions dynamic_var.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"reflect"
"strconv"
"strings"
)

type dynamicFlag struct {
Expand Down Expand Up @@ -54,6 +55,13 @@ func (df *dynamicFlag) Set(value string) error {
return nil
}
*stringField = value
case reflect.Slice:
sliceField := df.field.(*[]string)
if isBoolValue {
*sliceField = df.defaultValue.([]string)
return nil
}
*sliceField = append(*sliceField, strings.Split(value, ",")...)
default:
return errors.New("unsupported type")
}
Expand All @@ -70,8 +78,10 @@ func (df *dynamicFlag) String() string {

// DynamicVar acts as flag with a default value or a option with value
// example:
// var titleSize int
// flagSet.DynamicVar(&titleSize, "title", 50, "first N characters of the title")
//
// var titleSize int
// flagSet.DynamicVar(&titleSize, "title", 50, "first N characters of the title")
//
// > go run ./examples/basic -title or go run ./examples/basic -title=100
// In case of `go run ./examples/basic -title` it will use default value 50
func (flagSet *FlagSet) DynamicVar(field interface{}, long string, defaultValue interface{}, usage string) *FlagData {
Expand Down
3 changes: 3 additions & 0 deletions examples/basic/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type Options struct {
// Dynamic
titleSize int
target string
hashes []string
}

func main() {
Expand All @@ -46,6 +47,7 @@ func main() {
flagSet.CreateGroup("Dynmaic", "Dynamic",
flagSet.DynamicVarP(&testOptions.titleSize, "title", "t", 50, "first N characters of the title"),
flagSet.DynamicVarP(&testOptions.target, "target", "u", "https://example.com", "target url"),
flagSet.DynamicVarP(&testOptions.hashes, "hashes", "hs", []string{"md5", "sha1"}, "supported hashes"),
)
flagSet.SetCustomHelpText("EXAMPLE USAGE:\ngo run ./examples/basic [OPTIONS]")

Expand All @@ -56,6 +58,7 @@ func main() {
// TODO: remove this
fmt.Println("title size:", testOptions.titleSize)
fmt.Println("target:", testOptions.target)
fmt.Println("hashes:", testOptions.hashes)

// ratelimits value is
if len(testOptions.rls.AsMap()) > 0 {
Expand Down

0 comments on commit 14d114e

Please sign in to comment.