From 3de0cf3bb07969e827667bb61f67bbe3cc218dcb Mon Sep 17 00:00:00 2001 From: Benjamin Hallion Date: Tue, 10 Aug 2021 11:22:50 +0200 Subject: [PATCH 1/2] feat: Add RequiredIfNoDef option to avoid redudant required paramter on fields --- env.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/env.go b/env.go index 792c855..1492c56 100644 --- a/env.go +++ b/env.go @@ -101,6 +101,8 @@ type Options struct { Environment map[string]string // TagName specifies another tagname to use rather than the default env. TagName string + // RequiredIfNoDef automatically sets all env as required if they do not declare 'envDefault' + RequiredIfNoDef bool // Sets to true if we have already configured once. configured bool @@ -130,6 +132,7 @@ func configure(opts []Options) []Options { if item.TagName != "" { opt.TagName = item.TagName } + opt.RequiredIfNoDef = item.RequiredIfNoDef } return []Options{opt} @@ -215,7 +218,7 @@ func doParse(ref reflect.Value, funcMap map[reflect.Type]ParserFunc, opts []Opti } func get(field reflect.StructField, opts []Options) (val string, err error) { - var required bool + var required bool = opts[0].RequiredIfNoDef var exists bool var loadFile bool var unset bool From be171b4d97f140bde5b07cf3f3f1a076d271f5ff Mon Sep 17 00:00:00 2001 From: Benjamin Hallion Date: Tue, 10 Aug 2021 14:47:13 +0200 Subject: [PATCH 2/2] test: add missing test for Option.RequiredIfNoDef --- env_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/env_test.go b/env_test.go index e5b5169..f6b5b83 100644 --- a/env_test.go +++ b/env_test.go @@ -1321,6 +1321,24 @@ func TestCustomTimeParser(t *testing.T) { is.Equal(6, time.Time(cfg.SomeTime).Day()) } +func TestRequiredIfNoDefOption(t *testing.T) { + is := is.New(t) + + type config struct { + Name string `env:"NAME"` + Genre string `env:"GENRE" envDefault:"Unknown"` + } + + var cfg config + is.NoErr(Parse(&cfg)) + isErrorWithMessage(t, Parse(&cfg, Options{RequiredIfNoDef: true}), `env: required environment variable "NAME" is not set`) + + os.Setenv("NAME", "John") + defer os.Clearenv() + // should not trigger an error for the missing 'GENRE' env because it has a default value. + is.NoErr(Parse(&cfg, Options{RequiredIfNoDef: true})) +} + func isErrorWithMessage(tb testing.TB, err error, msg string) { tb.Helper()