Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add option: 'required' by default #187

Merged
merged 2 commits into from Aug 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion env.go
Expand Up @@ -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
Expand Down Expand Up @@ -130,6 +132,7 @@ func configure(opts []Options) []Options {
if item.TagName != "" {
opt.TagName = item.TagName
}
opt.RequiredIfNoDef = item.RequiredIfNoDef
}

return []Options{opt}
Expand Down Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions env_test.go
Expand Up @@ -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()

Expand Down