Skip to content

Commit e55230b

Browse files
authoredOct 21, 2024
fix: parsing into ptr fields with value (#340)
Closes #339
1 parent 4ab8b37 commit e55230b

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed
 

‎env.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ func doParseField(
355355
if !refField.CanSet() {
356356
return nil
357357
}
358-
if reflect.Ptr == refField.Kind() && !refField.IsNil() {
358+
if reflect.Ptr == refField.Kind() && refField.Elem().Kind() == reflect.Struct && !refField.IsNil() {
359359
return parseInternal(refField.Interface(), processField, optionsWithEnvPrefix(refTypeField, opts))
360360
}
361361
if reflect.Struct == refField.Kind() && refField.CanAddr() && refField.Type().Name() == "" {

‎env_test.go

+52
Original file line numberDiff line numberDiff line change
@@ -2254,3 +2254,55 @@ func TestNoEnvKeyIgnored(t *testing.T) {
22542254
isEqual(t, "", cfg.Foo)
22552255
isEqual(t, "202", cfg.FooBar)
22562256
}
2257+
2258+
func TestIssue339(t *testing.T) {
2259+
t.Run("Should parse with bool ptr set and env undefined", func(t *testing.T) {
2260+
existingValue := true
2261+
cfg := Config{
2262+
BoolPtr: &existingValue,
2263+
}
2264+
2265+
isNoErr(t, Parse(&cfg))
2266+
2267+
isEqual(t, &existingValue, cfg.BoolPtr)
2268+
})
2269+
2270+
t.Run("Should parse with bool ptr set and env defined", func(t *testing.T) {
2271+
existingValue := true
2272+
cfg := Config{
2273+
BoolPtr: &existingValue,
2274+
}
2275+
2276+
newValue := false
2277+
t.Setenv("BOOL", strconv.FormatBool(newValue))
2278+
2279+
isNoErr(t, Parse(&cfg))
2280+
2281+
isEqual(t, &newValue, cfg.BoolPtr)
2282+
})
2283+
2284+
t.Run("Should parse with string ptr set and env undefined", func(t *testing.T) {
2285+
existingValue := "one"
2286+
cfg := Config{
2287+
StringPtr: &existingValue,
2288+
}
2289+
2290+
isNoErr(t, Parse(&cfg))
2291+
2292+
isEqual(t, &existingValue, cfg.StringPtr)
2293+
})
2294+
2295+
t.Run("Should parse with string ptr set and env defined", func(t *testing.T) {
2296+
existingValue := "one"
2297+
cfg := Config{
2298+
StringPtr: &existingValue,
2299+
}
2300+
2301+
newValue := "two"
2302+
t.Setenv("STRING", newValue)
2303+
2304+
isNoErr(t, Parse(&cfg))
2305+
2306+
isEqual(t, &newValue, cfg.StringPtr)
2307+
})
2308+
}

0 commit comments

Comments
 (0)