From 53a0f7864cd6529cc410484426e116aba496ddfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Fabianski?= Date: Wed, 20 Dec 2023 11:22:58 +0100 Subject: [PATCH] feat: make env variables accessible --- viper.go | 6 ++++++ viper_test.go | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/viper.go b/viper.go index 20eb4da..6ae5a86 100644 --- a/viper.go +++ b/viper.go @@ -2059,6 +2059,12 @@ func (v *Viper) watchRemoteConfig(provider RemoteProvider) (map[string]any, erro return v.kvstore, err } +func AllEnvVar() map[string][]string { return v.AllEnvVar() } + +func (v *Viper) AllEnvVar() map[string][]string { + return v.env +} + // AllKeys returns all keys holding a value, regardless of where they are set. // Nested keys are returned with a v.keyDelim separator. func AllKeys() []string { return v.AllKeys() } diff --git a/viper_test.go b/viper_test.go index 0b1f407..0c8f067 100644 --- a/viper_test.go +++ b/viper_test.go @@ -27,6 +27,7 @@ import ( "github.com/spf13/pflag" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" "github.com/spf13/viper/internal/features" "github.com/spf13/viper/internal/testutil" @@ -654,6 +655,25 @@ func TestEmptyEnv_Allowed(t *testing.T) { assert.Equal(t, "Cake", Get("name")) } +func TestAllEnvVar(t *testing.T) { + initJSON() + + SetEnvPrefix("foo") // will be uppercased automatically + BindEnv("id") + BindEnv("f", "FOOD", "BAR") + + expectedEnvVariables := []byte(`f: + - FOO_FOOD + - FOO_BAR +id: + - FOO_ID +`) + yamlEnv, _ := yaml.Marshal(AllEnvVar()) + assert.Equal(t, string(expectedEnvVariables), string(yamlEnv)) + + AutomaticEnv() +} + func TestEnvPrefix(t *testing.T) { initJSON()