Skip to content

Commit

Permalink
Fixing struct pointer initialization with no values set (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
williamgcampbell committed May 31, 2022
1 parent e94cab6 commit 2e8a61d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
10 changes: 7 additions & 3 deletions envconfig.go
Expand Up @@ -238,6 +238,10 @@ func Process(ctx context.Context, i interface{}) error {
// ProcessWith processes the given interface with the given lookuper. See the
// package-level documentation for specific examples and behaviors.
func ProcessWith(ctx context.Context, i interface{}, l Lookuper, fns ...MutatorFunc) error {
return processWith(ctx, i, l, false, fns...)
}

func processWith(ctx context.Context, i interface{}, l Lookuper, pnoinit bool, fns ...MutatorFunc) error {
if l == nil {
return ErrLookuperNil
}
Expand Down Expand Up @@ -290,8 +294,8 @@ func ProcessWith(ctx context.Context, i interface{}, l Lookuper, fns ...MutatorF
// 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 {
if !reflect.DeepEqual(v.Interface(), empty) {
if !reflect.DeepEqual(v.Interface(), empty) || !(opts.NoInit || pnoinit) {
//if !reflect.DeepEqual(v.Interface(), empty) {
origin.Set(v)
}
}
Expand Down Expand Up @@ -344,7 +348,7 @@ func ProcessWith(ctx context.Context, i interface{}, l Lookuper, fns ...MutatorF
plu = PrefixLookuper(opts.Prefix, l)
}

if err := ProcessWith(ctx, ef.Interface(), plu, fns...); err != nil {
if err := processWith(ctx, ef.Interface(), plu, opts.NoInit, fns...); err != nil {
return fmt.Errorf("%s: %w", tf.Name, err)
}

Expand Down
20 changes: 20 additions & 0 deletions envconfig_test.go
Expand Up @@ -1655,6 +1655,26 @@ func TestProcessWith(t *testing.T) {
},

// No init
{
name: "noinit/init_with_nil_structs",
input: &struct {
Electron *Electron
}{},
exp: &struct {
Electron *Electron
}{
Electron: &Electron{
Name: "",
Lepton: &Lepton{
Name: "",
Quark: &Quark{
Value: 0,
},
},
},
},
lookuper: MapLookuper(map[string]string{}),
},
{
name: "noinit/no_init_when_sub_fields_unset",
input: &struct {
Expand Down

0 comments on commit 2e8a61d

Please sign in to comment.