Properly handle string slice values

This commit attempts to properly retrieve string slice values.  To
support that effort, I've copied over the readAsCSV() func from pflag,
which adds a dependency on encoding/csv.
This commit is contained in:
Cameron Moore 2016-09-26 21:16:45 -05:00
parent 651d9d916a
commit 94e8f72a4c
1 changed files with 17 additions and 2 deletions

View File

@ -21,6 +21,7 @@ package viper
import ( import (
"bytes" "bytes"
"encoding/csv"
"fmt" "fmt"
"io" "io"
"log" "log"
@ -879,8 +880,13 @@ func (v *Viper) find(lcaseKey string) interface{} {
case "bool": case "bool":
return cast.ToBool(flag.ValueString()) return cast.ToBool(flag.ValueString())
case "stringSlice": case "stringSlice":
s := strings.TrimPrefix(flag.ValueString(), "[") s := flag.ValueString()
return strings.TrimSuffix(s, "]") s = s[1 : len(s)-1] // trim []
if len(s) == 0 {
return []string{}
}
res, _ := readAsCSV(s)
return res
default: default:
return flag.ValueString() return flag.ValueString()
} }
@ -1503,6 +1509,15 @@ func (v *Viper) findConfigFile() (string, error) {
return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)} return "", ConfigFileNotFoundError{v.configName, fmt.Sprintf("%s", v.configPaths)}
} }
func readAsCSV(val string) ([]string, error) {
if val == "" {
return []string{}, nil
}
stringReader := strings.NewReader(val)
csvReader := csv.NewReader(stringReader)
return csvReader.Read()
}
// Debug prints all configuration registries for debugging // Debug prints all configuration registries for debugging
// purposes. // purposes.
func Debug() { v.Debug() } func Debug() { v.Debug() }