From fe0af402f900d2418181645cf9dff91450e6e953 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Fabianski?= Date: Mon, 18 Dec 2023 18:07:28 +0100 Subject: [PATCH] feat: handle other options for prefix --- viper.go | 25 +++++++++++++++++++++++-- viper_test.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/viper.go b/viper.go index 122280b115..9911c5bb22 100644 --- a/viper.go +++ b/viper.go @@ -1241,7 +1241,8 @@ func (v *Viper) BindFlagValue(key string, flag FlagValue) error { // If more arguments are provided, they will represent the env variable names that // should bind to this key and will be taken in the specified order. // EnvPrefix will be used when set when env name is not provided. -func BindEnv(input ...string) error { return v.BindEnv(input...) } +func BindEnv(input ...string) error { return v.BindEnv(input...) } +func BindEnvNoPrefix(input ...string) error { return v.BindEnvNoPrefix(input...) } func (v *Viper) BindEnv(input ...string) error { if len(input) == 0 { @@ -1253,7 +1254,27 @@ func (v *Viper) BindEnv(input ...string) error { if len(input) == 1 { v.env[key] = append(v.env[key], v.mergeWithEnvPrefix(key)) } else { - v.env[key] = append(v.env[key], input[1:]...) + for _, otherKey := range input[1:] { + v.env[key] = append(v.env[key], v.mergeWithEnvPrefix(otherKey)) + } + } + + return nil +} + +func (v *Viper) BindEnvNoPrefix(input ...string) error { + if len(input) == 0 { + return fmt.Errorf("missing key to bind to") + } + + key := strings.ToLower(input[0]) + + if len(input) == 1 { + v.env[key] = append(v.env[key], strings.ToUpper(key)) + } else { + for _, otherKey := range input[1:] { + v.env[key] = append(v.env[key], strings.ToUpper(otherKey)) + } } return nil diff --git a/viper_test.go b/viper_test.go index 4dc52ac27d..c102da57a9 100644 --- a/viper_test.go +++ b/viper_test.go @@ -694,6 +694,48 @@ func TestAutoEnvWithPrefix(t *testing.T) { assert.Equal(t, "13", Get("bar")) } +func TestAutoEnvWithPrefixAndOthers(t *testing.T) { + Reset() + + AutomaticEnv() + replacer := strings.NewReplacer("-", "_", ".", "_") + SetEnvKeyReplacer(replacer) + SetEnvPrefix("foo") + BindEnv([]string{"bar", "baz.id", "qux"}...) + + t.Setenv("FOO_BAZ_ID", "13") + + assert.Equal(t, "13", Get("bar")) +} + +func TestAutoEnvWithPrefixAndOthersNoPrefixArray(t *testing.T) { + Reset() + + AutomaticEnv() + replacer := strings.NewReplacer("-", "_", ".", "_") + SetEnvKeyReplacer(replacer) + SetEnvPrefix("foo") + BindEnvNoPrefix([]string{"bar", "OTHER"}...) + + t.Setenv("OTHER", "13") + + assert.Equal(t, "13", Get("bar")) +} + +func TestAutoEnvWithPrefixAndOthersNoPrefixSingle(t *testing.T) { + Reset() + + AutomaticEnv() + replacer := strings.NewReplacer("-", "_", ".", "_") + SetEnvKeyReplacer(replacer) + SetEnvPrefix("foo") + BindEnvNoPrefix([]string{"bar"}...) + + t.Setenv("BAR", "13") + + assert.Equal(t, "13", Get("bar")) +} + func TestSetEnvKeyReplacer(t *testing.T) { Reset()