Skip to content

Commit

Permalink
Merge branch 'master' into onset
Browse files Browse the repository at this point in the history
  • Loading branch information
caarlos0 committed Aug 10, 2021
2 parents a672706 + 92ab404 commit 8d3a039
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Expand Up @@ -39,7 +39,7 @@ jobs:
run: make setup ci
-
name: Upload coverage
uses: codecov/codecov-action@v1
uses: codecov/codecov-action@v2
if: matrix.os == 'ubuntu-latest'
with:
token: ${{ secrets.CODECOV_TOKEN }}
Expand Down
5 changes: 4 additions & 1 deletion env.go
Expand Up @@ -103,6 +103,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

OnSet OnSetFn

Expand Down Expand Up @@ -137,6 +139,7 @@ func configure(opts []Options) []Options {
if item.OnSet != nil {
opt.OnSet = item.OnSet
}
opt.RequiredIfNoDef = item.RequiredIfNoDef
}

return []Options{opt}
Expand Down Expand Up @@ -226,7 +229,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 isDefault bool
var loadFile bool
Expand Down
18 changes: 18 additions & 0 deletions env_test.go
Expand Up @@ -1376,6 +1376,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

0 comments on commit 8d3a039

Please sign in to comment.