Skip to content

Commit

Permalink
feat: handle other options for prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
cfabianski committed Dec 18, 2023
1 parent 0b0a110 commit fe0af40
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 2 deletions.
25 changes: 23 additions & 2 deletions viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down
42 changes: 42 additions & 0 deletions viper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit fe0af40

Please sign in to comment.