mirror of
https://github.com/spf13/viper
synced 2025-05-07 20:57:18 +00:00
extend stringToString pflag binding to stringToInt pflag
This commit is contained in:
parent
419fd86e49
commit
0573f404c9
2 changed files with 12 additions and 6 deletions
10
viper.go
10
viper.go
|
@ -1271,8 +1271,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 csvKeyValueConv(flag.ValueString())
|
||||
default:
|
||||
return flag.ValueString()
|
||||
}
|
||||
|
@ -1350,8 +1350,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 csvKeyValueConv(flag.ValueString())
|
||||
default:
|
||||
return flag.ValueString()
|
||||
}
|
||||
|
@ -1373,7 +1373,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 csvKeyValueConv(val string) interface{} {
|
||||
val = strings.Trim(val, "[]")
|
||||
// An empty string would cause an empty map
|
||||
if len(val) == 0 {
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Add table
Reference in a new issue