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

Add a nil case to the getValueFromInterface function #666

Merged
merged 3 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 16 additions & 11 deletions pkg/fieldpath/paved.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,9 @@ func (p *Paved) getValue(s Segments) (any, error) {
return getValueFromInterface(p.object, s)
}

func getValueFromInterface(it any, s Segments) (any, error) {
func getValueFromInterface(it any, s Segments) (any, error) { //nolint:gocyclo // See note below.
// Although the complexity of the function may seem high, in fact the same
// operation is performed in different cases.
for i, current := range s {
final := i == len(s)-1
switch current.Type {
Expand All @@ -129,18 +131,21 @@ func getValueFromInterface(it any, s Segments) (any, error) {
}
it = array[current.Index]
case SegmentField:
object, ok := it.(map[string]any)
if !ok {
switch object := it.(type) {
case map[string]any:
v, ok := object[current.Field]
if !ok {
return nil, errNotFound{errors.Errorf("%s: no such field", s[:i+1])}
}
if final {
return v, nil
}
it = object[current.Field]
case nil:
return nil, errNotFound{errors.Errorf("path %q is not found in the paved object", s[:i])}
sergenyalcin marked this conversation as resolved.
Show resolved Hide resolved
default:
return nil, errors.Errorf("%s: not an object", s[:i])
}
v, ok := object[current.Field]
if !ok {
return nil, errNotFound{errors.Errorf("%s: no such field", s[:i+1])}
}
if final {
return v, nil
}
it = object[current.Field]
}
}

Expand Down
8 changes: 8 additions & 0 deletions pkg/fieldpath/paved_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,14 @@ func TestGetValue(t *testing.T) {
err: errors.Wrap(errors.New("unexpected ']' at position 5"), "cannot parse path \"spec[]\""),
},
},
"NilParent": {
reason: "Request for a path with a nil parent value",
path: "spec.containers[*].name",
data: []byte(`{"spec":{"containers": null}}`),
want: want{
err: errNotFound{errors.Errorf("path %q is not found in the paved object", "spec.containers")},
},
},
}

for name, tc := range cases {
Expand Down
Loading