From e55230b50da897c64fe539fd3bce0887cc1c96bd Mon Sep 17 00:00:00 2001 From: Igor Zibarev Date: Mon, 21 Oct 2024 14:19:56 +0300 Subject: [PATCH] fix: parsing into ptr fields with value (#340) Closes #339 --- env.go | 2 +- env_test.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/env.go b/env.go index d24c32e..b815e79 100644 --- a/env.go +++ b/env.go @@ -355,7 +355,7 @@ func doParseField( if !refField.CanSet() { return nil } - if reflect.Ptr == refField.Kind() && !refField.IsNil() { + if reflect.Ptr == refField.Kind() && refField.Elem().Kind() == reflect.Struct && !refField.IsNil() { return parseInternal(refField.Interface(), processField, optionsWithEnvPrefix(refTypeField, opts)) } if reflect.Struct == refField.Kind() && refField.CanAddr() && refField.Type().Name() == "" { diff --git a/env_test.go b/env_test.go index 3ccaae4..6017889 100644 --- a/env_test.go +++ b/env_test.go @@ -2254,3 +2254,55 @@ func TestNoEnvKeyIgnored(t *testing.T) { isEqual(t, "", cfg.Foo) isEqual(t, "202", cfg.FooBar) } + +func TestIssue339(t *testing.T) { + t.Run("Should parse with bool ptr set and env undefined", func(t *testing.T) { + existingValue := true + cfg := Config{ + BoolPtr: &existingValue, + } + + isNoErr(t, Parse(&cfg)) + + isEqual(t, &existingValue, cfg.BoolPtr) + }) + + t.Run("Should parse with bool ptr set and env defined", func(t *testing.T) { + existingValue := true + cfg := Config{ + BoolPtr: &existingValue, + } + + newValue := false + t.Setenv("BOOL", strconv.FormatBool(newValue)) + + isNoErr(t, Parse(&cfg)) + + isEqual(t, &newValue, cfg.BoolPtr) + }) + + t.Run("Should parse with string ptr set and env undefined", func(t *testing.T) { + existingValue := "one" + cfg := Config{ + StringPtr: &existingValue, + } + + isNoErr(t, Parse(&cfg)) + + isEqual(t, &existingValue, cfg.StringPtr) + }) + + t.Run("Should parse with string ptr set and env defined", func(t *testing.T) { + existingValue := "one" + cfg := Config{ + StringPtr: &existingValue, + } + + newValue := "two" + t.Setenv("STRING", newValue) + + isNoErr(t, Parse(&cfg)) + + isEqual(t, &newValue, cfg.StringPtr) + }) +}