Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

extend stringToString pflag binding to stringToInt pflag #1435

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 5 additions & 5 deletions viper.go
Expand Up @@ -1269,8 +1269,8 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
return cast.ToIntSlice(res)
case "stringToString":
return stringToStringConv(flag.ValueString())
case "stringToString", "stringToInt":
return stringToInterfaceCong(flag.ValueString())
default:
return flag.ValueString()
}
Expand Down Expand Up @@ -1348,8 +1348,8 @@ func (v *Viper) find(lcaseKey string, flagDefault bool) interface{} {
s = strings.TrimSuffix(s, "]")
res, _ := readAsCSV(s)
return cast.ToIntSlice(res)
case "stringToString":
return stringToStringConv(flag.ValueString())
case "stringToString", "stringToInt":
return stringToInterfaceCong(flag.ValueString())
default:
return flag.ValueString()
}
Expand All @@ -1371,7 +1371,7 @@ func readAsCSV(val string) ([]string, error) {

// mostly copied from pflag's implementation of this operation here https://github.com/spf13/pflag/blob/master/string_to_string.go#L79
// alterations are: errors are swallowed, map[string]interface{} is returned in order to enable cast.ToStringMap
func stringToStringConv(val string) interface{} {
func stringToInterfaceCong(val string) interface{} {
val = strings.Trim(val, "[]")
// An empty string would cause an empty map
if len(val) == 0 {
Expand Down
8 changes: 7 additions & 1 deletion viper_test.go
Expand Up @@ -1166,16 +1166,22 @@ func TestBindPFlagDetectNilFlag(t *testing.T) {
assert.Error(t, result)
}

func TestBindPFlagStringToString(t *testing.T) {
func TestBindPFlagCSVKeyValue(t *testing.T) {
tests := []struct {
Expected map[string]string
Value string
}{
// stringToString
{map[string]string{}, ""},
{map[string]string{"yo": "hi"}, "yo=hi"},
{map[string]string{"yo": "hi", "oh": "hi=there"}, "yo=hi,oh=hi=there"},
{map[string]string{"yo": ""}, "yo="},
{map[string]string{"yo": "", "oh": "hi=there"}, "yo=,oh=hi=there"},
//stringToInt
{map[string]string{"yo": "1", "oh": "21"}, "yo=1,oh=21"},
{map[string]string{"yo": "2", "oh": "21.0"}, "yo=2,oh=21.0"},
{map[string]string{"yo": "", "oh": "20.99"}, "yo=,oh=20.99"},
{map[string]string{"yo": "", "oh": ""}, "yo=,oh="},
}

v := New() // create independent Viper object
Expand Down