Skip to content

Commit 62e8be1

Browse files
committed
🐛 [maps] Expand the Flatten function to support pointers
1 parent 21d1317 commit 62e8be1

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

changes/20250811090744.bugfix

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:bug: [`maps`] Expand the `Flatten` function to support pointers

utils/maps/flatten.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ func Flatten(thing map[string]any) (result Map, err error) {
3434

3535
func flatten(result map[string]string, prefix string, v reflect.Value) (err error) {
3636
if v.Kind() == reflect.Interface {
37+
if v.IsNil() {
38+
return
39+
}
3740
v = v.Elem()
3841
}
3942
switch v.Kind() {
@@ -82,11 +85,16 @@ func flatten(result map[string]string, prefix string, v reflect.Value) (err erro
8285
result[prefix] = v.String()
8386
case reflect.Invalid:
8487
result[prefix] = ""
88+
case reflect.Ptr:
89+
if v.IsNil() {
90+
return
91+
}
92+
err = flatten(result, prefix, v.Elem())
8593
default:
8694
if v.IsZero() {
8795
result[prefix] = ""
8896
} else {
89-
err = commonerrors.Newf(commonerrors.ErrUnknown, "unknown %v", v)
97+
err = commonerrors.Newf(commonerrors.ErrUnknown, "unknown value '%v'", v)
9098
}
9199
}
92100
return

utils/maps/flatten_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import (
88
"github.com/go-faker/faker/v4"
99
"github.com/stretchr/testify/assert"
1010
"github.com/stretchr/testify/require"
11+
12+
"github.com/ARM-software/golang-utils/utils/field"
1113
)
1214

1315
var randomNumber = faker.RandomUnixTime()
@@ -27,6 +29,16 @@ func TestFlatten(t *testing.T) {
2729
"bar": "baz",
2830
},
2931
},
32+
{
33+
Input: map[string]any{
34+
"foo": "bar",
35+
"bar": field.ToOptionalString("baz"),
36+
},
37+
Output: map[string]string{
38+
"foo": "bar",
39+
"bar": "baz",
40+
},
41+
},
3042

3143
{
3244
Input: map[string]any{

0 commit comments

Comments
 (0)