Skip to content

Commit

Permalink
cue: fix TextUnmarshal bug in Decode
Browse files Browse the repository at this point in the history
Silly boolean inversion in an unnecessary check.

Fixes #1466

Signed-off-by: Marcel van Lohuizen <[email protected]>

Change-Id: Ic116aeb7f0f9d1f421a858a54b932d38f542d121
Signed-off-by: Marcel van Lohuizen <[email protected]>
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/531170
Unity-Result: CUEcueckoo <[email protected]>
TryBot-Result: CUEcueckoo <[email protected]>
Reviewed-by: Marcel van Lohuizen <[email protected]>
  • Loading branch information
mpvl committed Feb 17, 2022
1 parent 6b37a01 commit 24c9117
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
10 changes: 5 additions & 5 deletions cue/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,12 @@ func (d *decoder) decode(x reflect.Value, v Value, isPtr bool) {
}

if it != nil {
if kind := v.Kind(); kind == StringKind || kind == BytesKind {
d.addErr(errors.Newf(v.Pos(),
"cannot unmarshal %v with TextUnmarshaler", kind))
}
b, err := v.Bytes()
d.addErr(err)
if err != nil {
err = errors.Wrapf(err, v.Pos(), "Decode")
d.addErr(err)
return
}
d.addErr(it.UnmarshalText(b))
return
}
Expand Down
39 changes: 39 additions & 0 deletions cue/decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package cue
import (
"reflect"
"testing"
"time"

"github.com/google/go-cmp/cmp"
)
Expand Down Expand Up @@ -212,6 +213,24 @@ func TestDecode(t *testing.T) {
"b": []interface{}{int(0)},
},
},
}, {
// Issue #1466
value: `{"x": "1s"}
`,
dst: &S{},
want: S{X: Duration{D: 1000000000}},
}, {
// Issue #1466
value: `{"x": '1s'}
`,
dst: &S{},
want: S{X: Duration{D: 1000000000}},
}, {
// Issue #1466
value: `{"x": 1}
`,
dst: &S{},
err: "Decode: x: cannot use value 1 (type int) as (string|bytes)",
}}
for _, tc := range testCases {
t.Run(tc.value, func(t *testing.T) {
Expand All @@ -226,3 +245,23 @@ func TestDecode(t *testing.T) {
})
}
}

type Duration struct {
D time.Duration
}
type S struct {
X Duration `json:"x"`
}

func (d *Duration) UnmarshalText(data []byte) error {
v, err := time.ParseDuration(string(data))
if err != nil {
return err
}
d.D = v
return nil
}

func (d *Duration) MarshalText() ([]byte, error) {
return []byte(d.D.String()), nil
}

0 comments on commit 24c9117

Please sign in to comment.