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

Try ConversionFrom if ConversionTo returns nil #194

Merged
merged 1 commit into from
Dec 7, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
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 {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is strictly speaking unnecessary, but decided to change the conversionFrom case in the same way for uniformity / in case more conversion methods would be added

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