Skip to content

Commit

Permalink
convert: Try ConversionFrom if ConversionTo returns nil
Browse files Browse the repository at this point in the history
This allows capsule-to-capsule conversions where the target type knows how to convert from the source.
  • Loading branch information
Andrew-Morozko authored Dec 7, 2024
1 parent fb9f51f commit 0cef5a1
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
8 changes: 6 additions & 2 deletions cty/convert/conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,12 +171,16 @@ func getConversionKnown(in cty.Type, out cty.Type, unsafe bool) conversion {
}
if out.IsCapsuleType() {
if fn := out.CapsuleOps().ConversionTo; fn != nil {
return conversionToCapsule(in, out, fn)
if conv := conversionToCapsule(in, out, fn); conv != nil {
return conv
}
}
}
if in.IsCapsuleType() {
if fn := in.CapsuleOps().ConversionFrom; fn != nil {
return conversionFromCapsule(in, out, fn)
if conv := conversionFromCapsule(in, out, fn); conv != nil {
return conv
}
}
}
// No conversion operation is available, then.
Expand Down
19 changes: 19 additions & 0 deletions cty/convert/conversion_capsule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,20 @@ func TestConvertCapsuleType(t *testing.T) {
return cty.CapsuleVal(capTy, &s)
}

capIntTy := cty.CapsuleWithOps("int test thingy", reflect.TypeOf(0), &cty.CapsuleOps{
ConversionFrom: func(src cty.Type) func(interface{}, cty.Path) (cty.Value, error) {
if src.Equals(capTy) {
return func(v interface{}, p cty.Path) (cty.Value, error) {
return capVal(fmt.Sprintf("%d", *(v.(*int)))), nil
}
}
return nil
},
})
capIntVal := func(i int) cty.Value {
return cty.CapsuleVal(capIntTy, &i)
}

tests := []struct {
From cty.Value
To cty.Type
Expand Down Expand Up @@ -102,6 +116,11 @@ func TestConvertCapsuleType(t *testing.T) {
To: cty.Bool,
WantErr: `bool required`,
},
{
From: capIntVal(42),
To: capTy,
Want: capVal("42"),
},
}

for _, test := range tests {
Expand Down

0 comments on commit 0cef5a1

Please sign in to comment.