Skip to content

Commit

Permalink
Make selector required by default
Browse files Browse the repository at this point in the history
  • Loading branch information
pjanotti committed May 4, 2021
1 parent f67b090 commit a95fdcf
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 14 deletions.
11 changes: 6 additions & 5 deletions internal/configsource/envvarconfigsource/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,11 @@ type (
)

type retrieveParams struct {
// Retrieve parameter for the config source. If set to true and the environment
// variable specified on the selector is not defined or not available on the
// defaults the call to Retrieve will fail.
Required bool `mapstructure:"required"`
// Optional is used to change the default behavior when an environment variable
// requested via the config source is not defined. By default the value of this
// field is 'false' which will cause an error if the specified environment variable
// is not defined. Set it to 'true' to ignore not defined environment variables.
Optional bool `mapstructure:"optional"`
}

// envVarSession implements the configsource.Session interface.
Expand All @@ -64,7 +65,7 @@ func (e *envVarSession) Retrieve(_ context.Context, selector string, params inte

defaultValue, ok := e.defaults[selector]
if !ok {
if actualParams.Required {
if !actualParams.Optional {
return nil, &errMissingRequiredEnvVar{fmt.Errorf("env var %q is required but not defined and not present on defaults", selector)}
}

Expand Down
11 changes: 4 additions & 7 deletions internal/configsource/envvarconfigsource/session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ func TestEnvVarConfigSource_Session(t *testing.T) {
{
name: "missing_not_required",
selector: "UNDEFINED_ENV_VAR",
params: map[string]interface{}{
"optional": true,
},
expected: "", // The default behavior for undefined env var is empty string.
},
{
Expand All @@ -55,18 +58,12 @@ func TestEnvVarConfigSource_Session(t *testing.T) {
wantErr: &errInvalidRetrieveParams{},
},
{
name: "missing_required",
params: map[string]interface{}{
"required": true,
},
name: "missing_required",
selector: "UNDEFINED_ENV_VAR",
wantErr: &errMissingRequiredEnvVar{},
},
{
name: "required_on_defaults",
params: map[string]interface{}{
"required": true,
},
defaults: map[string]interface{}{
"FALLBACK_ENV_VAR": "fallback_env_var",
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ config_sources:

config:
from_defined_env_var: ${env:_TEST_ENV_VAR_CFG_SRC}
from_undefined_env_var: ${env:_UNDEFINED_ENV_VAR}/some/path
from_undefined_env_var: ${env:_UNDEFINED_ENV_VAR?optional=true}/some/path
field_from_default: $env:k0
map_from_default: $env:cfg?required=true
map_from_default: $env:cfg?optional=true

0 comments on commit a95fdcf

Please sign in to comment.