Skip to content

Commit

Permalink
fix: load StringArray from config file
Browse files Browse the repository at this point in the history
  • Loading branch information
Baruch Odem committed Sep 10, 2023
1 parent 09a8355 commit a1b5e2c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
9 changes: 3 additions & 6 deletions lib/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,10 @@ func bindEnvVarIntoViper(v *viper.Viper, fullFlagName, envPrefix string) {
func applyViperFlagToCommand(flag *pflag.Flag, val interface{}, cmd *cobra.Command) {
switch t := val.(type) {
case []interface{}:
var paramSlice []string
for _, param := range t {
paramSlice = append(paramSlice, param.(string))
}
valStr := strings.Join(paramSlice, ",")
if err := flag.Value.Set(valStr); err != nil {
log.Err(err).Msg("Failed to set Viper flags")
if err := flag.Value.Set(param.(string)); err != nil {
log.Err(err).Msg("Failed to set Viper flags")
}
}
default:
newVal := fmt.Sprintf("%v", val)
Expand Down
28 changes: 28 additions & 0 deletions lib/flags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,34 @@ test-float: 123.456
assert.Equal(t, 123.456, testFloat)
})

t.Run("BindFlags_FromYAML_StringArrayVar", func(t *testing.T) {
assertClearEnv(t)
defer clearEnvVars(t)

yamlConfig := []byte(`
regex:
- test\=
- array\=
- flag\=
another-regex: [test\=, array\=, flag\=]
`)

cmd := &cobra.Command{}
v := getViper()
v.SetConfigType("yaml")
assert.NoError(t, v.ReadConfig(bytes.NewBuffer(yamlConfig)))

var testArray []string
cmd.Flags().StringArrayVar(&testArray, "regex", []string{}, "Test array flag")
cmd.Flags().StringArrayVar(&testArray, "another-regex", []string{}, "Test array flag")

err := lib.BindFlags(cmd, v, envVarPrefix)
assert.NoError(t, err)

assert.Equal(t, []string{"test\\=", "array\\=", "flag\\="}, testArray)
assert.Equal(t, []string{"test\\=", "array\\=", "flag\\="}, testArray)
})

t.Run("BindFlags_FromYAML_SubCMD", func(t *testing.T) {
assertClearEnv(t)
defer clearEnvVars(t)
Expand Down

0 comments on commit a1b5e2c

Please sign in to comment.