Skip to content

Commit

Permalink
river: fix capsule type loss when converting capsules to any
Browse files Browse the repository at this point in the history
This makes two changes to fix the loss of the capsule type when a
capsule value is converted to interface{}:

1. Structs with no River tags are no longer considered objects, and are
   now considered capsules.

2. Capsules can be converted if the Go types can be converted (such as
   assigning to an interface).

Fixes grafana#3171.
Related to #2547.
  • Loading branch information
rfratto committed Mar 7, 2023
1 parent 84d8681 commit 23eb32e
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 2 deletions.
11 changes: 11 additions & 0 deletions pkg/river/internal/value/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,17 @@ func tryCapsuleConvert(from Value, into reflect.Value, intoType Type) (ok bool,
}
}

// Last attempt: see if the Go types can be converted.
if from.Reflect().CanAddr() && from.Reflect().Addr().CanConvert(into.Type()) {
val := from.Reflect().Addr().Convert(into.Type())
into.Set(val)
return true, nil
} else if from.Reflect().CanConvert(into.Type()) {
val := from.Reflect().Convert(into.Type())
into.Set(val)
return true, nil
}

return false, nil
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/river/internal/value/decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ func TestDecode_CustomTypes(t *testing.T) {
}

type customUnmarshaler struct {
Called bool
Called bool `river:"called,attr,optional"`
}

func (cu *customUnmarshaler) UnmarshalRiver(f func(interface{}) error) error {
Expand Down
3 changes: 3 additions & 0 deletions pkg/river/internal/value/type.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,9 @@ func RiverType(t reflect.Type) Type {
return TypeObject

case reflect.Struct:
if getCachedTags(t).Len() == 0 {
return TypeCapsule
}
return TypeObject

case reflect.Func:
Expand Down
3 changes: 2 additions & 1 deletion pkg/river/internal/value/type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ var typeTests = []struct {
{[...]int{0, 1, 2}, value.TypeArray},
{[]int{0, 1, 2}, value.TypeArray},

{struct{}{}, value.TypeObject},
// Struct with no River tags is a capsule.
{struct{}{}, value.TypeCapsule},

// A slice of labeled blocks should be an object.
{[]struct {
Expand Down

0 comments on commit 23eb32e

Please sign in to comment.