Skip to content

Commit

Permalink
Add CheckDisallowed (kelseyhightower#106)
Browse files Browse the repository at this point in the history
  • Loading branch information
Carlo Alberto Ferraris authored and teepark committed Mar 5, 2018
1 parent 6191d37 commit 1f94cfa
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
32 changes: 32 additions & 0 deletions envconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"encoding"
"errors"
"fmt"
"os"
"reflect"
"regexp"
"strconv"
Expand Down Expand Up @@ -142,6 +143,37 @@ func gatherInfo(prefix string, spec interface{}) ([]varInfo, error) {
return infos, nil
}

// CheckDisallowed checks that no environment variables with the prefix are set
// that we don't know how or want to parse. This is likely only meaningful with
// a non-empty prefix.
func CheckDisallowed(prefix string, spec interface{}) error {
infos, err := gatherInfo(prefix, spec)
if err != nil {
return err
}

vars := make(map[string]struct{})
for _, info := range infos {
vars[info.Key] = struct{}{}
}

if prefix != "" {
prefix = strings.ToUpper(prefix) + "_"
}

for _, env := range os.Environ() {
if !strings.HasPrefix(env, prefix) {
continue
}
v := strings.SplitN(env, "=", 2)[0]
if _, found := vars[v]; !found {
return fmt.Errorf("unknown environment variable %s", v)
}
}

return nil
}

// Process populates the specified struct based on environment variables
func Process(prefix string, spec interface{}) error {
infos, err := gatherInfo(prefix, spec)
Expand Down
33 changes: 33 additions & 0 deletions envconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,39 @@ func TestBinaryUnmarshalerError(t *testing.T) {
}
}

func TestCheckDisallowedOnlyAllowed(t *testing.T) {
var s Specification
os.Clearenv()
os.Setenv("ENV_CONFIG_DEBUG", "true")
os.Setenv("UNRELATED_ENV_VAR", "true")
err := CheckDisallowed("env_config", &s)
if err != nil {
t.Errorf("expected no error, got %s", err)
}
}

func TestCheckDisallowedMispelled(t *testing.T) {
var s Specification
os.Clearenv()
os.Setenv("ENV_CONFIG_DEBUG", "true")
os.Setenv("ENV_CONFIG_ZEBUG", "false")
err := CheckDisallowed("env_config", &s)
if experr := "unknown environment variable ENV_CONFIG_ZEBUG"; err.Error() != experr {
t.Errorf("expected %s, got %s", experr, err)
}
}

func TestCheckDisallowedIgnored(t *testing.T) {
var s Specification
os.Clearenv()
os.Setenv("ENV_CONFIG_DEBUG", "true")
os.Setenv("ENV_CONFIG_IGNORED", "false")
err := CheckDisallowed("env_config", &s)
if experr := "unknown environment variable ENV_CONFIG_IGNORED"; err.Error() != experr {
t.Errorf("expected %s, got %s", experr, err)
}
}

type bracketed string

func (b *bracketed) Set(value string) error {
Expand Down

0 comments on commit 1f94cfa

Please sign in to comment.