Skip to content

Commit

Permalink
Cleanup docs and add another test after #57
Browse files Browse the repository at this point in the history
  • Loading branch information
sethvargo committed May 31, 2022
1 parent 2e8a61d commit befaf9a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 9 deletions.
15 changes: 8 additions & 7 deletions envconfig.go
Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
}
}
Expand Down
30 changes: 28 additions & 2 deletions envconfig_test.go
Expand Up @@ -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
}{},
Expand All @@ -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 {
Expand Down

0 comments on commit befaf9a

Please sign in to comment.