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

Fixing struct pointer initialization with no values set #57

Merged
merged 1 commit into from May 31, 2022
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
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