Skip to content

Commit

Permalink
Fix issue parsing into ptr fields with value
Browse files Browse the repository at this point in the history
Closes #339
  • Loading branch information
hypnoglow committed Oct 21, 2024
1 parent 4ab8b37 commit 4c201c6
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
2 changes: 1 addition & 1 deletion env.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() == "" {
Expand Down
52 changes: 52 additions & 0 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}

0 comments on commit 4c201c6

Please sign in to comment.