From befaf9a086c5e7db885e1ca3d36aa4e8b9d3a57d Mon Sep 17 00:00:00 2001 From: Seth Vargo Date: Tue, 31 May 2022 09:43:59 -0400 Subject: [PATCH] Cleanup docs and add another test after #57 --- envconfig.go | 15 ++++++++------- envconfig_test.go | 30 ++++++++++++++++++++++++++++-- 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/envconfig.go b/envconfig.go index c8ee7f8..26ef06c 100644 --- a/envconfig.go +++ b/envconfig.go @@ -241,7 +241,9 @@ func ProcessWith(ctx context.Context, i interface{}, l Lookuper, fns ...MutatorF return processWith(ctx, i, l, false, fns...) } -func processWith(ctx context.Context, i interface{}, l Lookuper, pnoinit bool, fns ...MutatorFunc) error { +// processWith is a helper that captures whether the parent wanted +// initialization. +func processWith(ctx context.Context, i interface{}, l Lookuper, parentNoInit bool, fns ...MutatorFunc) error { if l == nil { return ErrLookuperNil } @@ -290,12 +292,11 @@ func processWith(ctx context.Context, i interface{}, l Lookuper, pnoinit bool, f origin := e.Field(i) if isNilStructPtr { empty := reflect.New(origin.Type().Elem()).Interface() - // If a struct (after traversal) equals to the empty value, - // it means nothing was changed in any sub-fields. - // With the noinit opt, we skip setting the empty value - // to the original struct pointer (aka. keep it nil). - if !reflect.DeepEqual(v.Interface(), empty) || !(opts.NoInit || pnoinit) { - //if !reflect.DeepEqual(v.Interface(), empty) { + // If a struct (after traversal) equals to the empty value, it means + // nothing was changed in any sub-fields. With the noinit opt, we skip + // setting the empty value to the original struct pointer (aka. keep it + // nil). + if !reflect.DeepEqual(v.Interface(), empty) || (!opts.NoInit && !parentNoInit) { origin.Set(v) } } diff --git a/envconfig_test.go b/envconfig_test.go index fc46b3e..82404d7 100644 --- a/envconfig_test.go +++ b/envconfig_test.go @@ -1654,9 +1654,33 @@ func TestProcessWith(t *testing.T) { }), }, - // No init + // Init (default behavior) { - name: "noinit/init_with_nil_structs", + name: "init/basic", + input: &struct { + Field1 string `env:"FIELD1"` + Field2 bool `env:"FIELD2"` + Field3 int64 `env:"FIELD3"` + Field4 float64 `env:"FIELD4"` + Field5 complex64 `env:"FIELD5"` + }{}, + exp: &struct { + Field1 string `env:"FIELD1"` + Field2 bool `env:"FIELD2"` + Field3 int64 `env:"FIELD3"` + Field4 float64 `env:"FIELD4"` + Field5 complex64 `env:"FIELD5"` + }{ + Field1: "", + Field2: false, + Field3: 0, + Field4: 0, + Field5: 0, + }, + lookuper: MapLookuper(map[string]string{}), + }, + { + name: "init/structs", input: &struct { Electron *Electron }{}, @@ -1675,6 +1699,8 @@ func TestProcessWith(t *testing.T) { }, lookuper: MapLookuper(map[string]string{}), }, + + // No init { name: "noinit/no_init_when_sub_fields_unset", input: &struct {